Merge branch 'MDL-54830-master' of https://github.com/snake/moodle
[moodle.git] / lib / gradelib.php
blobcb31417de224c9d15824dcd6151c351b55cbd510
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library of functions for gradebook - both public and internal
20 * @package core_grades
21 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
27 /** Include essential files */
28 require_once($CFG->libdir . '/grade/constants.php');
30 require_once($CFG->libdir . '/grade/grade_category.php');
31 require_once($CFG->libdir . '/grade/grade_item.php');
32 require_once($CFG->libdir . '/grade/grade_grade.php');
33 require_once($CFG->libdir . '/grade/grade_scale.php');
34 require_once($CFG->libdir . '/grade/grade_outcome.php');
36 /////////////////////////////////////////////////////////////////////
37 ///// Start of public API for communication with modules/blocks /////
38 /////////////////////////////////////////////////////////////////////
40 /**
41 * Submit new or update grade; update/create grade_item definition. Grade must have userid specified,
42 * rawgrade and feedback with format are optional. rawgrade NULL means 'Not graded'.
43 * Missing property or key means does not change the existing value.
45 * Only following grade item properties can be changed 'itemname', 'idnumber', 'gradetype', 'grademax',
46 * 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted' and 'hidden'. 'reset' means delete all current grades including locked ones.
48 * Manual, course or category items can not be updated by this function.
50 * @category grade
51 * @param string $source Source of the grade such as 'mod/assignment'
52 * @param int $courseid ID of course
53 * @param string $itemtype Type of grade item. For example, mod or block
54 * @param string $itemmodule More specific then $itemtype. For example, assignment or forum. May be NULL for some item types
55 * @param int $iteminstance Instance ID of graded item
56 * @param int $itemnumber Most probably 0. Modules can use other numbers when having more than one grade for each user
57 * @param mixed $grades Grade (object, array) or several grades (arrays of arrays or objects), NULL if updating grade_item definition only
58 * @param mixed $itemdetails Object or array describing the grading item, NULL if no change
59 * @return int Returns GRADE_UPDATE_OK, GRADE_UPDATE_FAILED, GRADE_UPDATE_MULTIPLE or GRADE_UPDATE_ITEM_LOCKED
61 function grade_update($source, $courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $grades=NULL, $itemdetails=NULL) {
62 global $USER, $CFG, $DB;
64 // only following grade_item properties can be changed in this function
65 $allowed = array('itemname', 'idnumber', 'gradetype', 'grademax', 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted', 'hidden');
66 // list of 10,5 numeric fields
67 $floats = array('grademin', 'grademax', 'multfactor', 'plusfactor');
69 // grade item identification
70 $params = compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber');
72 if (is_null($courseid) or is_null($itemtype)) {
73 debugging('Missing courseid or itemtype');
74 return GRADE_UPDATE_FAILED;
77 if (!$grade_items = grade_item::fetch_all($params)) {
78 // create a new one
79 $grade_item = false;
81 } else if (count($grade_items) == 1){
82 $grade_item = reset($grade_items);
83 unset($grade_items); //release memory
85 } else {
86 debugging('Found more than one grade item');
87 return GRADE_UPDATE_MULTIPLE;
90 if (!empty($itemdetails['deleted'])) {
91 if ($grade_item) {
92 if ($grade_item->delete($source)) {
93 return GRADE_UPDATE_OK;
94 } else {
95 return GRADE_UPDATE_FAILED;
98 return GRADE_UPDATE_OK;
101 /// Create or update the grade_item if needed
103 if (!$grade_item) {
104 if ($itemdetails) {
105 $itemdetails = (array)$itemdetails;
107 // grademin and grademax ignored when scale specified
108 if (array_key_exists('scaleid', $itemdetails)) {
109 if ($itemdetails['scaleid']) {
110 unset($itemdetails['grademin']);
111 unset($itemdetails['grademax']);
115 foreach ($itemdetails as $k=>$v) {
116 if (!in_array($k, $allowed)) {
117 // ignore it
118 continue;
120 if ($k == 'gradetype' and $v == GRADE_TYPE_NONE) {
121 // no grade item needed!
122 return GRADE_UPDATE_OK;
124 $params[$k] = $v;
127 $grade_item = new grade_item($params);
128 $grade_item->insert();
130 } else {
131 if ($grade_item->is_locked()) {
132 // no notice() here, test returned value instead!
133 return GRADE_UPDATE_ITEM_LOCKED;
136 if ($itemdetails) {
137 $itemdetails = (array)$itemdetails;
138 $update = false;
139 foreach ($itemdetails as $k=>$v) {
140 if (!in_array($k, $allowed)) {
141 // ignore it
142 continue;
144 if (in_array($k, $floats)) {
145 if (grade_floats_different($grade_item->{$k}, $v)) {
146 $grade_item->{$k} = $v;
147 $update = true;
150 } else {
151 if ($grade_item->{$k} != $v) {
152 $grade_item->{$k} = $v;
153 $update = true;
157 if ($update) {
158 $grade_item->update();
163 /// reset grades if requested
164 if (!empty($itemdetails['reset'])) {
165 $grade_item->delete_all_grades('reset');
166 return GRADE_UPDATE_OK;
169 /// Some extra checks
170 // do we use grading?
171 if ($grade_item->gradetype == GRADE_TYPE_NONE) {
172 return GRADE_UPDATE_OK;
175 // no grade submitted
176 if (empty($grades)) {
177 return GRADE_UPDATE_OK;
180 /// Finally start processing of grades
181 if (is_object($grades)) {
182 $grades = array($grades->userid=>$grades);
183 } else {
184 if (array_key_exists('userid', $grades)) {
185 $grades = array($grades['userid']=>$grades);
189 /// normalize and verify grade array
190 foreach($grades as $k=>$g) {
191 if (!is_array($g)) {
192 $g = (array)$g;
193 $grades[$k] = $g;
196 if (empty($g['userid']) or $k != $g['userid']) {
197 debugging('Incorrect grade array index, must be user id! Grade ignored.');
198 unset($grades[$k]);
202 if (empty($grades)) {
203 return GRADE_UPDATE_FAILED;
206 $count = count($grades);
207 if ($count > 0 and $count < 200) {
208 list($uids, $params) = $DB->get_in_or_equal(array_keys($grades), SQL_PARAMS_NAMED, $start='uid');
209 $params['gid'] = $grade_item->id;
210 $sql = "SELECT * FROM {grade_grades} WHERE itemid = :gid AND userid $uids";
212 } else {
213 $sql = "SELECT * FROM {grade_grades} WHERE itemid = :gid";
214 $params = array('gid'=>$grade_item->id);
217 $rs = $DB->get_recordset_sql($sql, $params);
219 $failed = false;
221 while (count($grades) > 0) {
222 $grade_grade = null;
223 $grade = null;
225 foreach ($rs as $gd) {
227 $userid = $gd->userid;
228 if (!isset($grades[$userid])) {
229 // this grade not requested, continue
230 continue;
232 // existing grade requested
233 $grade = $grades[$userid];
234 $grade_grade = new grade_grade($gd, false);
235 unset($grades[$userid]);
236 break;
239 if (is_null($grade_grade)) {
240 if (count($grades) == 0) {
241 // no more grades to process
242 break;
245 $grade = reset($grades);
246 $userid = $grade['userid'];
247 $grade_grade = new grade_grade(array('itemid'=>$grade_item->id, 'userid'=>$userid), false);
248 $grade_grade->load_optional_fields(); // add feedback and info too
249 unset($grades[$userid]);
252 $rawgrade = false;
253 $feedback = false;
254 $feedbackformat = FORMAT_MOODLE;
255 $usermodified = $USER->id;
256 $datesubmitted = null;
257 $dategraded = null;
259 if (array_key_exists('rawgrade', $grade)) {
260 $rawgrade = $grade['rawgrade'];
263 if (array_key_exists('feedback', $grade)) {
264 $feedback = $grade['feedback'];
267 if (array_key_exists('feedbackformat', $grade)) {
268 $feedbackformat = $grade['feedbackformat'];
271 if (array_key_exists('usermodified', $grade)) {
272 $usermodified = $grade['usermodified'];
275 if (array_key_exists('datesubmitted', $grade)) {
276 $datesubmitted = $grade['datesubmitted'];
279 if (array_key_exists('dategraded', $grade)) {
280 $dategraded = $grade['dategraded'];
283 // update or insert the grade
284 if (!$grade_item->update_raw_grade($userid, $rawgrade, $source, $feedback, $feedbackformat, $usermodified, $dategraded, $datesubmitted, $grade_grade)) {
285 $failed = true;
289 if ($rs) {
290 $rs->close();
293 if (!$failed) {
294 return GRADE_UPDATE_OK;
295 } else {
296 return GRADE_UPDATE_FAILED;
301 * Updates a user's outcomes. Manual outcomes can not be updated.
303 * @category grade
304 * @param string $source Source of the grade such as 'mod/assignment'
305 * @param int $courseid ID of course
306 * @param string $itemtype Type of grade item. For example, 'mod' or 'block'
307 * @param string $itemmodule More specific then $itemtype. For example, 'forum' or 'quiz'. May be NULL for some item types
308 * @param int $iteminstance Instance ID of graded item. For example the forum ID.
309 * @param int $userid ID of the graded user
310 * @param array $data Array consisting of grade item itemnumber ({@link grade_update()}) => outcomegrade
311 * @return bool returns true if grade items were found and updated successfully
313 function grade_update_outcomes($source, $courseid, $itemtype, $itemmodule, $iteminstance, $userid, $data) {
314 if ($items = grade_item::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
315 $result = true;
316 foreach ($items as $item) {
317 if (!array_key_exists($item->itemnumber, $data)) {
318 continue;
320 $grade = $data[$item->itemnumber] < 1 ? null : $data[$item->itemnumber];
321 $result = ($item->update_final_grade($userid, $grade, $source) && $result);
323 return $result;
325 return false; //grade items not found
329 * Return true if the course needs regrading.
331 * @param int $courseid The course ID
332 * @return bool true if course grades need updating.
334 function grade_needs_regrade_final_grades($courseid) {
335 $course_item = grade_item::fetch_course_item($courseid);
336 return $course_item->needsupdate;
340 * Return true if the regrade process is likely to be time consuming and
341 * will therefore require the progress bar.
343 * @param int $courseid The course ID
344 * @return bool Whether the regrade process is likely to be time consuming
346 function grade_needs_regrade_progress_bar($courseid) {
347 global $DB;
348 $grade_items = grade_item::fetch_all(array('courseid' => $courseid));
350 list($sql, $params) = $DB->get_in_or_equal(array_keys($grade_items), SQL_PARAMS_NAMED, 'gi');
351 $gradecount = $DB->count_records_select('grade_grades', 'itemid ' . $sql, $params);
353 // This figure may seem arbitrary, but after analysis it seems that 100 grade_grades can be calculated in ~= 0.5 seconds.
354 // Any longer than this and we want to show the progress bar.
355 return $gradecount > 100;
359 * Check whether regarding of final grades is required and, if so, perform the regrade.
361 * If the regrade is expected to be time consuming (see grade_needs_regrade_progress_bar), then this
362 * function will output the progress bar, and redirect to the current PAGE->url after regrading
363 * completes. Otherwise the regrading will happen immediately and the page will be loaded as per
364 * normal.
366 * A callback may be specified, which is called if regrading has taken place.
367 * The callback may optionally return a URL which will be redirected to when the progress bar is present.
369 * @param stdClass $course The course to regrade
370 * @param callable $callback A function to call if regrading took place
371 * @return moodle_url The URL to redirect to if redirecting
373 function grade_regrade_final_grades_if_required($course, callable $callback = null) {
374 global $PAGE, $OUTPUT;
376 if (!grade_needs_regrade_final_grades($course->id)) {
377 return false;
380 if (grade_needs_regrade_progress_bar($course->id)) {
381 $PAGE->set_heading($course->fullname);
382 echo $OUTPUT->header();
383 echo $OUTPUT->heading(get_string('recalculatinggrades', 'grades'));
384 $progress = new \core\progress\display(true);
385 $status = grade_regrade_final_grades($course->id, null, null, $progress);
387 // Show regrade errors and set the course to no longer needing regrade (stop endless loop).
388 if (is_array($status)) {
389 foreach ($status as $error) {
390 $errortext = new \core\output\notification($error, \core\output\notification::NOTIFY_ERROR);
391 echo $OUTPUT->render($errortext);
393 $courseitem = grade_item::fetch_course_item($course->id);
394 $courseitem->regrading_finished();
397 if ($callback) {
399 $url = call_user_func($callback);
402 if (empty($url)) {
403 $url = $PAGE->url;
406 echo $OUTPUT->continue_button($url);
407 echo $OUTPUT->footer();
408 die();
409 } else {
410 $result = grade_regrade_final_grades($course->id);
411 if ($callback) {
412 call_user_func($callback);
414 return $result;
419 * Returns grading information for given activity, optionally with user grades
420 * Manual, course or category items can not be queried.
422 * @category grade
423 * @param int $courseid ID of course
424 * @param string $itemtype Type of grade item. For example, 'mod' or 'block'
425 * @param string $itemmodule More specific then $itemtype. For example, 'forum' or 'quiz'. May be NULL for some item types
426 * @param int $iteminstance ID of the item module
427 * @param mixed $userid_or_ids Either a single user ID, an array of user IDs or null. If user ID or IDs are not supplied returns information about grade_item
428 * @return array Array of grade information objects (scaleid, name, grade and locked status, etc.) indexed with itemnumbers
430 function grade_get_grades($courseid, $itemtype, $itemmodule, $iteminstance, $userid_or_ids=null) {
431 global $CFG;
433 $return = new stdClass();
434 $return->items = array();
435 $return->outcomes = array();
437 $course_item = grade_item::fetch_course_item($courseid);
438 $needsupdate = array();
439 if ($course_item->needsupdate) {
440 $result = grade_regrade_final_grades($courseid);
441 if ($result !== true) {
442 $needsupdate = array_keys($result);
446 if ($grade_items = grade_item::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
447 foreach ($grade_items as $grade_item) {
448 $decimalpoints = null;
450 if (empty($grade_item->outcomeid)) {
451 // prepare information about grade item
452 $item = new stdClass();
453 $item->id = $grade_item->id;
454 $item->itemnumber = $grade_item->itemnumber;
455 $item->itemtype = $grade_item->itemtype;
456 $item->itemmodule = $grade_item->itemmodule;
457 $item->iteminstance = $grade_item->iteminstance;
458 $item->scaleid = $grade_item->scaleid;
459 $item->name = $grade_item->get_name();
460 $item->grademin = $grade_item->grademin;
461 $item->grademax = $grade_item->grademax;
462 $item->gradepass = $grade_item->gradepass;
463 $item->locked = $grade_item->is_locked();
464 $item->hidden = $grade_item->is_hidden();
465 $item->grades = array();
467 switch ($grade_item->gradetype) {
468 case GRADE_TYPE_NONE:
469 continue;
471 case GRADE_TYPE_VALUE:
472 $item->scaleid = 0;
473 break;
475 case GRADE_TYPE_TEXT:
476 $item->scaleid = 0;
477 $item->grademin = 0;
478 $item->grademax = 0;
479 $item->gradepass = 0;
480 break;
483 if (empty($userid_or_ids)) {
484 $userids = array();
486 } else if (is_array($userid_or_ids)) {
487 $userids = $userid_or_ids;
489 } else {
490 $userids = array($userid_or_ids);
493 if ($userids) {
494 $grade_grades = grade_grade::fetch_users_grades($grade_item, $userids, true);
495 foreach ($userids as $userid) {
496 $grade_grades[$userid]->grade_item =& $grade_item;
498 $grade = new stdClass();
499 $grade->grade = $grade_grades[$userid]->finalgrade;
500 $grade->locked = $grade_grades[$userid]->is_locked();
501 $grade->hidden = $grade_grades[$userid]->is_hidden();
502 $grade->overridden = $grade_grades[$userid]->overridden;
503 $grade->feedback = $grade_grades[$userid]->feedback;
504 $grade->feedbackformat = $grade_grades[$userid]->feedbackformat;
505 $grade->usermodified = $grade_grades[$userid]->usermodified;
506 $grade->datesubmitted = $grade_grades[$userid]->get_datesubmitted();
507 $grade->dategraded = $grade_grades[$userid]->get_dategraded();
509 // create text representation of grade
510 if ($grade_item->gradetype == GRADE_TYPE_TEXT or $grade_item->gradetype == GRADE_TYPE_NONE) {
511 $grade->grade = null;
512 $grade->str_grade = '-';
513 $grade->str_long_grade = $grade->str_grade;
515 } else if (in_array($grade_item->id, $needsupdate)) {
516 $grade->grade = false;
517 $grade->str_grade = get_string('error');
518 $grade->str_long_grade = $grade->str_grade;
520 } else if (is_null($grade->grade)) {
521 $grade->str_grade = '-';
522 $grade->str_long_grade = $grade->str_grade;
524 } else {
525 $grade->str_grade = grade_format_gradevalue($grade->grade, $grade_item);
526 if ($grade_item->gradetype == GRADE_TYPE_SCALE or $grade_item->get_displaytype() != GRADE_DISPLAY_TYPE_REAL) {
527 $grade->str_long_grade = $grade->str_grade;
528 } else {
529 $a = new stdClass();
530 $a->grade = $grade->str_grade;
531 $a->max = grade_format_gradevalue($grade_item->grademax, $grade_item);
532 $grade->str_long_grade = get_string('gradelong', 'grades', $a);
536 // create html representation of feedback
537 if (is_null($grade->feedback)) {
538 $grade->str_feedback = '';
539 } else {
540 $grade->str_feedback = format_text($grade->feedback, $grade->feedbackformat);
543 $item->grades[$userid] = $grade;
546 $return->items[$grade_item->itemnumber] = $item;
548 } else {
549 if (!$grade_outcome = grade_outcome::fetch(array('id'=>$grade_item->outcomeid))) {
550 debugging('Incorect outcomeid found');
551 continue;
554 // outcome info
555 $outcome = new stdClass();
556 $outcome->id = $grade_item->id;
557 $outcome->itemnumber = $grade_item->itemnumber;
558 $outcome->itemtype = $grade_item->itemtype;
559 $outcome->itemmodule = $grade_item->itemmodule;
560 $outcome->iteminstance = $grade_item->iteminstance;
561 $outcome->scaleid = $grade_outcome->scaleid;
562 $outcome->name = $grade_outcome->get_name();
563 $outcome->locked = $grade_item->is_locked();
564 $outcome->hidden = $grade_item->is_hidden();
566 if (empty($userid_or_ids)) {
567 $userids = array();
568 } else if (is_array($userid_or_ids)) {
569 $userids = $userid_or_ids;
570 } else {
571 $userids = array($userid_or_ids);
574 if ($userids) {
575 $grade_grades = grade_grade::fetch_users_grades($grade_item, $userids, true);
576 foreach ($userids as $userid) {
577 $grade_grades[$userid]->grade_item =& $grade_item;
579 $grade = new stdClass();
580 $grade->grade = $grade_grades[$userid]->finalgrade;
581 $grade->locked = $grade_grades[$userid]->is_locked();
582 $grade->hidden = $grade_grades[$userid]->is_hidden();
583 $grade->feedback = $grade_grades[$userid]->feedback;
584 $grade->feedbackformat = $grade_grades[$userid]->feedbackformat;
585 $grade->usermodified = $grade_grades[$userid]->usermodified;
586 $grade->datesubmitted = $grade_grades[$userid]->get_datesubmitted();
587 $grade->dategraded = $grade_grades[$userid]->get_dategraded();
589 // create text representation of grade
590 if (in_array($grade_item->id, $needsupdate)) {
591 $grade->grade = false;
592 $grade->str_grade = get_string('error');
594 } else if (is_null($grade->grade)) {
595 $grade->grade = 0;
596 $grade->str_grade = get_string('nooutcome', 'grades');
598 } else {
599 $grade->grade = (int)$grade->grade;
600 $scale = $grade_item->load_scale();
601 $grade->str_grade = format_string($scale->scale_items[(int)$grade->grade-1]);
604 // create html representation of feedback
605 if (is_null($grade->feedback)) {
606 $grade->str_feedback = '';
607 } else {
608 $grade->str_feedback = format_text($grade->feedback, $grade->feedbackformat);
611 $outcome->grades[$userid] = $grade;
615 if (isset($return->outcomes[$grade_item->itemnumber])) {
616 // itemnumber duplicates - lets fix them!
617 $newnumber = $grade_item->itemnumber + 1;
618 while(grade_item::fetch(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid, 'itemnumber'=>$newnumber))) {
619 $newnumber++;
621 $outcome->itemnumber = $newnumber;
622 $grade_item->itemnumber = $newnumber;
623 $grade_item->update('system');
626 $return->outcomes[$grade_item->itemnumber] = $outcome;
632 // sort results using itemnumbers
633 ksort($return->items, SORT_NUMERIC);
634 ksort($return->outcomes, SORT_NUMERIC);
636 return $return;
639 ///////////////////////////////////////////////////////////////////
640 ///// End of public API for communication with modules/blocks /////
641 ///////////////////////////////////////////////////////////////////
645 ///////////////////////////////////////////////////////////////////
646 ///// Internal API: used by gradebook plugins and Moodle core /////
647 ///////////////////////////////////////////////////////////////////
650 * Returns a course gradebook setting
652 * @param int $courseid
653 * @param string $name of setting, maybe null if reset only
654 * @param string $default value to return if setting is not found
655 * @param bool $resetcache force reset of internal static cache
656 * @return string value of the setting, $default if setting not found, NULL if supplied $name is null
658 function grade_get_setting($courseid, $name, $default=null, $resetcache=false) {
659 global $DB;
661 static $cache = array();
663 if ($resetcache or !array_key_exists($courseid, $cache)) {
664 $cache[$courseid] = array();
666 } else if (is_null($name)) {
667 return null;
669 } else if (array_key_exists($name, $cache[$courseid])) {
670 return $cache[$courseid][$name];
673 if (!$data = $DB->get_record('grade_settings', array('courseid'=>$courseid, 'name'=>$name))) {
674 $result = null;
675 } else {
676 $result = $data->value;
679 if (is_null($result)) {
680 $result = $default;
683 $cache[$courseid][$name] = $result;
684 return $result;
688 * Returns all course gradebook settings as object properties
690 * @param int $courseid
691 * @return object
693 function grade_get_settings($courseid) {
694 global $DB;
696 $settings = new stdClass();
697 $settings->id = $courseid;
699 if ($records = $DB->get_records('grade_settings', array('courseid'=>$courseid))) {
700 foreach ($records as $record) {
701 $settings->{$record->name} = $record->value;
705 return $settings;
709 * Add, update or delete a course gradebook setting
711 * @param int $courseid The course ID
712 * @param string $name Name of the setting
713 * @param string $value Value of the setting. NULL means delete the setting.
715 function grade_set_setting($courseid, $name, $value) {
716 global $DB;
718 if (is_null($value)) {
719 $DB->delete_records('grade_settings', array('courseid'=>$courseid, 'name'=>$name));
721 } else if (!$existing = $DB->get_record('grade_settings', array('courseid'=>$courseid, 'name'=>$name))) {
722 $data = new stdClass();
723 $data->courseid = $courseid;
724 $data->name = $name;
725 $data->value = $value;
726 $DB->insert_record('grade_settings', $data);
728 } else {
729 $data = new stdClass();
730 $data->id = $existing->id;
731 $data->value = $value;
732 $DB->update_record('grade_settings', $data);
735 grade_get_setting($courseid, null, null, true); // reset the cache
739 * Returns string representation of grade value
741 * @param float $value The grade value
742 * @param object $grade_item Grade item object passed by reference to prevent scale reloading
743 * @param bool $localized use localised decimal separator
744 * @param int $displaytype type of display. For example GRADE_DISPLAY_TYPE_REAL, GRADE_DISPLAY_TYPE_PERCENTAGE, GRADE_DISPLAY_TYPE_LETTER
745 * @param int $decimals The number of decimal places when displaying float values
746 * @return string
748 function grade_format_gradevalue($value, &$grade_item, $localized=true, $displaytype=null, $decimals=null) {
749 if ($grade_item->gradetype == GRADE_TYPE_NONE or $grade_item->gradetype == GRADE_TYPE_TEXT) {
750 return '';
753 // no grade yet?
754 if (is_null($value)) {
755 return '-';
758 if ($grade_item->gradetype != GRADE_TYPE_VALUE and $grade_item->gradetype != GRADE_TYPE_SCALE) {
759 //unknown type??
760 return '';
763 if (is_null($displaytype)) {
764 $displaytype = $grade_item->get_displaytype();
767 if (is_null($decimals)) {
768 $decimals = $grade_item->get_decimals();
771 switch ($displaytype) {
772 case GRADE_DISPLAY_TYPE_REAL:
773 return grade_format_gradevalue_real($value, $grade_item, $decimals, $localized);
775 case GRADE_DISPLAY_TYPE_PERCENTAGE:
776 return grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized);
778 case GRADE_DISPLAY_TYPE_LETTER:
779 return grade_format_gradevalue_letter($value, $grade_item);
781 case GRADE_DISPLAY_TYPE_REAL_PERCENTAGE:
782 return grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ' (' .
783 grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ')';
785 case GRADE_DISPLAY_TYPE_REAL_LETTER:
786 return grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ' (' .
787 grade_format_gradevalue_letter($value, $grade_item) . ')';
789 case GRADE_DISPLAY_TYPE_PERCENTAGE_REAL:
790 return grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ' (' .
791 grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ')';
793 case GRADE_DISPLAY_TYPE_LETTER_REAL:
794 return grade_format_gradevalue_letter($value, $grade_item) . ' (' .
795 grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ')';
797 case GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE:
798 return grade_format_gradevalue_letter($value, $grade_item) . ' (' .
799 grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ')';
801 case GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER:
802 return grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ' (' .
803 grade_format_gradevalue_letter($value, $grade_item) . ')';
804 default:
805 return '';
810 * Returns a float representation of a grade value
812 * @param float $value The grade value
813 * @param object $grade_item Grade item object
814 * @param int $decimals The number of decimal places
815 * @param bool $localized use localised decimal separator
816 * @return string
818 function grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) {
819 if ($grade_item->gradetype == GRADE_TYPE_SCALE) {
820 if (!$scale = $grade_item->load_scale()) {
821 return get_string('error');
824 $value = $grade_item->bounded_grade($value);
825 return format_string($scale->scale_items[$value-1]);
827 } else {
828 return format_float($value, $decimals, $localized);
833 * Returns a percentage representation of a grade value
835 * @param float $value The grade value
836 * @param object $grade_item Grade item object
837 * @param int $decimals The number of decimal places
838 * @param bool $localized use localised decimal separator
839 * @return string
841 function grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) {
842 $min = $grade_item->grademin;
843 $max = $grade_item->grademax;
844 if ($min == $max) {
845 return '';
847 $value = $grade_item->bounded_grade($value);
848 $percentage = (($value-$min)*100)/($max-$min);
849 return format_float($percentage, $decimals, $localized).' %';
853 * Returns a letter grade representation of a grade value
854 * The array of grade letters used is produced by {@link grade_get_letters()} using the course context
856 * @param float $value The grade value
857 * @param object $grade_item Grade item object
858 * @return string
860 function grade_format_gradevalue_letter($value, $grade_item) {
861 global $CFG;
862 $context = context_course::instance($grade_item->courseid, IGNORE_MISSING);
863 if (!$letters = grade_get_letters($context)) {
864 return ''; // no letters??
867 if (is_null($value)) {
868 return '-';
871 $value = grade_grade::standardise_score($value, $grade_item->grademin, $grade_item->grademax, 0, 100);
872 $value = bounded_number(0, $value, 100); // just in case
874 $gradebookcalculationsfreeze = 'gradebook_calculations_freeze_' . $grade_item->courseid;
876 foreach ($letters as $boundary => $letter) {
877 if (property_exists($CFG, $gradebookcalculationsfreeze) && (int)$CFG->{$gradebookcalculationsfreeze} <= 20160518) {
878 // Do nothing.
879 } else {
880 // The boundary is a percentage out of 100 so use 0 as the min and 100 as the max.
881 $boundary = grade_grade::standardise_score($boundary, 0, 100, 0, 100);
883 if ($value >= $boundary) {
884 return format_string($letter);
887 return '-'; // no match? maybe '' would be more correct
892 * Returns grade options for gradebook grade category menu
894 * @param int $courseid The course ID
895 * @param bool $includenew Include option for new category at array index -1
896 * @return array of grade categories in course
898 function grade_get_categories_menu($courseid, $includenew=false) {
899 $result = array();
900 if (!$categories = grade_category::fetch_all(array('courseid'=>$courseid))) {
901 //make sure course category exists
902 if (!grade_category::fetch_course_category($courseid)) {
903 debugging('Can not create course grade category!');
904 return $result;
906 $categories = grade_category::fetch_all(array('courseid'=>$courseid));
908 foreach ($categories as $key=>$category) {
909 if ($category->is_course_category()) {
910 $result[$category->id] = get_string('uncategorised', 'grades');
911 unset($categories[$key]);
914 if ($includenew) {
915 $result[-1] = get_string('newcategory', 'grades');
917 $cats = array();
918 foreach ($categories as $category) {
919 $cats[$category->id] = $category->get_name();
921 core_collator::asort($cats);
923 return ($result+$cats);
927 * Returns the array of grade letters to be used in the supplied context
929 * @param object $context Context object or null for defaults
930 * @return array of grade_boundary (minimum) => letter_string
932 function grade_get_letters($context=null) {
933 global $DB;
935 if (empty($context)) {
936 //default grading letters
937 return array('93'=>'A', '90'=>'A-', '87'=>'B+', '83'=>'B', '80'=>'B-', '77'=>'C+', '73'=>'C', '70'=>'C-', '67'=>'D+', '60'=>'D', '0'=>'F');
940 static $cache = array();
942 if (array_key_exists($context->id, $cache)) {
943 return $cache[$context->id];
946 if (count($cache) > 100) {
947 $cache = array(); // cache size limit
950 $letters = array();
952 $contexts = $context->get_parent_context_ids();
953 array_unshift($contexts, $context->id);
955 foreach ($contexts as $ctxid) {
956 if ($records = $DB->get_records('grade_letters', array('contextid'=>$ctxid), 'lowerboundary DESC')) {
957 foreach ($records as $record) {
958 $letters[$record->lowerboundary] = $record->letter;
962 if (!empty($letters)) {
963 $cache[$context->id] = $letters;
964 return $letters;
968 $letters = grade_get_letters(null);
969 $cache[$context->id] = $letters;
970 return $letters;
975 * Verify new value of grade item idnumber. Checks for uniqueness of new ID numbers. Old ID numbers are kept intact.
977 * @param string $idnumber string (with magic quotes)
978 * @param int $courseid ID numbers are course unique only
979 * @param grade_item $grade_item The grade item this idnumber is associated with
980 * @param stdClass $cm used for course module idnumbers and items attached to modules
981 * @return bool true means idnumber ok
983 function grade_verify_idnumber($idnumber, $courseid, $grade_item=null, $cm=null) {
984 global $DB;
986 if ($idnumber == '') {
987 //we allow empty idnumbers
988 return true;
991 // keep existing even when not unique
992 if ($cm and $cm->idnumber == $idnumber) {
993 if ($grade_item and $grade_item->itemnumber != 0) {
994 // grade item with itemnumber > 0 can't have the same idnumber as the main
995 // itemnumber 0 which is synced with course_modules
996 return false;
998 return true;
999 } else if ($grade_item and $grade_item->idnumber == $idnumber) {
1000 return true;
1003 if ($DB->record_exists('course_modules', array('course'=>$courseid, 'idnumber'=>$idnumber))) {
1004 return false;
1007 if ($DB->record_exists('grade_items', array('courseid'=>$courseid, 'idnumber'=>$idnumber))) {
1008 return false;
1011 return true;
1015 * Force final grade recalculation in all course items
1017 * @param int $courseid The course ID to recalculate
1019 function grade_force_full_regrading($courseid) {
1020 global $DB;
1021 $DB->set_field('grade_items', 'needsupdate', 1, array('courseid'=>$courseid));
1025 * Forces regrading of all site grades. Used when changing site setings
1027 function grade_force_site_regrading() {
1028 global $CFG, $DB;
1029 $DB->set_field('grade_items', 'needsupdate', 1);
1033 * Recover a user's grades from grade_grades_history
1034 * @param int $userid the user ID whose grades we want to recover
1035 * @param int $courseid the relevant course
1036 * @return bool true if successful or false if there was an error or no grades could be recovered
1038 function grade_recover_history_grades($userid, $courseid) {
1039 global $CFG, $DB;
1041 if ($CFG->disablegradehistory) {
1042 debugging('Attempting to recover grades when grade history is disabled.');
1043 return false;
1046 //Were grades recovered? Flag to return.
1047 $recoveredgrades = false;
1049 //Check the user is enrolled in this course
1050 //Dont bother checking if they have a gradeable role. They may get one later so recover
1051 //whatever grades they have now just in case.
1052 $course_context = context_course::instance($courseid);
1053 if (!is_enrolled($course_context, $userid)) {
1054 debugging('Attempting to recover the grades of a user who is deleted or not enrolled. Skipping recover.');
1055 return false;
1058 //Check for existing grades for this user in this course
1059 //Recovering grades when the user already has grades can lead to duplicate indexes and bad data
1060 //In the future we could move the existing grades to the history table then recover the grades from before then
1061 $sql = "SELECT gg.id
1062 FROM {grade_grades} gg
1063 JOIN {grade_items} gi ON gi.id = gg.itemid
1064 WHERE gi.courseid = :courseid AND gg.userid = :userid";
1065 $params = array('userid' => $userid, 'courseid' => $courseid);
1066 if ($DB->record_exists_sql($sql, $params)) {
1067 debugging('Attempting to recover the grades of a user who already has grades. Skipping recover.');
1068 return false;
1069 } else {
1070 //Retrieve the user's old grades
1071 //have history ID as first column to guarantee we a unique first column
1072 $sql = "SELECT h.id, gi.itemtype, gi.itemmodule, gi.iteminstance as iteminstance, gi.itemnumber, h.source, h.itemid, h.userid, h.rawgrade, h.rawgrademax,
1073 h.rawgrademin, h.rawscaleid, h.usermodified, h.finalgrade, h.hidden, h.locked, h.locktime, h.exported, h.overridden, h.excluded, h.feedback,
1074 h.feedbackformat, h.information, h.informationformat, h.timemodified, itemcreated.tm AS timecreated
1075 FROM {grade_grades_history} h
1076 JOIN (SELECT itemid, MAX(id) AS id
1077 FROM {grade_grades_history}
1078 WHERE userid = :userid1
1079 GROUP BY itemid) maxquery ON h.id = maxquery.id AND h.itemid = maxquery.itemid
1080 JOIN {grade_items} gi ON gi.id = h.itemid
1081 JOIN (SELECT itemid, MAX(timemodified) AS tm
1082 FROM {grade_grades_history}
1083 WHERE userid = :userid2 AND action = :insertaction
1084 GROUP BY itemid) itemcreated ON itemcreated.itemid = h.itemid
1085 WHERE gi.courseid = :courseid";
1086 $params = array('userid1' => $userid, 'userid2' => $userid , 'insertaction' => GRADE_HISTORY_INSERT, 'courseid' => $courseid);
1087 $oldgrades = $DB->get_records_sql($sql, $params);
1089 //now move the old grades to the grade_grades table
1090 foreach ($oldgrades as $oldgrade) {
1091 unset($oldgrade->id);
1093 $grade = new grade_grade($oldgrade, false);//2nd arg false as dont want to try and retrieve a record from the DB
1094 $grade->insert($oldgrade->source);
1096 //dont include default empty grades created when activities are created
1097 if (!is_null($oldgrade->finalgrade) || !is_null($oldgrade->feedback)) {
1098 $recoveredgrades = true;
1103 //Some activities require manual grade synching (moving grades from the activity into the gradebook)
1104 //If the student was deleted when synching was done they may have grades in the activity that haven't been moved across
1105 grade_grab_course_grades($courseid, null, $userid);
1107 return $recoveredgrades;
1111 * Updates all final grades in course.
1113 * @param int $courseid The course ID
1114 * @param int $userid If specified try to do a quick regrading of the grades of this user only
1115 * @param object $updated_item Optional grade item to be marked for regrading
1116 * @param \core\progress\base $progress If provided, will be used to update progress on this long operation.
1117 * @return bool true if ok, array of errors if problems found. Grade item id => error message
1119 function grade_regrade_final_grades($courseid, $userid=null, $updated_item=null, $progress=null) {
1120 // This may take a very long time and extra memory.
1121 \core_php_time_limit::raise();
1122 raise_memory_limit(MEMORY_EXTRA);
1124 $course_item = grade_item::fetch_course_item($courseid);
1126 if ($progress == null) {
1127 $progress = new \core\progress\none();
1130 if ($userid) {
1131 // one raw grade updated for one user
1132 if (empty($updated_item)) {
1133 print_error("cannotbenull", 'debug', '', "updated_item");
1135 if ($course_item->needsupdate) {
1136 $updated_item->force_regrading();
1137 return array($course_item->id =>'Can not do fast regrading after updating of raw grades');
1140 } else {
1141 if (!$course_item->needsupdate) {
1142 // nothing to do :-)
1143 return true;
1147 // Categories might have to run some processing before we fetch the grade items.
1148 // This gives them a final opportunity to update and mark their children to be updated.
1149 // We need to work on the children categories up to the parent ones, so that, for instance,
1150 // if a category total is updated it will be reflected in the parent category.
1151 $cats = grade_category::fetch_all(array('courseid' => $courseid));
1152 $flatcattree = array();
1153 foreach ($cats as $cat) {
1154 if (!isset($flatcattree[$cat->depth])) {
1155 $flatcattree[$cat->depth] = array();
1157 $flatcattree[$cat->depth][] = $cat;
1159 krsort($flatcattree);
1160 foreach ($flatcattree as $depth => $cats) {
1161 foreach ($cats as $cat) {
1162 $cat->pre_regrade_final_grades();
1166 $progresstotal = 0;
1167 $progresscurrent = 0;
1169 $grade_items = grade_item::fetch_all(array('courseid'=>$courseid));
1170 $depends_on = array();
1172 foreach ($grade_items as $gid=>$gitem) {
1173 if ((!empty($updated_item) and $updated_item->id == $gid) ||
1174 $gitem->is_course_item() || $gitem->is_category_item() || $gitem->is_calculated()) {
1175 $grade_items[$gid]->needsupdate = 1;
1178 // We load all dependencies of these items later we can discard some grade_items based on this.
1179 if ($grade_items[$gid]->needsupdate) {
1180 $depends_on[$gid] = $grade_items[$gid]->depends_on();
1181 $progresstotal++;
1185 $progress->start_progress('regrade_course', $progresstotal);
1187 $errors = array();
1188 $finalids = array();
1189 $updatedids = array();
1190 $gids = array_keys($grade_items);
1191 $failed = 0;
1193 while (count($finalids) < count($gids)) { // work until all grades are final or error found
1194 $count = 0;
1195 foreach ($gids as $gid) {
1196 if (in_array($gid, $finalids)) {
1197 continue; // already final
1200 if (!$grade_items[$gid]->needsupdate) {
1201 $finalids[] = $gid; // we can make it final - does not need update
1202 continue;
1204 $thisprogress = $progresstotal;
1205 foreach ($grade_items as $item) {
1206 if ($item->needsupdate) {
1207 $thisprogress--;
1210 // Clip between $progresscurrent and $progresstotal.
1211 $thisprogress = max(min($thisprogress, $progresstotal), $progresscurrent);
1212 $progress->progress($thisprogress);
1213 $progresscurrent = $thisprogress;
1215 foreach ($depends_on[$gid] as $did) {
1216 if (!in_array($did, $finalids)) {
1217 // This item depends on something that is not yet in finals array.
1218 continue 2;
1222 // If this grade item has no dependancy with any updated item at all, then remove it from being recalculated.
1224 // When we get here, all of this grade item's decendents are marked as final so they would be marked as updated too
1225 // if they would have been regraded. We don't need to regrade items which dependants (not only the direct ones
1226 // but any dependant in the cascade) have not been updated.
1228 // If $updated_item was specified we discard the grade items that do not depend on it or on any grade item that
1229 // depend on $updated_item.
1231 // Here we check to see if the direct decendants are marked as updated.
1232 if (!empty($updated_item) && $gid != $updated_item->id && !in_array($updated_item->id, $depends_on[$gid])) {
1234 // We need to ensure that none of this item's dependencies have been updated.
1235 // If we find that one of the direct decendants of this grade item is marked as updated then this
1236 // grade item needs to be recalculated and marked as updated.
1237 // Being marked as updated is done further down in the code.
1239 $updateddependencies = false;
1240 foreach ($depends_on[$gid] as $dependency) {
1241 if (in_array($dependency, $updatedids)) {
1242 $updateddependencies = true;
1243 break;
1246 if ($updateddependencies === false) {
1247 // If no direct descendants are marked as updated, then we don't need to update this grade item. We then mark it
1248 // as final.
1250 $finalids[] = $gid;
1251 continue;
1255 // Let's update, calculate or aggregate.
1256 $result = $grade_items[$gid]->regrade_final_grades($userid);
1258 if ($result === true) {
1260 // We should only update the database if we regraded all users.
1261 if (empty($userid)) {
1262 $grade_items[$gid]->regrading_finished();
1263 // Do the locktime item locking.
1264 $grade_items[$gid]->check_locktime();
1265 } else {
1266 $grade_items[$gid]->needsupdate = 0;
1268 $count++;
1269 $finalids[] = $gid;
1270 $updatedids[] = $gid;
1272 } else {
1273 $grade_items[$gid]->force_regrading();
1274 $errors[$gid] = $result;
1278 if ($count == 0) {
1279 $failed++;
1280 } else {
1281 $failed = 0;
1284 if ($failed > 1) {
1285 foreach($gids as $gid) {
1286 if (in_array($gid, $finalids)) {
1287 continue; // this one is ok
1289 $grade_items[$gid]->force_regrading();
1290 $errors[$grade_items[$gid]->id] = get_string('errorcalculationbroken', 'grades');
1292 break; // Found error.
1295 $progress->end_progress();
1297 if (count($errors) == 0) {
1298 if (empty($userid)) {
1299 // do the locktime locking of grades, but only when doing full regrading
1300 grade_grade::check_locktime_all($gids);
1302 return true;
1303 } else {
1304 return $errors;
1309 * Refetches grade data from course activities
1311 * @param int $courseid The course ID
1312 * @param string $modname Limit the grade fetch to a single module type. For example 'forum'
1313 * @param int $userid limit the grade fetch to a single user
1315 function grade_grab_course_grades($courseid, $modname=null, $userid=0) {
1316 global $CFG, $DB;
1318 if ($modname) {
1319 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
1320 FROM {".$modname."} a, {course_modules} cm, {modules} m
1321 WHERE m.name=:modname AND m.visible=1 AND m.id=cm.module AND cm.instance=a.id AND cm.course=:courseid";
1322 $params = array('modname'=>$modname, 'courseid'=>$courseid);
1324 if ($modinstances = $DB->get_records_sql($sql, $params)) {
1325 foreach ($modinstances as $modinstance) {
1326 grade_update_mod_grades($modinstance, $userid);
1329 return;
1332 if (!$mods = core_component::get_plugin_list('mod') ) {
1333 print_error('nomodules', 'debug');
1336 foreach ($mods as $mod => $fullmod) {
1337 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
1338 continue;
1341 // include the module lib once
1342 if (file_exists($fullmod.'/lib.php')) {
1343 // get all instance of the activity
1344 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
1345 FROM {".$mod."} a, {course_modules} cm, {modules} m
1346 WHERE m.name=:mod AND m.visible=1 AND m.id=cm.module AND cm.instance=a.id AND cm.course=:courseid";
1347 $params = array('mod'=>$mod, 'courseid'=>$courseid);
1349 if ($modinstances = $DB->get_records_sql($sql, $params)) {
1350 foreach ($modinstances as $modinstance) {
1351 grade_update_mod_grades($modinstance, $userid);
1359 * Force full update of module grades in central gradebook
1361 * @param object $modinstance Module object with extra cmidnumber and modname property
1362 * @param int $userid Optional user ID if limiting the update to a single user
1363 * @return bool True if success
1365 function grade_update_mod_grades($modinstance, $userid=0) {
1366 global $CFG, $DB;
1368 $fullmod = $CFG->dirroot.'/mod/'.$modinstance->modname;
1369 if (!file_exists($fullmod.'/lib.php')) {
1370 debugging('missing lib.php file in module ' . $modinstance->modname);
1371 return false;
1373 include_once($fullmod.'/lib.php');
1375 $updateitemfunc = $modinstance->modname.'_grade_item_update';
1376 $updategradesfunc = $modinstance->modname.'_update_grades';
1378 if (function_exists($updategradesfunc) and function_exists($updateitemfunc)) {
1379 //new grading supported, force updating of grades
1380 $updateitemfunc($modinstance);
1381 $updategradesfunc($modinstance, $userid);
1382 } else if (function_exists($updategradesfunc) xor function_exists($updateitemfunc)) {
1383 // Module does not support grading?
1384 debugging("You have declared one of $updateitemfunc and $updategradesfunc but not both. " .
1385 "This will cause broken behaviour.", DEBUG_DEVELOPER);
1388 return true;
1392 * Remove grade letters for given context
1394 * @param context $context The context
1395 * @param bool $showfeedback If true a success notification will be displayed
1397 function remove_grade_letters($context, $showfeedback) {
1398 global $DB, $OUTPUT;
1400 $strdeleted = get_string('deleted');
1402 $records = $DB->get_records('grade_letters', array('contextid' => $context->id));
1403 foreach ($records as $record) {
1404 $DB->delete_record('grade_letters', array('id' => $record->id));
1405 // Trigger the letter grade deleted event.
1406 $event = \core\event\grade_letter_deleted::create(array(
1407 'objectid' => $record->id,
1408 'context' => $context,
1410 $event->trigger();
1412 if ($showfeedback) {
1413 echo $OUTPUT->notification($strdeleted.' - '.get_string('letters', 'grades'), 'notifysuccess');
1418 * Remove all grade related course data
1419 * Grade history is kept
1421 * @param int $courseid The course ID
1422 * @param bool $showfeedback If true success notifications will be displayed
1424 function remove_course_grades($courseid, $showfeedback) {
1425 global $DB, $OUTPUT;
1427 $fs = get_file_storage();
1428 $strdeleted = get_string('deleted');
1430 $course_category = grade_category::fetch_course_category($courseid);
1431 $course_category->delete('coursedelete');
1432 $fs->delete_area_files(context_course::instance($courseid)->id, 'grade', 'feedback');
1433 if ($showfeedback) {
1434 echo $OUTPUT->notification($strdeleted.' - '.get_string('grades', 'grades').', '.get_string('items', 'grades').', '.get_string('categories', 'grades'), 'notifysuccess');
1437 if ($outcomes = grade_outcome::fetch_all(array('courseid'=>$courseid))) {
1438 foreach ($outcomes as $outcome) {
1439 $outcome->delete('coursedelete');
1442 $DB->delete_records('grade_outcomes_courses', array('courseid'=>$courseid));
1443 if ($showfeedback) {
1444 echo $OUTPUT->notification($strdeleted.' - '.get_string('outcomes', 'grades'), 'notifysuccess');
1447 if ($scales = grade_scale::fetch_all(array('courseid'=>$courseid))) {
1448 foreach ($scales as $scale) {
1449 $scale->delete('coursedelete');
1452 if ($showfeedback) {
1453 echo $OUTPUT->notification($strdeleted.' - '.get_string('scales'), 'notifysuccess');
1456 $DB->delete_records('grade_settings', array('courseid'=>$courseid));
1457 if ($showfeedback) {
1458 echo $OUTPUT->notification($strdeleted.' - '.get_string('settings', 'grades'), 'notifysuccess');
1463 * Called when course category is deleted
1464 * Cleans the gradebook of associated data
1466 * @param int $categoryid The course category id
1467 * @param int $newparentid If empty everything is deleted. Otherwise the ID of the category where content moved
1468 * @param bool $showfeedback print feedback
1470 function grade_course_category_delete($categoryid, $newparentid, $showfeedback) {
1471 global $DB;
1473 $context = context_coursecat::instance($categoryid);
1474 $records = $DB->get_records('grade_letters', array('contextid' => $context->id));
1475 foreach ($records as $record) {
1476 $DB->delete_record('grade_letters', array('id' => $record->id));
1477 // Trigger the letter grade deleted event.
1478 $event = \core\event\grade_letter_deleted::create(array(
1479 'objectid' => $record->id,
1480 'context' => $context,
1482 $event->trigger();
1487 * Does gradebook cleanup when a module is uninstalled
1488 * Deletes all associated grade items
1490 * @param string $modname The grade item module name to remove. For example 'forum'
1492 function grade_uninstalled_module($modname) {
1493 global $CFG, $DB;
1495 $sql = "SELECT *
1496 FROM {grade_items}
1497 WHERE itemtype='mod' AND itemmodule=?";
1499 // go all items for this module and delete them including the grades
1500 $rs = $DB->get_recordset_sql($sql, array($modname));
1501 foreach ($rs as $item) {
1502 $grade_item = new grade_item($item, false);
1503 $grade_item->delete('moduninstall');
1505 $rs->close();
1509 * Deletes all of a user's grade data from gradebook
1511 * @param int $userid The user whose grade data should be deleted
1513 function grade_user_delete($userid) {
1514 if ($grades = grade_grade::fetch_all(array('userid'=>$userid))) {
1515 foreach ($grades as $grade) {
1516 $grade->delete('userdelete');
1522 * Purge course data when user unenrolls from a course
1524 * @param int $courseid The ID of the course the user has unenrolled from
1525 * @param int $userid The ID of the user unenrolling
1527 function grade_user_unenrol($courseid, $userid) {
1528 if ($items = grade_item::fetch_all(array('courseid'=>$courseid))) {
1529 foreach ($items as $item) {
1530 if ($grades = grade_grade::fetch_all(array('userid'=>$userid, 'itemid'=>$item->id))) {
1531 foreach ($grades as $grade) {
1532 $grade->delete('userdelete');
1540 * Grading cron job. Performs background clean up on the gradebook
1542 function grade_cron() {
1543 global $CFG, $DB;
1545 $now = time();
1547 $sql = "SELECT i.*
1548 FROM {grade_items} i
1549 WHERE i.locked = 0 AND i.locktime > 0 AND i.locktime < ? AND EXISTS (
1550 SELECT 'x' FROM {grade_items} c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
1552 // go through all courses that have proper final grades and lock them if needed
1553 $rs = $DB->get_recordset_sql($sql, array($now));
1554 foreach ($rs as $item) {
1555 $grade_item = new grade_item($item, false);
1556 $grade_item->locked = $now;
1557 $grade_item->update('locktime');
1559 $rs->close();
1561 $grade_inst = new grade_grade();
1562 $fields = 'g.'.implode(',g.', $grade_inst->required_fields);
1564 $sql = "SELECT $fields
1565 FROM {grade_grades} g, {grade_items} i
1566 WHERE g.locked = 0 AND g.locktime > 0 AND g.locktime < ? AND g.itemid=i.id AND EXISTS (
1567 SELECT 'x' FROM {grade_items} c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
1569 // go through all courses that have proper final grades and lock them if needed
1570 $rs = $DB->get_recordset_sql($sql, array($now));
1571 foreach ($rs as $grade) {
1572 $grade_grade = new grade_grade($grade, false);
1573 $grade_grade->locked = $now;
1574 $grade_grade->update('locktime');
1576 $rs->close();
1578 //TODO: do not run this cleanup every cron invocation
1579 // cleanup history tables
1580 if (!empty($CFG->gradehistorylifetime)) { // value in days
1581 $histlifetime = $now - ($CFG->gradehistorylifetime * 3600 * 24);
1582 $tables = array('grade_outcomes_history', 'grade_categories_history', 'grade_items_history', 'grade_grades_history', 'scale_history');
1583 foreach ($tables as $table) {
1584 if ($DB->delete_records_select($table, "timemodified < ?", array($histlifetime))) {
1585 mtrace(" Deleted old grade history records from '$table'");
1592 * Reset all course grades, refetch from the activities and recalculate
1594 * @param int $courseid The course to reset
1595 * @return bool success
1597 function grade_course_reset($courseid) {
1599 // no recalculations
1600 grade_force_full_regrading($courseid);
1602 $grade_items = grade_item::fetch_all(array('courseid'=>$courseid));
1603 foreach ($grade_items as $gid=>$grade_item) {
1604 $grade_item->delete_all_grades('reset');
1607 //refetch all grades
1608 grade_grab_course_grades($courseid);
1610 // recalculate all grades
1611 grade_regrade_final_grades($courseid);
1612 return true;
1616 * Convert a number to 5 decimal point float, an empty string or a null db compatible format
1617 * (we need this to decide if db value changed)
1619 * @param mixed $number The number to convert
1620 * @return mixed float or null
1622 function grade_floatval($number) {
1623 if (is_null($number) or $number === '') {
1624 return null;
1626 // we must round to 5 digits to get the same precision as in 10,5 db fields
1627 // note: db rounding for 10,5 is different from php round() function
1628 return round($number, 5);
1632 * Compare two float numbers safely. Uses 5 decimals php precision using {@link grade_floatval()}. Nulls accepted too.
1633 * Used for determining if a database update is required
1635 * @param float $f1 Float one to compare
1636 * @param float $f2 Float two to compare
1637 * @return bool True if the supplied values are different
1639 function grade_floats_different($f1, $f2) {
1640 // note: db rounding for 10,5 is different from php round() function
1641 return (grade_floatval($f1) !== grade_floatval($f2));
1645 * Compare two float numbers safely. Uses 5 decimals php precision using {@link grade_floatval()}
1647 * Do not use rounding for 10,5 at the database level as the results may be
1648 * different from php round() function.
1650 * @since Moodle 2.0
1651 * @param float $f1 Float one to compare
1652 * @param float $f2 Float two to compare
1653 * @return bool True if the values should be considered as the same grades
1655 function grade_floats_equal($f1, $f2) {
1656 return (grade_floatval($f1) === grade_floatval($f2));