MDL-46819 core_grades: Negative weights are changed to 0
[moodle.git] / lib / grade / grade_category.php
CommitLineData
b79fe189 1<?php
b79fe189 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.
13//
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/>.
a153c9f2 16
b79fe189 17/**
a153c9f2 18 * Definition of a class to represent a grade category
b79fe189 19 *
a153c9f2
AD
20 * @package core_grades
21 * @copyright 2006 Nicolas Connault
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
b79fe189 23 */
7ad5a627
PS
24
25defined('MOODLE_INTERNAL') || die();
26
8a31e65c 27require_once('grade_object.php');
28
b79fe189 29/**
a153c9f2 30 * grade_category is an object mapped to DB table {prefix}grade_categories
b79fe189 31 *
a153c9f2
AD
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
b79fe189 36 */
3058964f 37class grade_category extends grade_object {
8a31e65c 38 /**
7c8a963f 39 * The DB table.
8a31e65c 40 * @var string $table
41 */
da3801e8 42 public $table = 'grade_categories';
4a490db0 43
8a31e65c 44 /**
3f2b0c8a 45 * Array of required table fields, must start with 'id'.
46 * @var array $required_fields
8a31e65c 47 */
da3801e8 48 public $required_fields = array('id', 'courseid', 'parent', 'depth', 'path', 'fullname', 'aggregation',
3f2b0c8a 49 'keephigh', 'droplow', 'aggregateonlygraded', 'aggregateoutcomes',
a25bb902 50 'aggregatesubcats', 'timecreated', 'timemodified', 'hidden');
4a490db0 51
8a31e65c 52 /**
53 * The course this category belongs to.
54 * @var int $courseid
55 */
da3801e8 56 public $courseid;
4a490db0 57
8a31e65c 58 /**
59 * The category this category belongs to (optional).
4a490db0 60 * @var int $parent
8a31e65c 61 */
da3801e8 62 public $parent;
4a490db0 63
8c846243 64 /**
65 * The grade_category object referenced by $this->parent (PK).
a153c9f2 66 * @var grade_category $parent_category
8c846243 67 */
da3801e8 68 public $parent_category;
27f95e9b 69
e5c674f1 70 /**
71 * The number of parents this category has.
72 * @var int $depth
73 */
da3801e8 74 public $depth = 0;
e5c674f1 75
76 /**
c2efb501 77 * Shows the hierarchical path for this category as /1/2/3/ (like course_categories), the last number being
e5c674f1 78 * this category's autoincrement ID number.
79 * @var string $path
80 */
da3801e8 81 public $path;
e5c674f1 82
8a31e65c 83 /**
84 * The name of this category.
85 * @var string $fullname
86 */
da3801e8 87 public $fullname;
4a490db0 88
8a31e65c 89 /**
90 * A constant pointing to one of the predefined aggregation strategies (none, mean, median, sum etc) .
4a490db0 91 * @var int $aggregation
8a31e65c 92 */
2be0d5c3 93 public $aggregation = GRADE_AGGREGATE_SUM;
4a490db0 94
8a31e65c 95 /**
96 * Keep only the X highest items.
97 * @var int $keephigh
98 */
da3801e8 99 public $keephigh = 0;
4a490db0 100
8a31e65c 101 /**
102 * Drop the X lowest items.
103 * @var int $droplow
104 */
da3801e8 105 public $droplow = 0;
4a490db0 106
c2efb501 107 /**
108 * Aggregate only graded items
109 * @var int $aggregateonlygraded
110 */
da3801e8 111 public $aggregateonlygraded = 0;
c2efb501 112
29d509f5 113 /**
114 * Aggregate outcomes together with normal items
c2efb501 115 * @var int $aggregateoutcomes
29d509f5 116 */
da3801e8 117 public $aggregateoutcomes = 0;
29d509f5 118
c2efb501 119 /**
120 * Ignore subcategories when aggregating
121 * @var int $aggregatesubcats
122 */
da3801e8 123 public $aggregatesubcats = 0;
c2efb501 124
8a31e65c 125 /**
126 * Array of grade_items or grade_categories nested exactly 1 level below this category
127 * @var array $children
128 */
da3801e8 129 public $children;
8a31e65c 130
7c8a963f 131 /**
4a490db0 132 * A hierarchical array of all children below this category. This is stored separately from
7c8a963f 133 * $children because it is more memory-intensive and may not be used as often.
134 * @var array $all_children
135 */
da3801e8 136 public $all_children;
7c8a963f 137
f151b073 138 /**
139 * An associated grade_item object, with itemtype=category, used to calculate and cache a set of grade values
140 * for this category.
a153c9f2 141 * @var grade_item $grade_item
f151b073 142 */
da3801e8 143 public $grade_item;
f151b073 144
b3ac6c3e 145 /**
146 * Temporary sortorder for speedup of children resorting
a153c9f2 147 * @var int $sortorder
b3ac6c3e 148 */
da3801e8 149 public $sortorder;
b3ac6c3e 150
89a5f827 151 /**
152 * List of options which can be "forced" from site settings.
a153c9f2 153 * @var array $forceable
89a5f827 154 */
da3801e8 155 public $forceable = array('aggregation', 'keephigh', 'droplow', 'aggregateonlygraded', 'aggregateoutcomes', 'aggregatesubcats');
89a5f827 156
653a8648 157 /**
158 * String representing the aggregation coefficient. Variable is used as cache.
a153c9f2 159 * @var string $coefstring
653a8648 160 */
b79fe189 161 public $coefstring = null;
653a8648 162
4272386a
FM
163 /**
164 * Static variable storing the result from {@link self::can_apply_limit_rules}.
165 * @var bool
166 */
167 protected $canapplylimitrules;
168
e5c674f1 169 /**
170 * Builds this category's path string based on its parents (if any) and its own id number.
171 * This is typically done just before inserting this object in the DB for the first time,
ce385eb4 172 * or when a new parent is added or changed. It is a recursive function: once the calling
173 * object no longer has a parent, the path is complete.
174 *
a153c9f2
AD
175 * @param grade_category $grade_category A Grade_Category object
176 * @return string The category's path string
e5c674f1 177 */
22a9b6d8 178 public static function build_path($grade_category) {
da3801e8 179 global $DB;
180
ce385eb4 181 if (empty($grade_category->parent)) {
c2efb501 182 return '/'.$grade_category->id.'/';
b79fe189 183
ce385eb4 184 } else {
da3801e8 185 $parent = $DB->get_record('grade_categories', array('id' => $grade_category->parent));
9a68cffc 186 return grade_category::build_path($parent).$grade_category->id.'/';
ce385eb4 187 }
e5c674f1 188 }
189
8a31e65c 190 /**
f92dcad8 191 * Finds and returns a grade_category instance based on params.
8a31e65c 192 *
f92dcad8 193 * @param array $params associative arrays varname=>value
a153c9f2 194 * @return grade_category The retrieved grade_category instance or false if none found.
f92dcad8 195 */
da3801e8 196 public static function fetch($params) {
f3ac8eb4 197 return grade_object::fetch_helper('grade_categories', 'grade_category', $params);
f92dcad8 198 }
199
200 /**
201 * Finds and returns all grade_category instances based on params.
f92dcad8 202 *
203 * @param array $params associative arrays varname=>value
204 * @return array array of grade_category insatnces or false if none found.
205 */
da3801e8 206 public static function fetch_all($params) {
f3ac8eb4 207 return grade_object::fetch_all_helper('grade_categories', 'grade_category', $params);
ce385eb4 208 }
209
8f4a626d 210 /**
2cc4b0f9 211 * In addition to update() as defined in grade_object, call force_regrading of parent categories, if applicable.
a153c9f2 212 *
aaff71da 213 * @param string $source from where was the object updated (mod/forum, manual, etc.)
a153c9f2 214 * @return bool success
8f4a626d 215 */
da3801e8 216 public function update($source=null) {
b3ac6c3e 217 // load the grade item or create a new one
218 $this->load_grade_item();
219
220 // force recalculation of path;
221 if (empty($this->path)) {
9a68cffc 222 $this->path = grade_category::build_path($this);
c2efb501 223 $this->depth = substr_count($this->path, '/') - 1;
1909a127 224 $updatechildren = true;
b79fe189 225
1909a127 226 } else {
227 $updatechildren = false;
4a490db0 228 }
0fc7f624 229
89a5f827 230 $this->apply_forced_settings();
231
b79fe189 232 // these are exclusive
89a5f827 233 if ($this->droplow > 0) {
234 $this->keephigh = 0;
b79fe189 235
89a5f827 236 } else if ($this->keephigh > 0) {
237 $this->droplow = 0;
238 }
4a490db0 239
b3ac6c3e 240 // Recalculate grades if needed
241 if ($this->qualifies_for_regrading()) {
f8e6e4db 242 $this->force_regrading();
4a490db0 243 }
f8e6e4db 244
ced5ee59 245 $this->timemodified = time();
246
1909a127 247 $result = parent::update($source);
248
249 // now update paths in all child categories
250 if ($result and $updatechildren) {
b79fe189 251
1909a127 252 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 253
1909a127 254 foreach ($children as $child) {
1909a127 255 $child->path = null;
256 $child->depth = 0;
257 $child->update($source);
da3801e8 258 }
1909a127 259 }
260 }
261
262 return $result;
8f4a626d 263 }
4a490db0 264
8f4a626d 265 /**
2cc4b0f9 266 * If parent::delete() is successful, send force_regrading message to parent category.
a153c9f2 267 *
aaff71da 268 * @param string $source from where was the object deleted (mod/forum, manual, etc.)
a153c9f2 269 * @return bool success
8f4a626d 270 */
da3801e8 271 public function delete($source=null) {
f13002d5 272 $grade_item = $this->load_grade_item();
4a490db0 273
f615fbab 274 if ($this->is_course_category()) {
b79fe189 275
f3ac8eb4 276 if ($categories = grade_category::fetch_all(array('courseid'=>$this->courseid))) {
b79fe189 277
f615fbab 278 foreach ($categories as $category) {
b79fe189 279
f615fbab 280 if ($category->id == $this->id) {
281 continue; // do not delete course category yet
282 }
283 $category->delete($source);
284 }
aaff71da 285 }
2b0f65e2 286
f3ac8eb4 287 if ($items = grade_item::fetch_all(array('courseid'=>$this->courseid))) {
b79fe189 288
f615fbab 289 foreach ($items as $item) {
b79fe189 290
f615fbab 291 if ($item->id == $grade_item->id) {
292 continue; // do not delete course item yet
293 }
294 $item->delete($source);
295 }
296 }
297
298 } else {
299 $this->force_regrading();
2b0f65e2 300
f615fbab 301 $parent = $this->load_parent_category();
2b0f65e2 302
f615fbab 303 // Update children's categoryid/parent field first
f3ac8eb4 304 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
f615fbab 305 foreach ($children as $child) {
306 $child->set_parent($parent->id);
307 }
308 }
b79fe189 309
f3ac8eb4 310 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
f615fbab 311 foreach ($children as $child) {
312 $child->set_parent($parent->id);
313 }
aaff71da 314 }
315 }
f13002d5 316
aaff71da 317 // first delete the attached grade item and grades
318 $grade_item->delete($source);
f13002d5 319
320 // delete category itself
aaff71da 321 return parent::delete($source);
8f4a626d 322 }
4a490db0 323
ce385eb4 324 /**
325 * In addition to the normal insert() defined in grade_object, this method sets the depth
a153c9f2
AD
326 * and path for this object, and update the record accordingly.
327 *
328 * We do this here instead of in the constructor as they both need to know the record's
329 * ID number, which only gets created at insertion time.
f151b073 330 * This method also creates an associated grade_item if this wasn't done during construction.
a153c9f2 331 *
aaff71da 332 * @param string $source from where was the object inserted (mod/forum, manual, etc.)
333 * @return int PK ID if successful, false otherwise
ce385eb4 334 */
da3801e8 335 public function insert($source=null) {
b3ac6c3e 336
337 if (empty($this->courseid)) {
2f137aa1 338 print_error('cannotinsertgrade');
b8ff92b6 339 }
4a490db0 340
b3ac6c3e 341 if (empty($this->parent)) {
f3ac8eb4 342 $course_category = grade_category::fetch_course_category($this->courseid);
b3ac6c3e 343 $this->parent = $course_category->id;
ce385eb4 344 }
4a490db0 345
b3ac6c3e 346 $this->path = null;
347
ced5ee59 348 $this->timecreated = $this->timemodified = time();
349
aaff71da 350 if (!parent::insert($source)) {
b3ac6c3e 351 debugging("Could not insert this category: " . print_r($this, true));
352 return false;
353 }
354
f8e6e4db 355 $this->force_regrading();
356
b3ac6c3e 357 // build path and depth
aaff71da 358 $this->update($source);
4a490db0 359
aaff71da 360 return $this->id;
b3ac6c3e 361 }
362
f2c88356 363 /**
f615fbab 364 * Internal function - used only from fetch_course_category()
365 * Normal insert() can not be used for course category
b79fe189 366 *
367 * @param int $courseid The course ID
a153c9f2 368 * @return int The ID of the new course category
f2c88356 369 */
da3801e8 370 public function insert_course_category($courseid) {
1f0e4921 371 $this->courseid = $courseid;
8f6fdf43 372 $this->fullname = '?';
1f0e4921 373 $this->path = null;
374 $this->parent = null;
0c87b5aa 375 $this->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2;
4a490db0 376
190af29f 377 $this->apply_default_settings();
89a5f827 378 $this->apply_forced_settings();
379
ced5ee59 380 $this->timecreated = $this->timemodified = time();
381
aaff71da 382 if (!parent::insert('system')) {
b3ac6c3e 383 debugging("Could not insert this category: " . print_r($this, true));
384 return false;
f151b073 385 }
4a490db0 386
b3ac6c3e 387 // build path and depth
aaff71da 388 $this->update('system');
b3ac6c3e 389
aaff71da 390 return $this->id;
ce385eb4 391 }
4a490db0 392
8f4a626d 393 /**
394 * Compares the values held by this object with those of the matching record in DB, and returns
395 * whether or not these differences are sufficient to justify an update of all parent objects.
a153c9f2
AD
396 * This assumes that this object has an ID number and a matching record in DB. If not, it will return false.
397 *
398 * @return bool
8f4a626d 399 */
da3801e8 400 public function qualifies_for_regrading() {
8f4a626d 401 if (empty($this->id)) {
6639ead3 402 debugging("Can not regrade non existing category");
8f4a626d 403 return false;
404 }
f3ac8eb4 405
406 $db_item = grade_category::fetch(array('id'=>$this->id));
4a490db0 407
c2efb501 408 $aggregationdiff = $db_item->aggregation != $this->aggregation;
409 $keephighdiff = $db_item->keephigh != $this->keephigh;
410 $droplowdiff = $db_item->droplow != $this->droplow;
411 $aggonlygrddiff = $db_item->aggregateonlygraded != $this->aggregateonlygraded;
412 $aggoutcomesdiff = $db_item->aggregateoutcomes != $this->aggregateoutcomes;
413 $aggsubcatsdiff = $db_item->aggregatesubcats != $this->aggregatesubcats;
8f4a626d 414
c2efb501 415 return ($aggregationdiff || $keephighdiff || $droplowdiff || $aggonlygrddiff || $aggoutcomesdiff || $aggsubcatsdiff);
8f4a626d 416 }
8c846243 417
418 /**
a153c9f2 419 * Marks this grade categories' associated grade item as needing regrading
8c846243 420 */
da3801e8 421 public function force_regrading() {
f8e6e4db 422 $grade_item = $this->load_grade_item();
423 $grade_item->force_regrading();
8c846243 424 }
425
fcf6e015
FM
426 /**
427 * Something that should be called before we start regrading the whole course.
428 *
429 * @return void
430 */
431 public function pre_regrade_final_grades() {
fcf6e015 432 $this->auto_update_weights();
64055d50 433 $this->auto_update_max();
fcf6e015
FM
434 }
435
0aa32279 436 /**
0758a08e 437 * Generates and saves final grades in associated category grade item.
1994d890 438 * These immediate children must already have their own final grades.
0758a08e 439 * The category's aggregation method is used to generate final grades.
ac9b0805 440 *
a153c9f2 441 * Please note that category grade is either calculated or aggregated, not both at the same time.
ac9b0805 442 *
c86caae7 443 * This method must be used ONLY from grade_item::regrade_final_grades(),
ac9b0805 444 * because the calculation must be done in correct order!
b8ff92b6 445 *
4a490db0 446 * Steps to follow:
ac9b0805 447 * 1. Get final grades from immediate children
2df71235 448 * 3. Aggregate these grades
0758a08e 449 * 4. Save them in final grades of associated category grade item
b79fe189 450 *
a153c9f2 451 * @param int $userid The user ID if final grade generation should be limited to a single user
b79fe189 452 * @return bool
0aa32279 453 */
da3801e8 454 public function generate_grades($userid=null) {
455 global $CFG, $DB;
4a490db0 456
ac9b0805 457 $this->load_grade_item();
2cc4b0f9 458
459 if ($this->grade_item->is_locked()) {
460 return true; // no need to recalculate locked items
461 }
462
89a5f827 463 // find grade items of immediate children (category or grade items) and force site settings
61c33818 464 $depends_on = $this->grade_item->depends_on();
b3ac6c3e 465
f8e6e4db 466 if (empty($depends_on)) {
467 $items = false;
b79fe189 468
f8e6e4db 469 } else {
5b0af8c5 470 list($usql, $params) = $DB->get_in_or_equal($depends_on);
f8e6e4db 471 $sql = "SELECT *
5b0af8c5 472 FROM {grade_items}
473 WHERE id $usql";
474 $items = $DB->get_records_sql($sql, $params);
f8e6e4db 475 }
4a490db0 476
5b0af8c5 477 $grade_inst = new grade_grade();
478 $fields = 'g.'.implode(',g.', $grade_inst->required_fields);
479
480 // where to look for final grades - include grade of this item too, we will store the results there
481 $gis = array_merge($depends_on, array($this->grade_item->id));
482 list($usql, $params) = $DB->get_in_or_equal($gis);
483
f8e6e4db 484 if ($userid) {
5b0af8c5 485 $usersql = "AND g.userid=?";
486 $params[] = $userid;
b79fe189 487
f8e6e4db 488 } else {
489 $usersql = "";
b8ff92b6 490 }
4a490db0 491
3f2b0c8a 492 $sql = "SELECT $fields
5b0af8c5 493 FROM {grade_grades} g, {grade_items} gi
494 WHERE gi.id = g.itemid AND gi.id $usql $usersql
ac9b0805 495 ORDER BY g.userid";
b8ff92b6 496
9580a21f 497 // group the results by userid and aggregate the grades for this user
1b42e677
EL
498 $rs = $DB->get_recordset_sql($sql, $params);
499 if ($rs->valid()) {
03cedd62 500 $prevuser = 0;
501 $grade_values = array();
502 $excluded = array();
503 $oldgrade = null;
5a59aeb1
DW
504 $grademaxoverrides = array();
505 $grademinoverrides = array();
b79fe189 506
da3801e8 507 foreach ($rs as $used) {
b79fe189 508
03cedd62 509 if ($used->userid != $prevuser) {
5a59aeb1
DW
510 $this->aggregate_grades($prevuser,
511 $items,
512 $grade_values,
513 $oldgrade,
514 $excluded,
515 $grademinoverrides,
516 $grademaxoverrides);
03cedd62 517 $prevuser = $used->userid;
518 $grade_values = array();
519 $excluded = array();
520 $oldgrade = null;
5a59aeb1
DW
521 $grademaxoverrides = array();
522 $grademinoverrides = array();
03cedd62 523 }
524 $grade_values[$used->itemid] = $used->finalgrade;
5a59aeb1
DW
525 $grademaxoverrides[$used->itemid] = $used->rawgrademax;
526 $grademinoverrides[$used->itemid] = $used->rawgrademin;
b79fe189 527
03cedd62 528 if ($used->excluded) {
529 $excluded[] = $used->itemid;
530 }
b79fe189 531
03cedd62 532 if ($this->grade_item->id == $used->itemid) {
533 $oldgrade = $used;
2df71235 534 }
b8ff92b6 535 }
5a59aeb1
DW
536 $this->aggregate_grades($prevuser,
537 $items,
538 $grade_values,
539 $oldgrade,
540 $excluded,
541 $grademinoverrides,
542 $grademaxoverrides);//the last one
b8ff92b6 543 }
1b42e677 544 $rs->close();
b8ff92b6 545
b8ff92b6 546 return true;
547 }
548
549 /**
a153c9f2 550 * Internal function for grade category grade aggregation
ced5ee59 551 *
b79fe189 552 * @param int $userid The User ID
553 * @param array $items Grade items
554 * @param array $grade_values Array of grade values
555 * @param object $oldgrade Old grade
22a9b6d8 556 * @param array $excluded Excluded
5a59aeb1
DW
557 * @param array $grademinoverrides User specific grademin values if different to the grade_item grademin (key is itemid)
558 * @param array $grademaxoverrides User specific grademax values if different to the grade_item grademax (key is itemid)
b8ff92b6 559 */
5a59aeb1
DW
560 private function aggregate_grades($userid,
561 $items,
562 $grade_values,
563 $oldgrade,
564 $excluded,
565 $grademinoverrides,
566 $grademaxoverrides) {
ee07a54b 567 global $CFG, $DB;
bfe969e8
DW
568
569 // Remember these so we can set flags on them to describe how they were used in the aggregation.
570 $novalue = array();
571 $dropped = array();
53771c40 572 $extracredit = array();
bfe969e8
DW
573 $usedweights = array();
574
b8ff92b6 575 if (empty($userid)) {
f8e6e4db 576 //ignore first call
b8ff92b6 577 return;
578 }
4a490db0 579
f8e6e4db 580 if ($oldgrade) {
66690b69 581 $oldfinalgrade = $oldgrade->finalgrade;
f3ac8eb4 582 $grade = new grade_grade($oldgrade, false);
f8e6e4db 583 $grade->grade_item =& $this->grade_item;
b8ff92b6 584
f8e6e4db 585 } else {
586 // insert final grade - it will be needed later anyway
f3ac8eb4 587 $grade = new grade_grade(array('itemid'=>$this->grade_item->id, 'userid'=>$userid), false);
f8e6e4db 588 $grade->grade_item =& $this->grade_item;
f1ad9e04 589 $grade->insert('system');
590 $oldfinalgrade = null;
f8e6e4db 591 }
f1ad9e04 592
c86caae7 593 // no need to recalculate locked or overridden grades
594 if ($grade->is_locked() or $grade->is_overridden()) {
2cc4b0f9 595 return;
ac9b0805 596 }
597
f8e6e4db 598 // can not use own final category grade in calculation
9580a21f 599 unset($grade_values[$this->grade_item->id]);
f8e6e4db 600
53771c40 601 // Make sure a grade_grade exists for every grade_item.
6070e533
DW
602 // We need to do this so we can set the aggregationstatus
603 // with a set_field call instead of checking if each one exists and creating/updating.
c529f4b3 604 if (!empty($items)) {
ee07a54b
DW
605 list($ggsql, $params) = $DB->get_in_or_equal(array_keys($items), SQL_PARAMS_NAMED, 'g');
606
607
608 $params['userid'] = $userid;
609 $sql = "SELECT itemid
610 FROM {grade_grades}
611 WHERE itemid $ggsql AND userid = :userid";
612 $existingitems = $DB->get_records_sql($sql, $params);
613
614 $notexisting = array_diff(array_keys($items), array_keys($existingitems));
615 foreach ($notexisting as $itemid) {
6077a4d4 616 $gradeitem = $items[$itemid];
ee07a54b
DW
617 $gradegrade = new grade_grade(array('itemid' => $itemid,
618 'userid' => $userid,
619 'rawgrademin' => $gradeitem->grademin,
620 'rawgrademax' => $gradeitem->grademax), false);
621 $gradegrade->grade_item = $gradeitem;
53771c40
DW
622 $gradegrade->insert('system');
623 }
53771c40
DW
624 }
625
0758a08e 626 // if no grades calculation possible or grading not allowed clear final grade
9580a21f 627 if (empty($grade_values) or empty($items) or ($this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE)) {
f8e6e4db 628 $grade->finalgrade = null;
b79fe189 629
66690b69 630 if (!is_null($oldfinalgrade)) {
acd25c13
MN
631 $success = $grade->update('aggregation');
632
633 // If successful trigger a user_graded event.
634 if ($success) {
635 \core\event\user_graded::create_from_grade($grade)->trigger();
636 }
f8e6e4db 637 }
bfe969e8 638 $dropped = $grade_values;
53771c40 639 $this->set_usedinaggregation($userid, $usedweights, $novalue, $dropped, $extracredit);
b8ff92b6 640 return;
641 }
0758a08e 642
53771c40
DW
643 // Normalize the grades first - all will have value 0...1
644 // ungraded items are not used in aggregation.
825fba1c 645 foreach ($grade_values as $itemid=>$v) {
53771c40
DW
646 if (is_null($v)) {
647 // If null, it means no grade.
648 if ($this->aggregateonlygraded) {
aa705529 649 unset($grade_values[$itemid]);
ee07a54b 650 // Mark this item as "excluded empty" because it has no grade.
aa705529
JO
651 $novalue[$itemid] = 0;
652 continue;
aa705529 653 }
0e999796 654 }
53771c40
DW
655 if (in_array($itemid, $excluded)) {
656 unset($grade_values[$itemid]);
657 $dropped[$itemid] = 0;
658 continue;
659 }
5a59aeb1
DW
660 // Check for user specific grade min/max overrides.
661 $usergrademin = $items[$itemid]->grademin;
662 $usergrademax = $items[$itemid]->grademax;
663 if (isset($grademinoverrides[$itemid])) {
664 $usergrademin = $grademinoverrides[$itemid];
665 }
666 if (isset($grademaxoverrides[$itemid])) {
667 $usergrademax = $grademaxoverrides[$itemid];
668 }
0b2e8ae0
FM
669 if ($this->aggregation == GRADE_AGGREGATE_SUM) {
670 // Assume that the grademin is 0 when standardising the score, to preserve negative grades.
671 $grade_values[$itemid] = grade_grade::standardise_score($v, 0, $usergrademax, 0, 1);
672 } else {
673 $grade_values[$itemid] = grade_grade::standardise_score($v, $usergrademin, $usergrademax, 0, 1);
674 }
675
0aa32279 676 }
b79fe189 677
ee07a54b 678 // For items with no value, and not excluded - either set their grade to 0 or exclude them.
53771c40
DW
679 foreach ($items as $itemid=>$value) {
680 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
681 if (!$this->aggregateonlygraded) {
c2efb501 682 $grade_values[$itemid] = 0;
53771c40 683 } else {
ee07a54b 684 // We are specifically marking these items as "excluded empty".
53771c40 685 $novalue[$itemid] = 0;
eacd3700 686 }
c2efb501 687 }
eacd3700 688 }
689
690 // limit and sort
bfe969e8 691 $allvalues = $grade_values;
4272386a
FM
692 if ($this->can_apply_limit_rules()) {
693 $this->apply_limit_rules($grade_values, $items);
694 }
bfe969e8
DW
695
696 $moredropped = array_diff($allvalues, $grade_values);
697 foreach ($moredropped as $drop => $unused) {
698 $dropped[$drop] = 0;
699 }
53771c40
DW
700
701 foreach ($grade_values as $itemid => $val) {
702 if (self::is_extracredit_used() && ($items[$itemid]->aggregationcoef > 0)) {
703 $extracredit[$itemid] = 0;
704 }
705 }
706
9580a21f 707 asort($grade_values, SORT_NUMERIC);
4a490db0 708
d5f0aa01 709 // let's see we have still enough grades to do any statistics
9580a21f 710 if (count($grade_values) == 0) {
ac9b0805 711 // not enough attempts yet
f8e6e4db 712 $grade->finalgrade = null;
b79fe189 713
66690b69 714 if (!is_null($oldfinalgrade)) {
acd25c13
MN
715 $success = $grade->update('aggregation');
716
717 // If successful trigger a user_graded event.
718 if ($success) {
719 \core\event\user_graded::create_from_grade($grade)->trigger();
720 }
b8ff92b6 721 }
53771c40 722 $this->set_usedinaggregation($userid, $usedweights, $novalue, $dropped, $extracredit);
b8ff92b6 723 return;
724 }
2df71235 725
d297269d 726 // do the maths
5a59aeb1
DW
727 $result = $this->aggregate_values_and_adjust_bounds($grade_values,
728 $items,
729 $usedweights,
730 $grademinoverrides,
731 $grademaxoverrides);
5232d3f2 732 $agg_grade = $result['grade'];
d297269d 733
0b2e8ae0
FM
734 // Set the actual grademin and max to bind the grade properly.
735 $this->grade_item->grademin = $result['grademin'];
736 $this->grade_item->grademax = $result['grademax'];
737
738 if ($this->aggregation == GRADE_AGGREGATE_SUM) {
739 // The natural aggregation always displays the range as coming from 0 for categories.
740 // However, when we bind the grade we allow for negative values.
741 $result['grademin'] = 0;
742 }
743
825fba1c
FM
744 // Recalculate the grade back to requested range.
745 $finalgrade = grade_grade::standardise_score($agg_grade, 0, 1, $result['grademin'], $result['grademax']);
653a8648 746 $grade->finalgrade = $this->grade_item->bounded_grade($finalgrade);
0b2e8ae0
FM
747
748 $oldrawgrademin = $grade->rawgrademin;
90cc8ce7 749 $oldrawgrademax = $grade->rawgrademax;
0b2e8ae0 750 $grade->rawgrademin = $result['grademin'];
5a59aeb1 751 $grade->rawgrademax = $result['grademax'];
d297269d 752
0b2e8ae0 753 // Update in db if changed.
90cc8ce7 754 if (grade_floats_different($grade->finalgrade, $oldfinalgrade) ||
0b2e8ae0
FM
755 grade_floats_different($grade->rawgrademax, $oldrawgrademax) ||
756 grade_floats_different($grade->rawgrademin, $oldrawgrademin)) {
acd25c13
MN
757 $success = $grade->update('aggregation');
758
759 // If successful trigger a user_graded event.
760 if ($success) {
761 \core\event\user_graded::create_from_grade($grade)->trigger();
762 }
d297269d 763 }
764
53771c40 765 $this->set_usedinaggregation($userid, $usedweights, $novalue, $dropped, $extracredit);
bfe969e8 766
d297269d 767 return;
768 }
769
bfe969e8
DW
770 /**
771 * Set the flags on the grade_grade items to indicate how individual grades are used
772 * in the aggregation.
773 *
774 * @param int $userid The user we have aggregated the grades for.
775 * @param array $usedweights An array with keys for each of the grade_item columns included in the aggregation. The value are the relative weight.
776 * @param array $novalue An array with keys for each of the grade_item columns skipped because
6070e533 777 * they had no value in the aggregation.
bfe969e8 778 * @param array $dropped An array with keys for each of the grade_item columns dropped
6070e533
DW
779 * because of any drop lowest/highest settings in the aggregation.
780 * @param array $extracredit An array with keys for each of the grade_item columns
781 * considered extra credit by the aggregation.
bfe969e8 782 */
53771c40 783 private function set_usedinaggregation($userid, $usedweights, $novalue, $dropped, $extracredit) {
bfe969e8
DW
784 global $DB;
785
786 // Included.
787 if (!empty($usedweights)) {
788 // The usedweights items are updated individually to record the weights.
789 foreach ($usedweights as $gradeitemid => $contribution) {
bfe969e8 790 $DB->set_field_select('grade_grades',
a1740d7b 791 'aggregationweight',
bfe969e8
DW
792 $contribution,
793 "itemid = :itemid AND userid = :userid",
794 array('itemid'=>$gradeitemid, 'userid'=>$userid));
795 }
a1740d7b
DW
796
797 // Now set the status flag for all these weights.
798 list($itemsql, $itemlist) = $DB->get_in_or_equal(array_keys($usedweights), SQL_PARAMS_NAMED, 'g');
799 $itemlist['userid'] = $userid;
800
801 $DB->set_field_select('grade_grades',
802 'aggregationstatus',
803 'used',
804 "itemid $itemsql AND userid = :userid",
805 $itemlist);
bfe969e8
DW
806 }
807
808 // No value.
809 if (!empty($novalue)) {
810 list($itemsql, $itemlist) = $DB->get_in_or_equal(array_keys($novalue), SQL_PARAMS_NAMED, 'g');
811
812 $itemlist['userid'] = $userid;
813
814 $DB->set_field_select('grade_grades',
a1740d7b 815 'aggregationstatus',
bfe969e8
DW
816 'novalue',
817 "itemid $itemsql AND userid = :userid",
818 $itemlist);
819 }
820
821 // Dropped.
822 if (!empty($dropped)) {
823 list($itemsql, $itemlist) = $DB->get_in_or_equal(array_keys($dropped), SQL_PARAMS_NAMED, 'g');
824
825 $itemlist['userid'] = $userid;
826
827 $DB->set_field_select('grade_grades',
a1740d7b 828 'aggregationstatus',
bfe969e8
DW
829 'dropped',
830 "itemid $itemsql AND userid = :userid",
831 $itemlist);
832 }
53771c40
DW
833 // Extra credit.
834 if (!empty($extracredit)) {
835 list($itemsql, $itemlist) = $DB->get_in_or_equal(array_keys($extracredit), SQL_PARAMS_NAMED, 'g');
836
837 $itemlist['userid'] = $userid;
838
839 $DB->set_field_select('grade_grades',
840 'aggregationstatus',
841 'extra',
842 "itemid $itemsql AND userid = :userid",
843 $itemlist);
844 }
bfe969e8
DW
845 }
846
89a5f827 847 /**
5232d3f2 848 * Internal function that calculates the aggregated grade and new min/max for this grade category
b79fe189 849 *
a153c9f2 850 * Must be public as it is used by grade_grade::get_hiding_affected()
b79fe189 851 *
a153c9f2
AD
852 * @param array $grade_values An array of values to be aggregated
853 * @param array $items The array of grade_items
d6caf637 854 * @since Moodle 2.6.5, 2.7.2
bfe969e8
DW
855 * @param array & $weights If provided, will be filled with the normalized weights
856 * for each grade_item as used in the aggregation.
ee07a54b
DW
857 * Some rules for the weights are:
858 * 1. The weights must add up to 1 (unless there are extra credit)
859 * 2. The contributed points column must add up to the course
860 * final grade and this column is calculated from these weights.
5a59aeb1
DW
861 * @param array $grademinoverrides User specific grademin values if different to the grade_item grademin (key is itemid)
862 * @param array $grademaxoverrides User specific grademax values if different to the grade_item grademax (key is itemid)
5232d3f2
DW
863 * @return array containing values for:
864 * 'grade' => the new calculated grade
865 * 'grademin' => the new calculated min grade for the category
866 * 'grademax' => the new calculated max grade for the category
89a5f827 867 */
5a59aeb1
DW
868 public function aggregate_values_and_adjust_bounds($grade_values,
869 $items,
870 & $weights = null,
871 $grademinoverrides = array(),
872 $grademaxoverrides = array()) {
5232d3f2
DW
873 $category_item = $this->get_grade_item();
874 $grademin = $category_item->grademin;
875 $grademax = $category_item->grademax;
876
b8ff92b6 877 switch ($this->aggregation) {
b79fe189 878
c2efb501 879 case GRADE_AGGREGATE_MEDIAN: // Middle point value in the set: ignores frequencies
9580a21f 880 $num = count($grade_values);
c186c7b2 881 $grades = array_values($grade_values);
b79fe189 882
852fae0b
DW
883 // The median gets 100% - others get 0.
884 if ($weights !== null && $num > 0) {
885 $count = 0;
886 foreach ($grade_values as $itemid=>$grade_value) {
887 if (($num % 2 == 0) && ($count == intval($num/2)-1 || $count == intval($num/2))) {
888 $weights[$itemid] = 0.5;
889 } else if (($num % 2 != 0) && ($count == intval(($num/2)-0.5))) {
890 $weights[$itemid] = 1.0;
891 } else {
892 $weights[$itemid] = 0;
893 }
894 $count++;
895 }
896 }
c186c7b2 897 if ($num % 2 == 0) {
9c8d38fa 898 $agg_grade = ($grades[intval($num/2)-1] + $grades[intval($num/2)]) / 2;
b8ff92b6 899 } else {
9c8d38fa 900 $agg_grade = $grades[intval(($num/2)-0.5)];
b8ff92b6 901 }
bfe969e8 902
b8ff92b6 903 break;
ac9b0805 904
c2efb501 905 case GRADE_AGGREGATE_MIN:
9c8d38fa 906 $agg_grade = reset($grade_values);
bfe969e8
DW
907 // Record the weights as used.
908 if ($weights !== null) {
909 foreach ($grade_values as $itemid=>$grade_value) {
910 $weights[$itemid] = 0;
911 }
912 }
913 // Set the first item to 1.
914 $itemids = array_keys($grade_values);
915 $weights[reset($itemids)] = 1;
b8ff92b6 916 break;
917
c2efb501 918 case GRADE_AGGREGATE_MAX:
bfe969e8
DW
919 // Record the weights as used.
920 if ($weights !== null) {
921 foreach ($grade_values as $itemid=>$grade_value) {
922 $weights[$itemid] = 0;
923 }
924 }
925 // Set the last item to 1.
926 $itemids = array_keys($grade_values);
927 $weights[end($itemids)] = 1;
928 $agg_grade = end($grade_values);
b8ff92b6 929 break;
930
bfe969e8 931 case GRADE_AGGREGATE_MODE: // the most common value
0198929c 932 // array_count_values only counts INT and STRING, so if grades are floats we must convert them to string
933 $converted_grade_values = array();
934
935 foreach ($grade_values as $k => $gv) {
b79fe189 936
0198929c 937 if (!is_int($gv) && !is_string($gv)) {
938 $converted_grade_values[$k] = (string) $gv;
b79fe189 939
0198929c 940 } else {
941 $converted_grade_values[$k] = $gv;
942 }
bfe969e8
DW
943 if ($weights !== null) {
944 $weights[$k] = 0;
945 }
0198929c 946 }
947
948 $freq = array_count_values($converted_grade_values);
95affb8a 949 arsort($freq); // sort by frequency keeping keys
950 $top = reset($freq); // highest frequency count
951 $modes = array_keys($freq, $top); // search for all modes (have the same highest count)
f7d515b6 952 rsort($modes, SORT_NUMERIC); // get highest mode
9c8d38fa 953 $agg_grade = reset($modes);
bfe969e8
DW
954 // Record the weights as used.
955 if ($weights !== null && $top > 0) {
956 foreach ($grade_values as $k => $gv) {
957 if ($gv == $agg_grade) {
958 $weights[$k] = 1.0 / $top;
959 }
960 }
961 }
d5fab31f 962 break;
95affb8a 963
1426edac 964 case GRADE_AGGREGATE_WEIGHTED_MEAN: // Weighted average of all existing final grades, weight specified in coef
9580a21f 965 $weightsum = 0;
966 $sum = 0;
b79fe189 967
968 foreach ($grade_values as $itemid=>$grade_value) {
969
eacd3700 970 if ($items[$itemid]->aggregationcoef <= 0) {
9580a21f 971 continue;
972 }
eacd3700 973 $weightsum += $items[$itemid]->aggregationcoef;
974 $sum += $items[$itemid]->aggregationcoef * $grade_value;
bfe969e8
DW
975 if ($weights !== null) {
976 $weights[$itemid] = $items[$itemid]->aggregationcoef;
977 }
9580a21f 978 }
979 if ($weightsum == 0) {
9c8d38fa 980 $agg_grade = null;
b79fe189 981
9580a21f 982 } else {
9c8d38fa 983 $agg_grade = $sum / $weightsum;
bfe969e8
DW
984 if ($weights !== null) {
985 // Normalise the weights.
986 foreach ($weights as $itemid => $weight) {
987 $weights[$itemid] = $weight / $weightsum;
988 }
989 }
990
9580a21f 991 }
992 break;
993
d9ae2ab5 994 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
995 // Weighted average of all existing final grades with optional extra credit flag,
f7d515b6 996 // weight is the range of grade (usually grademax)
1426edac 997 $weightsum = 0;
d9ae2ab5 998 $sum = null;
b79fe189 999
1000 foreach ($grade_values as $itemid=>$grade_value) {
1426edac 1001 $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
b79fe189 1002
1426edac 1003 if ($weight <= 0) {
1004 continue;
1005 }
b79fe189 1006
d9ae2ab5 1007 if ($items[$itemid]->aggregationcoef == 0) {
1008 $weightsum += $weight;
1009 }
1010 $sum += $weight * $grade_value;
1426edac 1011 }
1012 if ($weightsum == 0) {
d9ae2ab5 1013 $agg_grade = $sum; // only extra credits
b79fe189 1014
1426edac 1015 } else {
1016 $agg_grade = $sum / $weightsum;
1017 }
bfe969e8
DW
1018 // Record the weights as used.
1019 if ($weights !== null) {
1020 foreach ($grade_values as $itemid=>$grade_value) {
852fae0b 1021 if ($weightsum > 0) {
bfe969e8 1022 $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
852fae0b 1023 $weights[$itemid] = $weight / $weightsum;
bfe969e8
DW
1024 } else {
1025 $weights[$itemid] = 0;
1026 }
1027 }
1028 }
1426edac 1029 break;
1030
c2efb501 1031 case GRADE_AGGREGATE_EXTRACREDIT_MEAN: // special average
9580a21f 1032 $num = 0;
d9ae2ab5 1033 $sum = null;
b79fe189 1034
1035 foreach ($grade_values as $itemid=>$grade_value) {
1036
eacd3700 1037 if ($items[$itemid]->aggregationcoef == 0) {
9580a21f 1038 $num += 1;
1039 $sum += $grade_value;
bfe969e8
DW
1040 if ($weights !== null) {
1041 $weights[$itemid] = 1;
1042 }
b79fe189 1043
eacd3700 1044 } else if ($items[$itemid]->aggregationcoef > 0) {
1045 $sum += $items[$itemid]->aggregationcoef * $grade_value;
bfe969e8 1046 if ($weights !== null) {
852fae0b 1047 $weights[$itemid] = 1;
bfe969e8
DW
1048 }
1049 }
1050 }
1051 if ($weights !== null && $num > 0) {
1052 foreach ($grade_values as $itemid=>$grade_value) {
1053 if ($weights[$itemid]) {
1054 $weights[$itemid] = 1.0 / $num;
1055 }
9580a21f 1056 }
1057 }
b79fe189 1058
9580a21f 1059 if ($num == 0) {
9c8d38fa 1060 $agg_grade = $sum; // only extra credits or wrong coefs
b79fe189 1061
9580a21f 1062 } else {
9c8d38fa 1063 $agg_grade = $sum / $num;
9580a21f 1064 }
1065 break;
1066
5232d3f2
DW
1067 case GRADE_AGGREGATE_SUM: // Add up all the items.
1068 $num = count($grade_values);
d57ea599 1069 $sum = 0;
a2c13f68 1070 $sumweights = 0;
a2c13f68
DW
1071 $grademin = 0;
1072 $grademax = 0;
1073 foreach ($grade_values as $itemid => $gradevalue) {
5a59aeb1 1074 // We need to check if the grademax/min was adjusted per user because of excluded items.
057063b1 1075 $usergrademin = $items[$itemid]->grademin;
5a59aeb1
DW
1076 $usergrademax = $items[$itemid]->grademax;
1077 if (isset($grademinoverrides[$itemid])) {
1078 $usergrademin = $grademinoverrides[$itemid];
1079 }
1080 if (isset($grademaxoverrides[$itemid])) {
1081 $usergrademax = $grademaxoverrides[$itemid];
1082 }
a2c13f68 1083
64055d50
FM
1084 // Ignore extra credit and items with a weight of 0.
1085 if ($items[$itemid]->aggregationcoef <= 0 && $items[$itemid]->aggregationcoef2 > 0) {
0b2e8ae0
FM
1086 $grademin += $usergrademin;
1087 $grademax += $usergrademax;
a2c13f68 1088 $sumweights += $items[$itemid]->aggregationcoef2;
aa705529
JO
1089 }
1090 }
057063b1
DW
1091 $userweights = array();
1092 $totaloverriddenweight = 0;
1093 $totaloverriddengrademax = 0;
1094 // We first need to rescale all manually assigned weights down by the
1095 // percentage of weights missing from the category.
1096 foreach ($grade_values as $itemid => $gradevalue) {
1097 if ($items[$itemid]->weightoverride) {
64055d50
FM
1098 if ($items[$itemid]->aggregationcoef2 <= 0) {
1099 // Records the weight of 0 and continue.
1100 $userweights[$itemid] = 0;
1101 continue;
1102 }
057063b1
DW
1103 $userweights[$itemid] = $items[$itemid]->aggregationcoef2 / $sumweights;
1104 $totaloverriddenweight += $userweights[$itemid];
1105 $usergrademax = $items[$itemid]->grademax;
1106 if (isset($grademaxoverrides[$itemid])) {
1107 $usergrademax = $grademaxoverrides[$itemid];
1108 }
1109 $totaloverriddengrademax += $usergrademax;
1110 }
1111 }
1112 $nonoverriddenpoints = $grademax - $totaloverriddengrademax;
1113
1114 // Then we need to recalculate the automatic weights.
1115 foreach ($grade_values as $itemid => $gradevalue) {
1116 if (!$items[$itemid]->weightoverride) {
64055d50
FM
1117 $usergrademax = $items[$itemid]->grademax;
1118 if (isset($grademaxoverrides[$itemid])) {
1119 $usergrademax = $grademaxoverrides[$itemid];
1120 }
057063b1 1121 if ($nonoverriddenpoints > 0) {
057063b1
DW
1122 $userweights[$itemid] = ($usergrademax/$nonoverriddenpoints) * (1 - $totaloverriddenweight);
1123 } else {
1124 $userweights[$itemid] = 0;
64055d50
FM
1125 if ($items[$itemid]->aggregationcoef2 > 0) {
1126 // Items with a weight of 0 should not count for the grade max,
1127 // though this only applies if the weight was changed to 0.
1128 $grademax -= $usergrademax;
1129 }
057063b1
DW
1130 }
1131 }
a2c13f68 1132 }
057063b1
DW
1133
1134 // We can use our freshly corrected weights below.
a2c13f68 1135 foreach ($grade_values as $itemid => $gradevalue) {
057063b1 1136 $sum += $gradevalue * $userweights[$itemid] * $grademax;
a2c13f68 1137 if ($weights !== null) {
057063b1 1138 $weights[$itemid] = $userweights[$itemid];
a2c13f68
DW
1139 }
1140 }
1141 if ($grademax > 0) {
1142 $agg_grade = $sum / $grademax; // Re-normalize score.
1143 } else {
1144 // Every item in the category is extra credit.
1145 $agg_grade = $sum;
1146 $grademax = $sum;
1147 }
b50b12b3 1148
5232d3f2
DW
1149 break;
1150
c2efb501 1151 case GRADE_AGGREGATE_MEAN: // Arithmetic average of all grade items (if ungraded aggregated, NULL counted as minimum)
ac9b0805 1152 default:
9580a21f 1153 $num = count($grade_values);
1154 $sum = array_sum($grade_values);
9c8d38fa 1155 $agg_grade = $sum / $num;
bfe969e8
DW
1156 // Record the weights evenly.
1157 if ($weights !== null && $num > 0) {
1158 foreach ($grade_values as $itemid=>$grade_value) {
1159 $weights[$itemid] = 1.0 / $num;
1160 }
1161 }
b8ff92b6 1162 break;
1163 }
1164
5232d3f2
DW
1165 return array('grade' => $agg_grade, 'grademin' => $grademin, 'grademax' => $grademax);
1166 }
1167
1168 /**
1169 * Internal function that calculates the aggregated grade for this grade category
1170 *
1171 * Must be public as it is used by grade_grade::get_hiding_affected()
1172 *
1173 * @deprecated since Moodle 2.8
1174 * @param array $grade_values An array of values to be aggregated
1175 * @param array $items The array of grade_items
1176 * @return float The aggregate grade for this grade category
1177 */
1178 public function aggregate_values($grade_values, $items) {
1179 debugging('grade_category::aggregate_values() is deprecated.
1180 Call grade_category::aggregate_values_and_adjust_bounds() instead.', DEBUG_DEVELOPER);
1181 $result = $this->aggregate_values_and_adjust_bounds($grade_values, $items);
1182 return $result['grade'];
0aa32279 1183 }
0758a08e 1184
3a03653e 1185 /**
fcf6e015 1186 * Some aggregation types may need to update their max grade.
a153c9f2 1187 *
64055d50
FM
1188 * This must be executed after updating the weights as it relies on them.
1189 *
fcf6e015 1190 * @return void
3a03653e 1191 */
fcf6e015
FM
1192 private function auto_update_max() {
1193 global $DB;
3a03653e 1194 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
1195 // not needed at all
1196 return;
1197 }
1198
fcf6e015
FM
1199 // Find grade items of immediate children (category or grade items) and force site settings.
1200 $this->load_grade_item();
1201 $depends_on = $this->grade_item->depends_on();
1202
1203 $items = false;
1204 if (!empty($depends_on)) {
1205 list($usql, $params) = $DB->get_in_or_equal($depends_on);
1206 $sql = "SELECT *
1207 FROM {grade_items}
1208 WHERE id $usql";
1209 $items = $DB->get_records_sql($sql, $params);
1210 }
1211
3a03653e 1212 if (!$items) {
b79fe189 1213
3a03653e 1214 if ($this->grade_item->grademax != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
1215 $this->grade_item->grademax = 0;
1216 $this->grade_item->grademin = 0;
1217 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
1218 $this->grade_item->update('aggregation');
1219 }
1220 return;
1221 }
1222
d57ea599 1223 //find max grade possible
59080eee 1224 $maxes = array();
b79fe189 1225
3a03653e 1226 foreach ($items as $item) {
b79fe189 1227
d57ea599
JO
1228 if ($item->aggregationcoef > 0) {
1229 // extra credit from this activity - does not affect total
1230 continue;
64055d50
FM
1231 } else if ($item->aggregationcoef2 <= 0) {
1232 // Items with a weight of 0 do not affect the total.
1233 continue;
3a03653e 1234 }
11eca362 1235
d57ea599
JO
1236 if ($item->gradetype == GRADE_TYPE_VALUE) {
1237 $maxes[$item->id] = $item->grademax;
1238
1239 } else if ($item->gradetype == GRADE_TYPE_SCALE) {
1240 $maxes[$item->id] = $item->grademax; // 0 = nograde, 1 = first scale item, 2 = second scale item
1241 }
1242 }
4272386a
FM
1243
1244 if ($this->can_apply_limit_rules()) {
1245 // Apply droplow and keephigh.
1246 $this->apply_limit_rules($maxes, $items);
1247 }
59080eee 1248 $max = array_sum($maxes);
3a03653e 1249
59080eee 1250 // update db if anything changed
1251 if ($this->grade_item->grademax != $max or $this->grade_item->grademin != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
3a03653e 1252 $this->grade_item->grademax = $max;
1253 $this->grade_item->grademin = 0;
1254 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
1255 $this->grade_item->update('aggregation');
1256 }
1257 }
1258
a2f1f65d
AD
1259 /**
1260 * Recalculate the weights of the grade items in this category.
fcf6e015 1261 *
64055d50
FM
1262 * The category total is not updated here, a further call to
1263 * {@link self::auto_update_max()} is required.
1264 *
fcf6e015 1265 * @return void
a2f1f65d
AD
1266 */
1267 private function auto_update_weights() {
1268 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
1269 // This is only required if we are using natural weights.
1270 return;
1271 }
1272 $children = $this->get_children();
1273
519429b2 1274 $gradeitem = null;
a2f1f65d
AD
1275
1276 // Calculate the sum of the grademax's of all the items within this category.
f70da024 1277 $totalnonoverriddengrademax = 0;
11c93e28 1278 $totalgrademax = 0;
45da5361
AD
1279
1280 // Out of 1, how much weight has been manually overriden by a user?
1281 $totaloverriddenweight = 0;
1282 $totaloverriddengrademax = 0;
519429b2
AG
1283
1284 // Has every assessment in this category been overridden?
f70da024 1285 $automaticgradeitemspresent = false;
519429b2
AG
1286 // Does the grade item require normalising?
1287 $requiresnormalising = false;
1288
1289 // This array keeps track of the id and weight of every grade item that has been overridden.
1290 $overridearray = array();
a2f1f65d 1291 foreach ($children as $sortorder => $child) {
519429b2 1292 $gradeitem = null;
a2f1f65d
AD
1293
1294 if ($child['type'] == 'item') {
519429b2 1295 $gradeitem = $child['object'];
a2f1f65d 1296 } else if ($child['type'] == 'category') {
519429b2
AG
1297 $gradeitem = $child['object']->load_grade_item();
1298 }
1299
1300 // Record the ID and the weight for this grade item.
1301 $overridearray[$gradeitem->id] = array();
11c93e28 1302 $overridearray[$gradeitem->id]['extracredit'] = intval($gradeitem->aggregationcoef);
519429b2 1303 $overridearray[$gradeitem->id]['weight'] = $gradeitem->aggregationcoef2;
11c93e28 1304 $overridearray[$gradeitem->id]['weightoverride'] = intval($gradeitem->weightoverride);
519429b2
AG
1305 // If this item has had its weight overridden then set the flag to true, but
1306 // only if all previous items were also overridden. Note that extra credit items
1307 // are counted as overridden grade items.
f70da024
AG
1308 if (!$gradeitem->weightoverride && $gradeitem->aggregationcoef == 0) {
1309 $automaticgradeitemspresent = true;
1310 }
45da5361 1311
f70da024 1312 if ($gradeitem->aggregationcoef > 0) {
64055d50
FM
1313 // An extra credit grade item doesn't contribute to $totaloverriddengrademax.
1314 continue;
11c93e28 1315 } else if ($gradeitem->weightoverride > 0 && $gradeitem->aggregationcoef2 <= 0) {
64055d50 1316 // An overriden item that defines a weight of 0 does not contribute to $totaloverriddengrademax.
b14c5870
AD
1317 continue;
1318 }
1319
11c93e28
DW
1320 $totalgrademax += $gradeitem->grademax;
1321 if ($gradeitem->weightoverride > 0) {
519429b2
AG
1322 $totaloverriddenweight += $gradeitem->aggregationcoef2;
1323 $totaloverriddengrademax += $gradeitem->grademax;
1324 }
1325 }
1326
1327 // Initialise this variable (used to keep track of the weight override total).
1328 $normalisetotal = 0;
1329 // 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
1330 // other weights to zero and normalise the others.
1331 $overriddentotal = 0;
f70da024
AG
1332 // If the overridden weight total is higher than 1 then set the other untouched weights to zero.
1333 $setotherweightstozero = false;
519429b2
AG
1334 // Total up all of the weights.
1335 foreach ($overridearray as $gradeitemdetail) {
1336 // If the grade item has extra credit, then don't add it to the normalisetotal.
11c93e28 1337 if (!$gradeitemdetail['extracredit']) {
519429b2
AG
1338 $normalisetotal += $gradeitemdetail['weight'];
1339 }
11c93e28 1340 if ($gradeitemdetail['weightoverride'] && !$gradeitemdetail['extracredit']) {
519429b2
AG
1341 // Add overriden weights up to see if they are greater than 1.
1342 $overriddentotal += $gradeitemdetail['weight'];
45da5361 1343 }
a2f1f65d 1344 }
f70da024 1345 if ($overriddentotal > 1) {
519429b2
AG
1346 // Make sure that this catergory of weights gets normalised.
1347 $requiresnormalising = true;
1348 // The normalised weights are only the overridden weights, so we just use the total of those.
1349 $normalisetotal = $overriddentotal;
519429b2
AG
1350 }
1351
11c93e28 1352 $totalnonoverriddengrademax = $totalgrademax - $totaloverriddengrademax;
45da5361 1353
a2f1f65d
AD
1354 reset($children);
1355 foreach ($children as $sortorder => $child) {
519429b2 1356 $gradeitem = null;
a2f1f65d
AD
1357
1358 if ($child['type'] == 'item') {
519429b2 1359 $gradeitem = $child['object'];
a2f1f65d 1360 } else if ($child['type'] == 'category') {
519429b2
AG
1361 $gradeitem = $child['object']->load_grade_item();
1362 }
1363
f70da024
AG
1364 if (!$gradeitem->weightoverride) {
1365 // Calculations with a grade maximum of zero will cause problems. Just set the weight to zero.
1366 if ($totaloverriddenweight >= 1 || $totalnonoverriddengrademax == 0 || $gradeitem->grademax == 0) {
64055d50 1367 // There is no more weight to distribute.
f70da024 1368 $gradeitem->aggregationcoef2 = 0;
64055d50
FM
1369 } else {
1370 // Calculate this item's weight as a percentage of the non-overridden total grade maxes
1371 // then convert it to a proportion of the available non-overriden weight.
f70da024
AG
1372 $gradeitem->aggregationcoef2 = ($gradeitem->grademax/$totalnonoverriddengrademax) *
1373 (1 - $totaloverriddenweight);
64055d50 1374 }
f70da024 1375 $gradeitem->update();
0cf12217
AG
1376 } else if ((!$automaticgradeitemspresent && $normalisetotal != 1) || ($requiresnormalising)
1377 || $overridearray[$gradeitem->id]['weight'] < 0) {
11c93e28
DW
1378 // Just divide the overriden weight for this item against the total weight override of all
1379 // items in this category.
0cf12217
AG
1380 if ($normalisetotal == 0 || $overridearray[$gradeitem->id]['weight'] < 0) {
1381 // If the normalised total equals zero, or the weight value is less than zero,
1382 // set the weight for the grade item to zero.
11c93e28
DW
1383 $gradeitem->aggregationcoef2 = 0;
1384 } else {
1385 $gradeitem->aggregationcoef2 = $overridearray[$gradeitem->id]['weight'] / $normalisetotal;
1386 }
1387 // Update the grade item to reflect these changes.
1388 $gradeitem->update();
45da5361 1389 }
a2f1f65d
AD
1390 }
1391 }
1392
adc2f286 1393 /**
a153c9f2 1394 * Given an array of grade values (numerical indices) applies droplow or keephigh rules to limit the final array.
b79fe189 1395 *
a153c9f2 1396 * @param array $grade_values itemid=>$grade_value float
b79fe189 1397 * @param array $items grade item objects
adc2f286 1398 * @return array Limited grades.
1399 */
a9e38ac8 1400 public function apply_limit_rules(&$grade_values, $items) {
1401 $extraused = $this->is_extracredit_used();
1402
adc2f286 1403 if (!empty($this->droplow)) {
a9e38ac8 1404 asort($grade_values, SORT_NUMERIC);
1405 $dropped = 0;
b79fe189 1406
fb80cb2a
AD
1407 // If we have fewer grade items available to drop than $this->droplow, use this flag to escape the loop
1408 // May occur because of "extra credit" or if droplow is higher than the number of grade items
1409 $droppedsomething = true;
b79fe189 1410
fb80cb2a
AD
1411 while ($dropped < $this->droplow && $droppedsomething) {
1412 $droppedsomething = false;
b79fe189 1413
fb80cb2a 1414 $grade_keys = array_keys($grade_values);
aee968da
AD
1415 $gradekeycount = count($grade_keys);
1416
1417 if ($gradekeycount === 0) {
fb80cb2a
AD
1418 //We've dropped all grade items
1419 break;
1420 }
b79fe189 1421
fb80cb2a
AD
1422 $originalindex = $founditemid = $foundmax = null;
1423
1424 // Find the first remaining grade item that is available to be dropped
1425 foreach ($grade_keys as $gradekeyindex=>$gradekey) {
1426 if (!$extraused || $items[$gradekey]->aggregationcoef <= 0) {
1427 // Found a non-extra credit grade item that is eligible to be dropped
1428 $originalindex = $gradekeyindex;
1429 $founditemid = $grade_keys[$originalindex];
1430 $foundmax = $items[$founditemid]->grademax;
1431 break;
a9e38ac8 1432 }
fb80cb2a 1433 }
b79fe189 1434
fb80cb2a
AD
1435 if (empty($founditemid)) {
1436 // No grade items available to drop
a9e38ac8 1437 break;
59080eee 1438 }
fb80cb2a
AD
1439
1440 // Now iterate over the remaining grade items
1441 // We're looking for other grade items with the same grade value but a higher grademax
1442 $i = 1;
aee968da 1443 while ($originalindex + $i < $gradekeycount) {
52929486 1444
fb80cb2a 1445 $possibleitemid = $grade_keys[$originalindex+$i];
52929486
AD
1446 $i++;
1447
fb80cb2a
AD
1448 if ($grade_values[$founditemid] != $grade_values[$possibleitemid]) {
1449 // The next grade item has a different grade value. Stop looking.
1450 break;
1451 }
1452
1453 if ($extraused && $items[$possibleitemid]->aggregationcoef > 0) {
1454 // Don't drop extra credit grade items. Continue the search.
1455 continue;
1456 }
1457
1458 if ($foundmax < $items[$possibleitemid]->grademax) {
1459 // Found a grade item with the same grade value and a higher grademax
1460 $foundmax = $items[$possibleitemid]->grademax;
1461 $founditemid = $possibleitemid;
1462 // Continue searching to see if there is an even higher grademax
1463 }
fb80cb2a
AD
1464 }
1465
1466 // Now drop whatever grade item we have found
1467 unset($grade_values[$founditemid]);
1468 $dropped++;
1469 $droppedsomething = true;
adc2f286 1470 }
a9e38ac8 1471
1472 } else if (!empty($this->keephigh)) {
1473 arsort($grade_values, SORT_NUMERIC);
1474 $kept = 0;
b79fe189 1475
a9e38ac8 1476 foreach ($grade_values as $itemid=>$value) {
b79fe189 1477
a9e38ac8 1478 if ($extraused and $items[$itemid]->aggregationcoef > 0) {
1479 // we keep all extra credits
b79fe189 1480
a9e38ac8 1481 } else if ($kept < $this->keephigh) {
1482 $kept++;
b79fe189 1483
a9e38ac8 1484 } else {
1485 unset($grade_values[$itemid]);
1486 }
adc2f286 1487 }
1488 }
0aa32279 1489 }
1490
4272386a
FM
1491 /**
1492 * Returns whether or not we can apply the limit rules.
1493 *
1494 * There are cases where drop lowest or keep highest should not be used
1495 * at all. This method will determine whether or not this logic can be
1496 * applied considering the current setup of the category.
1497 *
1498 * @return bool
1499 */
1500 public function can_apply_limit_rules() {
1501 if ($this->canapplylimitrules !== null) {
1502 return $this->canapplylimitrules;
1503 }
1504
1505 // Set it to be supported by default.
1506 $this->canapplylimitrules = true;
1507
1508 // Natural aggregation.
1509 if ($this->aggregation == GRADE_AGGREGATE_SUM) {
1510 $canapply = true;
1511
1512 // Check until one child breaks the rules.
1513 $gradeitems = $this->get_children();
1514 $validitems = 0;
1515 $lastweight = null;
1516 $lastmaxgrade = null;
1517 foreach ($gradeitems as $gradeitem) {
1518 $gi = $gradeitem['object'];
1519
1520 if ($gradeitem['type'] == 'category') {
1521 // Sub categories are not allowed because they can have dynamic weights/maxgrades.
1522 $canapply = false;
1523 break;
1524 }
1525
1526 if ($gi->aggregationcoef > 0) {
1527 // Extra credit items are not allowed.
1528 $canapply = false;
1529 break;
1530 }
1531
1532 if ($lastweight !== null && $lastweight != $gi->aggregationcoef2) {
1533 // One of the weight differs from another item.
1534 $canapply = false;
1535 break;
1536 }
1537
1538 if ($lastmaxgrade !== null && $lastmaxgrade != $gi->grademax) {
1539 // One of the max grade differ from another item. This is not allowed for now
1540 // because we could be end up with different max grade between users for this category.
1541 $canapply = false;
1542 break;
1543 }
1544
1545 $lastweight = $gi->aggregationcoef2;
1546 $lastmaxgrade = $gi->grademax;
1547 }
1548
1549 $this->canapplylimitrules = $canapply;
1550 }
1551
1552 return $this->canapplylimitrules;
1553 }
1554
793253ae 1555 /**
1556 * Returns true if category uses extra credit of any kind
b79fe189 1557 *
a153c9f2 1558 * @return bool True if extra credit used
793253ae 1559 */
134c514b
RT
1560 public function is_extracredit_used() {
1561 return self::aggregation_uses_extracredit($this->aggregation);
1562 }
1563
1564 /**
1565 * Returns true if aggregation passed is using extracredit.
1566 *
1567 * @param int $aggregation Aggregation const.
1568 * @return bool True if extra credit used
1569 */
1570 public static function aggregation_uses_extracredit($aggregation) {
1571 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1572 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1573 or $aggregation == GRADE_AGGREGATE_SUM);
793253ae 1574 }
1575
9580a21f 1576 /**
f7d515b6 1577 * Returns true if category uses special aggregation coefficient
b79fe189 1578 *
a153c9f2 1579 * @return bool True if an aggregation coefficient is being used
9580a21f 1580 */
4e9ca991 1581 public function is_aggregationcoef_used() {
134c514b
RT
1582 return self::aggregation_uses_aggregationcoef($this->aggregation);
1583
1584 }
1585
1586 /**
1587 * Returns true if aggregation uses aggregationcoef
1588 *
1589 * @param int $aggregation Aggregation const.
1590 * @return bool True if an aggregation coefficient is being used
1591 */
1592 public static function aggregation_uses_aggregationcoef($aggregation) {
1593 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN
1594 or $aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1595 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1596 or $aggregation == GRADE_AGGREGATE_SUM);
ba74762b 1597
9580a21f 1598 }
1599
653a8648 1600 /**
a153c9f2 1601 * Recursive function to find which weight/extra credit field to use in the grade item form.
b79fe189 1602 *
a153c9f2 1603 * Inherits from a parent category if that category has aggregatesubcats set to true.
b79fe189 1604 *
a153c9f2 1605 * @param string $first Whether or not this is the first item in the recursion
b79fe189 1606 * @return string
653a8648 1607 */
1608 public function get_coefstring($first=true) {
1609 if (!is_null($this->coefstring)) {
1610 return $this->coefstring;
1611 }
1612
1613 $overriding_coefstring = null;
1614
1615 // Stop recursing upwards if this category aggregates subcats or has no parent
1616 if (!$first && !$this->aggregatesubcats) {
b79fe189 1617
121d8006 1618 if ($parent_category = $this->load_parent_category()) {
653a8648 1619 return $parent_category->get_coefstring(false);
b79fe189 1620
653a8648 1621 } else {
1622 return null;
1623 }
b79fe189 1624
1625 } else if ($first) {
1626
653a8648 1627 if (!$this->aggregatesubcats) {
b79fe189 1628
121d8006 1629 if ($parent_category = $this->load_parent_category()) {
653a8648 1630 $overriding_coefstring = $parent_category->get_coefstring(false);
1631 }
1632 }
1633 }
1634
1635 // If an overriding coefstring has trickled down from one of the parent categories, return it. Otherwise, return self.
1636 if (!is_null($overriding_coefstring)) {
1637 return $overriding_coefstring;
1638 }
1639
1640 // No parent category is overriding this category's aggregation, return its string
1641 if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
1642 $this->coefstring = 'aggregationcoefweight';
b79fe189 1643
d9ae2ab5 1644 } else if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2) {
1645 $this->coefstring = 'aggregationcoefextrasum';
b79fe189 1646
653a8648 1647 } else if ($this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
3869ab1a 1648 $this->coefstring = 'aggregationcoefextraweight';
b79fe189 1649
653a8648 1650 } else if ($this->aggregation == GRADE_AGGREGATE_SUM) {
b6a1e366 1651 $this->coefstring = 'aggregationcoefextraweightsum';
b79fe189 1652
653a8648 1653 } else {
1654 $this->coefstring = 'aggregationcoef';
1655 }
1656 return $this->coefstring;
1657 }
1658
1c307f21 1659 /**
b3ac6c3e 1660 * Returns tree with all grade_items and categories as elements
b79fe189 1661 *
1662 * @param int $courseid The course ID
a153c9f2 1663 * @param bool $include_category_items as category children
b3ac6c3e 1664 * @return array
1c307f21 1665 */
da3801e8 1666 public static function fetch_course_tree($courseid, $include_category_items=false) {
f3ac8eb4 1667 $course_category = grade_category::fetch_course_category($courseid);
514a3467 1668 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
1669 'children'=>$course_category->get_children($include_category_items));
b146d984
AD
1670
1671 $course_category->sortorder = $course_category->get_sortorder();
e2bb3c92
PS
1672 $sortorder = $course_category->get_sortorder();
1673 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 1674 }
1675
b79fe189 1676 /**
a153c9f2 1677 * An internal function that recursively sorts grade categories within a course
b79fe189 1678 *
1679 * @param array $category_array The seed of the recursion
a153c9f2
AD
1680 * @param int $sortorder The current sortorder
1681 * @return array An array containing 'object', 'type', 'depth' and optionally 'children'
b79fe189 1682 */
1683 static private function _fetch_course_tree_recursion($category_array, &$sortorder) {
b3ac6c3e 1684 // update the sortorder in db if needed
b146d984
AD
1685 //NOTE: This leads to us resetting sort orders every time the categories and items page is viewed :(
1686 //if ($category_array['object']->sortorder != $sortorder) {
1687 //$category_array['object']->set_sortorder($sortorder);
1688 //}
ce385eb4 1689
7bac3777
AD
1690 if (isset($category_array['object']->gradetype) && $category_array['object']->gradetype==GRADE_TYPE_NONE) {
1691 return null;
1692 }
1693
314c4336 1694 // store the grade_item or grade_category instance with extra info
1695 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 1696
1697 // reuse final grades if there
1698 if (array_key_exists('finalgrades', $category_array)) {
1699 $result['finalgrades'] = $category_array['finalgrades'];
1700 }
1701
1702 // recursively resort children
1703 if (!empty($category_array['children'])) {
1704 $result['children'] = array();
29d509f5 1705 //process the category item first
7bac3777 1706 $child = null;
b79fe189 1707
1708 foreach ($category_array['children'] as $oldorder=>$child_array) {
1709
314c4336 1710 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
7bac3777
AD
1711 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1712 if (!empty($child)) {
1713 $result['children'][$sortorder] = $child;
1714 }
29d509f5 1715 }
2b0f65e2 1716 }
b79fe189 1717
1718 foreach ($category_array['children'] as $oldorder=>$child_array) {
1719
29d509f5 1720 if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
7bac3777
AD
1721 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1722 if (!empty($child)) {
1723 $result['children'][++$sortorder] = $child;
1724 }
b3ac6c3e 1725 }
1726 }
1727 }
1728
1729 return $result;
ce385eb4 1730 }
7c8a963f 1731
1732 /**
4a490db0 1733 * Fetches and returns all the children categories and/or grade_items belonging to this category.
1734 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 1735 * as well as all levels (0). The elements are indexed by sort order.
b79fe189 1736 *
1737 * @param bool $include_category_items Whether or not to include category grade_items in the children array
7c8a963f 1738 * @return array Array of child objects (grade_category and grade_item).
1739 */
da3801e8 1740 public function get_children($include_category_items=false) {
1741 global $DB;
b3ac6c3e 1742
1743 // This function must be as fast as possible ;-)
1744 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
1745 // we have to limit the number of queries though, because it will be used often in grade reports
1746
da3801e8 1747 $cats = $DB->get_records('grade_categories', array('courseid' => $this->courseid));
1748 $items = $DB->get_records('grade_items', array('courseid' => $this->courseid));
4a490db0 1749
b3ac6c3e 1750 // init children array first
1751 foreach ($cats as $catid=>$cat) {
1752 $cats[$catid]->children = array();
27f95e9b 1753 }
4a490db0 1754
b3ac6c3e 1755 //first attach items to cats and add category sortorder
1756 foreach ($items as $item) {
b79fe189 1757
b3ac6c3e 1758 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
1759 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 1760
b3ac6c3e 1761 if (!$include_category_items) {
1762 continue;
1763 }
1764 $categoryid = $item->iteminstance;
b79fe189 1765
b3ac6c3e 1766 } else {
1767 $categoryid = $item->categoryid;
63354ab5
AD
1768 if (empty($categoryid)) {
1769 debugging('Found a grade item that isnt in a category');
1770 }
b3ac6c3e 1771 }
1772
1773 // prevent problems with duplicate sortorders in db
1774 $sortorder = $item->sortorder;
b79fe189 1775
63354ab5
AD
1776 while (array_key_exists($categoryid, $cats)
1777 && array_key_exists($sortorder, $cats[$categoryid]->children)) {
1778
b3ac6c3e 1779 $sortorder++;
1780 }
1781
1782 $cats[$categoryid]->children[$sortorder] = $item;
1783
1784 }
1785
1786 // now find the requested category and connect categories as children
1787 $category = false;
b79fe189 1788
b3ac6c3e 1789 foreach ($cats as $catid=>$cat) {
b79fe189 1790
ec3717e1 1791 if (empty($cat->parent)) {
b79fe189 1792
ec3717e1 1793 if ($cat->path !== '/'.$cat->id.'/') {
1794 $grade_category = new grade_category($cat, false);
1795 $grade_category->path = '/'.$cat->id.'/';
1796 $grade_category->depth = 1;
1797 $grade_category->update('system');
1798 return $this->get_children($include_category_items);
1799 }
b79fe189 1800
ec3717e1 1801 } else {
b79fe189 1802
ec3717e1 1803 if (empty($cat->path) or !preg_match('|/'.$cat->parent.'/'.$cat->id.'/$|', $cat->path)) {
1804 //fix paths and depts
1805 static $recursioncounter = 0; // prevents infinite recursion
1806 $recursioncounter++;
b79fe189 1807
da3801e8 1808 if ($recursioncounter < 5) {
ec3717e1 1809 // fix paths and depths!
1810 $grade_category = new grade_category($cat, false);
1811 $grade_category->depth = 0;
1812 $grade_category->path = null;
1813 $grade_category->update('system');
1814 return $this->get_children($include_category_items);
1815 }
da3801e8 1816 }
b3ac6c3e 1817 // prevent problems with duplicate sortorders in db
1818 $sortorder = $cat->sortorder;
b79fe189 1819
1820 while (array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 1821 //debugging("$sortorder exists in cat loop");
b3ac6c3e 1822 $sortorder++;
1823 }
1824
65370356 1825 $cats[$cat->parent]->children[$sortorder] = &$cats[$catid];
b3ac6c3e 1826 }
f3ac8eb4 1827
b3ac6c3e 1828 if ($catid == $this->id) {
1829 $category = &$cats[$catid];
1830 }
1831 }
1832
1833 unset($items); // not needed
1834 unset($cats); // not needed
1835
f3ac8eb4 1836 $children_array = grade_category::_get_children_recursion($category);
b3ac6c3e 1837
1838 ksort($children_array);
1839
1840 return $children_array;
1841
1842 }
1843
b79fe189 1844 /**
1845 * Private method used to retrieve all children of this category recursively
1846 *
1847 * @param grade_category $category Source of current recursion
a153c9f2 1848 * @return array An array of child grade categories
b79fe189 1849 */
22a9b6d8 1850 private static function _get_children_recursion($category) {
b3ac6c3e 1851
1852 $children_array = array();
b79fe189 1853 foreach ($category->children as $sortorder=>$child) {
1854
b3ac6c3e 1855 if (array_key_exists('itemtype', $child)) {
f3ac8eb4 1856 $grade_item = new grade_item($child, false);
b79fe189 1857
4faf5f99 1858 if (in_array($grade_item->itemtype, array('course', 'category'))) {
1859 $type = $grade_item->itemtype.'item';
1860 $depth = $category->depth;
b79fe189 1861
314c4336 1862 } else {
1863 $type = 'item';
1864 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 1865 }
4faf5f99 1866 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 1867
7c8a963f 1868 } else {
f3ac8eb4 1869 $children = grade_category::_get_children_recursion($child);
1870 $grade_category = new grade_category($child, false);
b79fe189 1871
b3ac6c3e 1872 if (empty($children)) {
314c4336 1873 $children = array();
7c8a963f 1874 }
4faf5f99 1875 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
314c4336 1876 }
27f95e9b 1877 }
1878
b3ac6c3e 1879 // sort the array
1880 ksort($children_array);
1881
27f95e9b 1882 return $children_array;
1883 }
4a490db0 1884
f151b073 1885 /**
a4d76049 1886 * Uses {@link get_grade_item()} to load or create a grade_item, then saves it as $this->grade_item.
a153c9f2
AD
1887 *
1888 * @return grade_item
f151b073 1889 */
da3801e8 1890 public function load_grade_item() {
ac9b0805 1891 if (empty($this->grade_item)) {
1892 $this->grade_item = $this->get_grade_item();
1893 }
ab53054f 1894 return $this->grade_item;
1895 }
4a490db0 1896
ab53054f 1897 /**
a153c9f2
AD
1898 * Retrieves this grade categories' associated grade_item from the database
1899 *
1900 * If no grade_item exists yet, creates one.
1901 *
1902 * @return grade_item
ab53054f 1903 */
da3801e8 1904 public function get_grade_item() {
c91ed4be 1905 if (empty($this->id)) {
1906 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
1907 return false;
1908 }
1909
b3ac6c3e 1910 if (empty($this->parent)) {
1911 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
1912
1913 } else {
1914 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
1915 }
4ac209d5 1916
f3ac8eb4 1917 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 1918 // create a new one
f3ac8eb4 1919 $grade_item = new grade_item($params, false);
b8ff92b6 1920 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 1921 $grade_item->insert('system');
4a490db0 1922
b79fe189 1923 } else if (count($grade_items) == 1) {
b8ff92b6 1924 // found existing one
1925 $grade_item = reset($grade_items);
4a490db0 1926
b8ff92b6 1927 } else {
1928 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 1929 // return first one
1930 $grade_item = reset($grade_items);
2c72af1f 1931 }
1932
ab53054f 1933 return $grade_item;
f151b073 1934 }
8c846243 1935
1936 /**
a153c9f2
AD
1937 * Uses $this->parent to instantiate $this->parent_category based on the referenced record in the DB
1938 *
1939 * @return grade_category The parent category
8c846243 1940 */
da3801e8 1941 public function load_parent_category() {
8c846243 1942 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 1943 $this->parent_category = $this->get_parent_category();
8c846243 1944 }
1945 return $this->parent_category;
4a490db0 1946 }
1947
ab53054f 1948 /**
a153c9f2
AD
1949 * Uses $this->parent to instantiate and return a grade_category object
1950 *
1951 * @return grade_category Returns the parent category or null if this category has no parent
ab53054f 1952 */
da3801e8 1953 public function get_parent_category() {
ab53054f 1954 if (!empty($this->parent)) {
f3ac8eb4 1955 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 1956 return $parent_category;
ab53054f 1957 } else {
1958 return null;
1959 }
1960 }
1961
2186f72c 1962 /**
a153c9f2 1963 * Returns the most descriptive field for this grade category
b79fe189 1964 *
2186f72c 1965 * @return string name
1966 */
da3801e8 1967 public function get_name() {
1968 global $DB;
8f6fdf43 1969 // For a course category, we return the course name if the fullname is set to '?' in the DB (empty in the category edit form)
1970 if (empty($this->parent) && $this->fullname == '?') {
da3801e8 1971 $course = $DB->get_record('course', array('id'=> $this->courseid));
410753fb 1972 return format_string($course->fullname);
b79fe189 1973
314c4336 1974 } else {
1975 return $this->fullname;
1976 }
2186f72c 1977 }
c91ed4be 1978
65c2ac93
DW
1979 /**
1980 * Describe the aggregation settings for this category so the reports make more sense.
1981 *
1982 * @return string description
1983 */
1984 public function get_description() {
1985 $allhelp = array();
2be0d5c3
MG
1986 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
1987 $aggrstrings = grade_helper::get_aggregation_strings();
1988 $allhelp[] = $aggrstrings[$this->aggregation];
1989 }
65c2ac93 1990
ded8ea8f 1991 if ($this->droplow && $this->can_apply_limit_rules()) {
65c2ac93
DW
1992 $allhelp[] = get_string('droplowestvalues', 'grades', $this->droplow);
1993 }
ded8ea8f 1994 if ($this->keephigh && $this->can_apply_limit_rules()) {
65c2ac93
DW
1995 $allhelp[] = get_string('keephighestvalues', 'grades', $this->keephigh);
1996 }
1997 if (!$this->aggregateonlygraded) {
1998 $allhelp[] = get_string('aggregatenotonlygraded', 'grades');
1999 }
2000 if ($this->aggregatesubcats) {
2001 $allhelp[] = get_string('aggregatesubcatsshort', 'grades');
2002 }
2be0d5c3
MG
2003 if ($allhelp) {
2004 return implode('. ', $allhelp) . '.';
2005 }
2006 return '';
65c2ac93
DW
2007 }
2008
0fc7f624 2009 /**
a153c9f2 2010 * Sets this category's parent id
b79fe189 2011 *
a153c9f2
AD
2012 * @param int $parentid The ID of the category that is the new parent to $this
2013 * @param string $source From where was the object updated (mod/forum, manual, etc.)
2014 * @return bool success
0fc7f624 2015 */
da3801e8 2016 public function set_parent($parentid, $source=null) {
f13002d5 2017 if ($this->parent == $parentid) {
2018 return true;
2019 }
2020
2021 if ($parentid == $this->id) {
2f137aa1 2022 print_error('cannotassignselfasparent');
f13002d5 2023 }
2024
2025 if (empty($this->parent) and $this->is_course_category()) {
2f137aa1 2026 print_error('cannothaveparentcate');
b3ac6c3e 2027 }
f13002d5 2028
2029 // find parent and check course id
f3ac8eb4 2030 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 2031 return false;
2032 }
2033
f8e6e4db 2034 $this->force_regrading();
b3ac6c3e 2035
2036 // set new parent category
f8e6e4db 2037 $this->parent = $parent_category->id;
2038 $this->parent_category =& $parent_category;
b3ac6c3e 2039 $this->path = null; // remove old path and depth - will be recalculated in update()
ec3717e1 2040 $this->depth = 0; // remove old path and depth - will be recalculated in update()
f8e6e4db 2041 $this->update($source);
b3ac6c3e 2042
15b462da 2043 return $this->update($source);
b3ac6c3e 2044 }
2045
2046 /**
a153c9f2 2047 * Returns the final grade values for this grade category.
b79fe189 2048 *
a153c9f2 2049 * @param int $userid Optional user ID to retrieve a single user's final grade
b3ac6c3e 2050 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
2051 */
b79fe189 2052 public function get_final($userid=null) {
b3ac6c3e 2053 $this->load_grade_item();
2054 return $this->grade_item->get_final($userid);
0fc7f624 2055 }
4a490db0 2056
0fc7f624 2057 /**
a153c9f2
AD
2058 * Returns the sortorder of the grade categories' associated grade_item
2059 *
2060 * This method is also available in grade_item for cases where the object type is not known.
b79fe189 2061 *
0fc7f624 2062 * @return int Sort order
2063 */
da3801e8 2064 public function get_sortorder() {
b3ac6c3e 2065 $this->load_grade_item();
2066 return $this->grade_item->get_sortorder();
0fc7f624 2067 }
2068
be7c0693 2069 /**
a153c9f2
AD
2070 * Returns the idnumber of the grade categories' associated grade_item.
2071 *
2072 * This method is also available in grade_item for cases where the object type is not known.
b79fe189 2073 *
be7c0693 2074 * @return string idnumber
2075 */
da3801e8 2076 public function get_idnumber() {
be7c0693 2077 $this->load_grade_item();
2078 return $this->grade_item->get_idnumber();
2079 }
2080
0fc7f624 2081 /**
a153c9f2
AD
2082 * Sets the sortorder variable for this category.
2083 *
4a490db0 2084 * This method is also available in grade_item, for cases where the object type is not know.
b79fe189 2085 *
2086 * @param int $sortorder The sortorder to assign to this category
0fc7f624 2087 */
da3801e8 2088 public function set_sortorder($sortorder) {
b3ac6c3e 2089 $this->load_grade_item();
2090 $this->grade_item->set_sortorder($sortorder);
2091 }
2092
6639ead3 2093 /**
a153c9f2 2094 * Move this category after the given sortorder
b79fe189 2095 *
a153c9f2 2096 * Does not change the parent
b79fe189 2097 *
a153c9f2 2098 * @param int $sortorder to place after.
b79fe189 2099 * @return void
6639ead3 2100 */
da3801e8 2101 public function move_after_sortorder($sortorder) {
f13002d5 2102 $this->load_grade_item();
2103 $this->grade_item->move_after_sortorder($sortorder);
2104 }
2105
b3ac6c3e 2106 /**
f13002d5 2107 * Return true if this is the top most category that represents the total course grade.
b79fe189 2108 *
a153c9f2 2109 * @return bool
b3ac6c3e 2110 */
da3801e8 2111 public function is_course_category() {
b3ac6c3e 2112 $this->load_grade_item();
2113 return $this->grade_item->is_course_item();
2114 }
2115
2116 /**
a153c9f2 2117 * Return the course level grade_category object
b79fe189 2118 *
2119 * @param int $courseid The Course ID
a153c9f2 2120 * @return grade_category Returns the course level grade_category instance
b3ac6c3e 2121 */
22a9b6d8 2122 public static function fetch_course_category($courseid) {
a4503119 2123 if (empty($courseid)) {
2124 debugging('Missing course id!');
2125 return false;
2126 }
b3ac6c3e 2127
2128 // course category has no parent
f3ac8eb4 2129 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
b3ac6c3e 2130 return $course_category;
2131 }
2132
2133 // create a new one
f3ac8eb4 2134 $course_category = new grade_category();
b3ac6c3e 2135 $course_category->insert_course_category($courseid);
2136
2137 return $course_category;
0fc7f624 2138 }
4ac209d5 2139
79eabc2a 2140 /**
2141 * Is grading object editable?
b79fe189 2142 *
a153c9f2 2143 * @return bool
79eabc2a 2144 */
da3801e8 2145 public function is_editable() {
79eabc2a 2146 return true;
2147 }
2148
5fad5061 2149 /**
a153c9f2
AD
2150 * Returns the locked state/date of the grade categories' associated grade_item.
2151 *
2152 * This method is also available in grade_item, for cases where the object type is not known.
2153 *
2154 * @return bool
5fad5061 2155 */
da3801e8 2156 public function is_locked() {
5fad5061 2157 $this->load_grade_item();
22e23c78 2158 return $this->grade_item->is_locked();
5fad5061 2159 }
2160
2161 /**
2162 * Sets the grade_item's locked variable and updates the grade_item.
a153c9f2
AD
2163 *
2164 * Calls set_locked() on the categories' grade_item
b79fe189 2165 *
2166 * @param int $lockedstate 0, 1 or a timestamp int(10) after which date the item will be locked.
2167 * @param bool $cascade lock/unlock child objects too
2168 * @param bool $refresh refresh grades when unlocking
a153c9f2 2169 * @return bool success if category locked (not all children mayb be locked though)
5fad5061 2170 */
da3801e8 2171 public function set_locked($lockedstate, $cascade=false, $refresh=true) {
5fad5061 2172 $this->load_grade_item();
2b0f65e2 2173
fb0e3570 2174 $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
2175
2176 if ($cascade) {
2177 //process all children - items and categories
f3ac8eb4 2178 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
b79fe189 2179
2180 foreach ($children as $child) {
fb0e3570 2181 $child->set_locked($lockedstate, true, false);
b79fe189 2182
fb0e3570 2183 if (empty($lockedstate) and $refresh) {
2184 //refresh when unlocking
2185 $child->refresh_grades();
2186 }
2b0f65e2 2187 }
7a7a53d3 2188 }
b79fe189 2189
f3ac8eb4 2190 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 2191
2192 foreach ($children as $child) {
fb0e3570 2193 $child->set_locked($lockedstate, true, true);
2194 }
7a7a53d3 2195 }
2196 }
2b0f65e2 2197
b121b544 2198 return $result;
5fad5061 2199 }
4a490db0 2200
a153c9f2
AD
2201 /**
2202 * Overrides grade_object::set_properties() to add special handling for changes to category aggregation types
2203 *
2204 * @param stdClass $instance the object to set the properties on
2205 * @param array|stdClass $params Either an associative array or an object containing property name, property value pairs
2206 */
79b260cc
AD
2207 public static function set_properties(&$instance, $params) {
2208 global $DB;
2209
2210 parent::set_properties($instance, $params);
2211
c1024411 2212 //if they've changed aggregation type we made need to do some fiddling to provide appropriate defaults
79b260cc
AD
2213 if (!empty($params->aggregation)) {
2214
2215 //weight and extra credit share a column :( Would like a default of 1 for weight and 0 for extra credit
2216 //Flip from the default of 0 to 1 (or vice versa) if ALL items in the category are still set to the old default.
134c514b 2217 if (self::aggregation_uses_aggregationcoef($params->aggregation)) {
79b260cc 2218 $sql = $defaultaggregationcoef = null;
7ad5a627 2219
134c514b 2220 if (!self::aggregation_uses_extracredit($params->aggregation)) {
79b260cc
AD
2221 //if all items in this category have aggregation coefficient of 0 we can change it to 1 ie evenly weighted
2222 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=0";
2223 $defaultaggregationcoef = 1;
134c514b 2224 } else {
79b260cc
AD
2225 //if all items in this category have aggregation coefficient of 1 we can change it to 0 ie no extra credit
2226 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=1";
2227 $defaultaggregationcoef = 0;
2228 }
2229
2230 $params = array('categoryid'=>$instance->id);
2231 $count = $DB->count_records_sql($sql, $params);
2232 if ($count===0) { //category is either empty or all items are set to a default value so we can switch defaults
2233 $params['aggregationcoef'] = $defaultaggregationcoef;
2234 $DB->execute("update {grade_items} set aggregationcoef=:aggregationcoef where categoryid=:categoryid",$params);
2235 }
2236 }
2237 }
2238 }
2239
5fad5061 2240 /**
4a490db0 2241 * Sets the grade_item's hidden variable and updates the grade_item.
a153c9f2
AD
2242 *
2243 * Overrides grade_item::set_hidden() to add cascading of the hidden value to grade items in this grade category
2244 *
2245 * @param int $hidden 0 mean always visible, 1 means always hidden and a number > 1 is a timestamp to hide until
2246 * @param bool $cascade apply to child objects too
5fad5061 2247 */
da3801e8 2248 public function set_hidden($hidden, $cascade=false) {
5fad5061 2249 $this->load_grade_item();
a25bb902 2250 //this hides the associated grade item (the course total)
1762a264 2251 $this->grade_item->set_hidden($hidden, $cascade);
a25bb902
AD
2252 //this hides the category itself and everything it contains
2253 parent::set_hidden($hidden, $cascade);
b79fe189 2254
f60c61b1 2255 if ($cascade) {
b79fe189 2256
f3ac8eb4 2257 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
b79fe189 2258
2259 foreach ($children as $child) {
39873128
TH
2260 if ($child->can_control_visibility()) {
2261 $child->set_hidden($hidden, $cascade);
2262 }
f60c61b1 2263 }
f13002d5 2264 }
b79fe189 2265
f3ac8eb4 2266 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 2267
2268 foreach ($children as $child) {
f60c61b1 2269 $child->set_hidden($hidden, $cascade);
2270 }
f13002d5 2271 }
2272 }
d90aa634
AD
2273
2274 //if marking category visible make sure parent category is visible MDL-21367
93fad868 2275 if( !$hidden ) {
d90aa634
AD
2276 $category_array = grade_category::fetch_all(array('id'=>$this->parent));
2277 if ($category_array && array_key_exists($this->parent, $category_array)) {
2278 $category = $category_array[$this->parent];
93fad868
SH
2279 //call set_hidden on the category regardless of whether it is hidden as its parent might be hidden
2280 //if($category->is_hidden()) {
2281 $category->set_hidden($hidden, false);
2282 //}
d90aa634
AD
2283 }
2284 }
5fad5061 2285 }
89a5f827 2286
190af29f 2287 /**
2288 * Applies default settings on this category
a153c9f2
AD
2289 *
2290 * @return bool True if anything changed
190af29f 2291 */
da3801e8 2292 public function apply_default_settings() {
190af29f 2293 global $CFG;
2294
2295 foreach ($this->forceable as $property) {
b79fe189 2296
190af29f 2297 if (isset($CFG->{"grade_$property"})) {
b79fe189 2298
190af29f 2299 if ($CFG->{"grade_$property"} == -1) {
2300 continue; //temporary bc before version bump
2301 }
2302 $this->$property = $CFG->{"grade_$property"};
2303 }
2304 }
2305 }
2306
89a5f827 2307 /**
2308 * Applies forced settings on this category
a153c9f2
AD
2309 *
2310 * @return bool True if anything changed
89a5f827 2311 */
da3801e8 2312 public function apply_forced_settings() {
89a5f827 2313 global $CFG;
2314
2315 $updated = false;
b79fe189 2316
89a5f827 2317 foreach ($this->forceable as $property) {
b79fe189 2318
2319 if (isset($CFG->{"grade_$property"}) and isset($CFG->{"grade_{$property}_flag"}) and
2320 ((int) $CFG->{"grade_{$property}_flag"} & 1)) {
2321
190af29f 2322 if ($CFG->{"grade_$property"} == -1) {
2323 continue; //temporary bc before version bump
2324 }
89a5f827 2325 $this->$property = $CFG->{"grade_$property"};
2326 $updated = true;
2327 }
2328 }
2329
2330 return $updated;
2331 }
2332
2333 /**
2334 * Notification of change in forced category settings.
b79fe189 2335 *
a153c9f2 2336 * Causes all course and category grade items to be marked as needing to be updated
89a5f827 2337 */
da3801e8 2338 public static function updated_forced_settings() {
5b0af8c5 2339 global $CFG, $DB;
2340 $params = array(1, 'course', 'category');
2341 $sql = "UPDATE {grade_items} SET needsupdate=? WHERE itemtype=? or itemtype=?";
2342 $DB->execute($sql, $params);
89a5f827 2343 }
4a490db0 2344}