MDL-71669 editor_atto: Fire custom event when toggling button highlight
[moodle.git] / lib / grade / grade_item.php
blobfc32227da447896172ecae6feff7d0fc5fb9c3b2
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 * Definition of a class to represent a grade item
20 * @package core_grades
21 * @category grade
22 * @copyright 2006 Nicolas Connault
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
27 require_once('grade_object.php');
29 /**
30 * Class representing a grade item.
32 * It is responsible for handling its DB representation, modifying and returning its metadata.
34 * @package core_grades
35 * @category grade
36 * @copyright 2006 Nicolas Connault
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 class grade_item extends grade_object {
40 /**
41 * DB Table (used by grade_object).
42 * @var string $table
44 public $table = 'grade_items';
46 /**
47 * Array of required table fields, must start with 'id'.
48 * @var array $required_fields
50 public $required_fields = array('id', 'courseid', 'categoryid', 'itemname', 'itemtype', 'itemmodule', 'iteminstance',
51 'itemnumber', 'iteminfo', 'idnumber', 'calculation', 'gradetype', 'grademax', 'grademin',
52 'scaleid', 'outcomeid', 'gradepass', 'multfactor', 'plusfactor', 'aggregationcoef',
53 'aggregationcoef2', 'sortorder', 'display', 'decimals', 'hidden', 'locked', 'locktime',
54 'needsupdate', 'weightoverride', 'timecreated', 'timemodified');
56 /**
57 * The course this grade_item belongs to.
58 * @var int $courseid
60 public $courseid;
62 /**
63 * The category this grade_item belongs to (optional).
64 * @var int $categoryid
66 public $categoryid;
68 /**
69 * The grade_category object referenced $this->iteminstance if itemtype == 'category' or == 'course'.
70 * @var grade_category $item_category
72 public $item_category;
74 /**
75 * The grade_category object referenced by $this->categoryid.
76 * @var grade_category $parent_category
78 public $parent_category;
81 /**
82 * The name of this grade_item (pushed by the module).
83 * @var string $itemname
85 public $itemname;
87 /**
88 * e.g. 'category', 'course' and 'mod', 'blocks', 'import', etc...
89 * @var string $itemtype
91 public $itemtype;
93 /**
94 * The module pushing this grade (e.g. 'forum', 'quiz', 'assignment' etc).
95 * @var string $itemmodule
97 public $itemmodule;
99 /**
100 * ID of the item module
101 * @var int $iteminstance
103 public $iteminstance;
106 * Number of the item in a series of multiple grades pushed by an activity.
107 * @var int $itemnumber
109 public $itemnumber;
112 * Info and notes about this item.
113 * @var string $iteminfo
115 public $iteminfo;
118 * Arbitrary idnumber provided by the module responsible.
119 * @var string $idnumber
121 public $idnumber;
124 * Calculation string used for this item.
125 * @var string $calculation
127 public $calculation;
130 * Indicates if we already tried to normalize the grade calculation formula.
131 * This flag helps to minimize db access when broken formulas used in calculation.
132 * @var bool
134 public $calculation_normalized;
136 * Math evaluation object
137 * @var calc_formula A formula object
139 public $formula;
142 * The type of grade (0 = none, 1 = value, 2 = scale, 3 = text)
143 * @var int $gradetype
145 public $gradetype = GRADE_TYPE_VALUE;
148 * Maximum allowable grade.
149 * @var float $grademax
151 public $grademax = 100;
154 * Minimum allowable grade.
155 * @var float $grademin
157 public $grademin = 0;
160 * id of the scale, if this grade is based on a scale.
161 * @var int $scaleid
163 public $scaleid;
166 * The grade_scale object referenced by $this->scaleid.
167 * @var grade_scale $scale
169 public $scale;
172 * The id of the optional grade_outcome associated with this grade_item.
173 * @var int $outcomeid
175 public $outcomeid;
178 * The grade_outcome this grade is associated with, if applicable.
179 * @var grade_outcome $outcome
181 public $outcome;
184 * grade required to pass. (grademin <= gradepass <= grademax)
185 * @var float $gradepass
187 public $gradepass = 0;
190 * Multiply all grades by this number.
191 * @var float $multfactor
193 public $multfactor = 1.0;
196 * Add this to all grades.
197 * @var float $plusfactor
199 public $plusfactor = 0;
202 * Aggregation coeficient used for weighted averages or extra credit
203 * @var float $aggregationcoef
205 public $aggregationcoef = 0;
208 * Aggregation coeficient used for weighted averages only
209 * @var float $aggregationcoef2
211 public $aggregationcoef2 = 0;
214 * Sorting order of the columns.
215 * @var int $sortorder
217 public $sortorder = 0;
220 * Display type of the grades (Real, Percentage, Letter, or default).
221 * @var int $display
223 public $display = GRADE_DISPLAY_TYPE_DEFAULT;
226 * The number of digits after the decimal point symbol. Applies only to REAL and PERCENTAGE grade display types.
227 * @var int $decimals
229 public $decimals = null;
232 * Grade item lock flag. Empty if not locked, locked if any value present, usually date when item was locked. Locking prevents updating.
233 * @var int $locked
235 public $locked = 0;
238 * Date after which the grade will be locked. Empty means no automatic locking.
239 * @var int $locktime
241 public $locktime = 0;
244 * If set, the whole column will be recalculated, then this flag will be switched off.
245 * @var bool $needsupdate
247 public $needsupdate = 1;
250 * If set, the grade item's weight has been overridden by a user and should not be automatically adjusted.
252 public $weightoverride = 0;
255 * Cached dependson array
256 * @var array An array of cached grade item dependencies.
258 public $dependson_cache = null;
261 * @var bool If we regrade this item should we mark it as overridden?
263 public $markasoverriddenwhengraded = true;
266 * Constructor. Optionally (and by default) attempts to fetch corresponding row from the database
268 * @param array $params An array with required parameters for this grade object.
269 * @param bool $fetch Whether to fetch corresponding row from the database or not,
270 * optional fields might not be defined if false used
272 public function __construct($params = null, $fetch = true) {
273 global $CFG;
274 // Set grademax from $CFG->gradepointdefault .
275 self::set_properties($this, array('grademax' => $CFG->gradepointdefault));
276 parent::__construct($params, $fetch);
280 * In addition to update() as defined in grade_object, handle the grade_outcome and grade_scale objects.
281 * Force regrading if necessary, rounds the float numbers using php function,
282 * the reason is we need to compare the db value with computed number to skip regrading if possible.
284 * @param string $source from where was the object inserted (mod/forum, manual, etc.)
285 * @return bool success
287 public function update($source=null) {
288 // reset caches
289 $this->dependson_cache = null;
291 // Retrieve scale and infer grademax/min from it if needed
292 $this->load_scale();
294 // make sure there is not 0 in outcomeid
295 if (empty($this->outcomeid)) {
296 $this->outcomeid = null;
299 if ($this->qualifies_for_regrading()) {
300 $this->force_regrading();
303 $this->timemodified = time();
305 $this->grademin = grade_floatval($this->grademin);
306 $this->grademax = grade_floatval($this->grademax);
307 $this->multfactor = grade_floatval($this->multfactor);
308 $this->plusfactor = grade_floatval($this->plusfactor);
309 $this->aggregationcoef = grade_floatval($this->aggregationcoef);
310 $this->aggregationcoef2 = grade_floatval($this->aggregationcoef2);
312 $result = parent::update($source);
314 if ($result) {
315 $event = \core\event\grade_item_updated::create_from_grade_item($this);
316 $event->trigger();
319 return $result;
323 * Compares the values held by this object with those of the matching record in DB, and returns
324 * whether or not these differences are sufficient to justify an update of all parent objects.
325 * This assumes that this object has an id number and a matching record in DB. If not, it will return false.
327 * @return bool
329 public function qualifies_for_regrading() {
330 if (empty($this->id)) {
331 return false;
334 $db_item = new grade_item(array('id' => $this->id));
336 $calculationdiff = $db_item->calculation != $this->calculation;
337 $categorydiff = $db_item->categoryid != $this->categoryid;
338 $gradetypediff = $db_item->gradetype != $this->gradetype;
339 $scaleiddiff = $db_item->scaleid != $this->scaleid;
340 $outcomeiddiff = $db_item->outcomeid != $this->outcomeid;
341 $locktimediff = $db_item->locktime != $this->locktime;
342 $grademindiff = grade_floats_different($db_item->grademin, $this->grademin);
343 $grademaxdiff = grade_floats_different($db_item->grademax, $this->grademax);
344 $multfactordiff = grade_floats_different($db_item->multfactor, $this->multfactor);
345 $plusfactordiff = grade_floats_different($db_item->plusfactor, $this->plusfactor);
346 $acoefdiff = grade_floats_different($db_item->aggregationcoef, $this->aggregationcoef);
347 $acoefdiff2 = grade_floats_different($db_item->aggregationcoef2, $this->aggregationcoef2);
348 $weightoverride = grade_floats_different($db_item->weightoverride, $this->weightoverride);
350 $needsupdatediff = !$db_item->needsupdate && $this->needsupdate; // force regrading only if setting the flag first time
351 $lockeddiff = !empty($db_item->locked) && empty($this->locked); // force regrading only when unlocking
353 return ($calculationdiff || $categorydiff || $gradetypediff || $grademaxdiff || $grademindiff || $scaleiddiff
354 || $outcomeiddiff || $multfactordiff || $plusfactordiff || $needsupdatediff
355 || $lockeddiff || $acoefdiff || $acoefdiff2 || $weightoverride || $locktimediff);
359 * Finds and returns a grade_item instance based on params.
361 * @static
362 * @param array $params associative arrays varname=>value
363 * @return grade_item|bool Returns a grade_item instance or false if none found
365 public static function fetch($params) {
366 return grade_object::fetch_helper('grade_items', 'grade_item', $params);
370 * Check to see if there are any existing grades for this grade_item.
372 * @return boolean - true if there are valid grades for this grade_item.
374 public function has_grades() {
375 global $DB;
377 $count = $DB->count_records_select('grade_grades',
378 'itemid = :gradeitemid AND finalgrade IS NOT NULL',
379 array('gradeitemid' => $this->id));
380 return $count > 0;
384 * Check to see if there are existing overridden grades for this grade_item.
386 * @return boolean - true if there are overridden grades for this grade_item.
388 public function has_overridden_grades() {
389 global $DB;
391 $count = $DB->count_records_select('grade_grades',
392 'itemid = :gradeitemid AND finalgrade IS NOT NULL AND overridden > 0',
393 array('gradeitemid' => $this->id));
394 return $count > 0;
398 * Finds and returns all grade_item instances based on params.
400 * @static
401 * @param array $params associative arrays varname=>value
402 * @return array array of grade_item instances or false if none found.
404 public static function fetch_all($params) {
405 return grade_object::fetch_all_helper('grade_items', 'grade_item', $params);
409 * Delete all grades and force_regrading of parent category.
411 * @param string $source from where was the object deleted (mod/forum, manual, etc.)
412 * @return bool success
414 public function delete($source=null) {
415 global $DB;
417 $transaction = $DB->start_delegated_transaction();
418 $this->delete_all_grades($source);
419 $success = parent::delete($source);
420 $transaction->allow_commit();
422 if ($success) {
423 $event = \core\event\grade_item_deleted::create_from_grade_item($this);
424 $event->trigger();
427 return $success;
431 * Delete all grades
433 * @param string $source from where was the object deleted (mod/forum, manual, etc.)
434 * @return bool
436 public function delete_all_grades($source=null) {
437 global $DB;
439 $transaction = $DB->start_delegated_transaction();
441 if (!$this->is_course_item()) {
442 $this->force_regrading();
445 if ($grades = grade_grade::fetch_all(array('itemid'=>$this->id))) {
446 foreach ($grades as $grade) {
447 $grade->delete($source);
451 // Delete all the historical files.
452 // We only support feedback files for modules atm.
453 if ($this->is_external_item()) {
454 $fs = new file_storage();
455 $fs->delete_area_files($this->get_context()->id, GRADE_FILE_COMPONENT, GRADE_HISTORY_FEEDBACK_FILEAREA);
458 $transaction->allow_commit();
460 return true;
464 * Duplicate grade item.
466 * @return grade_item The duplicate grade item
468 public function duplicate() {
469 // Convert current object to array.
470 $copy = (array) $this;
472 if (empty($copy["id"])) {
473 throw new moodle_exception('invalidgradeitemid');
476 // Remove fields that will be either unique or automatically filled.
477 $removekeys = array();
478 $removekeys[] = 'id';
479 $removekeys[] = 'idnumber';
480 $removekeys[] = 'timecreated';
481 $removekeys[] = 'sortorder';
482 foreach ($removekeys as $key) {
483 unset($copy[$key]);
486 // Addendum to name.
487 $copy["itemname"] = get_string('duplicatedgradeitem', 'grades', $copy["itemname"]);
489 // Create new grade item.
490 $gradeitem = new grade_item($copy);
492 // Insert grade item into database.
493 $gradeitem->insert();
495 return $gradeitem;
499 * In addition to perform parent::insert(), calls force_regrading() method too.
501 * @param string $source From where was the object inserted (mod/forum, manual, etc.)
502 * @return int PK ID if successful, false otherwise
504 public function insert($source=null) {
505 global $CFG, $DB;
507 if (empty($this->courseid)) {
508 print_error('cannotinsertgrade');
511 // load scale if needed
512 $this->load_scale();
514 // add parent category if needed
515 if (empty($this->categoryid) and !$this->is_course_item() and !$this->is_category_item()) {
516 $course_category = grade_category::fetch_course_category($this->courseid);
517 $this->categoryid = $course_category->id;
521 // always place the new items at the end, move them after insert if needed
522 $last_sortorder = $DB->get_field_select('grade_items', 'MAX(sortorder)', "courseid = ?", array($this->courseid));
523 if (!empty($last_sortorder)) {
524 $this->sortorder = $last_sortorder + 1;
525 } else {
526 $this->sortorder = 1;
529 // add proper item numbers to manual items
530 if ($this->itemtype == 'manual') {
531 if (empty($this->itemnumber)) {
532 $this->itemnumber = 0;
536 // make sure there is not 0 in outcomeid
537 if (empty($this->outcomeid)) {
538 $this->outcomeid = null;
541 $this->timecreated = $this->timemodified = time();
543 if (parent::insert($source)) {
544 // force regrading of items if needed
545 $this->force_regrading();
547 $event = \core\event\grade_item_created::create_from_grade_item($this);
548 $event->trigger();
550 return $this->id;
552 } else {
553 debugging("Could not insert this grade_item in the database!");
554 return false;
559 * Set idnumber of grade item, updates also course_modules table
561 * @param string $idnumber (without magic quotes)
562 * @return bool success
564 public function add_idnumber($idnumber) {
565 global $DB;
566 if (!empty($this->idnumber)) {
567 return false;
570 if ($this->itemtype == 'mod' and !$this->is_outcome_item()) {
571 if ($this->itemnumber == 0) {
572 // for activity modules, itemnumber 0 is synced with the course_modules
573 if (!$cm = get_coursemodule_from_instance($this->itemmodule, $this->iteminstance, $this->courseid)) {
574 return false;
576 if (!empty($cm->idnumber)) {
577 return false;
579 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
580 $this->idnumber = $idnumber;
581 return $this->update();
582 } else {
583 $this->idnumber = $idnumber;
584 return $this->update();
587 } else {
588 $this->idnumber = $idnumber;
589 return $this->update();
594 * Returns the locked state of this grade_item (if the grade_item is locked OR no specific
595 * $userid is given) or the locked state of a specific grade within this item if a specific
596 * $userid is given and the grade_item is unlocked.
598 * @param int $userid The user's ID
599 * @return bool Locked state
601 public function is_locked($userid=NULL) {
602 global $CFG;
604 // Override for any grade items belonging to activities which are in the process of being deleted.
605 require_once($CFG->dirroot . '/course/lib.php');
606 if (course_module_instance_pending_deletion($this->courseid, $this->itemmodule, $this->iteminstance)) {
607 return true;
610 if (!empty($this->locked)) {
611 return true;
614 if (!empty($userid)) {
615 if ($grade = grade_grade::fetch(array('itemid'=>$this->id, 'userid'=>$userid))) {
616 $grade->grade_item =& $this; // prevent db fetching of cached grade_item
617 return $grade->is_locked();
621 return false;
625 * Locks or unlocks this grade_item and (optionally) all its associated final grades.
627 * @param int $lockedstate 0, 1 or a timestamp int(10) after which date the item will be locked.
628 * @param bool $cascade Lock/unlock child objects too
629 * @param bool $refresh Refresh grades when unlocking
630 * @return bool True if grade_item all grades updated, false if at least one update fails
632 public function set_locked($lockedstate, $cascade=false, $refresh=true) {
633 if ($lockedstate) {
634 /// setting lock
635 if ($this->needsupdate) {
636 return false; // can not lock grade without first having final grade
639 $this->locked = time();
640 $this->update();
642 if ($cascade) {
643 $grades = $this->get_final();
644 foreach($grades as $g) {
645 $grade = new grade_grade($g, false);
646 $grade->grade_item =& $this;
647 $grade->set_locked(1, null, false);
651 return true;
653 } else {
654 /// removing lock
655 if (!empty($this->locked) and $this->locktime < time()) {
656 //we have to reset locktime or else it would lock up again
657 $this->locktime = 0;
660 $this->locked = 0;
661 $this->update();
663 if ($cascade) {
664 if ($grades = grade_grade::fetch_all(array('itemid'=>$this->id))) {
665 foreach($grades as $grade) {
666 $grade->grade_item =& $this;
667 $grade->set_locked(0, null, false);
672 if ($refresh) {
673 //refresh when unlocking
674 $this->refresh_grades();
677 return true;
682 * Lock the grade if needed. Make sure this is called only when final grades are valid
684 public function check_locktime() {
685 if (!empty($this->locked)) {
686 return; // already locked
689 if ($this->locktime and $this->locktime < time()) {
690 $this->locked = time();
691 $this->update('locktime');
696 * Set the locktime for this grade item.
698 * @param int $locktime timestamp for lock to activate
699 * @return void
701 public function set_locktime($locktime) {
702 $this->locktime = $locktime;
703 $this->update();
707 * Set the locktime for this grade item.
709 * @return int $locktime timestamp for lock to activate
711 public function get_locktime() {
712 return $this->locktime;
716 * Set the hidden status of grade_item and all grades.
718 * 0 mean always visible, 1 means always hidden and a number > 1 is a timestamp to hide until
720 * @param int $hidden new hidden status
721 * @param bool $cascade apply to child objects too
723 public function set_hidden($hidden, $cascade=false) {
724 parent::set_hidden($hidden, $cascade);
726 if ($cascade) {
727 if ($grades = grade_grade::fetch_all(array('itemid'=>$this->id))) {
728 foreach($grades as $grade) {
729 $grade->grade_item =& $this;
730 $grade->set_hidden($hidden, $cascade);
735 //if marking item visible make sure category is visible MDL-21367
736 if( !$hidden ) {
737 $category_array = grade_category::fetch_all(array('id'=>$this->categoryid));
738 if ($category_array && array_key_exists($this->categoryid, $category_array)) {
739 $category = $category_array[$this->categoryid];
740 //call set_hidden on the category regardless of whether it is hidden as its parent might be hidden
741 $category->set_hidden($hidden, false);
747 * Returns the number of grades that are hidden
749 * @param string $groupsql SQL to limit the query by group
750 * @param array $params SQL params for $groupsql
751 * @param string $groupwheresql Where conditions for $groupsql
752 * @return int The number of hidden grades
754 public function has_hidden_grades($groupsql="", array $params=null, $groupwheresql="") {
755 global $DB;
756 $params = (array)$params;
757 $params['itemid'] = $this->id;
759 return $DB->get_field_sql("SELECT COUNT(*) FROM {grade_grades} g LEFT JOIN "
760 ."{user} u ON g.userid = u.id $groupsql WHERE itemid = :itemid AND hidden = 1 $groupwheresql", $params);
764 * Mark regrading as finished successfully. This will also be called when subsequent regrading will not change any grades.
765 * Situations such as an error being found will still result in the regrading being finished.
767 public function regrading_finished() {
768 global $DB;
769 $this->needsupdate = 0;
770 //do not use $this->update() because we do not want this logged in grade_item_history
771 $DB->set_field('grade_items', 'needsupdate', 0, array('id' => $this->id));
775 * Performs the necessary calculations on the grades_final referenced by this grade_item.
776 * Also resets the needsupdate flag once successfully performed.
778 * This function must be used ONLY from lib/gradeslib.php/grade_regrade_final_grades(),
779 * because the regrading must be done in correct order!!
781 * @param int $userid Supply a user ID to limit the regrading to a single user
782 * @return bool true if ok, error string otherwise
784 public function regrade_final_grades($userid=null) {
785 global $CFG, $DB;
787 // locked grade items already have correct final grades
788 if ($this->is_locked()) {
789 return true;
792 // calculation produces final value using formula from other final values
793 if ($this->is_calculated()) {
794 if ($this->compute($userid)) {
795 return true;
796 } else {
797 return "Could not calculate grades for grade item"; // TODO: improve and localize
800 // noncalculated outcomes already have final values - raw grades not used
801 } else if ($this->is_outcome_item()) {
802 return true;
804 // aggregate the category grade
805 } else if ($this->is_category_item() or $this->is_course_item()) {
806 // aggregate category grade item
807 $category = $this->load_item_category();
808 $category->grade_item =& $this;
809 if ($category->generate_grades($userid)) {
810 return true;
811 } else {
812 return "Could not aggregate final grades for category:".$this->id; // TODO: improve and localize
815 } else if ($this->is_manual_item()) {
816 // manual items track only final grades, no raw grades
817 return true;
819 } else if (!$this->is_raw_used()) {
820 // hmm - raw grades are not used- nothing to regrade
821 return true;
824 // normal grade item - just new final grades
825 $result = true;
826 $grade_inst = new grade_grade();
827 $fields = implode(',', $grade_inst->required_fields);
828 if ($userid) {
829 $params = array($this->id, $userid);
830 $rs = $DB->get_recordset_select('grade_grades', "itemid=? AND userid=?", $params, '', $fields);
831 } else {
832 $rs = $DB->get_recordset('grade_grades', array('itemid' => $this->id), '', $fields);
834 if ($rs) {
835 foreach ($rs as $grade_record) {
836 $grade = new grade_grade($grade_record, false);
838 if (!empty($grade_record->locked) or !empty($grade_record->overridden)) {
839 // this grade is locked - final grade must be ok
840 continue;
843 $grade->finalgrade = $this->adjust_raw_grade($grade->rawgrade, $grade->rawgrademin, $grade->rawgrademax);
845 if (grade_floats_different($grade_record->finalgrade, $grade->finalgrade)) {
846 $success = $grade->update('system');
848 // If successful trigger a user_graded event.
849 if ($success) {
850 $grade->load_grade_item();
851 \core\event\user_graded::create_from_grade($grade, \core\event\base::USER_OTHER)->trigger();
852 } else {
853 $result = "Internal error updating final grade";
857 $rs->close();
860 return $result;
864 * Given a float grade value or integer grade scale, applies a number of adjustment based on
865 * grade_item variables and returns the result.
867 * @param float $rawgrade The raw grade value
868 * @param float $rawmin original rawmin
869 * @param float $rawmax original rawmax
870 * @return mixed
872 public function adjust_raw_grade($rawgrade, $rawmin, $rawmax) {
873 if (is_null($rawgrade)) {
874 return null;
877 if ($this->gradetype == GRADE_TYPE_VALUE) { // Dealing with numerical grade
879 if ($this->grademax < $this->grademin) {
880 return null;
883 if ($this->grademax == $this->grademin) {
884 return $this->grademax; // no range
887 // Standardise score to the new grade range
888 // NOTE: skip if the activity provides a manual rescaling option.
889 $manuallyrescale = (component_callback_exists('mod_' . $this->itemmodule, 'rescale_activity_grades') !== false);
890 if (!$manuallyrescale && ($rawmin != $this->grademin or $rawmax != $this->grademax)) {
891 $rawgrade = grade_grade::standardise_score($rawgrade, $rawmin, $rawmax, $this->grademin, $this->grademax);
894 // Apply other grade_item factors
895 $rawgrade *= $this->multfactor;
896 $rawgrade += $this->plusfactor;
898 return $this->bounded_grade($rawgrade);
900 } else if ($this->gradetype == GRADE_TYPE_SCALE) { // Dealing with a scale value
901 if (empty($this->scale)) {
902 $this->load_scale();
905 if ($this->grademax < 0) {
906 return null; // scale not present - no grade
909 if ($this->grademax == 0) {
910 return $this->grademax; // only one option
913 // Convert scale if needed
914 // NOTE: skip if the activity provides a manual rescaling option.
915 $manuallyrescale = (component_callback_exists('mod_' . $this->itemmodule, 'rescale_activity_grades') !== false);
916 if (!$manuallyrescale && ($rawmin != $this->grademin or $rawmax != $this->grademax)) {
917 // This should never happen because scales are locked if they are in use.
918 $rawgrade = grade_grade::standardise_score($rawgrade, $rawmin, $rawmax, $this->grademin, $this->grademax);
921 return $this->bounded_grade($rawgrade);
924 } else if ($this->gradetype == GRADE_TYPE_TEXT or $this->gradetype == GRADE_TYPE_NONE) { // no value
925 // somebody changed the grading type when grades already existed
926 return null;
928 } else {
929 debugging("Unknown grade type");
930 return null;
935 * Update the rawgrademax and rawgrademin for all grade_grades records for this item.
936 * Scale every rawgrade to maintain the percentage. This function should be called
937 * after the gradeitem has been updated to the new min and max values.
939 * @param float $oldgrademin The previous grade min value
940 * @param float $oldgrademax The previous grade max value
941 * @param float $newgrademin The new grade min value
942 * @param float $newgrademax The new grade max value
943 * @param string $source from where was the object inserted (mod/forum, manual, etc.)
944 * @return bool True on success
946 public function rescale_grades_keep_percentage($oldgrademin, $oldgrademax, $newgrademin, $newgrademax, $source = null) {
947 global $DB;
949 if (empty($this->id)) {
950 return false;
953 if ($oldgrademax <= $oldgrademin) {
954 // Grades cannot be scaled.
955 return false;
957 $scale = ($newgrademax - $newgrademin) / ($oldgrademax - $oldgrademin);
958 if (($newgrademax - $newgrademin) <= 1) {
959 // We would lose too much precision, lets bail.
960 return false;
963 $rs = $DB->get_recordset('grade_grades', array('itemid' => $this->id));
965 foreach ($rs as $graderecord) {
966 // For each record, create an object to work on.
967 $grade = new grade_grade($graderecord, false);
968 // Set this object in the item so it doesn't re-fetch it.
969 $grade->grade_item = $this;
971 if (!$this->is_category_item() || ($this->is_category_item() && $grade->is_overridden())) {
972 // Updating the raw grade automatically updates the min/max.
973 if ($this->is_raw_used()) {
974 $rawgrade = (($grade->rawgrade - $oldgrademin) * $scale) + $newgrademin;
975 $this->update_raw_grade(false, $rawgrade, $source, false, FORMAT_MOODLE, null, null, null, $grade);
976 } else {
977 $finalgrade = (($grade->finalgrade - $oldgrademin) * $scale) + $newgrademin;
978 $this->update_final_grade($grade->userid, $finalgrade, $source);
982 $rs->close();
984 // Mark this item for regrading.
985 $this->force_regrading();
987 return true;
991 * Sets this grade_item's needsupdate to true. Also marks the course item as needing update.
993 * @return void
995 public function force_regrading() {
996 global $DB;
997 $this->needsupdate = 1;
998 //mark this item and course item only - categories and calculated items are always regraded
999 $wheresql = "(itemtype='course' OR id=?) AND courseid=?";
1000 $params = array($this->id, $this->courseid);
1001 $DB->set_field_select('grade_items', 'needsupdate', 1, $wheresql, $params);
1005 * Instantiates a grade_scale object from the DB if this item's scaleid variable is set
1007 * @return grade_scale Returns a grade_scale object or null if no scale used
1009 public function load_scale() {
1010 if ($this->gradetype != GRADE_TYPE_SCALE) {
1011 $this->scaleid = null;
1014 if (!empty($this->scaleid)) {
1015 //do not load scale if already present
1016 if (empty($this->scale->id) or $this->scale->id != $this->scaleid) {
1017 $this->scale = grade_scale::fetch(array('id'=>$this->scaleid));
1018 if (!$this->scale) {
1019 debugging('Incorrect scale id: '.$this->scaleid);
1020 $this->scale = null;
1021 return null;
1023 $this->scale->load_items();
1026 // Until scales are uniformly set to min=0 max=count(scaleitems)-1 throughout Moodle, we
1027 // stay with the current min=1 max=count(scaleitems)
1028 $this->grademax = count($this->scale->scale_items);
1029 $this->grademin = 1;
1031 } else {
1032 $this->scale = null;
1035 return $this->scale;
1039 * Instantiates a grade_outcome object from the DB if this item's outcomeid variable is set
1041 * @return grade_outcome This grade item's associated grade_outcome or null
1043 public function load_outcome() {
1044 if (!empty($this->outcomeid)) {
1045 $this->outcome = grade_outcome::fetch(array('id'=>$this->outcomeid));
1047 return $this->outcome;
1051 * Returns the grade_category object this grade_item belongs to (referenced by categoryid)
1052 * or category attached to category item.
1054 * @return grade_category|bool Returns a grade_category object if applicable or false if this is a course item
1056 public function get_parent_category() {
1057 if ($this->is_category_item() or $this->is_course_item()) {
1058 return $this->get_item_category();
1060 } else {
1061 return grade_category::fetch(array('id'=>$this->categoryid));
1066 * Calls upon the get_parent_category method to retrieve the grade_category object
1067 * from the DB and assigns it to $this->parent_category. It also returns the object.
1069 * @return grade_category This grade item's parent grade_category.
1071 public function load_parent_category() {
1072 if (empty($this->parent_category->id)) {
1073 $this->parent_category = $this->get_parent_category();
1075 return $this->parent_category;
1079 * Returns the grade_category for a grade category grade item
1081 * @return grade_category|bool Returns a grade_category instance if applicable or false otherwise
1083 public function get_item_category() {
1084 if (!$this->is_course_item() and !$this->is_category_item()) {
1085 return false;
1087 return grade_category::fetch(array('id'=>$this->iteminstance));
1091 * Calls upon the get_item_category method to retrieve the grade_category object
1092 * from the DB and assigns it to $this->item_category. It also returns the object.
1094 * @return grade_category
1096 public function load_item_category() {
1097 if (empty($this->item_category->id)) {
1098 $this->item_category = $this->get_item_category();
1100 return $this->item_category;
1104 * Is the grade item associated with category?
1106 * @return bool
1108 public function is_category_item() {
1109 return ($this->itemtype == 'category');
1113 * Is the grade item associated with course?
1115 * @return bool
1117 public function is_course_item() {
1118 return ($this->itemtype == 'course');
1122 * Is this a manually graded item?
1124 * @return bool
1126 public function is_manual_item() {
1127 return ($this->itemtype == 'manual');
1131 * Is this an outcome item?
1133 * @return bool
1135 public function is_outcome_item() {
1136 return !empty($this->outcomeid);
1140 * Is the grade item external - associated with module, plugin or something else?
1142 * @return bool
1144 public function is_external_item() {
1145 return ($this->itemtype == 'mod');
1149 * Is the grade item overridable
1151 * @return bool
1153 public function is_overridable_item() {
1154 if ($this->is_course_item() or $this->is_category_item()) {
1155 $overridable = (bool) get_config('moodle', 'grade_overridecat');
1156 } else {
1157 $overridable = false;
1160 return !$this->is_outcome_item() and ($this->is_external_item() or $this->is_calculated() or $overridable);
1164 * Is the grade item feedback overridable
1166 * @return bool
1168 public function is_overridable_item_feedback() {
1169 return !$this->is_outcome_item() and $this->is_external_item();
1173 * Returns true if grade items uses raw grades
1175 * @return bool
1177 public function is_raw_used() {
1178 return ($this->is_external_item() and !$this->is_calculated() and !$this->is_outcome_item());
1182 * Returns true if the grade item is an aggreggated type grade.
1184 * @since Moodle 2.8.7, 2.9.1
1185 * @return bool
1187 public function is_aggregate_item() {
1188 return ($this->is_category_item() || $this->is_course_item());
1192 * Returns the grade item associated with the course
1194 * @param int $courseid
1195 * @return grade_item Course level grade item object
1197 public static function fetch_course_item($courseid) {
1198 if ($course_item = grade_item::fetch(array('courseid'=>$courseid, 'itemtype'=>'course'))) {
1199 return $course_item;
1202 // first get category - it creates the associated grade item
1203 $course_category = grade_category::fetch_course_category($courseid);
1204 return $course_category->get_grade_item();
1208 * Is grading object editable?
1210 * @return bool
1212 public function is_editable() {
1213 return true;
1217 * Checks if grade calculated. Returns this object's calculation.
1219 * @return bool true if grade item calculated.
1221 public function is_calculated() {
1222 if (empty($this->calculation)) {
1223 return false;
1227 * The main reason why we use the ##gixxx## instead of [[idnumber]] is speed of depends_on(),
1228 * we would have to fetch all course grade items to find out the ids.
1229 * Also if user changes the idnumber the formula does not need to be updated.
1232 // first detect if we need to change calculation formula from [[idnumber]] to ##giXXX## (after backup, etc.)
1233 if (!$this->calculation_normalized and strpos($this->calculation, '[[') !== false) {
1234 $this->set_calculation($this->calculation);
1237 return !empty($this->calculation);
1241 * Returns calculation string if grade calculated.
1243 * @return string Returns the grade item's calculation if calculation is used, null if not
1245 public function get_calculation() {
1246 if ($this->is_calculated()) {
1247 return grade_item::denormalize_formula($this->calculation, $this->courseid);
1249 } else {
1250 return NULL;
1255 * Sets this item's calculation (creates it) if not yet set, or
1256 * updates it if already set (in the DB). If no calculation is given,
1257 * the calculation is removed.
1259 * @param string $formula string representation of formula used for calculation
1260 * @return bool success
1262 public function set_calculation($formula) {
1263 $this->calculation = grade_item::normalize_formula($formula, $this->courseid);
1264 $this->calculation_normalized = true;
1265 return $this->update();
1269 * Denormalizes the calculation formula to [idnumber] form
1271 * @param string $formula A string representation of the formula
1272 * @param int $courseid The course ID
1273 * @return string The denormalized formula as a string
1275 public static function denormalize_formula($formula, $courseid) {
1276 if (empty($formula)) {
1277 return '';
1280 // denormalize formula - convert ##giXX## to [[idnumber]]
1281 if (preg_match_all('/##gi(\d+)##/', $formula, $matches)) {
1282 foreach ($matches[1] as $id) {
1283 if ($grade_item = grade_item::fetch(array('id'=>$id, 'courseid'=>$courseid))) {
1284 if (!empty($grade_item->idnumber)) {
1285 $formula = str_replace('##gi'.$grade_item->id.'##', '[['.$grade_item->idnumber.']]', $formula);
1291 return $formula;
1296 * Normalizes the calculation formula to [#giXX#] form
1298 * @param string $formula The formula
1299 * @param int $courseid The course ID
1300 * @return string The normalized formula as a string
1302 public static function normalize_formula($formula, $courseid) {
1303 $formula = trim($formula);
1305 if (empty($formula)) {
1306 return NULL;
1310 // normalize formula - we want grade item ids ##giXXX## instead of [[idnumber]]
1311 if ($grade_items = grade_item::fetch_all(array('courseid'=>$courseid))) {
1312 foreach ($grade_items as $grade_item) {
1313 $formula = str_replace('[['.$grade_item->idnumber.']]', '##gi'.$grade_item->id.'##', $formula);
1317 return $formula;
1321 * Returns the final values for this grade item (as imported by module or other source).
1323 * @param int $userid Optional: to retrieve a single user's final grade
1324 * @return array|grade_grade An array of all grade_grade instances for this grade_item, or a single grade_grade instance.
1326 public function get_final($userid=NULL) {
1327 global $DB;
1328 if ($userid) {
1329 if ($user = $DB->get_record('grade_grades', array('itemid' => $this->id, 'userid' => $userid))) {
1330 return $user;
1333 } else {
1334 if ($grades = $DB->get_records('grade_grades', array('itemid' => $this->id))) {
1335 //TODO: speed up with better SQL (MDL-31380)
1336 $result = array();
1337 foreach ($grades as $grade) {
1338 $result[$grade->userid] = $grade;
1340 return $result;
1341 } else {
1342 return array();
1348 * Get (or create if not exist yet) grade for this user
1350 * @param int $userid The user ID
1351 * @param bool $create If true and the user has no grade for this grade item a new grade_grade instance will be inserted
1352 * @return grade_grade The grade_grade instance for the user for this grade item
1354 public function get_grade($userid, $create=true) {
1355 if (empty($this->id)) {
1356 debugging('Can not use before insert');
1357 return false;
1360 $grade = new grade_grade(array('userid'=>$userid, 'itemid'=>$this->id));
1361 if (empty($grade->id) and $create) {
1362 $grade->insert();
1365 return $grade;
1369 * Returns the sortorder of this grade_item. This method is also available in
1370 * grade_category, for cases where the object type is not know.
1372 * @return int Sort order
1374 public function get_sortorder() {
1375 return $this->sortorder;
1379 * Returns the idnumber of this grade_item. This method is also available in
1380 * grade_category, for cases where the object type is not know.
1382 * @return string The grade item idnumber
1384 public function get_idnumber() {
1385 return $this->idnumber;
1389 * Returns this grade_item. This method is also available in
1390 * grade_category, for cases where the object type is not know.
1392 * @return grade_item
1394 public function get_grade_item() {
1395 return $this;
1399 * Sets the sortorder of this grade_item. This method is also available in
1400 * grade_category, for cases where the object type is not know.
1402 * @param int $sortorder
1404 public function set_sortorder($sortorder) {
1405 if ($this->sortorder == $sortorder) {
1406 return;
1408 $this->sortorder = $sortorder;
1409 $this->update();
1413 * Update this grade item's sortorder so that it will appear after $sortorder
1415 * @param int $sortorder The sort order to place this grade item after
1417 public function move_after_sortorder($sortorder) {
1418 global $CFG, $DB;
1420 //make some room first
1421 $params = array($sortorder, $this->courseid);
1422 $sql = "UPDATE {grade_items}
1423 SET sortorder = sortorder + 1
1424 WHERE sortorder > ? AND courseid = ?";
1425 $DB->execute($sql, $params);
1427 $this->set_sortorder($sortorder + 1);
1431 * Detect duplicate grade item's sortorder and re-sort them.
1432 * Note: Duplicate sortorder will be introduced while duplicating activities or
1433 * merging two courses.
1435 * @param int $courseid id of the course for which grade_items sortorder need to be fixed.
1437 public static function fix_duplicate_sortorder($courseid) {
1438 global $DB;
1440 $transaction = $DB->start_delegated_transaction();
1442 $sql = "SELECT DISTINCT g1.id, g1.courseid, g1.sortorder
1443 FROM {grade_items} g1
1444 JOIN {grade_items} g2 ON g1.courseid = g2.courseid
1445 WHERE g1.sortorder = g2.sortorder AND g1.id != g2.id AND g1.courseid = :courseid
1446 ORDER BY g1.sortorder DESC, g1.id DESC";
1448 // Get all duplicates in course highest sort order, and higest id first so that we can make space at the
1449 // bottom higher end of the sort orders and work down by id.
1450 $rs = $DB->get_recordset_sql($sql, array('courseid' => $courseid));
1452 foreach($rs as $duplicate) {
1453 $DB->execute("UPDATE {grade_items}
1454 SET sortorder = sortorder + 1
1455 WHERE courseid = :courseid AND
1456 (sortorder > :sortorder OR (sortorder = :sortorder2 AND id > :id))",
1457 array('courseid' => $duplicate->courseid,
1458 'sortorder' => $duplicate->sortorder,
1459 'sortorder2' => $duplicate->sortorder,
1460 'id' => $duplicate->id));
1462 $rs->close();
1463 $transaction->allow_commit();
1467 * Returns the most descriptive field for this object.
1469 * Determines what type of grade item it is then returns the appropriate string
1471 * @param bool $fulltotal If the item is a category total, returns $categoryname."total" instead of "Category total" or "Course total"
1472 * @return string name
1474 public function get_name($fulltotal=false) {
1475 global $CFG;
1476 require_once($CFG->dirroot . '/course/lib.php');
1477 if (strval($this->itemname) !== '') {
1478 // MDL-10557
1480 // Make it obvious to users if the course module to which this grade item relates, is currently being removed.
1481 $deletionpending = course_module_instance_pending_deletion($this->courseid, $this->itemmodule, $this->iteminstance);
1482 $deletionnotice = get_string('gradesmoduledeletionprefix', 'grades');
1484 $options = ['context' => context_course::instance($this->courseid)];
1485 return $deletionpending ?
1486 format_string($deletionnotice . ' ' . $this->itemname, true, $options) :
1487 format_string($this->itemname, true, $options);
1489 } else if ($this->is_course_item()) {
1490 return get_string('coursetotal', 'grades');
1492 } else if ($this->is_category_item()) {
1493 if ($fulltotal) {
1494 $category = $this->load_parent_category();
1495 $a = new stdClass();
1496 $a->category = $category->get_name();
1497 return get_string('categorytotalfull', 'grades', $a);
1498 } else {
1499 return get_string('categorytotal', 'grades');
1502 } else {
1503 return get_string('grade');
1508 * A grade item can return a more detailed description which will be added to the header of the column/row in some reports.
1510 * @return string description
1512 public function get_description() {
1513 if ($this->is_course_item() || $this->is_category_item()) {
1514 $categoryitem = $this->load_item_category();
1515 return $categoryitem->get_description();
1517 return '';
1521 * Sets this item's categoryid. A generic method shared by objects that have a parent id of some kind.
1523 * @param int $parentid The ID of the new parent
1524 * @param bool $updateaggregationfields Whether or not to convert the aggregation fields when switching between category.
1525 * Set this to false when the aggregation fields have been updated in prevision of the new
1526 * category, typically when the item is freshly created.
1527 * @return bool True if success
1529 public function set_parent($parentid, $updateaggregationfields = true) {
1530 if ($this->is_course_item() or $this->is_category_item()) {
1531 print_error('cannotsetparentforcatoritem');
1534 if ($this->categoryid == $parentid) {
1535 return true;
1538 // find parent and check course id
1539 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
1540 return false;
1543 $currentparent = $this->load_parent_category();
1545 if ($updateaggregationfields) {
1546 $this->set_aggregation_fields_for_aggregation($currentparent->aggregation, $parent_category->aggregation);
1549 $this->force_regrading();
1551 // set new parent
1552 $this->categoryid = $parent_category->id;
1553 $this->parent_category =& $parent_category;
1555 return $this->update();
1559 * Update the aggregation fields when the aggregation changed.
1561 * This method should always be called when the aggregation has changed, but also when
1562 * the item was moved to another category, even it if uses the same aggregation method.
1564 * Some values such as the weight only make sense within a category, once moved the
1565 * values should be reset to let the user adapt them accordingly.
1567 * Note that this method does not save the grade item.
1568 * {@link grade_item::update()} has to be called manually after using this method.
1570 * @param int $from Aggregation method constant value.
1571 * @param int $to Aggregation method constant value.
1572 * @return boolean True when at least one field was changed, false otherwise
1574 public function set_aggregation_fields_for_aggregation($from, $to) {
1575 $defaults = grade_category::get_default_aggregation_coefficient_values($to);
1577 $origaggregationcoef = $this->aggregationcoef;
1578 $origaggregationcoef2 = $this->aggregationcoef2;
1579 $origweighoverride = $this->weightoverride;
1581 if ($from == GRADE_AGGREGATE_SUM && $to == GRADE_AGGREGATE_SUM && $this->weightoverride) {
1582 // Do nothing. We are switching from SUM to SUM and the weight is overriden,
1583 // a teacher would not expect any change in this situation.
1585 } else if ($from == GRADE_AGGREGATE_WEIGHTED_MEAN && $to == GRADE_AGGREGATE_WEIGHTED_MEAN) {
1586 // Do nothing. The weights can be kept in this case.
1588 } else if (in_array($from, array(GRADE_AGGREGATE_SUM, GRADE_AGGREGATE_EXTRACREDIT_MEAN, GRADE_AGGREGATE_WEIGHTED_MEAN2))
1589 && in_array($to, array(GRADE_AGGREGATE_SUM, GRADE_AGGREGATE_EXTRACREDIT_MEAN, GRADE_AGGREGATE_WEIGHTED_MEAN2))) {
1591 // Reset all but the the extra credit field.
1592 $this->aggregationcoef2 = $defaults['aggregationcoef2'];
1593 $this->weightoverride = $defaults['weightoverride'];
1595 if ($to != GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
1596 // Normalise extra credit, except for 'Mean with extra credit' which supports higher values than 1.
1597 $this->aggregationcoef = min(1, $this->aggregationcoef);
1599 } else {
1600 // Reset all.
1601 $this->aggregationcoef = $defaults['aggregationcoef'];
1602 $this->aggregationcoef2 = $defaults['aggregationcoef2'];
1603 $this->weightoverride = $defaults['weightoverride'];
1606 $acoefdiff = grade_floats_different($origaggregationcoef, $this->aggregationcoef);
1607 $acoefdiff2 = grade_floats_different($origaggregationcoef2, $this->aggregationcoef2);
1608 $weightoverride = grade_floats_different($origweighoverride, $this->weightoverride);
1610 return $acoefdiff || $acoefdiff2 || $weightoverride;
1614 * Makes sure value is a valid grade value.
1616 * @param float $gradevalue
1617 * @return mixed float or int fixed grade value
1619 public function bounded_grade($gradevalue) {
1620 global $CFG;
1622 if (is_null($gradevalue)) {
1623 return null;
1626 if ($this->gradetype == GRADE_TYPE_SCALE) {
1627 // no >100% grades hack for scale grades!
1628 // 1.5 is rounded to 2 ;-)
1629 return (int)bounded_number($this->grademin, round($gradevalue+0.00001), $this->grademax);
1632 $grademax = $this->grademax;
1634 // NOTE: if you change this value you must manually reset the needsupdate flag in all grade items
1635 $maxcoef = isset($CFG->gradeoverhundredprocentmax) ? $CFG->gradeoverhundredprocentmax : 10; // 1000% max by default
1637 if (!empty($CFG->unlimitedgrades)) {
1638 // NOTE: if you change this value you must manually reset the needsupdate flag in all grade items
1639 $grademax = $grademax * $maxcoef;
1640 } else if ($this->is_category_item() or $this->is_course_item()) {
1641 $category = $this->load_item_category();
1642 if ($category->aggregation >= 100) {
1643 // grade >100% hack
1644 $grademax = $grademax * $maxcoef;
1648 return (float)bounded_number($this->grademin, $gradevalue, $grademax);
1652 * Finds out on which other items does this depend directly when doing calculation or category aggregation
1654 * @param bool $reset_cache
1655 * @return array of grade_item IDs this one depends on
1657 public function depends_on($reset_cache=false) {
1658 global $CFG, $DB;
1660 if ($reset_cache) {
1661 $this->dependson_cache = null;
1662 } else if (isset($this->dependson_cache)) {
1663 return $this->dependson_cache;
1666 if ($this->is_locked() && !$this->is_category_item()) {
1667 // locked items do not need to be regraded
1668 $this->dependson_cache = array();
1669 return $this->dependson_cache;
1672 if ($this->is_calculated()) {
1673 if (preg_match_all('/##gi(\d+)##/', $this->calculation, $matches)) {
1674 $this->dependson_cache = array_unique($matches[1]); // remove duplicates
1675 return $this->dependson_cache;
1676 } else {
1677 $this->dependson_cache = array();
1678 return $this->dependson_cache;
1681 } else if ($grade_category = $this->load_item_category()) {
1682 $params = array();
1684 //only items with numeric or scale values can be aggregated
1685 if ($this->gradetype != GRADE_TYPE_VALUE and $this->gradetype != GRADE_TYPE_SCALE) {
1686 $this->dependson_cache = array();
1687 return $this->dependson_cache;
1690 $grade_category->apply_forced_settings();
1692 if (empty($CFG->enableoutcomes) or $grade_category->aggregateoutcomes) {
1693 $outcomes_sql = "";
1694 } else {
1695 $outcomes_sql = "AND gi.outcomeid IS NULL";
1698 if (empty($CFG->grade_includescalesinaggregation)) {
1699 $gtypes = "gi.gradetype = ?";
1700 $params[] = GRADE_TYPE_VALUE;
1701 } else {
1702 $gtypes = "(gi.gradetype = ? OR gi.gradetype = ?)";
1703 $params[] = GRADE_TYPE_VALUE;
1704 $params[] = GRADE_TYPE_SCALE;
1707 $params[] = $grade_category->id;
1708 $params[] = $this->courseid;
1709 $params[] = $grade_category->id;
1710 $params[] = $this->courseid;
1711 if (empty($CFG->grade_includescalesinaggregation)) {
1712 $params[] = GRADE_TYPE_VALUE;
1713 } else {
1714 $params[] = GRADE_TYPE_VALUE;
1715 $params[] = GRADE_TYPE_SCALE;
1717 $sql = "SELECT gi.id
1718 FROM {grade_items} gi
1719 WHERE $gtypes
1720 AND gi.categoryid = ?
1721 AND gi.courseid = ?
1722 $outcomes_sql
1723 UNION
1725 SELECT gi.id
1726 FROM {grade_items} gi, {grade_categories} gc
1727 WHERE (gi.itemtype = 'category' OR gi.itemtype = 'course') AND gi.iteminstance=gc.id
1728 AND gc.parent = ?
1729 AND gi.courseid = ?
1730 AND $gtypes
1731 $outcomes_sql";
1733 if ($children = $DB->get_records_sql($sql, $params)) {
1734 $this->dependson_cache = array_keys($children);
1735 return $this->dependson_cache;
1736 } else {
1737 $this->dependson_cache = array();
1738 return $this->dependson_cache;
1741 } else {
1742 $this->dependson_cache = array();
1743 return $this->dependson_cache;
1748 * Refetch grades from modules, plugins.
1750 * @param int $userid optional, limit the refetch to a single user
1751 * @return bool Returns true on success or if there is nothing to do
1753 public function refresh_grades($userid=0) {
1754 global $DB;
1755 if ($this->itemtype == 'mod') {
1756 if ($this->is_outcome_item()) {
1757 //nothing to do
1758 return true;
1761 if (!$activity = $DB->get_record($this->itemmodule, array('id' => $this->iteminstance))) {
1762 debugging("Can not find $this->itemmodule activity with id $this->iteminstance");
1763 return false;
1766 if (!$cm = get_coursemodule_from_instance($this->itemmodule, $activity->id, $this->courseid)) {
1767 debugging('Can not find course module');
1768 return false;
1771 $activity->modname = $this->itemmodule;
1772 $activity->cmidnumber = $cm->idnumber;
1774 return grade_update_mod_grades($activity, $userid);
1777 return true;
1781 * Updates final grade value for given user, this is a only way to update final
1782 * grades from gradebook and import because it logs the change in history table
1783 * and deals with overridden flag. This flag is set to prevent later overriding
1784 * from raw grades submitted from modules.
1786 * @param int $userid The graded user
1787 * @param float|false $finalgrade The float value of final grade, false means do not change
1788 * @param string $source The modification source
1789 * @param string $feedback Optional teacher feedback
1790 * @param int $feedbackformat A format like FORMAT_PLAIN or FORMAT_HTML
1791 * @param int $usermodified The ID of the user making the modification
1792 * @param int $timemodified Optional parameter to set the time modified, if not present current time.
1793 * @return bool success
1795 public function update_final_grade($userid, $finalgrade = false,
1796 $source = null, $feedback = false,
1797 $feedbackformat = FORMAT_MOODLE,
1798 $usermodified = null, $timemodified = null) {
1799 global $USER, $CFG;
1801 $result = true;
1803 // no grading used or locked
1804 if ($this->gradetype == GRADE_TYPE_NONE or $this->is_locked()) {
1805 return false;
1808 $grade = new grade_grade(array('itemid'=>$this->id, 'userid'=>$userid));
1809 $grade->grade_item =& $this; // prevent db fetching of this grade_item
1811 if (empty($usermodified)) {
1812 $grade->usermodified = $USER->id;
1813 } else {
1814 $grade->usermodified = $usermodified;
1817 if ($grade->is_locked()) {
1818 // do not update locked grades at all
1819 return false;
1822 $locktime = $grade->get_locktime();
1823 if ($locktime and $locktime < time()) {
1824 // do not update grades that should be already locked, force regrade instead
1825 $this->force_regrading();
1826 return false;
1829 $oldgrade = new stdClass();
1830 $oldgrade->finalgrade = $grade->finalgrade;
1831 $oldgrade->overridden = $grade->overridden;
1832 $oldgrade->feedback = $grade->feedback;
1833 $oldgrade->feedbackformat = $grade->feedbackformat;
1834 $oldgrade->rawgrademin = $grade->rawgrademin;
1835 $oldgrade->rawgrademax = $grade->rawgrademax;
1837 // MDL-31713 rawgramemin and max must be up to date so conditional access %'s works properly.
1838 $grade->rawgrademin = $this->grademin;
1839 $grade->rawgrademax = $this->grademax;
1840 $grade->rawscaleid = $this->scaleid;
1842 // changed grade?
1843 if ($finalgrade !== false) {
1844 if ($this->is_overridable_item() && $this->markasoverriddenwhengraded) {
1845 $grade->overridden = time();
1848 $grade->finalgrade = $this->bounded_grade($finalgrade);
1851 // do we have comment from teacher?
1852 if ($feedback !== false) {
1853 if ($this->is_overridable_item_feedback()) {
1854 // external items (modules, plugins) may have own feedback
1855 $grade->overridden = time();
1858 $grade->feedback = $feedback;
1859 $grade->feedbackformat = $feedbackformat;
1862 $gradechanged = false;
1863 if (empty($grade->id)) {
1864 $grade->timecreated = null; // Hack alert - date submitted - no submission yet.
1865 $grade->timemodified = $timemodified ?? time(); // Hack alert - date graded.
1866 $result = (bool)$grade->insert($source);
1868 // If the grade insert was successful and the final grade was not null then trigger a user_graded event.
1869 if ($result && !is_null($grade->finalgrade)) {
1870 \core\event\user_graded::create_from_grade($grade)->trigger();
1872 $gradechanged = true;
1873 } else {
1874 // Existing grade_grades.
1876 if (grade_floats_different($grade->finalgrade, $oldgrade->finalgrade)
1877 or grade_floats_different($grade->rawgrademin, $oldgrade->rawgrademin)
1878 or grade_floats_different($grade->rawgrademax, $oldgrade->rawgrademax)
1879 or ($oldgrade->overridden == 0 and $grade->overridden > 0)) {
1880 $gradechanged = true;
1883 if ($grade->feedback === $oldgrade->feedback and $grade->feedbackformat == $oldgrade->feedbackformat and
1884 $gradechanged === false) {
1885 // No grade nor feedback changed.
1886 return $result;
1889 $grade->timemodified = $timemodified ?? time(); // Hack alert - date graded.
1890 $result = $grade->update($source);
1892 // If the grade update was successful and the actual grade has changed then trigger a user_graded event.
1893 if ($result && grade_floats_different($grade->finalgrade, $oldgrade->finalgrade)) {
1894 \core\event\user_graded::create_from_grade($grade)->trigger();
1898 if (!$result) {
1899 // Something went wrong - better force final grade recalculation.
1900 $this->force_regrading();
1901 return $result;
1904 // If we are not updating grades we don't need to recalculate the whole course.
1905 if (!$gradechanged) {
1906 return $result;
1909 if ($this->is_course_item() and !$this->needsupdate) {
1910 if (grade_regrade_final_grades($this->courseid, $userid, $this) !== true) {
1911 $this->force_regrading();
1914 } else if (!$this->needsupdate) {
1916 $course_item = grade_item::fetch_course_item($this->courseid);
1917 if (!$course_item->needsupdate) {
1918 if (grade_regrade_final_grades($this->courseid, $userid, $this) !== true) {
1919 $this->force_regrading();
1921 } else {
1922 $this->force_regrading();
1926 return $result;
1931 * Updates raw grade value for given user, this is a only way to update raw
1932 * grades from external source (modules, etc.),
1933 * because it logs the change in history table and deals with final grade recalculation.
1935 * @param int $userid the graded user
1936 * @param mixed $rawgrade float value of raw grade - false means do not change
1937 * @param string $source modification source
1938 * @param string $feedback optional teacher feedback
1939 * @param int $feedbackformat A format like FORMAT_PLAIN or FORMAT_HTML
1940 * @param int $usermodified the ID of the user who did the grading
1941 * @param int $dategraded A timestamp of when the student's work was graded
1942 * @param int $datesubmitted A timestamp of when the student's work was submitted
1943 * @param grade_grade $grade A grade object, useful for bulk upgrades
1944 * @param array $feedbackfiles An array identifying the location of files we want to copy to the gradebook feedback area.
1945 * Example -
1947 * 'contextid' => 1,
1948 * 'component' => 'mod_xyz',
1949 * 'filearea' => 'mod_xyz_feedback',
1950 * 'itemid' => 2
1951 * ];
1952 * @return bool success
1954 public function update_raw_grade($userid, $rawgrade = false, $source = null, $feedback = false,
1955 $feedbackformat = FORMAT_MOODLE, $usermodified = null, $dategraded = null, $datesubmitted=null,
1956 $grade = null, array $feedbackfiles = []) {
1957 global $USER;
1959 $result = true;
1961 // calculated grades can not be updated; course and category can not be updated because they are aggregated
1962 if (!$this->is_raw_used() or $this->gradetype == GRADE_TYPE_NONE or $this->is_locked()) {
1963 return false;
1966 if (is_null($grade)) {
1967 //fetch from db
1968 $grade = new grade_grade(array('itemid'=>$this->id, 'userid'=>$userid));
1970 $grade->grade_item =& $this; // prevent db fetching of this grade_item
1972 if (empty($usermodified)) {
1973 $grade->usermodified = $USER->id;
1974 } else {
1975 $grade->usermodified = $usermodified;
1978 if ($grade->is_locked()) {
1979 // do not update locked grades at all
1980 return false;
1983 $locktime = $grade->get_locktime();
1984 if ($locktime and $locktime < time()) {
1985 // do not update grades that should be already locked and force regrade
1986 $this->force_regrading();
1987 return false;
1990 $oldgrade = new stdClass();
1991 $oldgrade->finalgrade = $grade->finalgrade;
1992 $oldgrade->rawgrade = $grade->rawgrade;
1993 $oldgrade->rawgrademin = $grade->rawgrademin;
1994 $oldgrade->rawgrademax = $grade->rawgrademax;
1995 $oldgrade->rawscaleid = $grade->rawscaleid;
1996 $oldgrade->feedback = $grade->feedback;
1997 $oldgrade->feedbackformat = $grade->feedbackformat;
1999 // use new min and max
2000 $grade->rawgrade = $grade->rawgrade;
2001 $grade->rawgrademin = $this->grademin;
2002 $grade->rawgrademax = $this->grademax;
2003 $grade->rawscaleid = $this->scaleid;
2005 // change raw grade?
2006 if ($rawgrade !== false) {
2007 $grade->rawgrade = $rawgrade;
2010 // empty feedback means no feedback at all
2011 if ($feedback === '') {
2012 $feedback = null;
2015 // do we have comment from teacher?
2016 if ($feedback !== false and !$grade->is_overridden()) {
2017 $grade->feedback = $feedback;
2018 $grade->feedbackformat = $feedbackformat;
2019 $grade->feedbackfiles = $feedbackfiles;
2022 // update final grade if possible
2023 if (!$grade->is_locked() and !$grade->is_overridden()) {
2024 $grade->finalgrade = $this->adjust_raw_grade($grade->rawgrade, $grade->rawgrademin, $grade->rawgrademax);
2027 // TODO: hack alert - create new fields for these in 2.0
2028 $oldgrade->timecreated = $grade->timecreated;
2029 $oldgrade->timemodified = $grade->timemodified;
2031 $grade->timecreated = $datesubmitted;
2033 if ($grade->is_overridden()) {
2034 // keep original graded date - update_final_grade() sets this for overridden grades
2036 } else if (is_null($grade->rawgrade) and is_null($grade->feedback)) {
2037 // no grade and feedback means no grading yet
2038 $grade->timemodified = null;
2040 } else if (!empty($dategraded)) {
2041 // fine - module sends info when graded (yay!)
2042 $grade->timemodified = $dategraded;
2044 } else if (grade_floats_different($grade->finalgrade, $oldgrade->finalgrade)
2045 or $grade->feedback !== $oldgrade->feedback) {
2046 // guess - if either grade or feedback changed set new graded date
2047 $grade->timemodified = time();
2049 } else {
2050 //keep original graded date
2052 // end of hack alert
2054 $gradechanged = false;
2055 if (empty($grade->id)) {
2056 $result = (bool)$grade->insert($source);
2058 // If the grade insert was successful and the final grade was not null then trigger a user_graded event.
2059 if ($result && !is_null($grade->finalgrade)) {
2060 \core\event\user_graded::create_from_grade($grade)->trigger();
2062 $gradechanged = true;
2063 } else {
2064 // Existing grade_grades.
2066 if (grade_floats_different($grade->finalgrade, $oldgrade->finalgrade)
2067 or grade_floats_different($grade->rawgrade, $oldgrade->rawgrade)
2068 or grade_floats_different($grade->rawgrademin, $oldgrade->rawgrademin)
2069 or grade_floats_different($grade->rawgrademax, $oldgrade->rawgrademax)
2070 or $grade->rawscaleid != $oldgrade->rawscaleid) {
2071 $gradechanged = true;
2074 // The timecreated and timemodified checking is part of the hack above.
2075 if ($gradechanged === false and
2076 $grade->feedback === $oldgrade->feedback and
2077 $grade->feedbackformat == $oldgrade->feedbackformat and
2078 $grade->timecreated == $oldgrade->timecreated and
2079 $grade->timemodified == $oldgrade->timemodified) {
2080 // No changes.
2081 return $result;
2083 $result = $grade->update($source);
2085 // If the grade update was successful and the actual grade has changed then trigger a user_graded event.
2086 if ($result && grade_floats_different($grade->finalgrade, $oldgrade->finalgrade)) {
2087 \core\event\user_graded::create_from_grade($grade)->trigger();
2091 if (!$result) {
2092 // Something went wrong - better force final grade recalculation.
2093 $this->force_regrading();
2094 return $result;
2097 // If we are not updating grades we don't need to recalculate the whole course.
2098 if (!$gradechanged) {
2099 return $result;
2102 if (!$this->needsupdate) {
2103 $course_item = grade_item::fetch_course_item($this->courseid);
2104 if (!$course_item->needsupdate) {
2105 if (grade_regrade_final_grades($this->courseid, $userid, $this) !== true) {
2106 $this->force_regrading();
2111 return $result;
2115 * Calculates final grade values using the formula in the calculation property.
2116 * The parameters are taken from final grades of grade items in current course only.
2118 * @param int $userid Supply a user ID to limit the calculations to the grades of a single user
2119 * @return bool false if error
2121 public function compute($userid=null) {
2122 global $CFG, $DB;
2124 if (!$this->is_calculated()) {
2125 return false;
2128 require_once($CFG->libdir.'/mathslib.php');
2130 if ($this->is_locked()) {
2131 return true; // no need to recalculate locked items
2134 // Precreate grades - we need them to exist
2135 if ($userid) {
2136 $missing = array();
2137 if (!$DB->record_exists('grade_grades', array('itemid'=>$this->id, 'userid'=>$userid))) {
2138 $m = new stdClass();
2139 $m->userid = $userid;
2140 $missing[] = $m;
2142 } else {
2143 // Find any users who have grades for some but not all grade items in this course
2144 $params = array('gicourseid' => $this->courseid, 'ggitemid' => $this->id);
2145 $sql = "SELECT gg.userid
2146 FROM {grade_grades} gg
2147 JOIN {grade_items} gi
2148 ON (gi.id = gg.itemid AND gi.courseid = :gicourseid)
2149 GROUP BY gg.userid
2150 HAVING SUM(CASE WHEN gg.itemid = :ggitemid THEN 1 ELSE 0 END) = 0";
2151 $missing = $DB->get_records_sql($sql, $params);
2154 if ($missing) {
2155 foreach ($missing as $m) {
2156 $grade = new grade_grade(array('itemid'=>$this->id, 'userid'=>$m->userid), false);
2157 $grade->grade_item =& $this;
2158 $grade->insert('system');
2162 // get used items
2163 $useditems = $this->depends_on();
2165 // prepare formula and init maths library
2166 $formula = preg_replace('/##(gi\d+)##/', '\1', $this->calculation);
2167 if (strpos($formula, '[[') !== false) {
2168 // missing item
2169 return false;
2171 $this->formula = new calc_formula($formula);
2173 // where to look for final grades?
2174 // this itemid is added so that we use only one query for source and final grades
2175 $gis = array_merge($useditems, array($this->id));
2176 list($usql, $params) = $DB->get_in_or_equal($gis);
2178 if ($userid) {
2179 $usersql = "AND g.userid=?";
2180 $params[] = $userid;
2181 } else {
2182 $usersql = "";
2185 $grade_inst = new grade_grade();
2186 $fields = 'g.'.implode(',g.', $grade_inst->required_fields);
2188 $params[] = $this->courseid;
2189 $sql = "SELECT $fields
2190 FROM {grade_grades} g, {grade_items} gi
2191 WHERE gi.id = g.itemid AND gi.id $usql $usersql AND gi.courseid=?
2192 ORDER BY g.userid";
2194 $return = true;
2196 // group the grades by userid and use formula on the group
2197 $rs = $DB->get_recordset_sql($sql, $params);
2198 if ($rs->valid()) {
2199 $prevuser = 0;
2200 $grade_records = array();
2201 $oldgrade = null;
2202 foreach ($rs as $used) {
2203 if ($used->userid != $prevuser) {
2204 if (!$this->use_formula($prevuser, $grade_records, $useditems, $oldgrade)) {
2205 $return = false;
2207 $prevuser = $used->userid;
2208 $grade_records = array();
2209 $oldgrade = null;
2211 if ($used->itemid == $this->id) {
2212 $oldgrade = $used;
2214 $grade_records['gi'.$used->itemid] = $used->finalgrade;
2216 if (!$this->use_formula($prevuser, $grade_records, $useditems, $oldgrade)) {
2217 $return = false;
2220 $rs->close();
2222 return $return;
2226 * Internal function that does the final grade calculation
2228 * @param int $userid The user ID
2229 * @param array $params An array of grade items of the form {'gi'.$itemid]} => $finalgrade
2230 * @param array $useditems An array of grade item IDs that this grade item depends on plus its own ID
2231 * @param grade_grade $oldgrade A grade_grade instance containing the old values from the database
2232 * @return bool False if an error occurred
2234 public function use_formula($userid, $params, $useditems, $oldgrade) {
2235 if (empty($userid)) {
2236 return true;
2239 // add missing final grade values
2240 // not graded (null) is counted as 0 - the spreadsheet way
2241 $allinputsnull = true;
2242 foreach($useditems as $gi) {
2243 if (!array_key_exists('gi'.$gi, $params) || is_null($params['gi'.$gi])) {
2244 $params['gi'.$gi] = 0;
2245 } else {
2246 $params['gi'.$gi] = (float)$params['gi'.$gi];
2247 if ($gi != $this->id) {
2248 $allinputsnull = false;
2253 // can not use own final grade during calculation
2254 unset($params['gi'.$this->id]);
2256 // Check to see if the gradebook is frozen. This allows grades to not be altered at all until a user verifies that they
2257 // wish to update the grades.
2258 $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->courseid);
2260 $rawminandmaxchanged = false;
2261 // insert final grade - will be needed later anyway
2262 if ($oldgrade) {
2263 // Only run through this code if the gradebook isn't frozen.
2264 if ($gradebookcalculationsfreeze && (int)$gradebookcalculationsfreeze <= 20150627) {
2265 // Do nothing.
2266 } else {
2267 // The grade_grade for a calculated item should have the raw grade maximum and minimum set to the
2268 // grade_item grade maximum and minimum respectively.
2269 if ($oldgrade->rawgrademax != $this->grademax || $oldgrade->rawgrademin != $this->grademin) {
2270 $rawminandmaxchanged = true;
2271 $oldgrade->rawgrademax = $this->grademax;
2272 $oldgrade->rawgrademin = $this->grademin;
2275 $oldfinalgrade = $oldgrade->finalgrade;
2276 $grade = new grade_grade($oldgrade, false); // fetching from db is not needed
2277 $grade->grade_item =& $this;
2279 } else {
2280 $grade = new grade_grade(array('itemid'=>$this->id, 'userid'=>$userid), false);
2281 $grade->grade_item =& $this;
2282 $rawminandmaxchanged = false;
2283 if ($gradebookcalculationsfreeze && (int)$gradebookcalculationsfreeze <= 20150627) {
2284 // Do nothing.
2285 } else {
2286 // The grade_grade for a calculated item should have the raw grade maximum and minimum set to the
2287 // grade_item grade maximum and minimum respectively.
2288 $rawminandmaxchanged = true;
2289 $grade->rawgrademax = $this->grademax;
2290 $grade->rawgrademin = $this->grademin;
2292 $grade->insert('system');
2293 $oldfinalgrade = null;
2296 // no need to recalculate locked or overridden grades
2297 if ($grade->is_locked() or $grade->is_overridden()) {
2298 return true;
2301 if ($allinputsnull) {
2302 $grade->finalgrade = null;
2303 $result = true;
2305 } else {
2307 // do the calculation
2308 $this->formula->set_params($params);
2309 $result = $this->formula->evaluate();
2311 if ($result === false) {
2312 $grade->finalgrade = null;
2314 } else {
2315 // normalize
2316 $grade->finalgrade = $this->bounded_grade($result);
2320 // Only run through this code if the gradebook isn't frozen.
2321 if ($gradebookcalculationsfreeze && (int)$gradebookcalculationsfreeze <= 20150627) {
2322 // Update in db if changed.
2323 if (grade_floats_different($grade->finalgrade, $oldfinalgrade)) {
2324 $grade->timemodified = time();
2325 $success = $grade->update('compute');
2327 // If successful trigger a user_graded event.
2328 if ($success) {
2329 \core\event\user_graded::create_from_grade($grade)->trigger();
2332 } else {
2333 // Update in db if changed.
2334 if (grade_floats_different($grade->finalgrade, $oldfinalgrade) || $rawminandmaxchanged) {
2335 $grade->timemodified = time();
2336 $success = $grade->update('compute');
2338 // If successful trigger a user_graded event.
2339 if ($success) {
2340 \core\event\user_graded::create_from_grade($grade)->trigger();
2345 if ($result !== false) {
2346 //lock grade if needed
2349 if ($result === false) {
2350 return false;
2351 } else {
2352 return true;
2358 * Validate the formula.
2360 * @param string $formulastr
2361 * @return bool true if calculation possible, false otherwise
2363 public function validate_formula($formulastr) {
2364 global $CFG, $DB;
2365 require_once($CFG->libdir.'/mathslib.php');
2367 $formulastr = grade_item::normalize_formula($formulastr, $this->courseid);
2369 if (empty($formulastr)) {
2370 return true;
2373 if (strpos($formulastr, '=') !== 0) {
2374 return get_string('errorcalculationnoequal', 'grades');
2377 // get used items
2378 if (preg_match_all('/##gi(\d+)##/', $formulastr, $matches)) {
2379 $useditems = array_unique($matches[1]); // remove duplicates
2380 } else {
2381 $useditems = array();
2384 // MDL-11902
2385 // unset the value if formula is trying to reference to itself
2386 // but array keys does not match itemid
2387 if (!empty($this->id)) {
2388 $useditems = array_diff($useditems, array($this->id));
2389 //unset($useditems[$this->id]);
2392 // prepare formula and init maths library
2393 $formula = preg_replace('/##(gi\d+)##/', '\1', $formulastr);
2394 $formula = new calc_formula($formula);
2397 if (empty($useditems)) {
2398 $grade_items = array();
2400 } else {
2401 list($usql, $params) = $DB->get_in_or_equal($useditems);
2402 $params[] = $this->courseid;
2403 $sql = "SELECT gi.*
2404 FROM {grade_items} gi
2405 WHERE gi.id $usql and gi.courseid=?"; // from the same course only!
2407 if (!$grade_items = $DB->get_records_sql($sql, $params)) {
2408 $grade_items = array();
2412 $params = array();
2413 foreach ($useditems as $itemid) {
2414 // make sure all grade items exist in this course
2415 if (!array_key_exists($itemid, $grade_items)) {
2416 return false;
2418 // use max grade when testing formula, this should be ok in 99.9%
2419 // division by 0 is one of possible problems
2420 $params['gi'.$grade_items[$itemid]->id] = $grade_items[$itemid]->grademax;
2423 // do the calculation
2424 $formula->set_params($params);
2425 $result = $formula->evaluate();
2427 // false as result indicates some problem
2428 if ($result === false) {
2429 // TODO: add more error hints
2430 return get_string('errorcalculationunknown', 'grades');
2431 } else {
2432 return true;
2437 * Returns the value of the display type
2439 * It can be set at 3 levels: grade_item, course setting and site. The lowest level overrides the higher ones.
2441 * @return int Display type
2443 public function get_displaytype() {
2444 global $CFG;
2446 if ($this->display == GRADE_DISPLAY_TYPE_DEFAULT) {
2447 return grade_get_setting($this->courseid, 'displaytype', $CFG->grade_displaytype);
2449 } else {
2450 return $this->display;
2455 * Returns the value of the decimals field
2457 * It can be set at 3 levels: grade_item, course setting and site. The lowest level overrides the higher ones.
2459 * @return int Decimals (0 - 5)
2461 public function get_decimals() {
2462 global $CFG;
2464 if (is_null($this->decimals)) {
2465 return grade_get_setting($this->courseid, 'decimalpoints', $CFG->grade_decimalpoints);
2467 } else {
2468 return $this->decimals;
2473 * Returns a string representing the range of grademin - grademax for this grade item.
2475 * @param int $rangesdisplaytype
2476 * @param int $rangesdecimalpoints
2477 * @return string
2479 function get_formatted_range($rangesdisplaytype=null, $rangesdecimalpoints=null) {
2481 global $USER;
2483 // Determine which display type to use for this average
2484 if (isset($USER->gradeediting) && array_key_exists($this->courseid, $USER->gradeediting) && $USER->gradeediting[$this->courseid]) {
2485 $displaytype = GRADE_DISPLAY_TYPE_REAL;
2487 } else if ($rangesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave report and user prefs
2488 $displaytype = $this->get_displaytype();
2490 } else {
2491 $displaytype = $rangesdisplaytype;
2494 // Override grade_item setting if a display preference (not default) was set for the averages
2495 if ($rangesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
2496 $decimalpoints = $this->get_decimals();
2498 } else {
2499 $decimalpoints = $rangesdecimalpoints;
2502 if ($displaytype == GRADE_DISPLAY_TYPE_PERCENTAGE) {
2503 $grademin = "0 %";
2504 $grademax = "100 %";
2506 } else {
2507 $grademin = grade_format_gradevalue($this->grademin, $this, true, $displaytype, $decimalpoints);
2508 $grademax = grade_format_gradevalue($this->grademax, $this, true, $displaytype, $decimalpoints);
2511 return $grademin.'&ndash;'. $grademax;
2515 * Queries parent categories recursively to find the aggregationcoef type that applies to this grade item.
2517 * @return string|false Returns the coefficient string of false is no coefficient is being used
2519 public function get_coefstring() {
2520 $parent_category = $this->load_parent_category();
2521 if ($this->is_category_item()) {
2522 $parent_category = $parent_category->load_parent_category();
2525 if ($parent_category->is_aggregationcoef_used()) {
2526 return $parent_category->get_coefstring();
2527 } else {
2528 return false;
2533 * Returns whether the grade item can control the visibility of the grades
2535 * @return bool
2537 public function can_control_visibility() {
2538 if (core_component::get_plugin_directory($this->itemtype, $this->itemmodule)) {
2539 return !plugin_supports($this->itemtype, $this->itemmodule, FEATURE_CONTROLS_GRADE_VISIBILITY, false);
2541 return parent::can_control_visibility();
2545 * Used to notify the completion system (if necessary) that a user's grade
2546 * has changed, and clear up a possible score cache.
2548 * @param bool $deleted True if grade was actually deleted
2550 protected function notify_changed($deleted) {
2551 global $CFG;
2553 // Condition code may cache the grades for conditional availability of
2554 // modules or sections. (This code should use a hook for communication
2555 // with plugin, but hooks are not implemented at time of writing.)
2556 if (!empty($CFG->enableavailability) && class_exists('\availability_grade\callbacks')) {
2557 \availability_grade\callbacks::grade_item_changed($this->courseid);
2562 * Helper function to get the accurate context for this grade column.
2564 * @return context
2566 public function get_context() {
2567 if ($this->itemtype == 'mod') {
2568 $modinfo = get_fast_modinfo($this->courseid);
2569 // Sometimes the course module cache is out of date and needs to be rebuilt.
2570 if (!isset($modinfo->instances[$this->itemmodule][$this->iteminstance])) {
2571 rebuild_course_cache($this->courseid, true);
2572 $modinfo = get_fast_modinfo($this->courseid);
2574 // Even with a rebuilt cache the module does not exist. This means the
2575 // database is in an invalid state - we will log an error and return
2576 // the course context but the calling code should be updated.
2577 if (!isset($modinfo->instances[$this->itemmodule][$this->iteminstance])) {
2578 mtrace(get_string('moduleinstancedoesnotexist', 'error'));
2579 $context = \context_course::instance($this->courseid);
2580 } else {
2581 $cm = $modinfo->instances[$this->itemmodule][$this->iteminstance];
2582 $context = \context_module::instance($cm->id);
2584 } else {
2585 $context = \context_course::instance($this->courseid);
2587 return $context;