Merge branch 'MDL-62945-master' of https://github.com/HuongNV13/moodle
[moodle.git] / lib / grade / grade_category.php
blob768d834f351e366aad69ed198bcf4e6b9028aced
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 category
20 * @package core_grades
21 * @copyright 2006 Nicolas Connault
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
27 require_once(__DIR__ . '/grade_object.php');
29 /**
30 * grade_category is an object mapped to DB table {prefix}grade_categories
32 * @package core_grades
33 * @category grade
34 * @copyright 2007 Nicolas Connault
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 class grade_category extends grade_object {
38 /**
39 * The DB table.
40 * @var string $table
42 public $table = 'grade_categories';
44 /**
45 * Array of required table fields, must start with 'id'.
46 * @var array $required_fields
48 public $required_fields = array('id', 'courseid', 'parent', 'depth', 'path', 'fullname', 'aggregation',
49 'keephigh', 'droplow', 'aggregateonlygraded', 'aggregateoutcomes',
50 'timecreated', 'timemodified', 'hidden');
52 /**
53 * The course this category belongs to.
54 * @var int $courseid
56 public $courseid;
58 /**
59 * The category this category belongs to (optional).
60 * @var int $parent
62 public $parent;
64 /**
65 * The grade_category object referenced by $this->parent (PK).
66 * @var grade_category $parent_category
68 public $parent_category;
70 /**
71 * The number of parents this category has.
72 * @var int $depth
74 public $depth = 0;
76 /**
77 * Shows the hierarchical path for this category as /1/2/3/ (like course_categories), the last number being
78 * this category's autoincrement ID number.
79 * @var string $path
81 public $path;
83 /**
84 * The name of this category.
85 * @var string $fullname
87 public $fullname;
89 /**
90 * A constant pointing to one of the predefined aggregation strategies (none, mean, median, sum etc) .
91 * @var int $aggregation
93 public $aggregation = GRADE_AGGREGATE_SUM;
95 /**
96 * Keep only the X highest items.
97 * @var int $keephigh
99 public $keephigh = 0;
102 * Drop the X lowest items.
103 * @var int $droplow
105 public $droplow = 0;
108 * Aggregate only graded items
109 * @var int $aggregateonlygraded
111 public $aggregateonlygraded = 0;
114 * Aggregate outcomes together with normal items
115 * @var int $aggregateoutcomes
117 public $aggregateoutcomes = 0;
120 * Array of grade_items or grade_categories nested exactly 1 level below this category
121 * @var array $children
123 public $children;
126 * A hierarchical array of all children below this category. This is stored separately from
127 * $children because it is more memory-intensive and may not be used as often.
128 * @var array $all_children
130 public $all_children;
133 * An associated grade_item object, with itemtype=category, used to calculate and cache a set of grade values
134 * for this category.
135 * @var grade_item $grade_item
137 public $grade_item;
140 * Temporary sortorder for speedup of children resorting
141 * @var int $sortorder
143 public $sortorder;
146 * List of options which can be "forced" from site settings.
147 * @var array $forceable
149 public $forceable = array('aggregation', 'keephigh', 'droplow', 'aggregateonlygraded', 'aggregateoutcomes');
152 * String representing the aggregation coefficient. Variable is used as cache.
153 * @var string $coefstring
155 public $coefstring = null;
158 * Static variable storing the result from {@link self::can_apply_limit_rules}.
159 * @var bool
161 protected $canapplylimitrules;
164 * Builds this category's path string based on its parents (if any) and its own id number.
165 * This is typically done just before inserting this object in the DB for the first time,
166 * or when a new parent is added or changed. It is a recursive function: once the calling
167 * object no longer has a parent, the path is complete.
169 * @param grade_category $grade_category A Grade_Category object
170 * @return string The category's path string
172 public static function build_path($grade_category) {
173 global $DB;
175 if (empty($grade_category->parent)) {
176 return '/'.$grade_category->id.'/';
178 } else {
179 $parent = $DB->get_record('grade_categories', array('id' => $grade_category->parent));
180 return grade_category::build_path($parent).$grade_category->id.'/';
185 * Finds and returns a grade_category instance based on params.
187 * @param array $params associative arrays varname=>value
188 * @return grade_category The retrieved grade_category instance or false if none found.
190 public static function fetch($params) {
191 if ($records = self::retrieve_record_set($params)) {
192 return reset($records);
195 $record = grade_object::fetch_helper('grade_categories', 'grade_category', $params);
197 // We store it as an array to keep a key => result set interface in the cache, grade_object::fetch_helper is
198 // managing exceptions. We return only the first element though.
199 $records = false;
200 if ($record) {
201 $records = array($record->id => $record);
204 self::set_record_set($params, $records);
206 return $record;
210 * Finds and returns all grade_category instances based on params.
212 * @param array $params associative arrays varname=>value
213 * @return array array of grade_category insatnces or false if none found.
215 public static function fetch_all($params) {
216 if ($records = self::retrieve_record_set($params)) {
217 return $records;
220 $records = grade_object::fetch_all_helper('grade_categories', 'grade_category', $params);
221 self::set_record_set($params, $records);
223 return $records;
227 * In addition to update() as defined in grade_object, call force_regrading of parent categories, if applicable.
229 * @param string $source from where was the object updated (mod/forum, manual, etc.)
230 * @return bool success
232 public function update($source=null) {
233 // load the grade item or create a new one
234 $this->load_grade_item();
236 // force recalculation of path;
237 if (empty($this->path)) {
238 $this->path = grade_category::build_path($this);
239 $this->depth = substr_count($this->path, '/') - 1;
240 $updatechildren = true;
242 } else {
243 $updatechildren = false;
246 $this->apply_forced_settings();
248 // these are exclusive
249 if ($this->droplow > 0) {
250 $this->keephigh = 0;
252 } else if ($this->keephigh > 0) {
253 $this->droplow = 0;
256 // Recalculate grades if needed
257 if ($this->qualifies_for_regrading()) {
258 $this->force_regrading();
261 $this->timemodified = time();
263 $result = parent::update($source);
265 // now update paths in all child categories
266 if ($result and $updatechildren) {
268 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
270 foreach ($children as $child) {
271 $child->path = null;
272 $child->depth = 0;
273 $child->update($source);
278 return $result;
282 * If parent::delete() is successful, send force_regrading message to parent category.
284 * @param string $source from where was the object deleted (mod/forum, manual, etc.)
285 * @return bool success
287 public function delete($source=null) {
288 $grade_item = $this->load_grade_item();
290 if ($this->is_course_category()) {
292 if ($categories = grade_category::fetch_all(array('courseid'=>$this->courseid))) {
294 foreach ($categories as $category) {
296 if ($category->id == $this->id) {
297 continue; // do not delete course category yet
299 $category->delete($source);
303 if ($items = grade_item::fetch_all(array('courseid'=>$this->courseid))) {
305 foreach ($items as $item) {
307 if ($item->id == $grade_item->id) {
308 continue; // do not delete course item yet
310 $item->delete($source);
314 } else {
315 $this->force_regrading();
317 $parent = $this->load_parent_category();
319 // Update children's categoryid/parent field first
320 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
321 foreach ($children as $child) {
322 $child->set_parent($parent->id);
326 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
327 foreach ($children as $child) {
328 $child->set_parent($parent->id);
333 // first delete the attached grade item and grades
334 $grade_item->delete($source);
336 // delete category itself
337 return parent::delete($source);
341 * In addition to the normal insert() defined in grade_object, this method sets the depth
342 * and path for this object, and update the record accordingly.
344 * We do this here instead of in the constructor as they both need to know the record's
345 * ID number, which only gets created at insertion time.
346 * This method also creates an associated grade_item if this wasn't done during construction.
348 * @param string $source from where was the object inserted (mod/forum, manual, etc.)
349 * @return int PK ID if successful, false otherwise
351 public function insert($source=null) {
353 if (empty($this->courseid)) {
354 print_error('cannotinsertgrade');
357 if (empty($this->parent)) {
358 $course_category = grade_category::fetch_course_category($this->courseid);
359 $this->parent = $course_category->id;
362 $this->path = null;
364 $this->timecreated = $this->timemodified = time();
366 if (!parent::insert($source)) {
367 debugging("Could not insert this category: " . print_r($this, true));
368 return false;
371 $this->force_regrading();
373 // build path and depth
374 $this->update($source);
376 return $this->id;
380 * Internal function - used only from fetch_course_category()
381 * Normal insert() can not be used for course category
383 * @param int $courseid The course ID
384 * @return int The ID of the new course category
386 public function insert_course_category($courseid) {
387 $this->courseid = $courseid;
388 $this->fullname = '?';
389 $this->path = null;
390 $this->parent = null;
391 $this->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2;
393 $this->apply_default_settings();
394 $this->apply_forced_settings();
396 $this->timecreated = $this->timemodified = time();
398 if (!parent::insert('system')) {
399 debugging("Could not insert this category: " . print_r($this, true));
400 return false;
403 // build path and depth
404 $this->update('system');
406 return $this->id;
410 * Compares the values held by this object with those of the matching record in DB, and returns
411 * whether or not these differences are sufficient to justify an update of all parent objects.
412 * This assumes that this object has an ID number and a matching record in DB. If not, it will return false.
414 * @return bool
416 public function qualifies_for_regrading() {
417 if (empty($this->id)) {
418 debugging("Can not regrade non existing category");
419 return false;
422 $db_item = grade_category::fetch(array('id'=>$this->id));
424 $aggregationdiff = $db_item->aggregation != $this->aggregation;
425 $keephighdiff = $db_item->keephigh != $this->keephigh;
426 $droplowdiff = $db_item->droplow != $this->droplow;
427 $aggonlygrddiff = $db_item->aggregateonlygraded != $this->aggregateonlygraded;
428 $aggoutcomesdiff = $db_item->aggregateoutcomes != $this->aggregateoutcomes;
430 return ($aggregationdiff || $keephighdiff || $droplowdiff || $aggonlygrddiff || $aggoutcomesdiff);
434 * Marks this grade categories' associated grade item as needing regrading
436 public function force_regrading() {
437 $grade_item = $this->load_grade_item();
438 $grade_item->force_regrading();
442 * Something that should be called before we start regrading the whole course.
444 * @return void
446 public function pre_regrade_final_grades() {
447 $this->auto_update_weights();
448 $this->auto_update_max();
452 * Generates and saves final grades in associated category grade item.
453 * These immediate children must already have their own final grades.
454 * The category's aggregation method is used to generate final grades.
456 * Please note that category grade is either calculated or aggregated, not both at the same time.
458 * This method must be used ONLY from grade_item::regrade_final_grades(),
459 * because the calculation must be done in correct order!
461 * Steps to follow:
462 * 1. Get final grades from immediate children
463 * 3. Aggregate these grades
464 * 4. Save them in final grades of associated category grade item
466 * @param int $userid The user ID if final grade generation should be limited to a single user
467 * @return bool
469 public function generate_grades($userid=null) {
470 global $CFG, $DB;
472 $this->load_grade_item();
474 if ($this->grade_item->is_locked()) {
475 return true; // no need to recalculate locked items
478 // find grade items of immediate children (category or grade items) and force site settings
479 $depends_on = $this->grade_item->depends_on();
481 if (empty($depends_on)) {
482 $items = false;
484 } else {
485 list($usql, $params) = $DB->get_in_or_equal($depends_on);
486 $sql = "SELECT *
487 FROM {grade_items}
488 WHERE id $usql";
489 $items = $DB->get_records_sql($sql, $params);
490 foreach ($items as $id => $item) {
491 $items[$id] = new grade_item($item, false);
495 $grade_inst = new grade_grade();
496 $fields = 'g.'.implode(',g.', $grade_inst->required_fields);
498 // where to look for final grades - include grade of this item too, we will store the results there
499 $gis = array_merge($depends_on, array($this->grade_item->id));
500 list($usql, $params) = $DB->get_in_or_equal($gis);
502 if ($userid) {
503 $usersql = "AND g.userid=?";
504 $params[] = $userid;
506 } else {
507 $usersql = "";
510 $sql = "SELECT $fields
511 FROM {grade_grades} g, {grade_items} gi
512 WHERE gi.id = g.itemid AND gi.id $usql $usersql
513 ORDER BY g.userid";
515 // group the results by userid and aggregate the grades for this user
516 $rs = $DB->get_recordset_sql($sql, $params);
517 if ($rs->valid()) {
518 $prevuser = 0;
519 $grade_values = array();
520 $excluded = array();
521 $oldgrade = null;
522 $grademaxoverrides = array();
523 $grademinoverrides = array();
525 foreach ($rs as $used) {
526 $grade = new grade_grade($used, false);
527 if (isset($items[$grade->itemid])) {
528 // Prevent grade item to be fetched from DB.
529 $grade->grade_item =& $items[$grade->itemid];
530 } else if ($grade->itemid == $this->grade_item->id) {
531 // This grade's grade item is not in $items.
532 $grade->grade_item =& $this->grade_item;
534 if ($grade->userid != $prevuser) {
535 $this->aggregate_grades($prevuser,
536 $items,
537 $grade_values,
538 $oldgrade,
539 $excluded,
540 $grademinoverrides,
541 $grademaxoverrides);
542 $prevuser = $grade->userid;
543 $grade_values = array();
544 $excluded = array();
545 $oldgrade = null;
546 $grademaxoverrides = array();
547 $grademinoverrides = array();
549 $grade_values[$grade->itemid] = $grade->finalgrade;
550 $grademaxoverrides[$grade->itemid] = $grade->get_grade_max();
551 $grademinoverrides[$grade->itemid] = $grade->get_grade_min();
553 if ($grade->excluded) {
554 $excluded[] = $grade->itemid;
557 if ($this->grade_item->id == $grade->itemid) {
558 $oldgrade = $grade;
561 $this->aggregate_grades($prevuser,
562 $items,
563 $grade_values,
564 $oldgrade,
565 $excluded,
566 $grademinoverrides,
567 $grademaxoverrides);//the last one
569 $rs->close();
571 return true;
575 * Internal function for grade category grade aggregation
577 * @param int $userid The User ID
578 * @param array $items Grade items
579 * @param array $grade_values Array of grade values
580 * @param object $oldgrade Old grade
581 * @param array $excluded Excluded
582 * @param array $grademinoverrides User specific grademin values if different to the grade_item grademin (key is itemid)
583 * @param array $grademaxoverrides User specific grademax values if different to the grade_item grademax (key is itemid)
585 private function aggregate_grades($userid,
586 $items,
587 $grade_values,
588 $oldgrade,
589 $excluded,
590 $grademinoverrides,
591 $grademaxoverrides) {
592 global $CFG, $DB;
594 // Remember these so we can set flags on them to describe how they were used in the aggregation.
595 $novalue = array();
596 $dropped = array();
597 $extracredit = array();
598 $usedweights = array();
600 if (empty($userid)) {
601 //ignore first call
602 return;
605 if ($oldgrade) {
606 $oldfinalgrade = $oldgrade->finalgrade;
607 $grade = new grade_grade($oldgrade, false);
608 $grade->grade_item =& $this->grade_item;
610 } else {
611 // insert final grade - it will be needed later anyway
612 $grade = new grade_grade(array('itemid'=>$this->grade_item->id, 'userid'=>$userid), false);
613 $grade->grade_item =& $this->grade_item;
614 $grade->insert('system');
615 $oldfinalgrade = null;
618 // no need to recalculate locked or overridden grades
619 if ($grade->is_locked() or $grade->is_overridden()) {
620 return;
623 // can not use own final category grade in calculation
624 unset($grade_values[$this->grade_item->id]);
626 // Make sure a grade_grade exists for every grade_item.
627 // We need to do this so we can set the aggregationstatus
628 // with a set_field call instead of checking if each one exists and creating/updating.
629 if (!empty($items)) {
630 list($ggsql, $params) = $DB->get_in_or_equal(array_keys($items), SQL_PARAMS_NAMED, 'g');
633 $params['userid'] = $userid;
634 $sql = "SELECT itemid
635 FROM {grade_grades}
636 WHERE itemid $ggsql AND userid = :userid";
637 $existingitems = $DB->get_records_sql($sql, $params);
639 $notexisting = array_diff(array_keys($items), array_keys($existingitems));
640 foreach ($notexisting as $itemid) {
641 $gradeitem = $items[$itemid];
642 $gradegrade = new grade_grade(array('itemid' => $itemid,
643 'userid' => $userid,
644 'rawgrademin' => $gradeitem->grademin,
645 'rawgrademax' => $gradeitem->grademax), false);
646 $gradegrade->grade_item = $gradeitem;
647 $gradegrade->insert('system');
651 // if no grades calculation possible or grading not allowed clear final grade
652 if (empty($grade_values) or empty($items) or ($this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE)) {
653 $grade->finalgrade = null;
655 if (!is_null($oldfinalgrade)) {
656 $grade->timemodified = time();
657 $success = $grade->update('aggregation');
659 // If successful trigger a user_graded event.
660 if ($success) {
661 \core\event\user_graded::create_from_grade($grade, \core\event\base::USER_OTHER)->trigger();
664 $dropped = $grade_values;
665 $this->set_usedinaggregation($userid, $usedweights, $novalue, $dropped, $extracredit);
666 return;
669 // Normalize the grades first - all will have value 0...1
670 // ungraded items are not used in aggregation.
671 foreach ($grade_values as $itemid=>$v) {
672 if (is_null($v)) {
673 // If null, it means no grade.
674 if ($this->aggregateonlygraded) {
675 unset($grade_values[$itemid]);
676 // Mark this item as "excluded empty" because it has no grade.
677 $novalue[$itemid] = 0;
678 continue;
681 if (in_array($itemid, $excluded)) {
682 unset($grade_values[$itemid]);
683 $dropped[$itemid] = 0;
684 continue;
686 // Check for user specific grade min/max overrides.
687 $usergrademin = $items[$itemid]->grademin;
688 $usergrademax = $items[$itemid]->grademax;
689 if (isset($grademinoverrides[$itemid])) {
690 $usergrademin = $grademinoverrides[$itemid];
692 if (isset($grademaxoverrides[$itemid])) {
693 $usergrademax = $grademaxoverrides[$itemid];
695 if ($this->aggregation == GRADE_AGGREGATE_SUM) {
696 // Assume that the grademin is 0 when standardising the score, to preserve negative grades.
697 $grade_values[$itemid] = grade_grade::standardise_score($v, 0, $usergrademax, 0, 1);
698 } else {
699 $grade_values[$itemid] = grade_grade::standardise_score($v, $usergrademin, $usergrademax, 0, 1);
704 // For items with no value, and not excluded - either set their grade to 0 or exclude them.
705 foreach ($items as $itemid=>$value) {
706 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
707 if (!$this->aggregateonlygraded) {
708 $grade_values[$itemid] = 0;
709 } else {
710 // We are specifically marking these items as "excluded empty".
711 $novalue[$itemid] = 0;
716 // limit and sort
717 $allvalues = $grade_values;
718 if ($this->can_apply_limit_rules()) {
719 $this->apply_limit_rules($grade_values, $items);
722 $moredropped = array_diff($allvalues, $grade_values);
723 foreach ($moredropped as $drop => $unused) {
724 $dropped[$drop] = 0;
727 foreach ($grade_values as $itemid => $val) {
728 if (self::is_extracredit_used() && ($items[$itemid]->aggregationcoef > 0)) {
729 $extracredit[$itemid] = 0;
733 asort($grade_values, SORT_NUMERIC);
735 // let's see we have still enough grades to do any statistics
736 if (count($grade_values) == 0) {
737 // not enough attempts yet
738 $grade->finalgrade = null;
740 if (!is_null($oldfinalgrade)) {
741 $grade->timemodified = time();
742 $success = $grade->update('aggregation');
744 // If successful trigger a user_graded event.
745 if ($success) {
746 \core\event\user_graded::create_from_grade($grade, \core\event\base::USER_OTHER)->trigger();
749 $this->set_usedinaggregation($userid, $usedweights, $novalue, $dropped, $extracredit);
750 return;
753 // do the maths
754 $result = $this->aggregate_values_and_adjust_bounds($grade_values,
755 $items,
756 $usedweights,
757 $grademinoverrides,
758 $grademaxoverrides);
759 $agg_grade = $result['grade'];
761 // Set the actual grademin and max to bind the grade properly.
762 $this->grade_item->grademin = $result['grademin'];
763 $this->grade_item->grademax = $result['grademax'];
765 if ($this->aggregation == GRADE_AGGREGATE_SUM) {
766 // The natural aggregation always displays the range as coming from 0 for categories.
767 // However, when we bind the grade we allow for negative values.
768 $result['grademin'] = 0;
771 // Recalculate the grade back to requested range.
772 $finalgrade = grade_grade::standardise_score($agg_grade, 0, 1, $result['grademin'], $result['grademax']);
773 $grade->finalgrade = $this->grade_item->bounded_grade($finalgrade);
775 $oldrawgrademin = $grade->rawgrademin;
776 $oldrawgrademax = $grade->rawgrademax;
777 $grade->rawgrademin = $result['grademin'];
778 $grade->rawgrademax = $result['grademax'];
780 // Update in db if changed.
781 if (grade_floats_different($grade->finalgrade, $oldfinalgrade) ||
782 grade_floats_different($grade->rawgrademax, $oldrawgrademax) ||
783 grade_floats_different($grade->rawgrademin, $oldrawgrademin)) {
784 $grade->timemodified = time();
785 $success = $grade->update('aggregation');
787 // If successful trigger a user_graded event.
788 if ($success) {
789 \core\event\user_graded::create_from_grade($grade, \core\event\base::USER_OTHER)->trigger();
793 $this->set_usedinaggregation($userid, $usedweights, $novalue, $dropped, $extracredit);
795 return;
799 * Set the flags on the grade_grade items to indicate how individual grades are used
800 * in the aggregation.
802 * WARNING: This function is called a lot during gradebook recalculation, be very performance considerate.
804 * @param int $userid The user we have aggregated the grades for.
805 * @param array $usedweights An array with keys for each of the grade_item columns included in the aggregation. The value are the relative weight.
806 * @param array $novalue An array with keys for each of the grade_item columns skipped because
807 * they had no value in the aggregation.
808 * @param array $dropped An array with keys for each of the grade_item columns dropped
809 * because of any drop lowest/highest settings in the aggregation.
810 * @param array $extracredit An array with keys for each of the grade_item columns
811 * considered extra credit by the aggregation.
813 private function set_usedinaggregation($userid, $usedweights, $novalue, $dropped, $extracredit) {
814 global $DB;
816 // We want to know all current user grades so we can decide whether they need to be updated or they already contain the
817 // expected value.
818 $sql = "SELECT gi.id, gg.aggregationstatus, gg.aggregationweight FROM {grade_grades} gg
819 JOIN {grade_items} gi ON (gg.itemid = gi.id)
820 WHERE gg.userid = :userid";
821 $params = array('categoryid' => $this->id, 'userid' => $userid);
823 // These are all grade_item ids which grade_grades will NOT end up being 'unknown' (because they are not unknown or
824 // because we will update them to something different that 'unknown').
825 $giids = array_keys($usedweights + $novalue + $dropped + $extracredit);
827 if ($giids) {
828 // We include grade items that might not be in categoryid.
829 list($itemsql, $itemlist) = $DB->get_in_or_equal($giids, SQL_PARAMS_NAMED, 'gg');
830 $sql .= ' AND (gi.categoryid = :categoryid OR gi.id ' . $itemsql . ')';
831 $params = $params + $itemlist;
832 } else {
833 $sql .= ' AND gi.categoryid = :categoryid';
835 $currentgrades = $DB->get_recordset_sql($sql, $params);
837 // We will store here the grade_item ids that need to be updated on db.
838 $toupdate = array();
840 if ($currentgrades->valid()) {
842 // Iterate through the user grades to see if we really need to update any of them.
843 foreach ($currentgrades as $currentgrade) {
845 // Unset $usedweights that we do not need to update.
846 if (!empty($usedweights) && isset($usedweights[$currentgrade->id]) && $currentgrade->aggregationstatus === 'used') {
847 // We discard the ones that already have the contribution specified in $usedweights and are marked as 'used'.
848 if (grade_floats_equal($currentgrade->aggregationweight, $usedweights[$currentgrade->id])) {
849 unset($usedweights[$currentgrade->id]);
851 // Used weights can be present in multiple set_usedinaggregation arguments.
852 if (!isset($novalue[$currentgrade->id]) && !isset($dropped[$currentgrade->id]) &&
853 !isset($extracredit[$currentgrade->id])) {
854 continue;
858 // No value grades.
859 if (!empty($novalue) && isset($novalue[$currentgrade->id])) {
860 if ($currentgrade->aggregationstatus !== 'novalue' ||
861 grade_floats_different($currentgrade->aggregationweight, 0)) {
862 $toupdate['novalue'][] = $currentgrade->id;
864 continue;
867 // Dropped grades.
868 if (!empty($dropped) && isset($dropped[$currentgrade->id])) {
869 if ($currentgrade->aggregationstatus !== 'dropped' ||
870 grade_floats_different($currentgrade->aggregationweight, 0)) {
871 $toupdate['dropped'][] = $currentgrade->id;
873 continue;
876 // Extra credit grades.
877 if (!empty($extracredit) && isset($extracredit[$currentgrade->id])) {
879 // If this grade item is already marked as 'extra' and it already has the provided $usedweights value would be
880 // silly to update to 'used' to later update to 'extra'.
881 if (!empty($usedweights) && isset($usedweights[$currentgrade->id]) &&
882 grade_floats_equal($currentgrade->aggregationweight, $usedweights[$currentgrade->id])) {
883 unset($usedweights[$currentgrade->id]);
886 // Update the item to extra if it is not already marked as extra in the database or if the item's
887 // aggregationweight will be updated when going through $usedweights items.
888 if ($currentgrade->aggregationstatus !== 'extra' ||
889 (!empty($usedweights) && isset($usedweights[$currentgrade->id]))) {
890 $toupdate['extracredit'][] = $currentgrade->id;
892 continue;
895 // If is not in any of the above groups it should be set to 'unknown', checking that the item is not already
896 // unknown, if it is we don't need to update it.
897 if ($currentgrade->aggregationstatus !== 'unknown' || grade_floats_different($currentgrade->aggregationweight, 0)) {
898 $toupdate['unknown'][] = $currentgrade->id;
901 $currentgrades->close();
904 // Update items to 'unknown' status.
905 if (!empty($toupdate['unknown'])) {
906 list($itemsql, $itemlist) = $DB->get_in_or_equal($toupdate['unknown'], SQL_PARAMS_NAMED, 'g');
908 $itemlist['userid'] = $userid;
910 $sql = "UPDATE {grade_grades}
911 SET aggregationstatus = 'unknown',
912 aggregationweight = 0
913 WHERE itemid $itemsql AND userid = :userid";
914 $DB->execute($sql, $itemlist);
917 // Update items to 'used' status and setting the proper weight.
918 if (!empty($usedweights)) {
919 // The usedweights items are updated individually to record the weights.
920 foreach ($usedweights as $gradeitemid => $contribution) {
921 $sql = "UPDATE {grade_grades}
922 SET aggregationstatus = 'used',
923 aggregationweight = :contribution
924 WHERE itemid = :itemid AND userid = :userid";
926 $params = array('contribution' => $contribution, 'itemid' => $gradeitemid, 'userid' => $userid);
927 $DB->execute($sql, $params);
931 // Update items to 'novalue' status.
932 if (!empty($toupdate['novalue'])) {
933 list($itemsql, $itemlist) = $DB->get_in_or_equal($toupdate['novalue'], SQL_PARAMS_NAMED, 'g');
935 $itemlist['userid'] = $userid;
937 $sql = "UPDATE {grade_grades}
938 SET aggregationstatus = 'novalue',
939 aggregationweight = 0
940 WHERE itemid $itemsql AND userid = :userid";
942 $DB->execute($sql, $itemlist);
945 // Update items to 'dropped' status.
946 if (!empty($toupdate['dropped'])) {
947 list($itemsql, $itemlist) = $DB->get_in_or_equal($toupdate['dropped'], SQL_PARAMS_NAMED, 'g');
949 $itemlist['userid'] = $userid;
951 $sql = "UPDATE {grade_grades}
952 SET aggregationstatus = 'dropped',
953 aggregationweight = 0
954 WHERE itemid $itemsql AND userid = :userid";
956 $DB->execute($sql, $itemlist);
959 // Update items to 'extracredit' status.
960 if (!empty($toupdate['extracredit'])) {
961 list($itemsql, $itemlist) = $DB->get_in_or_equal($toupdate['extracredit'], SQL_PARAMS_NAMED, 'g');
963 $itemlist['userid'] = $userid;
965 $DB->set_field_select('grade_grades',
966 'aggregationstatus',
967 'extra',
968 "itemid $itemsql AND userid = :userid",
969 $itemlist);
974 * Internal function that calculates the aggregated grade and new min/max for this grade category
976 * Must be public as it is used by grade_grade::get_hiding_affected()
978 * @param array $grade_values An array of values to be aggregated
979 * @param array $items The array of grade_items
980 * @since Moodle 2.6.5, 2.7.2
981 * @param array & $weights If provided, will be filled with the normalized weights
982 * for each grade_item as used in the aggregation.
983 * Some rules for the weights are:
984 * 1. The weights must add up to 1 (unless there are extra credit)
985 * 2. The contributed points column must add up to the course
986 * final grade and this column is calculated from these weights.
987 * @param array $grademinoverrides User specific grademin values if different to the grade_item grademin (key is itemid)
988 * @param array $grademaxoverrides User specific grademax values if different to the grade_item grademax (key is itemid)
989 * @return array containing values for:
990 * 'grade' => the new calculated grade
991 * 'grademin' => the new calculated min grade for the category
992 * 'grademax' => the new calculated max grade for the category
994 public function aggregate_values_and_adjust_bounds($grade_values,
995 $items,
996 & $weights = null,
997 $grademinoverrides = array(),
998 $grademaxoverrides = array()) {
999 global $CFG;
1001 $category_item = $this->load_grade_item();
1002 $grademin = $category_item->grademin;
1003 $grademax = $category_item->grademax;
1005 switch ($this->aggregation) {
1007 case GRADE_AGGREGATE_MEDIAN: // Middle point value in the set: ignores frequencies
1008 $num = count($grade_values);
1009 $grades = array_values($grade_values);
1011 // The median gets 100% - others get 0.
1012 if ($weights !== null && $num > 0) {
1013 $count = 0;
1014 foreach ($grade_values as $itemid=>$grade_value) {
1015 if (($num % 2 == 0) && ($count == intval($num/2)-1 || $count == intval($num/2))) {
1016 $weights[$itemid] = 0.5;
1017 } else if (($num % 2 != 0) && ($count == intval(($num/2)-0.5))) {
1018 $weights[$itemid] = 1.0;
1019 } else {
1020 $weights[$itemid] = 0;
1022 $count++;
1025 if ($num % 2 == 0) {
1026 $agg_grade = ($grades[intval($num/2)-1] + $grades[intval($num/2)]) / 2;
1027 } else {
1028 $agg_grade = $grades[intval(($num/2)-0.5)];
1031 break;
1033 case GRADE_AGGREGATE_MIN:
1034 $agg_grade = reset($grade_values);
1035 // Record the weights as used.
1036 if ($weights !== null) {
1037 foreach ($grade_values as $itemid=>$grade_value) {
1038 $weights[$itemid] = 0;
1041 // Set the first item to 1.
1042 $itemids = array_keys($grade_values);
1043 $weights[reset($itemids)] = 1;
1044 break;
1046 case GRADE_AGGREGATE_MAX:
1047 // Record the weights as used.
1048 if ($weights !== null) {
1049 foreach ($grade_values as $itemid=>$grade_value) {
1050 $weights[$itemid] = 0;
1053 // Set the last item to 1.
1054 $itemids = array_keys($grade_values);
1055 $weights[end($itemids)] = 1;
1056 $agg_grade = end($grade_values);
1057 break;
1059 case GRADE_AGGREGATE_MODE: // the most common value
1060 // array_count_values only counts INT and STRING, so if grades are floats we must convert them to string
1061 $converted_grade_values = array();
1063 foreach ($grade_values as $k => $gv) {
1065 if (!is_int($gv) && !is_string($gv)) {
1066 $converted_grade_values[$k] = (string) $gv;
1068 } else {
1069 $converted_grade_values[$k] = $gv;
1071 if ($weights !== null) {
1072 $weights[$k] = 0;
1076 $freq = array_count_values($converted_grade_values);
1077 arsort($freq); // sort by frequency keeping keys
1078 $top = reset($freq); // highest frequency count
1079 $modes = array_keys($freq, $top); // search for all modes (have the same highest count)
1080 rsort($modes, SORT_NUMERIC); // get highest mode
1081 $agg_grade = reset($modes);
1082 // Record the weights as used.
1083 if ($weights !== null && $top > 0) {
1084 foreach ($grade_values as $k => $gv) {
1085 if ($gv == $agg_grade) {
1086 $weights[$k] = 1.0 / $top;
1090 break;
1092 case GRADE_AGGREGATE_WEIGHTED_MEAN: // Weighted average of all existing final grades, weight specified in coef
1093 $weightsum = 0;
1094 $sum = 0;
1096 foreach ($grade_values as $itemid=>$grade_value) {
1097 if ($weights !== null) {
1098 $weights[$itemid] = $items[$itemid]->aggregationcoef;
1100 if ($items[$itemid]->aggregationcoef <= 0) {
1101 continue;
1103 $weightsum += $items[$itemid]->aggregationcoef;
1104 $sum += $items[$itemid]->aggregationcoef * $grade_value;
1106 if ($weightsum == 0) {
1107 $agg_grade = null;
1109 } else {
1110 $agg_grade = $sum / $weightsum;
1111 if ($weights !== null) {
1112 // Normalise the weights.
1113 foreach ($weights as $itemid => $weight) {
1114 $weights[$itemid] = $weight / $weightsum;
1119 break;
1121 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1122 // Weighted average of all existing final grades with optional extra credit flag,
1123 // weight is the range of grade (usually grademax)
1124 $this->load_grade_item();
1125 $weightsum = 0;
1126 $sum = null;
1128 foreach ($grade_values as $itemid=>$grade_value) {
1129 if ($items[$itemid]->aggregationcoef > 0) {
1130 continue;
1133 $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
1134 if ($weight <= 0) {
1135 continue;
1138 $weightsum += $weight;
1139 $sum += $weight * $grade_value;
1142 // Handle the extra credit items separately to calculate their weight accurately.
1143 foreach ($grade_values as $itemid => $grade_value) {
1144 if ($items[$itemid]->aggregationcoef <= 0) {
1145 continue;
1148 $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
1149 if ($weight <= 0) {
1150 $weights[$itemid] = 0;
1151 continue;
1154 $oldsum = $sum;
1155 $weightedgrade = $weight * $grade_value;
1156 $sum += $weightedgrade;
1158 if ($weights !== null) {
1159 if ($weightsum <= 0) {
1160 $weights[$itemid] = 0;
1161 continue;
1164 $oldgrade = $oldsum / $weightsum;
1165 $grade = $sum / $weightsum;
1166 $normoldgrade = grade_grade::standardise_score($oldgrade, 0, 1, $grademin, $grademax);
1167 $normgrade = grade_grade::standardise_score($grade, 0, 1, $grademin, $grademax);
1168 $boundedoldgrade = $this->grade_item->bounded_grade($normoldgrade);
1169 $boundedgrade = $this->grade_item->bounded_grade($normgrade);
1171 if ($boundedgrade - $boundedoldgrade <= 0) {
1172 // Nothing new was added to the grade.
1173 $weights[$itemid] = 0;
1174 } else if ($boundedgrade < $normgrade) {
1175 // The grade has been bounded, the extra credit item needs to have a different weight.
1176 $gradediff = $boundedgrade - $normoldgrade;
1177 $gradediffnorm = grade_grade::standardise_score($gradediff, $grademin, $grademax, 0, 1);
1178 $weights[$itemid] = $gradediffnorm / $grade_value;
1179 } else {
1180 // Default weighting.
1181 $weights[$itemid] = $weight / $weightsum;
1186 if ($weightsum == 0) {
1187 $agg_grade = $sum; // only extra credits
1189 } else {
1190 $agg_grade = $sum / $weightsum;
1193 // Record the weights as used.
1194 if ($weights !== null) {
1195 foreach ($grade_values as $itemid=>$grade_value) {
1196 if ($items[$itemid]->aggregationcoef > 0) {
1197 // Ignore extra credit items, the weights have already been computed.
1198 continue;
1200 if ($weightsum > 0) {
1201 $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
1202 $weights[$itemid] = $weight / $weightsum;
1203 } else {
1204 $weights[$itemid] = 0;
1208 break;
1210 case GRADE_AGGREGATE_EXTRACREDIT_MEAN: // special average
1211 $this->load_grade_item();
1212 $num = 0;
1213 $sum = null;
1215 foreach ($grade_values as $itemid=>$grade_value) {
1216 if ($items[$itemid]->aggregationcoef == 0) {
1217 $num += 1;
1218 $sum += $grade_value;
1219 if ($weights !== null) {
1220 $weights[$itemid] = 1;
1225 // Treating the extra credit items separately to get a chance to calculate their effective weights.
1226 foreach ($grade_values as $itemid=>$grade_value) {
1227 if ($items[$itemid]->aggregationcoef > 0) {
1228 $oldsum = $sum;
1229 $sum += $items[$itemid]->aggregationcoef * $grade_value;
1231 if ($weights !== null) {
1232 if ($num <= 0) {
1233 // The category only contains extra credit items, not setting the weight.
1234 continue;
1237 $oldgrade = $oldsum / $num;
1238 $grade = $sum / $num;
1239 $normoldgrade = grade_grade::standardise_score($oldgrade, 0, 1, $grademin, $grademax);
1240 $normgrade = grade_grade::standardise_score($grade, 0, 1, $grademin, $grademax);
1241 $boundedoldgrade = $this->grade_item->bounded_grade($normoldgrade);
1242 $boundedgrade = $this->grade_item->bounded_grade($normgrade);
1244 if ($boundedgrade - $boundedoldgrade <= 0) {
1245 // Nothing new was added to the grade.
1246 $weights[$itemid] = 0;
1247 } else if ($boundedgrade < $normgrade) {
1248 // The grade has been bounded, the extra credit item needs to have a different weight.
1249 $gradediff = $boundedgrade - $normoldgrade;
1250 $gradediffnorm = grade_grade::standardise_score($gradediff, $grademin, $grademax, 0, 1);
1251 $weights[$itemid] = $gradediffnorm / $grade_value;
1252 } else {
1253 // Default weighting.
1254 $weights[$itemid] = 1.0 / $num;
1260 if ($weights !== null && $num > 0) {
1261 foreach ($grade_values as $itemid=>$grade_value) {
1262 if ($items[$itemid]->aggregationcoef > 0) {
1263 // Extra credit weights were already calculated.
1264 continue;
1266 if ($weights[$itemid]) {
1267 $weights[$itemid] = 1.0 / $num;
1272 if ($num == 0) {
1273 $agg_grade = $sum; // only extra credits or wrong coefs
1275 } else {
1276 $agg_grade = $sum / $num;
1279 break;
1281 case GRADE_AGGREGATE_SUM: // Add up all the items.
1282 $this->load_grade_item();
1283 $num = count($grade_values);
1284 $sum = 0;
1286 // This setting indicates if we should use algorithm prior to MDL-49257 fix for calculating extra credit weights.
1287 // Even though old algorith has bugs in it, we need to preserve existing grades.
1288 $gradebookcalculationfreeze = 'gradebook_calculations_freeze_' . $this->courseid;
1289 $oldextracreditcalculation = isset($CFG->$gradebookcalculationfreeze)
1290 && ($CFG->$gradebookcalculationfreeze <= 20150619);
1292 $sumweights = 0;
1293 $grademin = 0;
1294 $grademax = 0;
1295 $extracredititems = array();
1296 foreach ($grade_values as $itemid => $gradevalue) {
1297 // We need to check if the grademax/min was adjusted per user because of excluded items.
1298 $usergrademin = $items[$itemid]->grademin;
1299 $usergrademax = $items[$itemid]->grademax;
1300 if (isset($grademinoverrides[$itemid])) {
1301 $usergrademin = $grademinoverrides[$itemid];
1303 if (isset($grademaxoverrides[$itemid])) {
1304 $usergrademax = $grademaxoverrides[$itemid];
1307 // Keep track of the extra credit items, we will need them later on.
1308 if ($items[$itemid]->aggregationcoef > 0) {
1309 $extracredititems[$itemid] = $items[$itemid];
1312 // Ignore extra credit and items with a weight of 0.
1313 if (!isset($extracredititems[$itemid]) && $items[$itemid]->aggregationcoef2 > 0) {
1314 $grademin += $usergrademin;
1315 $grademax += $usergrademax;
1316 $sumweights += $items[$itemid]->aggregationcoef2;
1319 $userweights = array();
1320 $totaloverriddenweight = 0;
1321 $totaloverriddengrademax = 0;
1322 // We first need to rescale all manually assigned weights down by the
1323 // percentage of weights missing from the category.
1324 foreach ($grade_values as $itemid => $gradevalue) {
1325 if ($items[$itemid]->weightoverride) {
1326 if ($items[$itemid]->aggregationcoef2 <= 0) {
1327 // Records the weight of 0 and continue.
1328 $userweights[$itemid] = 0;
1329 continue;
1331 $userweights[$itemid] = $sumweights ? ($items[$itemid]->aggregationcoef2 / $sumweights) : 0;
1332 if (!$oldextracreditcalculation && isset($extracredititems[$itemid])) {
1333 // Extra credit items do not affect totals.
1334 continue;
1336 $totaloverriddenweight += $userweights[$itemid];
1337 $usergrademax = $items[$itemid]->grademax;
1338 if (isset($grademaxoverrides[$itemid])) {
1339 $usergrademax = $grademaxoverrides[$itemid];
1341 $totaloverriddengrademax += $usergrademax;
1344 $nonoverriddenpoints = $grademax - $totaloverriddengrademax;
1346 // Then we need to recalculate the automatic weights except for extra credit items.
1347 foreach ($grade_values as $itemid => $gradevalue) {
1348 if (!$items[$itemid]->weightoverride && ($oldextracreditcalculation || !isset($extracredititems[$itemid]))) {
1349 $usergrademax = $items[$itemid]->grademax;
1350 if (isset($grademaxoverrides[$itemid])) {
1351 $usergrademax = $grademaxoverrides[$itemid];
1353 if ($nonoverriddenpoints > 0) {
1354 $userweights[$itemid] = ($usergrademax/$nonoverriddenpoints) * (1 - $totaloverriddenweight);
1355 } else {
1356 $userweights[$itemid] = 0;
1357 if ($items[$itemid]->aggregationcoef2 > 0) {
1358 // Items with a weight of 0 should not count for the grade max,
1359 // though this only applies if the weight was changed to 0.
1360 $grademax -= $usergrademax;
1366 // Now when we finally know the grademax we can adjust the automatic weights of extra credit items.
1367 if (!$oldextracreditcalculation) {
1368 foreach ($grade_values as $itemid => $gradevalue) {
1369 if (!$items[$itemid]->weightoverride && isset($extracredititems[$itemid])) {
1370 $usergrademax = $items[$itemid]->grademax;
1371 if (isset($grademaxoverrides[$itemid])) {
1372 $usergrademax = $grademaxoverrides[$itemid];
1374 $userweights[$itemid] = $grademax ? ($usergrademax / $grademax) : 0;
1379 // We can use our freshly corrected weights below.
1380 foreach ($grade_values as $itemid => $gradevalue) {
1381 if (isset($extracredititems[$itemid])) {
1382 // We skip the extra credit items first.
1383 continue;
1385 $sum += $gradevalue * $userweights[$itemid] * $grademax;
1386 if ($weights !== null) {
1387 $weights[$itemid] = $userweights[$itemid];
1391 // No we proceed with the extra credit items. They might have a different final
1392 // weight in case the final grade was bounded. So we need to treat them different.
1393 // Also, as we need to use the bounded_grade() method, we have to inject the
1394 // right values there, and restore them afterwards.
1395 $oldgrademax = $this->grade_item->grademax;
1396 $oldgrademin = $this->grade_item->grademin;
1397 foreach ($grade_values as $itemid => $gradevalue) {
1398 if (!isset($extracredititems[$itemid])) {
1399 continue;
1401 $oldsum = $sum;
1402 $weightedgrade = $gradevalue * $userweights[$itemid] * $grademax;
1403 $sum += $weightedgrade;
1405 // Only go through this when we need to record the weights.
1406 if ($weights !== null) {
1407 if ($grademax <= 0) {
1408 // There are only extra credit items in this category,
1409 // all the weights should be accurate (and be 0).
1410 $weights[$itemid] = $userweights[$itemid];
1411 continue;
1414 $oldfinalgrade = $this->grade_item->bounded_grade($oldsum);
1415 $newfinalgrade = $this->grade_item->bounded_grade($sum);
1416 $finalgradediff = $newfinalgrade - $oldfinalgrade;
1417 if ($finalgradediff <= 0) {
1418 // This item did not contribute to the category total at all.
1419 $weights[$itemid] = 0;
1420 } else if ($finalgradediff < $weightedgrade) {
1421 // The weight needs to be adjusted because only a portion of the
1422 // extra credit item contributed to the category total.
1423 $weights[$itemid] = $finalgradediff / ($gradevalue * $grademax);
1424 } else {
1425 // The weight was accurate.
1426 $weights[$itemid] = $userweights[$itemid];
1430 $this->grade_item->grademax = $oldgrademax;
1431 $this->grade_item->grademin = $oldgrademin;
1433 if ($grademax > 0) {
1434 $agg_grade = $sum / $grademax; // Re-normalize score.
1435 } else {
1436 // Every item in the category is extra credit.
1437 $agg_grade = $sum;
1438 $grademax = $sum;
1441 break;
1443 case GRADE_AGGREGATE_MEAN: // Arithmetic average of all grade items (if ungraded aggregated, NULL counted as minimum)
1444 default:
1445 $num = count($grade_values);
1446 $sum = array_sum($grade_values);
1447 $agg_grade = $sum / $num;
1448 // Record the weights evenly.
1449 if ($weights !== null && $num > 0) {
1450 foreach ($grade_values as $itemid=>$grade_value) {
1451 $weights[$itemid] = 1.0 / $num;
1454 break;
1457 return array('grade' => $agg_grade, 'grademin' => $grademin, 'grademax' => $grademax);
1461 * Internal function that calculates the aggregated grade for this grade category
1463 * Must be public as it is used by grade_grade::get_hiding_affected()
1465 * @deprecated since Moodle 2.8
1466 * @param array $grade_values An array of values to be aggregated
1467 * @param array $items The array of grade_items
1468 * @return float The aggregate grade for this grade category
1470 public function aggregate_values($grade_values, $items) {
1471 debugging('grade_category::aggregate_values() is deprecated.
1472 Call grade_category::aggregate_values_and_adjust_bounds() instead.', DEBUG_DEVELOPER);
1473 $result = $this->aggregate_values_and_adjust_bounds($grade_values, $items);
1474 return $result['grade'];
1478 * Some aggregation types may need to update their max grade.
1480 * This must be executed after updating the weights as it relies on them.
1482 * @return void
1484 private function auto_update_max() {
1485 global $CFG, $DB;
1486 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
1487 // not needed at all
1488 return;
1491 // Find grade items of immediate children (category or grade items) and force site settings.
1492 $this->load_grade_item();
1493 $depends_on = $this->grade_item->depends_on();
1495 // Check to see if the gradebook is frozen. This allows grades to not be altered at all until a user verifies that they
1496 // wish to update the grades.
1497 $gradebookcalculationfreeze = 'gradebook_calculations_freeze_' . $this->courseid;
1498 $oldextracreditcalculation = isset($CFG->$gradebookcalculationfreeze) && ($CFG->$gradebookcalculationfreeze <= 20150627);
1499 // Only run if the gradebook isn't frozen.
1500 if (!$oldextracreditcalculation) {
1501 // Don't automatically update the max for calculated items.
1502 if ($this->grade_item->is_calculated()) {
1503 return;
1507 $items = false;
1508 if (!empty($depends_on)) {
1509 list($usql, $params) = $DB->get_in_or_equal($depends_on);
1510 $sql = "SELECT *
1511 FROM {grade_items}
1512 WHERE id $usql";
1513 $items = $DB->get_records_sql($sql, $params);
1516 if (!$items) {
1518 if ($this->grade_item->grademax != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
1519 $this->grade_item->grademax = 0;
1520 $this->grade_item->grademin = 0;
1521 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
1522 $this->grade_item->update('aggregation');
1524 return;
1527 //find max grade possible
1528 $maxes = array();
1530 foreach ($items as $item) {
1532 if ($item->aggregationcoef > 0) {
1533 // extra credit from this activity - does not affect total
1534 continue;
1535 } else if ($item->aggregationcoef2 <= 0) {
1536 // Items with a weight of 0 do not affect the total.
1537 continue;
1540 if ($item->gradetype == GRADE_TYPE_VALUE) {
1541 $maxes[$item->id] = $item->grademax;
1543 } else if ($item->gradetype == GRADE_TYPE_SCALE) {
1544 $maxes[$item->id] = $item->grademax; // 0 = nograde, 1 = first scale item, 2 = second scale item
1548 if ($this->can_apply_limit_rules()) {
1549 // Apply droplow and keephigh.
1550 $this->apply_limit_rules($maxes, $items);
1552 $max = array_sum($maxes);
1554 // update db if anything changed
1555 if ($this->grade_item->grademax != $max or $this->grade_item->grademin != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
1556 $this->grade_item->grademax = $max;
1557 $this->grade_item->grademin = 0;
1558 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
1559 $this->grade_item->update('aggregation');
1564 * Recalculate the weights of the grade items in this category.
1566 * The category total is not updated here, a further call to
1567 * {@link self::auto_update_max()} is required.
1569 * @return void
1571 private function auto_update_weights() {
1572 global $CFG;
1573 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
1574 // This is only required if we are using natural weights.
1575 return;
1577 $children = $this->get_children();
1579 $gradeitem = null;
1581 // Calculate the sum of the grademax's of all the items within this category.
1582 $totalnonoverriddengrademax = 0;
1583 $totalgrademax = 0;
1585 // Out of 1, how much weight has been manually overriden by a user?
1586 $totaloverriddenweight = 0;
1587 $totaloverriddengrademax = 0;
1589 // Has every assessment in this category been overridden?
1590 $automaticgradeitemspresent = false;
1591 // Does the grade item require normalising?
1592 $requiresnormalising = false;
1594 // This array keeps track of the id and weight of every grade item that has been overridden.
1595 $overridearray = array();
1596 foreach ($children as $sortorder => $child) {
1597 $gradeitem = null;
1599 if ($child['type'] == 'item') {
1600 $gradeitem = $child['object'];
1601 } else if ($child['type'] == 'category') {
1602 $gradeitem = $child['object']->load_grade_item();
1605 if ($gradeitem->gradetype == GRADE_TYPE_NONE || $gradeitem->gradetype == GRADE_TYPE_TEXT) {
1606 // Text items and none items do not have a weight.
1607 continue;
1608 } else if (!$this->aggregateoutcomes && $gradeitem->is_outcome_item()) {
1609 // We will not aggregate outcome items, so we can ignore them.
1610 continue;
1611 } else if (empty($CFG->grade_includescalesinaggregation) && $gradeitem->gradetype == GRADE_TYPE_SCALE) {
1612 // The scales are not included in the aggregation, ignore them.
1613 continue;
1616 // Record the ID and the weight for this grade item.
1617 $overridearray[$gradeitem->id] = array();
1618 $overridearray[$gradeitem->id]['extracredit'] = intval($gradeitem->aggregationcoef);
1619 $overridearray[$gradeitem->id]['weight'] = $gradeitem->aggregationcoef2;
1620 $overridearray[$gradeitem->id]['weightoverride'] = intval($gradeitem->weightoverride);
1621 // If this item has had its weight overridden then set the flag to true, but
1622 // only if all previous items were also overridden. Note that extra credit items
1623 // are counted as overridden grade items.
1624 if (!$gradeitem->weightoverride && $gradeitem->aggregationcoef == 0) {
1625 $automaticgradeitemspresent = true;
1628 if ($gradeitem->aggregationcoef > 0) {
1629 // An extra credit grade item doesn't contribute to $totaloverriddengrademax.
1630 continue;
1631 } else if ($gradeitem->weightoverride > 0 && $gradeitem->aggregationcoef2 <= 0) {
1632 // An overriden item that defines a weight of 0 does not contribute to $totaloverriddengrademax.
1633 continue;
1636 $totalgrademax += $gradeitem->grademax;
1637 if ($gradeitem->weightoverride > 0) {
1638 $totaloverriddenweight += $gradeitem->aggregationcoef2;
1639 $totaloverriddengrademax += $gradeitem->grademax;
1643 // Initialise this variable (used to keep track of the weight override total).
1644 $normalisetotal = 0;
1645 // Keep a record of how much the override total is to see if it is above 100. It it is then we need to set the
1646 // other weights to zero and normalise the others.
1647 $overriddentotal = 0;
1648 // If the overridden weight total is higher than 1 then set the other untouched weights to zero.
1649 $setotherweightstozero = false;
1650 // Total up all of the weights.
1651 foreach ($overridearray as $gradeitemdetail) {
1652 // If the grade item has extra credit, then don't add it to the normalisetotal.
1653 if (!$gradeitemdetail['extracredit']) {
1654 $normalisetotal += $gradeitemdetail['weight'];
1656 // The overridden total comprises of items that are set as overridden, that aren't extra credit and have a value
1657 // greater than zero.
1658 if ($gradeitemdetail['weightoverride'] && !$gradeitemdetail['extracredit'] && $gradeitemdetail['weight'] > 0) {
1659 // Add overriden weights up to see if they are greater than 1.
1660 $overriddentotal += $gradeitemdetail['weight'];
1663 if ($overriddentotal > 1) {
1664 // Make sure that this catergory of weights gets normalised.
1665 $requiresnormalising = true;
1666 // The normalised weights are only the overridden weights, so we just use the total of those.
1667 $normalisetotal = $overriddentotal;
1670 $totalnonoverriddengrademax = $totalgrademax - $totaloverriddengrademax;
1672 // This setting indicates if we should use algorithm prior to MDL-49257 fix for calculating extra credit weights.
1673 // Even though old algorith has bugs in it, we need to preserve existing grades.
1674 $gradebookcalculationfreeze = (int)get_config('core', 'gradebook_calculations_freeze_' . $this->courseid);
1675 $oldextracreditcalculation = $gradebookcalculationfreeze && ($gradebookcalculationfreeze <= 20150619);
1677 reset($children);
1678 foreach ($children as $sortorder => $child) {
1679 $gradeitem = null;
1681 if ($child['type'] == 'item') {
1682 $gradeitem = $child['object'];
1683 } else if ($child['type'] == 'category') {
1684 $gradeitem = $child['object']->load_grade_item();
1687 if ($gradeitem->gradetype == GRADE_TYPE_NONE || $gradeitem->gradetype == GRADE_TYPE_TEXT) {
1688 // Text items and none items do not have a weight, no need to set their weight to
1689 // zero as they must never be used during aggregation.
1690 continue;
1691 } else if (!$this->aggregateoutcomes && $gradeitem->is_outcome_item()) {
1692 // We will not aggregate outcome items, so we can ignore updating their weights.
1693 continue;
1694 } else if (empty($CFG->grade_includescalesinaggregation) && $gradeitem->gradetype == GRADE_TYPE_SCALE) {
1695 // We will not aggregate the scales, so we can ignore upating their weights.
1696 continue;
1697 } else if (!$oldextracreditcalculation && $gradeitem->aggregationcoef > 0 && $gradeitem->weightoverride) {
1698 // For an item with extra credit ignore other weigths and overrides but do not change anything at all
1699 // if it's weight was already overridden.
1700 continue;
1703 // Store the previous value here, no need to update if it is the same value.
1704 $prevaggregationcoef2 = $gradeitem->aggregationcoef2;
1706 if (!$oldextracreditcalculation && $gradeitem->aggregationcoef > 0 && !$gradeitem->weightoverride) {
1707 // For an item with extra credit ignore other weigths and overrides.
1708 $gradeitem->aggregationcoef2 = $totalgrademax ? ($gradeitem->grademax / $totalgrademax) : 0;
1710 } else if (!$gradeitem->weightoverride) {
1711 // Calculations with a grade maximum of zero will cause problems. Just set the weight to zero.
1712 if ($totaloverriddenweight >= 1 || $totalnonoverriddengrademax == 0 || $gradeitem->grademax == 0) {
1713 // There is no more weight to distribute.
1714 $gradeitem->aggregationcoef2 = 0;
1715 } else {
1716 // Calculate this item's weight as a percentage of the non-overridden total grade maxes
1717 // then convert it to a proportion of the available non-overriden weight.
1718 $gradeitem->aggregationcoef2 = ($gradeitem->grademax/$totalnonoverriddengrademax) *
1719 (1 - $totaloverriddenweight);
1722 } else if ((!$automaticgradeitemspresent && $normalisetotal != 1) || ($requiresnormalising)
1723 || $overridearray[$gradeitem->id]['weight'] < 0) {
1724 // Just divide the overriden weight for this item against the total weight override of all
1725 // items in this category.
1726 if ($normalisetotal == 0 || $overridearray[$gradeitem->id]['weight'] < 0) {
1727 // If the normalised total equals zero, or the weight value is less than zero,
1728 // set the weight for the grade item to zero.
1729 $gradeitem->aggregationcoef2 = 0;
1730 } else {
1731 $gradeitem->aggregationcoef2 = $overridearray[$gradeitem->id]['weight'] / $normalisetotal;
1735 if (grade_floatval($prevaggregationcoef2) !== grade_floatval($gradeitem->aggregationcoef2)) {
1736 // Update the grade item to reflect these changes.
1737 $gradeitem->update();
1743 * Given an array of grade values (numerical indices) applies droplow or keephigh rules to limit the final array.
1745 * @param array $grade_values itemid=>$grade_value float
1746 * @param array $items grade item objects
1747 * @return array Limited grades.
1749 public function apply_limit_rules(&$grade_values, $items) {
1750 $extraused = $this->is_extracredit_used();
1752 if (!empty($this->droplow)) {
1753 asort($grade_values, SORT_NUMERIC);
1754 $dropped = 0;
1756 // If we have fewer grade items available to drop than $this->droplow, use this flag to escape the loop
1757 // May occur because of "extra credit" or if droplow is higher than the number of grade items
1758 $droppedsomething = true;
1760 while ($dropped < $this->droplow && $droppedsomething) {
1761 $droppedsomething = false;
1763 $grade_keys = array_keys($grade_values);
1764 $gradekeycount = count($grade_keys);
1766 if ($gradekeycount === 0) {
1767 //We've dropped all grade items
1768 break;
1771 $originalindex = $founditemid = $foundmax = null;
1773 // Find the first remaining grade item that is available to be dropped
1774 foreach ($grade_keys as $gradekeyindex=>$gradekey) {
1775 if (!$extraused || $items[$gradekey]->aggregationcoef <= 0) {
1776 // Found a non-extra credit grade item that is eligible to be dropped
1777 $originalindex = $gradekeyindex;
1778 $founditemid = $grade_keys[$originalindex];
1779 $foundmax = $items[$founditemid]->grademax;
1780 break;
1784 if (empty($founditemid)) {
1785 // No grade items available to drop
1786 break;
1789 // Now iterate over the remaining grade items
1790 // We're looking for other grade items with the same grade value but a higher grademax
1791 $i = 1;
1792 while ($originalindex + $i < $gradekeycount) {
1794 $possibleitemid = $grade_keys[$originalindex+$i];
1795 $i++;
1797 if ($grade_values[$founditemid] != $grade_values[$possibleitemid]) {
1798 // The next grade item has a different grade value. Stop looking.
1799 break;
1802 if ($extraused && $items[$possibleitemid]->aggregationcoef > 0) {
1803 // Don't drop extra credit grade items. Continue the search.
1804 continue;
1807 if ($foundmax < $items[$possibleitemid]->grademax) {
1808 // Found a grade item with the same grade value and a higher grademax
1809 $foundmax = $items[$possibleitemid]->grademax;
1810 $founditemid = $possibleitemid;
1811 // Continue searching to see if there is an even higher grademax
1815 // Now drop whatever grade item we have found
1816 unset($grade_values[$founditemid]);
1817 $dropped++;
1818 $droppedsomething = true;
1821 } else if (!empty($this->keephigh)) {
1822 arsort($grade_values, SORT_NUMERIC);
1823 $kept = 0;
1825 foreach ($grade_values as $itemid=>$value) {
1827 if ($extraused and $items[$itemid]->aggregationcoef > 0) {
1828 // we keep all extra credits
1830 } else if ($kept < $this->keephigh) {
1831 $kept++;
1833 } else {
1834 unset($grade_values[$itemid]);
1841 * Returns whether or not we can apply the limit rules.
1843 * There are cases where drop lowest or keep highest should not be used
1844 * at all. This method will determine whether or not this logic can be
1845 * applied considering the current setup of the category.
1847 * @return bool
1849 public function can_apply_limit_rules() {
1850 if ($this->canapplylimitrules !== null) {
1851 return $this->canapplylimitrules;
1854 // Set it to be supported by default.
1855 $this->canapplylimitrules = true;
1857 // Natural aggregation.
1858 if ($this->aggregation == GRADE_AGGREGATE_SUM) {
1859 $canapply = true;
1861 // Check until one child breaks the rules.
1862 $gradeitems = $this->get_children();
1863 $validitems = 0;
1864 $lastweight = null;
1865 $lastmaxgrade = null;
1866 foreach ($gradeitems as $gradeitem) {
1867 $gi = $gradeitem['object'];
1869 if ($gradeitem['type'] == 'category') {
1870 // Sub categories are not allowed because they can have dynamic weights/maxgrades.
1871 $canapply = false;
1872 break;
1875 if ($gi->aggregationcoef > 0) {
1876 // Extra credit items are not allowed.
1877 $canapply = false;
1878 break;
1881 if ($lastweight !== null && $lastweight != $gi->aggregationcoef2) {
1882 // One of the weight differs from another item.
1883 $canapply = false;
1884 break;
1887 if ($lastmaxgrade !== null && $lastmaxgrade != $gi->grademax) {
1888 // One of the max grade differ from another item. This is not allowed for now
1889 // because we could be end up with different max grade between users for this category.
1890 $canapply = false;
1891 break;
1894 $lastweight = $gi->aggregationcoef2;
1895 $lastmaxgrade = $gi->grademax;
1898 $this->canapplylimitrules = $canapply;
1901 return $this->canapplylimitrules;
1905 * Returns true if category uses extra credit of any kind
1907 * @return bool True if extra credit used
1909 public function is_extracredit_used() {
1910 return self::aggregation_uses_extracredit($this->aggregation);
1914 * Returns true if aggregation passed is using extracredit.
1916 * @param int $aggregation Aggregation const.
1917 * @return bool True if extra credit used
1919 public static function aggregation_uses_extracredit($aggregation) {
1920 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1921 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1922 or $aggregation == GRADE_AGGREGATE_SUM);
1926 * Returns true if category uses special aggregation coefficient
1928 * @return bool True if an aggregation coefficient is being used
1930 public function is_aggregationcoef_used() {
1931 return self::aggregation_uses_aggregationcoef($this->aggregation);
1936 * Returns true if aggregation uses aggregationcoef
1938 * @param int $aggregation Aggregation const.
1939 * @return bool True if an aggregation coefficient is being used
1941 public static function aggregation_uses_aggregationcoef($aggregation) {
1942 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN
1943 or $aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1944 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1945 or $aggregation == GRADE_AGGREGATE_SUM);
1950 * Recursive function to find which weight/extra credit field to use in the grade item form.
1952 * @param string $first Whether or not this is the first item in the recursion
1953 * @return string
1955 public function get_coefstring($first=true) {
1956 if (!is_null($this->coefstring)) {
1957 return $this->coefstring;
1960 $overriding_coefstring = null;
1962 // Stop recursing upwards if this category has no parent
1963 if (!$first) {
1965 if ($parent_category = $this->load_parent_category()) {
1966 return $parent_category->get_coefstring(false);
1968 } else {
1969 return null;
1972 } else if ($first) {
1974 if ($parent_category = $this->load_parent_category()) {
1975 $overriding_coefstring = $parent_category->get_coefstring(false);
1979 // If an overriding coefstring has trickled down from one of the parent categories, return it. Otherwise, return self.
1980 if (!is_null($overriding_coefstring)) {
1981 return $overriding_coefstring;
1984 // No parent category is overriding this category's aggregation, return its string
1985 if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
1986 $this->coefstring = 'aggregationcoefweight';
1988 } else if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2) {
1989 $this->coefstring = 'aggregationcoefextrasum';
1991 } else if ($this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
1992 $this->coefstring = 'aggregationcoefextraweight';
1994 } else if ($this->aggregation == GRADE_AGGREGATE_SUM) {
1995 $this->coefstring = 'aggregationcoefextraweightsum';
1997 } else {
1998 $this->coefstring = 'aggregationcoef';
2000 return $this->coefstring;
2004 * Returns tree with all grade_items and categories as elements
2006 * @param int $courseid The course ID
2007 * @param bool $include_category_items as category children
2008 * @return array
2010 public static function fetch_course_tree($courseid, $include_category_items=false) {
2011 $course_category = grade_category::fetch_course_category($courseid);
2012 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
2013 'children'=>$course_category->get_children($include_category_items));
2015 $course_category->sortorder = $course_category->get_sortorder();
2016 $sortorder = $course_category->get_sortorder();
2017 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
2021 * An internal function that recursively sorts grade categories within a course
2023 * @param array $category_array The seed of the recursion
2024 * @param int $sortorder The current sortorder
2025 * @return array An array containing 'object', 'type', 'depth' and optionally 'children'
2027 static private function _fetch_course_tree_recursion($category_array, &$sortorder) {
2028 if (isset($category_array['object']->gradetype) && $category_array['object']->gradetype==GRADE_TYPE_NONE) {
2029 return null;
2032 // store the grade_item or grade_category instance with extra info
2033 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
2035 // reuse final grades if there
2036 if (array_key_exists('finalgrades', $category_array)) {
2037 $result['finalgrades'] = $category_array['finalgrades'];
2040 // recursively resort children
2041 if (!empty($category_array['children'])) {
2042 $result['children'] = array();
2043 //process the category item first
2044 $child = null;
2046 foreach ($category_array['children'] as $oldorder=>$child_array) {
2048 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
2049 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
2050 if (!empty($child)) {
2051 $result['children'][$sortorder] = $child;
2056 foreach ($category_array['children'] as $oldorder=>$child_array) {
2058 if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
2059 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
2060 if (!empty($child)) {
2061 $result['children'][++$sortorder] = $child;
2067 return $result;
2071 * Fetches and returns all the children categories and/or grade_items belonging to this category.
2072 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
2073 * as well as all levels (0). The elements are indexed by sort order.
2075 * @param bool $include_category_items Whether or not to include category grade_items in the children array
2076 * @return array Array of child objects (grade_category and grade_item).
2078 public function get_children($include_category_items=false) {
2079 global $DB;
2081 // This function must be as fast as possible ;-)
2082 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
2083 // we have to limit the number of queries though, because it will be used often in grade reports
2085 $cats = $DB->get_records('grade_categories', array('courseid' => $this->courseid));
2086 $items = $DB->get_records('grade_items', array('courseid' => $this->courseid));
2088 // init children array first
2089 foreach ($cats as $catid=>$cat) {
2090 $cats[$catid]->children = array();
2093 //first attach items to cats and add category sortorder
2094 foreach ($items as $item) {
2096 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
2097 $cats[$item->iteminstance]->sortorder = $item->sortorder;
2099 if (!$include_category_items) {
2100 continue;
2102 $categoryid = $item->iteminstance;
2104 } else {
2105 $categoryid = $item->categoryid;
2106 if (empty($categoryid)) {
2107 debugging('Found a grade item that isnt in a category');
2111 // prevent problems with duplicate sortorders in db
2112 $sortorder = $item->sortorder;
2114 while (array_key_exists($categoryid, $cats)
2115 && array_key_exists($sortorder, $cats[$categoryid]->children)) {
2117 $sortorder++;
2120 $cats[$categoryid]->children[$sortorder] = $item;
2124 // now find the requested category and connect categories as children
2125 $category = false;
2127 foreach ($cats as $catid=>$cat) {
2129 if (empty($cat->parent)) {
2131 if ($cat->path !== '/'.$cat->id.'/') {
2132 $grade_category = new grade_category($cat, false);
2133 $grade_category->path = '/'.$cat->id.'/';
2134 $grade_category->depth = 1;
2135 $grade_category->update('system');
2136 return $this->get_children($include_category_items);
2139 } else {
2141 if (empty($cat->path) or !preg_match('|/'.$cat->parent.'/'.$cat->id.'/$|', $cat->path)) {
2142 //fix paths and depts
2143 static $recursioncounter = 0; // prevents infinite recursion
2144 $recursioncounter++;
2146 if ($recursioncounter < 5) {
2147 // fix paths and depths!
2148 $grade_category = new grade_category($cat, false);
2149 $grade_category->depth = 0;
2150 $grade_category->path = null;
2151 $grade_category->update('system');
2152 return $this->get_children($include_category_items);
2155 // prevent problems with duplicate sortorders in db
2156 $sortorder = $cat->sortorder;
2158 while (array_key_exists($sortorder, $cats[$cat->parent]->children)) {
2159 //debugging("$sortorder exists in cat loop");
2160 $sortorder++;
2163 $cats[$cat->parent]->children[$sortorder] = &$cats[$catid];
2166 if ($catid == $this->id) {
2167 $category = &$cats[$catid];
2171 unset($items); // not needed
2172 unset($cats); // not needed
2174 $children_array = array();
2175 if (is_object($category)) {
2176 $children_array = grade_category::_get_children_recursion($category);
2177 ksort($children_array);
2180 return $children_array;
2185 * Private method used to retrieve all children of this category recursively
2187 * @param grade_category $category Source of current recursion
2188 * @return array An array of child grade categories
2190 private static function _get_children_recursion($category) {
2192 $children_array = array();
2193 foreach ($category->children as $sortorder=>$child) {
2195 if (array_key_exists('itemtype', $child)) {
2196 $grade_item = new grade_item($child, false);
2198 if (in_array($grade_item->itemtype, array('course', 'category'))) {
2199 $type = $grade_item->itemtype.'item';
2200 $depth = $category->depth;
2202 } else {
2203 $type = 'item';
2204 $depth = $category->depth; // we use this to set the same colour
2206 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
2208 } else {
2209 $children = grade_category::_get_children_recursion($child);
2210 $grade_category = new grade_category($child, false);
2212 if (empty($children)) {
2213 $children = array();
2215 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
2219 // sort the array
2220 ksort($children_array);
2222 return $children_array;
2226 * Uses {@link get_grade_item()} to load or create a grade_item, then saves it as $this->grade_item.
2228 * @return grade_item
2230 public function load_grade_item() {
2231 if (empty($this->grade_item)) {
2232 $this->grade_item = $this->get_grade_item();
2234 return $this->grade_item;
2238 * Retrieves this grade categories' associated grade_item from the database
2240 * If no grade_item exists yet, creates one.
2242 * @return grade_item
2244 public function get_grade_item() {
2245 if (empty($this->id)) {
2246 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
2247 return false;
2250 if (empty($this->parent)) {
2251 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
2253 } else {
2254 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
2257 if (!$grade_items = grade_item::fetch_all($params)) {
2258 // create a new one
2259 $grade_item = new grade_item($params, false);
2260 $grade_item->gradetype = GRADE_TYPE_VALUE;
2261 $grade_item->insert('system');
2263 } else if (count($grade_items) == 1) {
2264 // found existing one
2265 $grade_item = reset($grade_items);
2267 } else {
2268 debugging("Found more than one grade_item attached to category id:".$this->id);
2269 // return first one
2270 $grade_item = reset($grade_items);
2273 return $grade_item;
2277 * Uses $this->parent to instantiate $this->parent_category based on the referenced record in the DB
2279 * @return grade_category The parent category
2281 public function load_parent_category() {
2282 if (empty($this->parent_category) && !empty($this->parent)) {
2283 $this->parent_category = $this->get_parent_category();
2285 return $this->parent_category;
2289 * Uses $this->parent to instantiate and return a grade_category object
2291 * @return grade_category Returns the parent category or null if this category has no parent
2293 public function get_parent_category() {
2294 if (!empty($this->parent)) {
2295 $parent_category = new grade_category(array('id' => $this->parent));
2296 return $parent_category;
2297 } else {
2298 return null;
2303 * Returns the most descriptive field for this grade category
2305 * @return string name
2307 public function get_name() {
2308 global $DB;
2309 // For a course category, we return the course name if the fullname is set to '?' in the DB (empty in the category edit form)
2310 if (empty($this->parent) && $this->fullname == '?') {
2311 $course = $DB->get_record('course', array('id'=> $this->courseid));
2312 return format_string($course->fullname);
2314 } else {
2315 return $this->fullname;
2320 * Describe the aggregation settings for this category so the reports make more sense.
2322 * @return string description
2324 public function get_description() {
2325 $allhelp = array();
2326 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
2327 $aggrstrings = grade_helper::get_aggregation_strings();
2328 $allhelp[] = $aggrstrings[$this->aggregation];
2331 if ($this->droplow && $this->can_apply_limit_rules()) {
2332 $allhelp[] = get_string('droplowestvalues', 'grades', $this->droplow);
2334 if ($this->keephigh && $this->can_apply_limit_rules()) {
2335 $allhelp[] = get_string('keephighestvalues', 'grades', $this->keephigh);
2337 if (!$this->aggregateonlygraded) {
2338 $allhelp[] = get_string('aggregatenotonlygraded', 'grades');
2340 if ($allhelp) {
2341 return implode('. ', $allhelp) . '.';
2343 return '';
2347 * Sets this category's parent id
2349 * @param int $parentid The ID of the category that is the new parent to $this
2350 * @param string $source From where was the object updated (mod/forum, manual, etc.)
2351 * @return bool success
2353 public function set_parent($parentid, $source=null) {
2354 if ($this->parent == $parentid) {
2355 return true;
2358 if ($parentid == $this->id) {
2359 print_error('cannotassignselfasparent');
2362 if (empty($this->parent) and $this->is_course_category()) {
2363 print_error('cannothaveparentcate');
2366 // find parent and check course id
2367 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
2368 return false;
2371 $this->force_regrading();
2373 // set new parent category
2374 $this->parent = $parent_category->id;
2375 $this->parent_category =& $parent_category;
2376 $this->path = null; // remove old path and depth - will be recalculated in update()
2377 $this->depth = 0; // remove old path and depth - will be recalculated in update()
2378 $this->update($source);
2380 return $this->update($source);
2384 * Returns the final grade values for this grade category.
2386 * @param int $userid Optional user ID to retrieve a single user's final grade
2387 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
2389 public function get_final($userid=null) {
2390 $this->load_grade_item();
2391 return $this->grade_item->get_final($userid);
2395 * Returns the sortorder of the grade categories' associated grade_item
2397 * This method is also available in grade_item for cases where the object type is not known.
2399 * @return int Sort order
2401 public function get_sortorder() {
2402 $this->load_grade_item();
2403 return $this->grade_item->get_sortorder();
2407 * Returns the idnumber of the grade categories' associated grade_item.
2409 * This method is also available in grade_item for cases where the object type is not known.
2411 * @return string idnumber
2413 public function get_idnumber() {
2414 $this->load_grade_item();
2415 return $this->grade_item->get_idnumber();
2419 * Sets the sortorder variable for this category.
2421 * This method is also available in grade_item, for cases where the object type is not know.
2423 * @param int $sortorder The sortorder to assign to this category
2425 public function set_sortorder($sortorder) {
2426 $this->load_grade_item();
2427 $this->grade_item->set_sortorder($sortorder);
2431 * Move this category after the given sortorder
2433 * Does not change the parent
2435 * @param int $sortorder to place after.
2436 * @return void
2438 public function move_after_sortorder($sortorder) {
2439 $this->load_grade_item();
2440 $this->grade_item->move_after_sortorder($sortorder);
2444 * Return true if this is the top most category that represents the total course grade.
2446 * @return bool
2448 public function is_course_category() {
2449 $this->load_grade_item();
2450 return $this->grade_item->is_course_item();
2454 * Return the course level grade_category object
2456 * @param int $courseid The Course ID
2457 * @return grade_category Returns the course level grade_category instance
2459 public static function fetch_course_category($courseid) {
2460 if (empty($courseid)) {
2461 debugging('Missing course id!');
2462 return false;
2465 // course category has no parent
2466 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
2467 return $course_category;
2470 // create a new one
2471 $course_category = new grade_category();
2472 $course_category->insert_course_category($courseid);
2474 return $course_category;
2478 * Is grading object editable?
2480 * @return bool
2482 public function is_editable() {
2483 return true;
2487 * Returns the locked state/date of the grade categories' associated grade_item.
2489 * This method is also available in grade_item, for cases where the object type is not known.
2491 * @return bool
2493 public function is_locked() {
2494 $this->load_grade_item();
2495 return $this->grade_item->is_locked();
2499 * Sets the grade_item's locked variable and updates the grade_item.
2501 * Calls set_locked() on the categories' grade_item
2503 * @param int $lockedstate 0, 1 or a timestamp int(10) after which date the item will be locked.
2504 * @param bool $cascade lock/unlock child objects too
2505 * @param bool $refresh refresh grades when unlocking
2506 * @return bool success if category locked (not all children mayb be locked though)
2508 public function set_locked($lockedstate, $cascade=false, $refresh=true) {
2509 $this->load_grade_item();
2511 $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
2513 if ($cascade) {
2514 //process all children - items and categories
2515 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
2517 foreach ($children as $child) {
2518 $child->set_locked($lockedstate, true, false);
2520 if (empty($lockedstate) and $refresh) {
2521 //refresh when unlocking
2522 $child->refresh_grades();
2527 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
2529 foreach ($children as $child) {
2530 $child->set_locked($lockedstate, true, true);
2535 return $result;
2539 * Overrides grade_object::set_properties() to add special handling for changes to category aggregation types
2541 * @param stdClass $instance the object to set the properties on
2542 * @param array|stdClass $params Either an associative array or an object containing property name, property value pairs
2544 public static function set_properties(&$instance, $params) {
2545 global $DB;
2547 $fromaggregation = $instance->aggregation;
2549 parent::set_properties($instance, $params);
2551 // The aggregation method is changing and this category has already been saved.
2552 if (isset($params->aggregation) && !empty($instance->id)) {
2553 $achildwasdupdated = false;
2555 // Get all its children.
2556 $children = $instance->get_children();
2557 foreach ($children as $child) {
2558 $item = $child['object'];
2559 if ($child['type'] == 'category') {
2560 $item = $item->load_grade_item();
2563 // Set the new aggregation fields.
2564 if ($item->set_aggregation_fields_for_aggregation($fromaggregation, $params->aggregation)) {
2565 $item->update();
2566 $achildwasdupdated = true;
2570 // If this is the course category, it is possible that its grade item was set as needsupdate
2571 // by one of its children. If we keep a reference to that stale object we might cause the
2572 // needsupdate flag to be lost. It's safer to just reload the grade_item from the database.
2573 if ($achildwasdupdated && !empty($instance->grade_item) && $instance->is_course_category()) {
2574 $instance->grade_item = null;
2575 $instance->load_grade_item();
2581 * Sets the grade_item's hidden variable and updates the grade_item.
2583 * Overrides grade_item::set_hidden() to add cascading of the hidden value to grade items in this grade category
2585 * @param int $hidden 0 mean always visible, 1 means always hidden and a number > 1 is a timestamp to hide until
2586 * @param bool $cascade apply to child objects too
2588 public function set_hidden($hidden, $cascade=false) {
2589 $this->load_grade_item();
2590 //this hides the associated grade item (the course total)
2591 $this->grade_item->set_hidden($hidden, $cascade);
2592 //this hides the category itself and everything it contains
2593 parent::set_hidden($hidden, $cascade);
2595 if ($cascade) {
2597 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
2599 foreach ($children as $child) {
2600 if ($child->can_control_visibility()) {
2601 $child->set_hidden($hidden, $cascade);
2606 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
2608 foreach ($children as $child) {
2609 $child->set_hidden($hidden, $cascade);
2614 //if marking category visible make sure parent category is visible MDL-21367
2615 if( !$hidden ) {
2616 $category_array = grade_category::fetch_all(array('id'=>$this->parent));
2617 if ($category_array && array_key_exists($this->parent, $category_array)) {
2618 $category = $category_array[$this->parent];
2619 //call set_hidden on the category regardless of whether it is hidden as its parent might be hidden
2620 //if($category->is_hidden()) {
2621 $category->set_hidden($hidden, false);
2628 * Applies default settings on this category
2630 * @return bool True if anything changed
2632 public function apply_default_settings() {
2633 global $CFG;
2635 foreach ($this->forceable as $property) {
2637 if (isset($CFG->{"grade_$property"})) {
2639 if ($CFG->{"grade_$property"} == -1) {
2640 continue; //temporary bc before version bump
2642 $this->$property = $CFG->{"grade_$property"};
2648 * Applies forced settings on this category
2650 * @return bool True if anything changed
2652 public function apply_forced_settings() {
2653 global $CFG;
2655 $updated = false;
2657 foreach ($this->forceable as $property) {
2659 if (isset($CFG->{"grade_$property"}) and isset($CFG->{"grade_{$property}_flag"}) and
2660 ((int) $CFG->{"grade_{$property}_flag"} & 1)) {
2662 if ($CFG->{"grade_$property"} == -1) {
2663 continue; //temporary bc before version bump
2665 $this->$property = $CFG->{"grade_$property"};
2666 $updated = true;
2670 return $updated;
2674 * Notification of change in forced category settings.
2676 * Causes all course and category grade items to be marked as needing to be updated
2678 public static function updated_forced_settings() {
2679 global $CFG, $DB;
2680 $params = array(1, 'course', 'category');
2681 $sql = "UPDATE {grade_items} SET needsupdate=? WHERE itemtype=? or itemtype=?";
2682 $DB->execute($sql, $params);
2686 * Determine the default aggregation values for a given aggregation method.
2688 * @param int $aggregationmethod The aggregation method constant value.
2689 * @return array Containing the keys 'aggregationcoef', 'aggregationcoef2' and 'weightoverride'.
2691 public static function get_default_aggregation_coefficient_values($aggregationmethod) {
2692 $defaultcoefficients = array(
2693 'aggregationcoef' => 0,
2694 'aggregationcoef2' => 0,
2695 'weightoverride' => 0
2698 switch ($aggregationmethod) {
2699 case GRADE_AGGREGATE_WEIGHTED_MEAN:
2700 $defaultcoefficients['aggregationcoef'] = 1;
2701 break;
2702 case GRADE_AGGREGATE_SUM:
2703 $defaultcoefficients['aggregationcoef2'] = 1;
2704 break;
2707 return $defaultcoefficients;
2711 * Cleans the cache.
2713 * We invalidate them all so it can be completely reloaded.
2715 * Being conservative here, if there is a new grade_category we purge them, the important part
2716 * is that this is not purged when there are no changes in grade_categories.
2718 * @param bool $deleted
2719 * @return void
2721 protected function notify_changed($deleted) {
2722 self::clean_record_set();
2726 * Generates a unique key per query.
2728 * Not unique between grade_object children. self::retrieve_record_set and self::set_record_set will be in charge of
2729 * selecting the appropriate cache.
2731 * @param array $params An array of conditions like $fieldname => $fieldvalue
2732 * @return string
2734 protected static function generate_record_set_key($params) {
2735 return sha1(json_encode($params));
2739 * Tries to retrieve a record set from the cache.
2741 * @param array $params The query params
2742 * @return grade_object[]|bool An array of grade_objects or false if not found.
2744 protected static function retrieve_record_set($params) {
2745 $cache = cache::make('core', 'grade_categories');
2746 return $cache->get(self::generate_record_set_key($params));
2750 * Sets a result to the records cache, even if there were no results.
2752 * @param string $params The query params
2753 * @param grade_object[]|bool $records An array of grade_objects or false if there are no records matching the $key filters
2754 * @return void
2756 protected static function set_record_set($params, $records) {
2757 $cache = cache::make('core', 'grade_categories');
2758 return $cache->set(self::generate_record_set_key($params), $records);
2762 * Cleans the cache.
2764 * Aggressive deletion to be conservative given the gradebook design.
2765 * The key is based on the requested params, not easy nor worth to purge selectively.
2767 * @return void
2769 public static function clean_record_set() {
2770 cache_helper::purge_by_event('changesingradecategories');