Merge branch 'wip-mdl-48190-m27' of https://github.com/rajeshtaneja/moodle into MOODL...
[moodle.git] / lib / grade / grade_category.php
blobe97e4bbd8d28fae3c1c3a04da2e4443548cbac3d
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('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 'aggregatesubcats', '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_MEAN;
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 * Ignore subcategories when aggregating
121 * @var int $aggregatesubcats
123 public $aggregatesubcats = 0;
126 * Array of grade_items or grade_categories nested exactly 1 level below this category
127 * @var array $children
129 public $children;
132 * A hierarchical array of all children below this category. This is stored separately from
133 * $children because it is more memory-intensive and may not be used as often.
134 * @var array $all_children
136 public $all_children;
139 * An associated grade_item object, with itemtype=category, used to calculate and cache a set of grade values
140 * for this category.
141 * @var grade_item $grade_item
143 public $grade_item;
146 * Temporary sortorder for speedup of children resorting
147 * @var int $sortorder
149 public $sortorder;
152 * List of options which can be "forced" from site settings.
153 * @var array $forceable
155 public $forceable = array('aggregation', 'keephigh', 'droplow', 'aggregateonlygraded', 'aggregateoutcomes', 'aggregatesubcats');
158 * String representing the aggregation coefficient. Variable is used as cache.
159 * @var string $coefstring
161 public $coefstring = null;
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 return grade_object::fetch_helper('grade_categories', 'grade_category', $params);
195 * Finds and returns all grade_category instances based on params.
197 * @param array $params associative arrays varname=>value
198 * @return array array of grade_category insatnces or false if none found.
200 public static function fetch_all($params) {
201 return grade_object::fetch_all_helper('grade_categories', 'grade_category', $params);
205 * In addition to update() as defined in grade_object, call force_regrading of parent categories, if applicable.
207 * @param string $source from where was the object updated (mod/forum, manual, etc.)
208 * @return bool success
210 public function update($source=null) {
211 // load the grade item or create a new one
212 $this->load_grade_item();
214 // force recalculation of path;
215 if (empty($this->path)) {
216 $this->path = grade_category::build_path($this);
217 $this->depth = substr_count($this->path, '/') - 1;
218 $updatechildren = true;
220 } else {
221 $updatechildren = false;
224 $this->apply_forced_settings();
226 // these are exclusive
227 if ($this->droplow > 0) {
228 $this->keephigh = 0;
230 } else if ($this->keephigh > 0) {
231 $this->droplow = 0;
234 // Recalculate grades if needed
235 if ($this->qualifies_for_regrading()) {
236 $this->force_regrading();
239 $this->timemodified = time();
241 $result = parent::update($source);
243 // now update paths in all child categories
244 if ($result and $updatechildren) {
246 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
248 foreach ($children as $child) {
249 $child->path = null;
250 $child->depth = 0;
251 $child->update($source);
256 return $result;
260 * If parent::delete() is successful, send force_regrading message to parent category.
262 * @param string $source from where was the object deleted (mod/forum, manual, etc.)
263 * @return bool success
265 public function delete($source=null) {
266 $grade_item = $this->load_grade_item();
268 if ($this->is_course_category()) {
270 if ($categories = grade_category::fetch_all(array('courseid'=>$this->courseid))) {
272 foreach ($categories as $category) {
274 if ($category->id == $this->id) {
275 continue; // do not delete course category yet
277 $category->delete($source);
281 if ($items = grade_item::fetch_all(array('courseid'=>$this->courseid))) {
283 foreach ($items as $item) {
285 if ($item->id == $grade_item->id) {
286 continue; // do not delete course item yet
288 $item->delete($source);
292 } else {
293 $this->force_regrading();
295 $parent = $this->load_parent_category();
297 // Update children's categoryid/parent field first
298 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
299 foreach ($children as $child) {
300 $child->set_parent($parent->id);
304 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
305 foreach ($children as $child) {
306 $child->set_parent($parent->id);
311 // first delete the attached grade item and grades
312 $grade_item->delete($source);
314 // delete category itself
315 return parent::delete($source);
319 * In addition to the normal insert() defined in grade_object, this method sets the depth
320 * and path for this object, and update the record accordingly.
322 * We do this here instead of in the constructor as they both need to know the record's
323 * ID number, which only gets created at insertion time.
324 * This method also creates an associated grade_item if this wasn't done during construction.
326 * @param string $source from where was the object inserted (mod/forum, manual, etc.)
327 * @return int PK ID if successful, false otherwise
329 public function insert($source=null) {
331 if (empty($this->courseid)) {
332 print_error('cannotinsertgrade');
335 if (empty($this->parent)) {
336 $course_category = grade_category::fetch_course_category($this->courseid);
337 $this->parent = $course_category->id;
340 $this->path = null;
342 $this->timecreated = $this->timemodified = time();
344 if (!parent::insert($source)) {
345 debugging("Could not insert this category: " . print_r($this, true));
346 return false;
349 $this->force_regrading();
351 // build path and depth
352 $this->update($source);
354 return $this->id;
358 * Internal function - used only from fetch_course_category()
359 * Normal insert() can not be used for course category
361 * @param int $courseid The course ID
362 * @return int The ID of the new course category
364 public function insert_course_category($courseid) {
365 $this->courseid = $courseid;
366 $this->fullname = '?';
367 $this->path = null;
368 $this->parent = null;
369 $this->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2;
371 $this->apply_default_settings();
372 $this->apply_forced_settings();
374 $this->timecreated = $this->timemodified = time();
376 if (!parent::insert('system')) {
377 debugging("Could not insert this category: " . print_r($this, true));
378 return false;
381 // build path and depth
382 $this->update('system');
384 return $this->id;
388 * Compares the values held by this object with those of the matching record in DB, and returns
389 * whether or not these differences are sufficient to justify an update of all parent objects.
390 * This assumes that this object has an ID number and a matching record in DB. If not, it will return false.
392 * @return bool
394 public function qualifies_for_regrading() {
395 if (empty($this->id)) {
396 debugging("Can not regrade non existing category");
397 return false;
400 $db_item = grade_category::fetch(array('id'=>$this->id));
402 $aggregationdiff = $db_item->aggregation != $this->aggregation;
403 $keephighdiff = $db_item->keephigh != $this->keephigh;
404 $droplowdiff = $db_item->droplow != $this->droplow;
405 $aggonlygrddiff = $db_item->aggregateonlygraded != $this->aggregateonlygraded;
406 $aggoutcomesdiff = $db_item->aggregateoutcomes != $this->aggregateoutcomes;
407 $aggsubcatsdiff = $db_item->aggregatesubcats != $this->aggregatesubcats;
409 return ($aggregationdiff || $keephighdiff || $droplowdiff || $aggonlygrddiff || $aggoutcomesdiff || $aggsubcatsdiff);
413 * Marks this grade categories' associated grade item as needing regrading
415 public function force_regrading() {
416 $grade_item = $this->load_grade_item();
417 $grade_item->force_regrading();
421 * Generates and saves final grades in associated category grade item.
422 * These immediate children must already have their own final grades.
423 * The category's aggregation method is used to generate final grades.
425 * Please note that category grade is either calculated or aggregated, not both at the same time.
427 * This method must be used ONLY from grade_item::regrade_final_grades(),
428 * because the calculation must be done in correct order!
430 * Steps to follow:
431 * 1. Get final grades from immediate children
432 * 3. Aggregate these grades
433 * 4. Save them in final grades of associated category grade item
435 * @param int $userid The user ID if final grade generation should be limited to a single user
436 * @return bool
438 public function generate_grades($userid=null) {
439 global $CFG, $DB;
441 $this->load_grade_item();
443 if ($this->grade_item->is_locked()) {
444 return true; // no need to recalculate locked items
447 // find grade items of immediate children (category or grade items) and force site settings
448 $depends_on = $this->grade_item->depends_on();
450 if (empty($depends_on)) {
451 $items = false;
453 } else {
454 list($usql, $params) = $DB->get_in_or_equal($depends_on);
455 $sql = "SELECT *
456 FROM {grade_items}
457 WHERE id $usql";
458 $items = $DB->get_records_sql($sql, $params);
461 // needed mostly for SUM agg type
462 $this->auto_update_max($items);
464 $grade_inst = new grade_grade();
465 $fields = 'g.'.implode(',g.', $grade_inst->required_fields);
467 // where to look for final grades - include grade of this item too, we will store the results there
468 $gis = array_merge($depends_on, array($this->grade_item->id));
469 list($usql, $params) = $DB->get_in_or_equal($gis);
471 if ($userid) {
472 $usersql = "AND g.userid=?";
473 $params[] = $userid;
475 } else {
476 $usersql = "";
479 $sql = "SELECT $fields
480 FROM {grade_grades} g, {grade_items} gi
481 WHERE gi.id = g.itemid AND gi.id $usql $usersql
482 ORDER BY g.userid";
484 // group the results by userid and aggregate the grades for this user
485 $rs = $DB->get_recordset_sql($sql, $params);
486 if ($rs->valid()) {
487 $prevuser = 0;
488 $grade_values = array();
489 $excluded = array();
490 $oldgrade = null;
492 foreach ($rs as $used) {
494 if ($used->userid != $prevuser) {
495 $this->aggregate_grades($prevuser, $items, $grade_values, $oldgrade, $excluded);
496 $prevuser = $used->userid;
497 $grade_values = array();
498 $excluded = array();
499 $oldgrade = null;
501 $grade_values[$used->itemid] = $used->finalgrade;
503 if ($used->excluded) {
504 $excluded[] = $used->itemid;
507 if ($this->grade_item->id == $used->itemid) {
508 $oldgrade = $used;
511 $this->aggregate_grades($prevuser, $items, $grade_values, $oldgrade, $excluded);//the last one
513 $rs->close();
515 return true;
519 * Internal function for grade category grade aggregation
521 * @param int $userid The User ID
522 * @param array $items Grade items
523 * @param array $grade_values Array of grade values
524 * @param object $oldgrade Old grade
525 * @param array $excluded Excluded
527 private function aggregate_grades($userid, $items, $grade_values, $oldgrade, $excluded) {
528 global $CFG;
529 if (empty($userid)) {
530 //ignore first call
531 return;
534 if ($oldgrade) {
535 $oldfinalgrade = $oldgrade->finalgrade;
536 $grade = new grade_grade($oldgrade, false);
537 $grade->grade_item =& $this->grade_item;
539 } else {
540 // insert final grade - it will be needed later anyway
541 $grade = new grade_grade(array('itemid'=>$this->grade_item->id, 'userid'=>$userid), false);
542 $grade->grade_item =& $this->grade_item;
543 $grade->insert('system');
544 $oldfinalgrade = null;
547 // no need to recalculate locked or overridden grades
548 if ($grade->is_locked() or $grade->is_overridden()) {
549 return;
552 // can not use own final category grade in calculation
553 unset($grade_values[$this->grade_item->id]);
556 // sum is a special aggregation types - it adjusts the min max, does not use relative values
557 if ($this->aggregation == GRADE_AGGREGATE_SUM) {
558 $this->sum_grades($grade, $oldfinalgrade, $items, $grade_values, $excluded);
559 return;
562 // if no grades calculation possible or grading not allowed clear final grade
563 if (empty($grade_values) or empty($items) or ($this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE)) {
564 $grade->finalgrade = null;
566 if (!is_null($oldfinalgrade)) {
567 $grade->timemodified = time();
568 $grade->update('aggregation');
570 return;
573 // normalize the grades first - all will have value 0...1
574 // ungraded items are not used in aggregation
575 foreach ($grade_values as $itemid=>$v) {
577 if (is_null($v)) {
578 // null means no grade
579 unset($grade_values[$itemid]);
580 continue;
582 } else if (in_array($itemid, $excluded)) {
583 unset($grade_values[$itemid]);
584 continue;
586 $grade_values[$itemid] = grade_grade::standardise_score($v, $items[$itemid]->grademin, $items[$itemid]->grademax, 0, 1);
589 // use min grade if grade missing for these types
590 if (!$this->aggregateonlygraded) {
592 foreach ($items as $itemid=>$value) {
594 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
595 $grade_values[$itemid] = 0;
600 // limit and sort
601 $this->apply_limit_rules($grade_values, $items);
602 asort($grade_values, SORT_NUMERIC);
604 // let's see we have still enough grades to do any statistics
605 if (count($grade_values) == 0) {
606 // not enough attempts yet
607 $grade->finalgrade = null;
609 if (!is_null($oldfinalgrade)) {
610 $grade->timemodified = time();
611 $grade->update('aggregation');
613 return;
616 // do the maths
617 $result = $this->aggregate_values_and_adjust_bounds($grade_values, $items);
618 $agg_grade = $result['grade'];
620 // recalculate the grade back to requested range
621 $finalgrade = grade_grade::standardise_score($agg_grade, 0, 1, $result['grademin'], $result['grademax']);
623 $grade->finalgrade = $this->grade_item->bounded_grade($finalgrade);
625 // update in db if changed
626 if (grade_floats_different($grade->finalgrade, $oldfinalgrade)) {
627 $grade->timemodified = time();
628 $grade->update('aggregation');
631 return;
635 * Internal function that calculates the aggregated grade and new min/max for this grade category
637 * Must be public as it is used by grade_grade::get_hiding_affected()
639 * @param array $grade_values An array of values to be aggregated
640 * @param array $items The array of grade_items
641 * @since Moodle 2.6.5, 2.7.2
642 * @return array containing values for:
643 * 'grade' => the new calculated grade
644 * 'grademin' => the new calculated min grade for the category
645 * 'grademax' => the new calculated max grade for the category
647 public function aggregate_values_and_adjust_bounds($grade_values, $items) {
648 $category_item = $this->get_grade_item();
649 $grademin = $category_item->grademin;
650 $grademax = $category_item->grademax;
652 switch ($this->aggregation) {
654 case GRADE_AGGREGATE_MEDIAN: // Middle point value in the set: ignores frequencies
655 $num = count($grade_values);
656 $grades = array_values($grade_values);
658 if ($num % 2 == 0) {
659 $agg_grade = ($grades[intval($num/2)-1] + $grades[intval($num/2)]) / 2;
661 } else {
662 $agg_grade = $grades[intval(($num/2)-0.5)];
664 break;
666 case GRADE_AGGREGATE_MIN:
667 $agg_grade = reset($grade_values);
668 break;
670 case GRADE_AGGREGATE_MAX:
671 $agg_grade = array_pop($grade_values);
672 break;
674 case GRADE_AGGREGATE_MODE: // the most common value, average used if multimode
675 // array_count_values only counts INT and STRING, so if grades are floats we must convert them to string
676 $converted_grade_values = array();
678 foreach ($grade_values as $k => $gv) {
680 if (!is_int($gv) && !is_string($gv)) {
681 $converted_grade_values[$k] = (string) $gv;
683 } else {
684 $converted_grade_values[$k] = $gv;
688 $freq = array_count_values($converted_grade_values);
689 arsort($freq); // sort by frequency keeping keys
690 $top = reset($freq); // highest frequency count
691 $modes = array_keys($freq, $top); // search for all modes (have the same highest count)
692 rsort($modes, SORT_NUMERIC); // get highest mode
693 $agg_grade = reset($modes);
694 break;
696 case GRADE_AGGREGATE_WEIGHTED_MEAN: // Weighted average of all existing final grades, weight specified in coef
697 $weightsum = 0;
698 $sum = 0;
700 foreach ($grade_values as $itemid=>$grade_value) {
702 if ($items[$itemid]->aggregationcoef <= 0) {
703 continue;
705 $weightsum += $items[$itemid]->aggregationcoef;
706 $sum += $items[$itemid]->aggregationcoef * $grade_value;
709 if ($weightsum == 0) {
710 $agg_grade = null;
712 } else {
713 $agg_grade = $sum / $weightsum;
715 break;
717 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
718 // Weighted average of all existing final grades with optional extra credit flag,
719 // weight is the range of grade (usually grademax)
720 $weightsum = 0;
721 $sum = null;
723 foreach ($grade_values as $itemid=>$grade_value) {
724 $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
726 if ($weight <= 0) {
727 continue;
730 if ($items[$itemid]->aggregationcoef == 0) {
731 $weightsum += $weight;
733 $sum += $weight * $grade_value;
736 if ($weightsum == 0) {
737 $agg_grade = $sum; // only extra credits
739 } else {
740 $agg_grade = $sum / $weightsum;
742 break;
744 case GRADE_AGGREGATE_EXTRACREDIT_MEAN: // special average
745 $num = 0;
746 $sum = null;
748 foreach ($grade_values as $itemid=>$grade_value) {
750 if ($items[$itemid]->aggregationcoef == 0) {
751 $num += 1;
752 $sum += $grade_value;
754 } else if ($items[$itemid]->aggregationcoef > 0) {
755 $sum += $items[$itemid]->aggregationcoef * $grade_value;
759 if ($num == 0) {
760 $agg_grade = $sum; // only extra credits or wrong coefs
762 } else {
763 $agg_grade = $sum / $num;
765 break;
767 case GRADE_AGGREGATE_SUM: // Add up all the items.
768 $num = count($grade_values);
769 // Excluded items can affect the grademax for this grade_item.
770 $grademin = 0;
771 $grademax = 0;
772 $sum = 0;
773 foreach ($grade_values as $itemid => $grade_value) {
774 $sum += $grade_value * ($items[$itemid]->grademax - $items[$itemid]->grademin);
775 if ($items[$itemid]->aggregationcoef == 0) {
776 $grademin += $items[$itemid]->grademin;
777 $grademax += $items[$itemid]->grademax;
781 $agg_grade = $sum / ($grademax - $grademin);
782 break;
784 case GRADE_AGGREGATE_MEAN: // Arithmetic average of all grade items (if ungraded aggregated, NULL counted as minimum)
785 default:
786 $num = count($grade_values);
787 $sum = array_sum($grade_values);
788 $agg_grade = $sum / $num;
789 break;
792 return array('grade' => $agg_grade, 'grademin' => $grademin, 'grademax' => $grademax);
796 * Internal function that calculates the aggregated grade for this grade category
798 * Must be public as it is used by grade_grade::get_hiding_affected()
800 * Will be deprecated in Moodle 2.8
801 * @param array $grade_values An array of values to be aggregated
802 * @param array $items The array of grade_items
803 * @return float The aggregate grade for this grade category
805 public function aggregate_values($grade_values, $items) {
806 $result = $this->aggregate_values_and_adjust_bounds($grade_values, $items);
807 return $result['grade'];
811 * Some aggregation types may automatically update max grade
813 * @param array $items sub items
815 private function auto_update_max($items) {
816 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
817 // not needed at all
818 return;
821 if (!$items) {
823 if ($this->grade_item->grademax != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
824 $this->grade_item->grademax = 0;
825 $this->grade_item->grademin = 0;
826 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
827 $this->grade_item->update('aggregation');
829 return;
832 //find max grade possible
833 $maxes = array();
835 foreach ($items as $item) {
837 if ($item->aggregationcoef > 0) {
838 // extra credit from this activity - does not affect total
839 continue;
842 if ($item->gradetype == GRADE_TYPE_VALUE) {
843 $maxes[$item->id] = $item->grademax;
845 } else if ($item->gradetype == GRADE_TYPE_SCALE) {
846 $maxes[$item->id] = $item->grademax; // 0 = nograde, 1 = first scale item, 2 = second scale item
849 // apply droplow and keephigh
850 $this->apply_limit_rules($maxes, $items);
851 $max = array_sum($maxes);
853 // update db if anything changed
854 if ($this->grade_item->grademax != $max or $this->grade_item->grademin != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
855 $this->grade_item->grademax = $max;
856 $this->grade_item->grademin = 0;
857 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
858 $this->grade_item->update('aggregation');
863 * Internal function for category grades summing
865 * @param grade_grade $grade The grade item
866 * @param float $oldfinalgrade Old Final grade
867 * @param array $items Grade items
868 * @param array $grade_values Grade values
869 * @param array $excluded Excluded
871 private function sum_grades(&$grade, $oldfinalgrade, $items, $grade_values, $excluded) {
872 if (empty($items)) {
873 return null;
876 // ungraded and excluded items are not used in aggregation
877 foreach ($grade_values as $itemid=>$v) {
879 if (is_null($v)) {
880 unset($grade_values[$itemid]);
882 } else if (in_array($itemid, $excluded)) {
883 unset($grade_values[$itemid]);
887 // use 0 if grade missing, droplow used and aggregating all items
888 if (!$this->aggregateonlygraded and !empty($this->droplow)) {
890 foreach ($items as $itemid=>$value) {
892 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
893 $grade_values[$itemid] = 0;
898 $this->apply_limit_rules($grade_values, $items);
900 $sum = array_sum($grade_values);
901 $grade->finalgrade = $this->grade_item->bounded_grade($sum);
903 // update in db if changed
904 if (grade_floats_different($grade->finalgrade, $oldfinalgrade)) {
905 $grade->timemodified = time();
906 $grade->update('aggregation');
909 return;
913 * Given an array of grade values (numerical indices) applies droplow or keephigh rules to limit the final array.
915 * @param array $grade_values itemid=>$grade_value float
916 * @param array $items grade item objects
917 * @return array Limited grades.
919 public function apply_limit_rules(&$grade_values, $items) {
920 $extraused = $this->is_extracredit_used();
922 if (!empty($this->droplow)) {
923 asort($grade_values, SORT_NUMERIC);
924 $dropped = 0;
926 // If we have fewer grade items available to drop than $this->droplow, use this flag to escape the loop
927 // May occur because of "extra credit" or if droplow is higher than the number of grade items
928 $droppedsomething = true;
930 while ($dropped < $this->droplow && $droppedsomething) {
931 $droppedsomething = false;
933 $grade_keys = array_keys($grade_values);
934 $gradekeycount = count($grade_keys);
936 if ($gradekeycount === 0) {
937 //We've dropped all grade items
938 break;
941 $originalindex = $founditemid = $foundmax = null;
943 // Find the first remaining grade item that is available to be dropped
944 foreach ($grade_keys as $gradekeyindex=>$gradekey) {
945 if (!$extraused || $items[$gradekey]->aggregationcoef <= 0) {
946 // Found a non-extra credit grade item that is eligible to be dropped
947 $originalindex = $gradekeyindex;
948 $founditemid = $grade_keys[$originalindex];
949 $foundmax = $items[$founditemid]->grademax;
950 break;
954 if (empty($founditemid)) {
955 // No grade items available to drop
956 break;
959 // Now iterate over the remaining grade items
960 // We're looking for other grade items with the same grade value but a higher grademax
961 $i = 1;
962 while ($originalindex + $i < $gradekeycount) {
964 $possibleitemid = $grade_keys[$originalindex+$i];
965 $i++;
967 if ($grade_values[$founditemid] != $grade_values[$possibleitemid]) {
968 // The next grade item has a different grade value. Stop looking.
969 break;
972 if ($extraused && $items[$possibleitemid]->aggregationcoef > 0) {
973 // Don't drop extra credit grade items. Continue the search.
974 continue;
977 if ($foundmax < $items[$possibleitemid]->grademax) {
978 // Found a grade item with the same grade value and a higher grademax
979 $foundmax = $items[$possibleitemid]->grademax;
980 $founditemid = $possibleitemid;
981 // Continue searching to see if there is an even higher grademax
985 // Now drop whatever grade item we have found
986 unset($grade_values[$founditemid]);
987 $dropped++;
988 $droppedsomething = true;
991 } else if (!empty($this->keephigh)) {
992 arsort($grade_values, SORT_NUMERIC);
993 $kept = 0;
995 foreach ($grade_values as $itemid=>$value) {
997 if ($extraused and $items[$itemid]->aggregationcoef > 0) {
998 // we keep all extra credits
1000 } else if ($kept < $this->keephigh) {
1001 $kept++;
1003 } else {
1004 unset($grade_values[$itemid]);
1011 * Returns true if category uses extra credit of any kind
1013 * @return bool True if extra credit used
1015 public function is_extracredit_used() {
1016 return self::aggregation_uses_extracredit($this->aggregation);
1020 * Returns true if aggregation passed is using extracredit.
1022 * @param int $aggregation Aggregation const.
1023 * @return bool True if extra credit used
1025 public static function aggregation_uses_extracredit($aggregation) {
1026 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1027 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1028 or $aggregation == GRADE_AGGREGATE_SUM);
1032 * Returns true if category uses special aggregation coefficient
1034 * @return bool True if an aggregation coefficient is being used
1036 public function is_aggregationcoef_used() {
1037 return self::aggregation_uses_aggregationcoef($this->aggregation);
1042 * Returns true if aggregation uses aggregationcoef
1044 * @param int $aggregation Aggregation const.
1045 * @return bool True if an aggregation coefficient is being used
1047 public static function aggregation_uses_aggregationcoef($aggregation) {
1048 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN
1049 or $aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1050 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1051 or $aggregation == GRADE_AGGREGATE_SUM);
1056 * Recursive function to find which weight/extra credit field to use in the grade item form.
1058 * Inherits from a parent category if that category has aggregatesubcats set to true.
1060 * @param string $first Whether or not this is the first item in the recursion
1061 * @return string
1063 public function get_coefstring($first=true) {
1064 if (!is_null($this->coefstring)) {
1065 return $this->coefstring;
1068 $overriding_coefstring = null;
1070 // Stop recursing upwards if this category aggregates subcats or has no parent
1071 if (!$first && !$this->aggregatesubcats) {
1073 if ($parent_category = $this->load_parent_category()) {
1074 return $parent_category->get_coefstring(false);
1076 } else {
1077 return null;
1080 } else if ($first) {
1082 if (!$this->aggregatesubcats) {
1084 if ($parent_category = $this->load_parent_category()) {
1085 $overriding_coefstring = $parent_category->get_coefstring(false);
1090 // If an overriding coefstring has trickled down from one of the parent categories, return it. Otherwise, return self.
1091 if (!is_null($overriding_coefstring)) {
1092 return $overriding_coefstring;
1095 // No parent category is overriding this category's aggregation, return its string
1096 if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
1097 $this->coefstring = 'aggregationcoefweight';
1099 } else if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2) {
1100 $this->coefstring = 'aggregationcoefextrasum';
1102 } else if ($this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
1103 $this->coefstring = 'aggregationcoefextraweight';
1105 } else if ($this->aggregation == GRADE_AGGREGATE_SUM) {
1106 $this->coefstring = 'aggregationcoefextrasum';
1108 } else {
1109 $this->coefstring = 'aggregationcoef';
1111 return $this->coefstring;
1115 * Returns tree with all grade_items and categories as elements
1117 * @param int $courseid The course ID
1118 * @param bool $include_category_items as category children
1119 * @return array
1121 public static function fetch_course_tree($courseid, $include_category_items=false) {
1122 $course_category = grade_category::fetch_course_category($courseid);
1123 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
1124 'children'=>$course_category->get_children($include_category_items));
1126 $course_category->sortorder = $course_category->get_sortorder();
1127 $sortorder = $course_category->get_sortorder();
1128 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1132 * An internal function that recursively sorts grade categories within a course
1134 * @param array $category_array The seed of the recursion
1135 * @param int $sortorder The current sortorder
1136 * @return array An array containing 'object', 'type', 'depth' and optionally 'children'
1138 static private function _fetch_course_tree_recursion($category_array, &$sortorder) {
1139 // update the sortorder in db if needed
1140 //NOTE: This leads to us resetting sort orders every time the categories and items page is viewed :(
1141 //if ($category_array['object']->sortorder != $sortorder) {
1142 //$category_array['object']->set_sortorder($sortorder);
1145 if (isset($category_array['object']->gradetype) && $category_array['object']->gradetype==GRADE_TYPE_NONE) {
1146 return null;
1149 // store the grade_item or grade_category instance with extra info
1150 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
1152 // reuse final grades if there
1153 if (array_key_exists('finalgrades', $category_array)) {
1154 $result['finalgrades'] = $category_array['finalgrades'];
1157 // recursively resort children
1158 if (!empty($category_array['children'])) {
1159 $result['children'] = array();
1160 //process the category item first
1161 $child = null;
1163 foreach ($category_array['children'] as $oldorder=>$child_array) {
1165 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
1166 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1167 if (!empty($child)) {
1168 $result['children'][$sortorder] = $child;
1173 foreach ($category_array['children'] as $oldorder=>$child_array) {
1175 if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
1176 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1177 if (!empty($child)) {
1178 $result['children'][++$sortorder] = $child;
1184 return $result;
1188 * Fetches and returns all the children categories and/or grade_items belonging to this category.
1189 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
1190 * as well as all levels (0). The elements are indexed by sort order.
1192 * @param bool $include_category_items Whether or not to include category grade_items in the children array
1193 * @return array Array of child objects (grade_category and grade_item).
1195 public function get_children($include_category_items=false) {
1196 global $DB;
1198 // This function must be as fast as possible ;-)
1199 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
1200 // we have to limit the number of queries though, because it will be used often in grade reports
1202 $cats = $DB->get_records('grade_categories', array('courseid' => $this->courseid));
1203 $items = $DB->get_records('grade_items', array('courseid' => $this->courseid));
1205 // init children array first
1206 foreach ($cats as $catid=>$cat) {
1207 $cats[$catid]->children = array();
1210 //first attach items to cats and add category sortorder
1211 foreach ($items as $item) {
1213 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
1214 $cats[$item->iteminstance]->sortorder = $item->sortorder;
1216 if (!$include_category_items) {
1217 continue;
1219 $categoryid = $item->iteminstance;
1221 } else {
1222 $categoryid = $item->categoryid;
1223 if (empty($categoryid)) {
1224 debugging('Found a grade item that isnt in a category');
1228 // prevent problems with duplicate sortorders in db
1229 $sortorder = $item->sortorder;
1231 while (array_key_exists($categoryid, $cats)
1232 && array_key_exists($sortorder, $cats[$categoryid]->children)) {
1234 $sortorder++;
1237 $cats[$categoryid]->children[$sortorder] = $item;
1241 // now find the requested category and connect categories as children
1242 $category = false;
1244 foreach ($cats as $catid=>$cat) {
1246 if (empty($cat->parent)) {
1248 if ($cat->path !== '/'.$cat->id.'/') {
1249 $grade_category = new grade_category($cat, false);
1250 $grade_category->path = '/'.$cat->id.'/';
1251 $grade_category->depth = 1;
1252 $grade_category->update('system');
1253 return $this->get_children($include_category_items);
1256 } else {
1258 if (empty($cat->path) or !preg_match('|/'.$cat->parent.'/'.$cat->id.'/$|', $cat->path)) {
1259 //fix paths and depts
1260 static $recursioncounter = 0; // prevents infinite recursion
1261 $recursioncounter++;
1263 if ($recursioncounter < 5) {
1264 // fix paths and depths!
1265 $grade_category = new grade_category($cat, false);
1266 $grade_category->depth = 0;
1267 $grade_category->path = null;
1268 $grade_category->update('system');
1269 return $this->get_children($include_category_items);
1272 // prevent problems with duplicate sortorders in db
1273 $sortorder = $cat->sortorder;
1275 while (array_key_exists($sortorder, $cats[$cat->parent]->children)) {
1276 //debugging("$sortorder exists in cat loop");
1277 $sortorder++;
1280 $cats[$cat->parent]->children[$sortorder] = &$cats[$catid];
1283 if ($catid == $this->id) {
1284 $category = &$cats[$catid];
1288 unset($items); // not needed
1289 unset($cats); // not needed
1291 $children_array = grade_category::_get_children_recursion($category);
1293 ksort($children_array);
1295 return $children_array;
1300 * Private method used to retrieve all children of this category recursively
1302 * @param grade_category $category Source of current recursion
1303 * @return array An array of child grade categories
1305 private static function _get_children_recursion($category) {
1307 $children_array = array();
1308 foreach ($category->children as $sortorder=>$child) {
1310 if (array_key_exists('itemtype', $child)) {
1311 $grade_item = new grade_item($child, false);
1313 if (in_array($grade_item->itemtype, array('course', 'category'))) {
1314 $type = $grade_item->itemtype.'item';
1315 $depth = $category->depth;
1317 } else {
1318 $type = 'item';
1319 $depth = $category->depth; // we use this to set the same colour
1321 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
1323 } else {
1324 $children = grade_category::_get_children_recursion($child);
1325 $grade_category = new grade_category($child, false);
1327 if (empty($children)) {
1328 $children = array();
1330 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
1334 // sort the array
1335 ksort($children_array);
1337 return $children_array;
1341 * Uses {@link get_grade_item()} to load or create a grade_item, then saves it as $this->grade_item.
1343 * @return grade_item
1345 public function load_grade_item() {
1346 if (empty($this->grade_item)) {
1347 $this->grade_item = $this->get_grade_item();
1349 return $this->grade_item;
1353 * Retrieves this grade categories' associated grade_item from the database
1355 * If no grade_item exists yet, creates one.
1357 * @return grade_item
1359 public function get_grade_item() {
1360 if (empty($this->id)) {
1361 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
1362 return false;
1365 if (empty($this->parent)) {
1366 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
1368 } else {
1369 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
1372 if (!$grade_items = grade_item::fetch_all($params)) {
1373 // create a new one
1374 $grade_item = new grade_item($params, false);
1375 $grade_item->gradetype = GRADE_TYPE_VALUE;
1376 $grade_item->insert('system');
1378 } else if (count($grade_items) == 1) {
1379 // found existing one
1380 $grade_item = reset($grade_items);
1382 } else {
1383 debugging("Found more than one grade_item attached to category id:".$this->id);
1384 // return first one
1385 $grade_item = reset($grade_items);
1388 return $grade_item;
1392 * Uses $this->parent to instantiate $this->parent_category based on the referenced record in the DB
1394 * @return grade_category The parent category
1396 public function load_parent_category() {
1397 if (empty($this->parent_category) && !empty($this->parent)) {
1398 $this->parent_category = $this->get_parent_category();
1400 return $this->parent_category;
1404 * Uses $this->parent to instantiate and return a grade_category object
1406 * @return grade_category Returns the parent category or null if this category has no parent
1408 public function get_parent_category() {
1409 if (!empty($this->parent)) {
1410 $parent_category = new grade_category(array('id' => $this->parent));
1411 return $parent_category;
1412 } else {
1413 return null;
1418 * Returns the most descriptive field for this grade category
1420 * @return string name
1422 public function get_name() {
1423 global $DB;
1424 // For a course category, we return the course name if the fullname is set to '?' in the DB (empty in the category edit form)
1425 if (empty($this->parent) && $this->fullname == '?') {
1426 $course = $DB->get_record('course', array('id'=> $this->courseid));
1427 return format_string($course->fullname);
1429 } else {
1430 return $this->fullname;
1435 * Sets this category's parent id
1437 * @param int $parentid The ID of the category that is the new parent to $this
1438 * @param string $source From where was the object updated (mod/forum, manual, etc.)
1439 * @return bool success
1441 public function set_parent($parentid, $source=null) {
1442 if ($this->parent == $parentid) {
1443 return true;
1446 if ($parentid == $this->id) {
1447 print_error('cannotassignselfasparent');
1450 if (empty($this->parent) and $this->is_course_category()) {
1451 print_error('cannothaveparentcate');
1454 // find parent and check course id
1455 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
1456 return false;
1459 $this->force_regrading();
1461 // set new parent category
1462 $this->parent = $parent_category->id;
1463 $this->parent_category =& $parent_category;
1464 $this->path = null; // remove old path and depth - will be recalculated in update()
1465 $this->depth = 0; // remove old path and depth - will be recalculated in update()
1466 $this->update($source);
1468 return $this->update($source);
1472 * Returns the final grade values for this grade category.
1474 * @param int $userid Optional user ID to retrieve a single user's final grade
1475 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
1477 public function get_final($userid=null) {
1478 $this->load_grade_item();
1479 return $this->grade_item->get_final($userid);
1483 * Returns the sortorder of the grade categories' associated grade_item
1485 * This method is also available in grade_item for cases where the object type is not known.
1487 * @return int Sort order
1489 public function get_sortorder() {
1490 $this->load_grade_item();
1491 return $this->grade_item->get_sortorder();
1495 * Returns the idnumber of the grade categories' associated grade_item.
1497 * This method is also available in grade_item for cases where the object type is not known.
1499 * @return string idnumber
1501 public function get_idnumber() {
1502 $this->load_grade_item();
1503 return $this->grade_item->get_idnumber();
1507 * Sets the sortorder variable for this category.
1509 * This method is also available in grade_item, for cases where the object type is not know.
1511 * @param int $sortorder The sortorder to assign to this category
1513 public function set_sortorder($sortorder) {
1514 $this->load_grade_item();
1515 $this->grade_item->set_sortorder($sortorder);
1519 * Move this category after the given sortorder
1521 * Does not change the parent
1523 * @param int $sortorder to place after.
1524 * @return void
1526 public function move_after_sortorder($sortorder) {
1527 $this->load_grade_item();
1528 $this->grade_item->move_after_sortorder($sortorder);
1532 * Return true if this is the top most category that represents the total course grade.
1534 * @return bool
1536 public function is_course_category() {
1537 $this->load_grade_item();
1538 return $this->grade_item->is_course_item();
1542 * Return the course level grade_category object
1544 * @param int $courseid The Course ID
1545 * @return grade_category Returns the course level grade_category instance
1547 public static function fetch_course_category($courseid) {
1548 if (empty($courseid)) {
1549 debugging('Missing course id!');
1550 return false;
1553 // course category has no parent
1554 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
1555 return $course_category;
1558 // create a new one
1559 $course_category = new grade_category();
1560 $course_category->insert_course_category($courseid);
1562 return $course_category;
1566 * Is grading object editable?
1568 * @return bool
1570 public function is_editable() {
1571 return true;
1575 * Returns the locked state/date of the grade categories' associated grade_item.
1577 * This method is also available in grade_item, for cases where the object type is not known.
1579 * @return bool
1581 public function is_locked() {
1582 $this->load_grade_item();
1583 return $this->grade_item->is_locked();
1587 * Sets the grade_item's locked variable and updates the grade_item.
1589 * Calls set_locked() on the categories' grade_item
1591 * @param int $lockedstate 0, 1 or a timestamp int(10) after which date the item will be locked.
1592 * @param bool $cascade lock/unlock child objects too
1593 * @param bool $refresh refresh grades when unlocking
1594 * @return bool success if category locked (not all children mayb be locked though)
1596 public function set_locked($lockedstate, $cascade=false, $refresh=true) {
1597 $this->load_grade_item();
1599 $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
1601 if ($cascade) {
1602 //process all children - items and categories
1603 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
1605 foreach ($children as $child) {
1606 $child->set_locked($lockedstate, true, false);
1608 if (empty($lockedstate) and $refresh) {
1609 //refresh when unlocking
1610 $child->refresh_grades();
1615 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
1617 foreach ($children as $child) {
1618 $child->set_locked($lockedstate, true, true);
1623 return $result;
1627 * Overrides grade_object::set_properties() to add special handling for changes to category aggregation types
1629 * @param stdClass $instance the object to set the properties on
1630 * @param array|stdClass $params Either an associative array or an object containing property name, property value pairs
1632 public static function set_properties(&$instance, $params) {
1633 global $DB;
1635 parent::set_properties($instance, $params);
1637 //if they've changed aggregation type we made need to do some fiddling to provide appropriate defaults
1638 if (!empty($params->aggregation)) {
1640 //weight and extra credit share a column :( Would like a default of 1 for weight and 0 for extra credit
1641 //Flip from the default of 0 to 1 (or vice versa) if ALL items in the category are still set to the old default.
1642 if (self::aggregation_uses_aggregationcoef($params->aggregation)) {
1643 $sql = $defaultaggregationcoef = null;
1645 if (!self::aggregation_uses_extracredit($params->aggregation)) {
1646 //if all items in this category have aggregation coefficient of 0 we can change it to 1 ie evenly weighted
1647 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=0";
1648 $defaultaggregationcoef = 1;
1649 } else {
1650 //if all items in this category have aggregation coefficient of 1 we can change it to 0 ie no extra credit
1651 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=1";
1652 $defaultaggregationcoef = 0;
1655 $params = array('categoryid'=>$instance->id);
1656 $count = $DB->count_records_sql($sql, $params);
1657 if ($count===0) { //category is either empty or all items are set to a default value so we can switch defaults
1658 $params['aggregationcoef'] = $defaultaggregationcoef;
1659 $DB->execute("update {grade_items} set aggregationcoef=:aggregationcoef where categoryid=:categoryid",$params);
1666 * Sets the grade_item's hidden variable and updates the grade_item.
1668 * Overrides grade_item::set_hidden() to add cascading of the hidden value to grade items in this grade category
1670 * @param int $hidden 0 mean always visible, 1 means always hidden and a number > 1 is a timestamp to hide until
1671 * @param bool $cascade apply to child objects too
1673 public function set_hidden($hidden, $cascade=false) {
1674 $this->load_grade_item();
1675 //this hides the associated grade item (the course total)
1676 $this->grade_item->set_hidden($hidden, $cascade);
1677 //this hides the category itself and everything it contains
1678 parent::set_hidden($hidden, $cascade);
1680 if ($cascade) {
1682 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
1684 foreach ($children as $child) {
1685 if ($child->can_control_visibility()) {
1686 $child->set_hidden($hidden, $cascade);
1691 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
1693 foreach ($children as $child) {
1694 $child->set_hidden($hidden, $cascade);
1699 //if marking category visible make sure parent category is visible MDL-21367
1700 if( !$hidden ) {
1701 $category_array = grade_category::fetch_all(array('id'=>$this->parent));
1702 if ($category_array && array_key_exists($this->parent, $category_array)) {
1703 $category = $category_array[$this->parent];
1704 //call set_hidden on the category regardless of whether it is hidden as its parent might be hidden
1705 //if($category->is_hidden()) {
1706 $category->set_hidden($hidden, false);
1713 * Applies default settings on this category
1715 * @return bool True if anything changed
1717 public function apply_default_settings() {
1718 global $CFG;
1720 foreach ($this->forceable as $property) {
1722 if (isset($CFG->{"grade_$property"})) {
1724 if ($CFG->{"grade_$property"} == -1) {
1725 continue; //temporary bc before version bump
1727 $this->$property = $CFG->{"grade_$property"};
1733 * Applies forced settings on this category
1735 * @return bool True if anything changed
1737 public function apply_forced_settings() {
1738 global $CFG;
1740 $updated = false;
1742 foreach ($this->forceable as $property) {
1744 if (isset($CFG->{"grade_$property"}) and isset($CFG->{"grade_{$property}_flag"}) and
1745 ((int) $CFG->{"grade_{$property}_flag"} & 1)) {
1747 if ($CFG->{"grade_$property"} == -1) {
1748 continue; //temporary bc before version bump
1750 $this->$property = $CFG->{"grade_$property"};
1751 $updated = true;
1755 return $updated;
1759 * Notification of change in forced category settings.
1761 * Causes all course and category grade items to be marked as needing to be updated
1763 public static function updated_forced_settings() {
1764 global $CFG, $DB;
1765 $params = array(1, 'course', 'category');
1766 $sql = "UPDATE {grade_items} SET needsupdate=? WHERE itemtype=? or itemtype=?";
1767 $DB->execute($sql, $params);