3 ///////////////////////////////////////////////////////////////////////////
4 // NOTICE OF COPYRIGHT //
6 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
7 // http://moodle.org //
9 // Copyright (C) 1999 onwards Martin Dougiamas http://moodle.com //
11 // This program is free software; you can redistribute it and/or modify //
12 // it under the terms of the GNU General Public License as published by //
13 // the Free Software Foundation; either version 2 of the License, or //
14 // (at your option) any later version. //
16 // This program is distributed in the hope that it will be useful, //
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
19 // GNU General Public License for more details: //
21 // http://www.gnu.org/copyleft/gpl.html //
23 ///////////////////////////////////////////////////////////////////////////
26 * Library of functions for gradebook - both public and internal
28 * @author Moodle HQ developers
30 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
34 require_once($CFG->libdir
. '/grade/constants.php');
36 require_once($CFG->libdir
. '/grade/grade_category.php');
37 require_once($CFG->libdir
. '/grade/grade_item.php');
38 require_once($CFG->libdir
. '/grade/grade_grade.php');
39 require_once($CFG->libdir
. '/grade/grade_scale.php');
40 require_once($CFG->libdir
. '/grade/grade_outcome.php');
42 /////////////////////////////////////////////////////////////////////
43 ///// Start of public API for communication with modules/blocks /////
44 /////////////////////////////////////////////////////////////////////
47 * Submit new or update grade; update/create grade_item definition. Grade must have userid specified,
48 * rawgrade and feedback with format are optional. rawgrade NULL means 'Not graded', missing property
49 * or key means do not change existing.
51 * Only following grade item properties can be changed 'itemname', 'idnumber', 'gradetype', 'grademax',
52 * 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted' and 'hidden'. 'reset' means delete all current grades including locked ones.
54 * Manual, course or category items can not be updated by this function.
56 * @param string $source source of the grade such as 'mod/assignment'
57 * @param int $courseid id of course
58 * @param string $itemtype type of grade item - mod, block
59 * @param string $itemmodule more specific then $itemtype - assignment, forum, etc.; maybe NULL for some item types
60 * @param int $iteminstance instance it of graded subject
61 * @param int $itemnumber most probably 0, modules can use other numbers when having more than one grades for each user
62 * @param mixed $grades grade (object, array) or several grades (arrays of arrays or objects), NULL if updating grade_item definition only
63 * @param mixed $itemdetails object or array describing the grading item, NULL if no change
65 function grade_update($source, $courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $grades=NULL, $itemdetails=NULL) {
68 // only following grade_item properties can be changed in this function
69 $allowed = array('itemname', 'idnumber', 'gradetype', 'grademax', 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted', 'hidden');
70 // list of 10,5 numeric fields
71 $floats = array('grademin', 'grademax', 'multfactor', 'plusfactor');
73 // grade item identification
74 $params = compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber');
76 if (is_null($courseid) or is_null($itemtype)) {
77 debugging('Missing courseid or itemtype');
78 return GRADE_UPDATE_FAILED
;
81 if (!$grade_items = grade_item
::fetch_all($params)) {
85 } else if (count($grade_items) == 1){
86 $grade_item = reset($grade_items);
87 unset($grade_items); //release memory
90 debugging('Found more than one grade item');
91 return GRADE_UPDATE_MULTIPLE
;
94 if (!empty($itemdetails['deleted'])) {
96 if ($grade_item->delete($source)) {
97 return GRADE_UPDATE_OK
;
99 return GRADE_UPDATE_FAILED
;
102 return GRADE_UPDATE_OK
;
105 /// Create or update the grade_item if needed
109 $itemdetails = (array)$itemdetails;
111 // grademin and grademax ignored when scale specified
112 if (array_key_exists('scaleid', $itemdetails)) {
113 if ($itemdetails['scaleid']) {
114 unset($itemdetails['grademin']);
115 unset($itemdetails['grademax']);
119 foreach ($itemdetails as $k=>$v) {
120 if (!in_array($k, $allowed)) {
124 if ($k == 'gradetype' and $v == GRADE_TYPE_NONE
) {
125 // no grade item needed!
126 return GRADE_UPDATE_OK
;
131 $grade_item = new grade_item($params);
132 $grade_item->insert();
135 if ($grade_item->is_locked()) {
136 // no notice() here, test returned value instead!
137 return GRADE_UPDATE_ITEM_LOCKED
;
141 $itemdetails = (array)$itemdetails;
143 foreach ($itemdetails as $k=>$v) {
144 if (!in_array($k, $allowed)) {
148 if (in_array($k, $floats)) {
149 if (grade_floats_different($grade_item->{$k}, $v)) {
150 $grade_item->{$k} = $v;
155 if ($grade_item->{$k} != $v) {
156 $grade_item->{$k} = $v;
162 $grade_item->update();
167 /// reset grades if requested
168 if (!empty($itemdetails['reset'])) {
169 $grade_item->delete_all_grades('reset');
170 return GRADE_UPDATE_OK
;
173 /// Some extra checks
174 // do we use grading?
175 if ($grade_item->gradetype
== GRADE_TYPE_NONE
) {
176 return GRADE_UPDATE_OK
;
179 // no grade submitted
180 if (empty($grades)) {
181 return GRADE_UPDATE_OK
;
184 /// Finally start processing of grades
185 if (is_object($grades)) {
186 $grades = array($grades->userid
=>$grades);
188 if (array_key_exists('userid', $grades)) {
189 $grades = array($grades['userid']=>$grades);
193 /// normalize and verify grade array
194 foreach($grades as $k=>$g) {
200 if (empty($g['userid']) or $k != $g['userid']) {
201 debugging('Incorrect grade array index, must be user id! Grade ignored.');
206 if (empty($grades)) {
207 return GRADE_UPDATE_FAILED
;
210 $count = count($grades);
214 $sql = "SELECT * FROM {$CFG->prefix}grade_grades WHERE itemid = $grade_item->id AND userid = $uid";
216 } else if ($count < 200) {
217 $uids = implode(',', array_keys($grades));
218 $sql = "SELECT * FROM {$CFG->prefix}grade_grades WHERE itemid = $grade_item->id AND userid IN ($uids)";
221 $sql = "SELECT * FROM {$CFG->prefix}grade_grades WHERE itemid = $grade_item->id";
224 $rs = get_recordset_sql($sql);
228 while (count($grades) > 0) {
232 while ($rs and !rs_EOF($rs)) {
233 if (!$gd = rs_fetch_next_record($rs)) {
236 $userid = $gd->userid
;
237 if (!isset($grades[$userid])) {
238 // this grade not requested, continue
241 // existing grade requested
242 $grade = $grades[$userid];
243 $grade_grade = new grade_grade($gd, false);
244 unset($grades[$userid]);
248 if (is_null($grade_grade)) {
249 if (count($grades) == 0) {
250 // no more grades to process
254 $grade = reset($grades);
255 $userid = $grade['userid'];
256 $grade_grade = new grade_grade(array('itemid'=>$grade_item->id
, 'userid'=>$userid), false);
257 $grade_grade->load_optional_fields(); // add feedback and info too
258 unset($grades[$userid]);
263 $feedbackformat = FORMAT_MOODLE
;
264 $usermodified = $USER->id
;
265 $datesubmitted = null;
268 if (array_key_exists('rawgrade', $grade)) {
269 $rawgrade = $grade['rawgrade'];
272 if (array_key_exists('feedback', $grade)) {
273 $feedback = $grade['feedback'];
276 if (array_key_exists('feedbackformat', $grade)) {
277 $feedbackformat = $grade['feedbackformat'];
280 if (array_key_exists('usermodified', $grade)) {
281 $usermodified = $grade['usermodified'];
284 if (array_key_exists('datesubmitted', $grade)) {
285 $datesubmitted = $grade['datesubmitted'];
288 if (array_key_exists('dategraded', $grade)) {
289 $dategraded = $grade['dategraded'];
292 // update or insert the grade
293 if (!$grade_item->update_raw_grade($userid, $rawgrade, $source, $feedback, $feedbackformat, $usermodified, $dategraded, $datesubmitted, $grade_grade)) {
303 return GRADE_UPDATE_OK
;
305 return GRADE_UPDATE_FAILED
;
310 * Updates outcomes of user
311 * Manual outcomes can not be updated.
313 * @param string $source source of the grade such as 'mod/assignment'
314 * @param int $courseid id of course
315 * @param string $itemtype 'mod', 'block'
316 * @param string $itemmodule 'forum, 'quiz', etc.
317 * @param int $iteminstance id of the item module
318 * @param int $userid ID of the graded user
319 * @param array $data array itemnumber=>outcomegrade
321 function grade_update_outcomes($source, $courseid, $itemtype, $itemmodule, $iteminstance, $userid, $data) {
322 if ($items = grade_item
::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
323 foreach ($items as $item) {
324 if (!array_key_exists($item->itemnumber
, $data)) {
327 $grade = $data[$item->itemnumber
] < 1 ?
null : $data[$item->itemnumber
];
328 $item->update_final_grade($userid, $grade, $source);
334 * Returns grading information for given activity - optionally with users grades
335 * Manual, course or category items can not be queried.
337 * @param int $courseid id of course
338 * @param string $itemtype 'mod', 'block'
339 * @param string $itemmodule 'forum, 'quiz', etc.
340 * @param int $iteminstance id of the item module
341 * @param int $userid_or_ids optional id of the graded user or array of ids; if userid not used, returns only information about grade_item
342 * @return array of grade information objects (scaleid, name, grade and locked status, etc.) indexed with itemnumbers
344 function grade_get_grades($courseid, $itemtype, $itemmodule, $iteminstance, $userid_or_ids=null) {
347 $return = new object();
348 $return->items
= array();
349 $return->outcomes
= array();
351 $course_item = grade_item
::fetch_course_item($courseid);
352 $needsupdate = array();
353 if ($course_item->needsupdate
) {
354 $result = grade_regrade_final_grades($courseid);
355 if ($result !== true) {
356 $needsupdate = array_keys($result);
360 if ($grade_items = grade_item
::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
361 foreach ($grade_items as $grade_item) {
362 $decimalpoints = null;
364 if (empty($grade_item->outcomeid
)) {
365 // prepare information about grade item
366 $item = new object();
367 $item->itemnumber
= $grade_item->itemnumber
;
368 $item->scaleid
= $grade_item->scaleid
;
369 $item->name
= $grade_item->get_name();
370 $item->grademin
= $grade_item->grademin
;
371 $item->grademax
= $grade_item->grademax
;
372 $item->gradepass
= $grade_item->gradepass
;
373 $item->locked
= $grade_item->is_locked();
374 $item->hidden
= $grade_item->is_hidden();
375 $item->grades
= array();
377 switch ($grade_item->gradetype
) {
378 case GRADE_TYPE_NONE
:
381 case GRADE_TYPE_VALUE
:
385 case GRADE_TYPE_TEXT
:
389 $item->gradepass
= 0;
393 if (empty($userid_or_ids)) {
396 } else if (is_array($userid_or_ids)) {
397 $userids = $userid_or_ids;
400 $userids = array($userid_or_ids);
404 $grade_grades = grade_grade
::fetch_users_grades($grade_item, $userids, true);
405 foreach ($userids as $userid) {
406 $grade_grades[$userid]->grade_item
=& $grade_item;
408 $grade = new object();
409 $grade->grade
= $grade_grades[$userid]->finalgrade
;
410 $grade->locked
= $grade_grades[$userid]->is_locked();
411 $grade->hidden
= $grade_grades[$userid]->is_hidden();
412 $grade->overridden
= $grade_grades[$userid]->overridden
;
413 $grade->feedback
= $grade_grades[$userid]->feedback
;
414 $grade->feedbackformat
= $grade_grades[$userid]->feedbackformat
;
415 $grade->usermodified
= $grade_grades[$userid]->usermodified
;
416 $grade->datesubmitted
= $grade_grades[$userid]->get_datesubmitted();
417 $grade->dategraded
= $grade_grades[$userid]->get_dategraded();
419 // create text representation of grade
420 if ($grade_item->gradetype
== GRADE_TYPE_TEXT
or $grade_item->gradetype
== GRADE_TYPE_NONE
) {
421 $grade->grade
= null;
422 $grade->str_grade
= '-';
423 $grade->str_long_grade
= $grade->str_grade
;
425 } else if (in_array($grade_item->id
, $needsupdate)) {
426 $grade->grade
= false;
427 $grade->str_grade
= get_string('error');
428 $grade->str_long_grade
= $grade->str_grade
;
430 } else if (is_null($grade->grade
)) {
431 $grade->str_grade
= '-';
432 $grade->str_long_grade
= $grade->str_grade
;
435 $grade->str_grade
= grade_format_gradevalue($grade->grade
, $grade_item);
436 if ($grade_item->gradetype
== GRADE_TYPE_SCALE
or $grade_item->get_displaytype() != GRADE_DISPLAY_TYPE_REAL
) {
437 $grade->str_long_grade
= $grade->str_grade
;
440 $a->grade
= $grade->str_grade
;
441 $a->max
= grade_format_gradevalue($grade_item->grademax
, $grade_item);
442 $grade->str_long_grade
= get_string('gradelong', 'grades', $a);
446 // create html representation of feedback
447 if (is_null($grade->feedback
)) {
448 $grade->str_feedback
= '';
450 $grade->str_feedback
= format_text($grade->feedback
, $grade->feedbackformat
);
453 $item->grades
[$userid] = $grade;
456 $return->items
[$grade_item->itemnumber
] = $item;
459 if (!$grade_outcome = grade_outcome
::fetch(array('id'=>$grade_item->outcomeid
))) {
460 debugging('Incorect outcomeid found');
465 $outcome = new object();
466 $outcome->itemnumber
= $grade_item->itemnumber
;
467 $outcome->scaleid
= $grade_outcome->scaleid
;
468 $outcome->name
= $grade_outcome->get_name();
469 $outcome->locked
= $grade_item->is_locked();
470 $outcome->hidden
= $grade_item->is_hidden();
472 if (empty($userid_or_ids)) {
474 } else if (is_array($userid_or_ids)) {
475 $userids = $userid_or_ids;
477 $userids = array($userid_or_ids);
481 $grade_grades = grade_grade
::fetch_users_grades($grade_item, $userids, true);
482 foreach ($userids as $userid) {
483 $grade_grades[$userid]->grade_item
=& $grade_item;
485 $grade = new object();
486 $grade->grade
= $grade_grades[$userid]->finalgrade
;
487 $grade->locked
= $grade_grades[$userid]->is_locked();
488 $grade->hidden
= $grade_grades[$userid]->is_hidden();
489 $grade->feedback
= $grade_grades[$userid]->feedback
;
490 $grade->feedbackformat
= $grade_grades[$userid]->feedbackformat
;
491 $grade->usermodified
= $grade_grades[$userid]->usermodified
;
493 // create text representation of grade
494 if (in_array($grade_item->id
, $needsupdate)) {
495 $grade->grade
= false;
496 $grade->str_grade
= get_string('error');
498 } else if (is_null($grade->grade
)) {
500 $grade->str_grade
= get_string('nooutcome', 'grades');
503 $grade->grade
= (int)$grade->grade
;
504 $scale = $grade_item->load_scale();
505 $grade->str_grade
= format_string($scale->scale_items
[(int)$grade->grade
-1]);
508 // create html representation of feedback
509 if (is_null($grade->feedback
)) {
510 $grade->str_feedback
= '';
512 $grade->str_feedback
= format_text($grade->feedback
, $grade->feedbackformat
);
515 $outcome->grades
[$userid] = $grade;
519 if (isset($return->outcomes
[$grade_item->itemnumber
])) {
520 // itemnumber duplicates - lets fix them!
521 $newnumber = $grade_item->itemnumber +
1;
522 while(grade_item
::fetch(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid, 'itemnumber'=>$newnumber))) {
525 $outcome->itemnumber
= $newnumber;
526 $grade_item->itemnumber
= $newnumber;
527 $grade_item->update('system');
530 $return->outcomes
[$grade_item->itemnumber
] = $outcome;
536 // sort results using itemnumbers
537 ksort($return->items
, SORT_NUMERIC
);
538 ksort($return->outcomes
, SORT_NUMERIC
);
543 ///////////////////////////////////////////////////////////////////
544 ///// End of public API for communication with modules/blocks /////
545 ///////////////////////////////////////////////////////////////////
549 ///////////////////////////////////////////////////////////////////
550 ///// Internal API: used by gradebook plugins and Moodle core /////
551 ///////////////////////////////////////////////////////////////////
554 * Returns course gradebook setting
555 * @param int $courseid
556 * @param string $name of setting, maybe null if reset only
557 * @param bool $resetcache force reset of internal static cache
558 * @return string value, NULL if no setting
560 function grade_get_setting($courseid, $name, $default=null, $resetcache=false) {
561 static $cache = array();
563 if ($resetcache or !array_key_exists($courseid, $cache)) {
564 $cache[$courseid] = array();
566 } else if (is_null($name)) {
569 } else if (array_key_exists($name, $cache[$courseid])) {
570 return $cache[$courseid][$name];
573 if (!$data = get_record('grade_settings', 'courseid', $courseid, 'name', addslashes($name))) {
576 $result = $data->value
;
579 if (is_null($result)) {
583 $cache[$courseid][$name] = $result;
588 * Returns all course gradebook settings as object properties
589 * @param int $courseid
592 function grade_get_settings($courseid) {
593 $settings = new object();
594 $settings->id
= $courseid;
596 if ($records = get_records('grade_settings', 'courseid', $courseid)) {
597 foreach ($records as $record) {
598 $settings->{$record->name
} = $record->value
;
606 * Add/update course gradebook setting
607 * @param int $courseid
608 * @param string $name of setting
609 * @param string value, NULL means no setting==remove
612 function grade_set_setting($courseid, $name, $value) {
613 if (is_null($value)) {
614 delete_records('grade_settings', 'courseid', $courseid, 'name', addslashes($name));
616 } else if (!$existing = get_record('grade_settings', 'courseid', $courseid, 'name', addslashes($name))) {
617 $data = new object();
618 $data->courseid
= $courseid;
619 $data->name
= addslashes($name);
620 $data->value
= addslashes($value);
621 insert_record('grade_settings', $data);
624 $data = new object();
625 $data->id
= $existing->id
;
626 $data->value
= addslashes($value);
627 update_record('grade_settings', $data);
630 grade_get_setting($courseid, null, null, true); // reset the cache
634 * Returns string representation of grade value
635 * @param float $value grade value
636 * @param object $grade_item - by reference to prevent scale reloading
637 * @param bool $localized use localised decimal separator
638 * @param int $displaytype type of display - GRADE_DISPLAY_TYPE_REAL, GRADE_DISPLAY_TYPE_PERCENTAGE, GRADE_DISPLAY_TYPE_LETTER
639 * @param int $decimalplaces number of decimal places when displaying float values
642 function grade_format_gradevalue($value, &$grade_item, $localized=true, $displaytype=null, $decimals=null) {
643 if ($grade_item->gradetype
== GRADE_TYPE_NONE
or $grade_item->gradetype
== GRADE_TYPE_TEXT
) {
648 if (is_null($value)) {
652 if ($grade_item->gradetype
!= GRADE_TYPE_VALUE
and $grade_item->gradetype
!= GRADE_TYPE_SCALE
) {
657 if (is_null($displaytype)) {
658 $displaytype = $grade_item->get_displaytype();
661 if (is_null($decimals)) {
662 $decimals = $grade_item->get_decimals();
665 switch ($displaytype) {
666 case GRADE_DISPLAY_TYPE_REAL
:
667 if ($grade_item->gradetype
== GRADE_TYPE_SCALE
) {
668 if (!$scale = $grade_item->load_scale()) {
669 return get_string('error');
672 $value = (int)bounded_number($grade_item->grademin
, $value, $grade_item->grademax
);
673 return format_string($scale->scale_items
[$value-1]);
676 return format_float($value, $decimals, $localized);
679 case GRADE_DISPLAY_TYPE_PERCENTAGE
:
680 $min = $grade_item->grademin
;
681 $max = $grade_item->grademax
;
685 $value = bounded_number($min, $value, $max);
686 $percentage = (($value-$min)*100)/($max-$min);
687 return format_float($percentage, $decimals, $localized).' %';
689 case GRADE_DISPLAY_TYPE_LETTER
:
690 $context = get_context_instance(CONTEXT_COURSE
, $grade_item->courseid
);
691 if (!$letters = grade_get_letters($context)) {
692 return ''; // no letters??
695 $value = grade_grade
::standardise_score($value, $grade_item->grademin
, $grade_item->grademax
, 0, 100);
696 $value = bounded_number(0, $value, 100); // just in case
697 foreach ($letters as $boundary => $letter) {
698 if ($value >= $boundary) {
699 return format_string($letter);
702 return '-'; // no match? maybe '' would be more correct
710 * Returns grade options for gradebook category menu
711 * @param int $courseid
712 * @param bool $includenew include option for new category (-1)
713 * @return array of grade categories in course
715 function grade_get_categories_menu($courseid, $includenew=false) {
717 if (!$categories = grade_category
::fetch_all(array('courseid'=>$courseid))) {
718 //make sure course category exists
719 if (!grade_category
::fetch_course_category($courseid)) {
720 debugging('Can not create course grade category!');
723 $categories = grade_category
::fetch_all(array('courseid'=>$courseid));
725 foreach ($categories as $key=>$category) {
726 if ($category->is_course_category()) {
727 $result[$category->id
] = get_string('uncategorised', 'grades');
728 unset($categories[$key]);
732 $result[-1] = get_string('newcategory', 'grades');
735 foreach ($categories as $category) {
736 $cats[$category->id
] = $category->get_name();
738 asort($cats, SORT_LOCALE_STRING
);
740 return ($result+
$cats);
744 * Returns grade letters array used in context
745 * @param object $context object or null for defaults
746 * @return array of grade_boundary=>letter_string
748 function grade_get_letters($context=null) {
749 if (empty($context)) {
750 //default grading letters
751 return array('93'=>'A', '90'=>'A-', '87'=>'B+', '83'=>'B', '80'=>'B-', '77'=>'C+', '73'=>'C', '70'=>'C-', '67'=>'D+', '60'=>'D', '0'=>'F');
754 static $cache = array();
756 if (array_key_exists($context->id
, $cache)) {
757 return $cache[$context->id
];
760 if (count($cache) > 100) {
761 $cache = array(); // cache size limit
766 $contexts = get_parent_contexts($context);
767 array_unshift($contexts, $context->id
);
769 foreach ($contexts as $ctxid) {
770 if ($records = get_records('grade_letters', 'contextid', $ctxid, 'lowerboundary DESC')) {
771 foreach ($records as $record) {
772 $letters[$record->lowerboundary
] = $record->letter
;
776 if (!empty($letters)) {
777 $cache[$context->id
] = $letters;
782 $letters = grade_get_letters(null);
783 $cache[$context->id
] = $letters;
789 * Verify new value of idnumber - checks for uniqueness of new idnumbers, old are kept intact
790 * @param string idnumber string (with magic quotes)
791 * @param int $courseid - id numbers are course unique only
792 * @param object $cm used for course module idnumbers and items attached to modules
793 * @param object $gradeitem is item idnumber
794 * @return boolean true means idnumber ok
796 function grade_verify_idnumber($idnumber, $courseid, $grade_item=null, $cm=null) {
797 if ($idnumber == '') {
798 //we allow empty idnumbers
802 // keep existing even when not unique
803 if ($cm and $cm->idnumber
== $idnumber) {
805 } else if ($grade_item and $grade_item->idnumber
== $idnumber) {
809 if (get_records_select('course_modules', "course = $courseid AND idnumber='$idnumber'")) {
813 if (get_records_select('grade_items', "courseid = $courseid AND idnumber='$idnumber'")) {
821 * Force final grade recalculation in all course items
822 * @param int $courseid
824 function grade_force_full_regrading($courseid) {
825 set_field('grade_items', 'needsupdate', 1, 'courseid', $courseid);
829 * Updates all final grades in course.
831 * @param int $courseid
832 * @param int $userid if specified, try to do a quick regrading of grades of this user only
833 * @param object $updated_item the item in which
834 * @return boolean true if ok, array of errors if problems found (item id is used as key)
836 function grade_regrade_final_grades($courseid, $userid=null, $updated_item=null) {
838 $course_item = grade_item
::fetch_course_item($courseid);
841 // one raw grade updated for one user
842 if (empty($updated_item)) {
843 error("updated_item_id can not be null!");
845 if ($course_item->needsupdate
) {
846 $updated_item->force_regrading();
847 return array($course_item->id
=>'Can not do fast regrading after updating of raw grades');
851 if (!$course_item->needsupdate
) {
857 $grade_items = grade_item
::fetch_all(array('courseid'=>$courseid));
858 $depends_on = array();
860 // first mark all category and calculated items as needing regrading
861 // this is slower, but 100% accurate
862 foreach ($grade_items as $gid=>$gitem) {
863 if (!empty($updated_item) and $updated_item->id
== $gid) {
864 $grade_items[$gid]->needsupdate
= 1;
866 } else if ($gitem->is_course_item() or $gitem->is_category_item() or $gitem->is_calculated()) {
867 $grade_items[$gid]->needsupdate
= 1;
870 // construct depends_on lookup array
871 $depends_on[$gid] = $grade_items[$gid]->depends_on();
876 $gids = array_keys($grade_items);
879 while (count($finalids) < count($gids)) { // work until all grades are final or error found
881 foreach ($gids as $gid) {
882 if (in_array($gid, $finalids)) {
883 continue; // already final
886 if (!$grade_items[$gid]->needsupdate
) {
887 $finalids[] = $gid; // we can make it final - does not need update
892 foreach ($depends_on[$gid] as $did) {
893 if (!in_array($did, $finalids)) {
895 continue; // this item depends on something that is not yet in finals array
899 //oki - let's update, calculate or aggregate :-)
901 $result = $grade_items[$gid]->regrade_final_grades($userid);
903 if ($result === true) {
904 $grade_items[$gid]->regrading_finished();
905 $grade_items[$gid]->check_locktime(); // do the locktime item locking
910 $grade_items[$gid]->force_regrading();
911 $errors[$gid] = $result;
923 foreach($gids as $gid) {
924 if (in_array($gid, $finalids)) {
925 continue; // this one is ok
927 $grade_items[$gid]->force_regrading();
928 $errors[$grade_items[$gid]->id
] = 'Probably circular reference or broken calculation formula'; // TODO: localize
930 break; // oki, found error
934 if (count($errors) == 0) {
935 if (empty($userid)) {
936 // do the locktime locking of grades, but only when doing full regrading
937 grade_grade
::check_locktime_all($gids);
946 * For backwards compatibility with old third-party modules, this function can
947 * be used to import all grades from activities with legacy grading.
948 * @param int $courseid
950 function grade_grab_legacy_grades($courseid) {
953 if (!$mods = get_list_of_plugins('mod') ) {
954 error('No modules installed!');
957 foreach ($mods as $mod) {
958 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
962 $fullmod = $CFG->dirroot
.'/mod/'.$mod;
964 // include the module lib once
965 if (file_exists($fullmod.'/lib.php')) {
966 include_once($fullmod.'/lib.php');
967 // look for modname_grades() function - old gradebook pulling function
968 // if present sync the grades with new grading system
969 $gradefunc = $mod.'_grades';
970 if (function_exists($gradefunc)) {
971 grade_grab_course_grades($courseid, $mod);
978 * Refetches data from all course activities
979 * @param int $courseid
980 * @param string $modname
983 function grade_grab_course_grades($courseid, $modname=null) {
987 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
988 FROM {$CFG->prefix}$modname a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
989 WHERE m.name='$modname' AND m.visible=1 AND m.id=cm.module AND cm.instance=a.id AND cm.course=$courseid";
991 if ($modinstances = get_records_sql($sql)) {
992 foreach ($modinstances as $modinstance) {
993 grade_update_mod_grades($modinstance);
999 if (!$mods = get_list_of_plugins('mod') ) {
1000 error('No modules installed!');
1003 foreach ($mods as $mod) {
1004 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
1008 $fullmod = $CFG->dirroot
.'/mod/'.$mod;
1010 // include the module lib once
1011 if (file_exists($fullmod.'/lib.php')) {
1012 // get all instance of the activity
1013 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
1014 FROM {$CFG->prefix}$mod a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
1015 WHERE m.name='$mod' AND m.visible=1 AND m.id=cm.module AND cm.instance=a.id AND cm.course=$courseid";
1017 if ($modinstances = get_records_sql($sql)) {
1018 foreach ($modinstances as $modinstance) {
1019 grade_update_mod_grades($modinstance);
1027 * Force full update of module grades in central gradebook - works for both legacy and converted activities.
1028 * @param object $modinstance object with extra cmidnumber and modname property
1029 * @return boolean success
1031 function grade_update_mod_grades($modinstance, $userid=0) {
1034 $fullmod = $CFG->dirroot
.'/mod/'.$modinstance->modname
;
1035 if (!file_exists($fullmod.'/lib.php')) {
1036 debugging('missing lib.php file in module');
1039 include_once($fullmod.'/lib.php');
1041 // does it use legacy grading?
1042 $gradefunc = $modinstance->modname
.'_grades';
1043 $updategradesfunc = $modinstance->modname
.'_update_grades';
1044 $updateitemfunc = $modinstance->modname
.'_grade_item_update';
1046 if (function_exists($gradefunc)) {
1048 // legacy module - not yet converted
1049 if ($oldgrades = $gradefunc($modinstance->id
)) {
1051 $grademax = $oldgrades->maxgrade
;
1053 if (!is_numeric($grademax)) {
1054 // scale name is provided as a string, try to find it
1055 if (!$scale = get_record('scale', 'name', $grademax)) {
1056 debugging('Incorrect scale name! name:'.$grademax);
1059 $scaleid = $scale->id
;
1062 if (!$grade_item = grade_get_legacy_grade_item($modinstance, $grademax, $scaleid)) {
1063 debugging('Can not get/create legacy grade item!');
1067 if (!empty($oldgrades->grades
)) {
1070 foreach ($oldgrades->grades
as $uid=>$usergrade) {
1071 if ($userid and $uid != $userid) {
1074 $grade = new object();
1075 $grade->userid
= $uid;
1077 if ($usergrade == '-') {
1079 $grade->rawgrade
= null;
1081 } else if ($scaleid) {
1082 // scale in use, words used
1083 $gradescale = explode(",", $scale->scale
);
1084 $grade->rawgrade
= array_search($usergrade, $gradescale) +
1;
1087 // good old numeric value
1088 $grade->rawgrade
= $usergrade;
1093 grade_update('legacygrab', $grade_item->courseid
, $grade_item->itemtype
, $grade_item->itemmodule
,
1094 $grade_item->iteminstance
, $grade_item->itemnumber
, $grades);
1098 } else if (function_exists($updategradesfunc) and function_exists($updateitemfunc)) {
1099 //new grading supported, force updating of grades
1100 $updateitemfunc($modinstance);
1101 $updategradesfunc($modinstance, $userid);
1104 // mudule does not support grading??
1111 * Get and update/create grade item for legacy modules.
1113 function grade_get_legacy_grade_item($modinstance, $grademax, $scaleid) {
1115 // does it already exist?
1116 if ($grade_items = grade_item
::fetch_all(array('courseid'=>$modinstance->course
, 'itemtype'=>'mod', 'itemmodule'=>$modinstance->modname
, 'iteminstance'=>$modinstance->id
, 'itemnumber'=>0))) {
1117 if (count($grade_items) > 1) {
1118 debugging('Multiple legacy grade_items found.');
1122 $grade_item = reset($grade_items);
1124 if (is_null($grademax) and is_null($scaleid)) {
1125 $grade_item->gradetype
= GRADE_TYPE_NONE
;
1127 } else if ($scaleid) {
1128 $grade_item->gradetype
= GRADE_TYPE_SCALE
;
1129 $grade_item->scaleid
= $scaleid;
1130 $grade_item->grademin
= 1;
1133 $grade_item->gradetype
= GRADE_TYPE_VALUE
;
1134 $grade_item->grademax
= $grademax;
1135 $grade_item->grademin
= 0;
1138 $grade_item->itemname
= $modinstance->name
;
1139 $grade_item->idnumber
= $modinstance->cmidnumber
;
1141 $grade_item->update();
1147 $params = array('courseid' =>$modinstance->course
,
1149 'itemmodule' =>$modinstance->modname
,
1150 'iteminstance'=>$modinstance->id
,
1152 'itemname' =>$modinstance->name
,
1153 'idnumber' =>$modinstance->cmidnumber
);
1155 if (is_null($grademax) and is_null($scaleid)) {
1156 $params['gradetype'] = GRADE_TYPE_NONE
;
1158 } else if ($scaleid) {
1159 $params['gradetype'] = GRADE_TYPE_SCALE
;
1160 $params['scaleid'] = $scaleid;
1161 $grade_item->grademin
= 1;
1163 $params['gradetype'] = GRADE_TYPE_VALUE
;
1164 $params['grademax'] = $grademax;
1165 $params['grademin'] = 0;
1168 $grade_item = new grade_item($params);
1169 $grade_item->insert();
1175 * Remove grade letters for given context
1176 * @param object $context
1178 function remove_grade_letters($context, $showfeedback) {
1179 $strdeleted = get_string('deleted');
1181 delete_records('grade_letters', 'contextid', $context->id
);
1182 if ($showfeedback) {
1183 notify($strdeleted.' - '.get_string('letters', 'grades'));
1187 * Remove all grade related course data - history is kept
1188 * @param int $courseid
1189 * @param bool $showfeedback print feedback
1191 function remove_course_grades($courseid, $showfeedback) {
1192 $strdeleted = get_string('deleted');
1194 $course_category = grade_category
::fetch_course_category($courseid);
1195 $course_category->delete('coursedelete');
1196 if ($showfeedback) {
1197 notify($strdeleted.' - '.get_string('grades', 'grades').', '.get_string('items', 'grades').', '.get_string('categories', 'grades'));
1200 if ($outcomes = grade_outcome
::fetch_all(array('courseid'=>$courseid))) {
1201 foreach ($outcomes as $outcome) {
1202 $outcome->delete('coursedelete');
1205 delete_records('grade_outcomes_courses', 'courseid', $courseid);
1206 if ($showfeedback) {
1207 notify($strdeleted.' - '.get_string('outcomes', 'grades'));
1210 if ($scales = grade_scale
::fetch_all(array('courseid'=>$courseid))) {
1211 foreach ($scales as $scale) {
1212 $scale->delete('coursedelete');
1215 if ($showfeedback) {
1216 notify($strdeleted.' - '.get_string('scales'));
1219 delete_records('grade_settings', 'courseid', $courseid);
1220 if ($showfeedback) {
1221 notify($strdeleted.' - '.get_string('settings', 'grades'));
1226 * Called when course category deleted - cleanup gradebook
1227 * @param int $categoryid course category id
1228 * @param int $newparentid empty means everything deleted, otherwise id of category where content moved
1229 * @param bool $showfeedback print feedback
1231 function grade_course_category_delete($categoryid, $newparentid, $showfeedback) {
1232 $context = get_context_instance(CONTEXT_COURSECAT
, $categoryid);
1233 delete_records('grade_letters', 'contextid', $context->id
);
1237 * Does gradebook cleanup when module uninstalled.
1239 function grade_uninstalled_module($modname) {
1243 FROM {$CFG->prefix}grade_items
1244 WHERE itemtype='mod' AND itemmodule='$modname'";
1246 // go all items for this module and delete them including the grades
1247 if ($rs = get_recordset_sql($sql)) {
1248 while ($item = rs_fetch_next_record($rs)) {
1249 $grade_item = new grade_item($item, false);
1250 $grade_item->delete('moduninstall');
1259 function grade_cron() {
1265 FROM {$CFG->prefix}grade_items i
1266 WHERE i.locked = 0 AND i.locktime > 0 AND i.locktime < $now AND EXISTS (
1267 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
1269 // go through all courses that have proper final grades and lock them if needed
1270 if ($rs = get_recordset_sql($sql)) {
1271 while ($item = rs_fetch_next_record($rs)) {
1272 $grade_item = new grade_item($item, false);
1273 $grade_item->locked
= $now;
1274 $grade_item->update('locktime');
1279 $grade_inst = new grade_grade();
1280 $fields = 'g.'.implode(',g.', $grade_inst->required_fields
);
1282 $sql = "SELECT $fields
1283 FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items i
1284 WHERE g.locked = 0 AND g.locktime > 0 AND g.locktime < $now AND g.itemid=i.id AND EXISTS (
1285 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
1287 // go through all courses that have proper final grades and lock them if needed
1288 if ($rs = get_recordset_sql($sql)) {
1289 while ($grade = rs_fetch_next_record($rs)) {
1290 $grade_grade = new grade_grade($grade, false);
1291 $grade_grade->locked
= $now;
1292 $grade_grade->update('locktime');
1297 //TODO: do not run this cleanup every cron invocation
1298 // cleanup history tables
1299 if (!empty($CFG->gradehistorylifetime
)) { // value in days
1300 $histlifetime = $now - ($CFG->gradehistorylifetime
* 3600 * 24);
1301 $tables = array('grade_outcomes_history', 'grade_categories_history', 'grade_items_history', 'grade_grades_history', 'scale_history');
1302 foreach ($tables as $table) {
1303 if (delete_records_select($table, "timemodified < $histlifetime")) {
1304 mtrace(" Deleted old grade history records from '$table'");
1311 * Resel all course grades
1312 * @param int $courseid
1315 function grade_course_reset($courseid) {
1317 // no recalculations
1318 grade_force_full_regrading($courseid);
1320 $grade_items = grade_item
::fetch_all(array('courseid'=>$courseid));
1321 foreach ($grade_items as $gid=>$grade_item) {
1322 $grade_item->delete_all_grades('reset');
1325 //refetch all grades
1326 grade_grab_course_grades($courseid);
1328 // recalculate all grades
1329 grade_regrade_final_grades($courseid);
1334 * Convert number to 5 decimalfloat, empty tring or null db compatible format
1335 * (we need this to decide if db value changed)
1336 * @param mixed number
1337 * @return mixed float or null
1339 function grade_floatval($number) {
1340 if (is_null($number) or $number === '') {
1343 // we must round to 5 digits to get the same precision as in 10,5 db fields
1344 // note: db rounding for 10,5 is different from php round() function
1345 return round($number, 5);
1349 * Compare two float numbers safely. Uses 5 decimals php precision. Nulls accepted too.
1350 * Used for skipping of db updates
1353 * @return true if different
1355 function grade_floats_different($f1, $f2) {
1356 // note: db rounding for 10,5 is different from php round() function
1357 return (grade_floatval($f1) !== grade_floatval($f2));