MDL-47463 core_grades: Behat checks the contribution of scales
[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) {
21dd6842
FM
969 if ($weights !== null) {
970 $weights[$itemid] = $items[$itemid]->aggregationcoef;
971 }
eacd3700 972 if ($items[$itemid]->aggregationcoef <= 0) {
9580a21f 973 continue;
974 }
eacd3700 975 $weightsum += $items[$itemid]->aggregationcoef;
976 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 977 }
978 if ($weightsum == 0) {
9c8d38fa 979 $agg_grade = null;
b79fe189 980
9580a21f 981 } else {
9c8d38fa 982 $agg_grade = $sum / $weightsum;
bfe969e8
DW
983 if ($weights !== null) {
984 // Normalise the weights.
985 foreach ($weights as $itemid => $weight) {
986 $weights[$itemid] = $weight / $weightsum;
987 }
988 }
989
9580a21f 990 }
991 break;
992
d9ae2ab5 993 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
994 // Weighted average of all existing final grades with optional extra credit flag,
f7d515b6 995 // weight is the range of grade (usually grademax)
1426edac 996 $weightsum = 0;
d9ae2ab5 997 $sum = null;
b79fe189 998
999 foreach ($grade_values as $itemid=>$grade_value) {
1426edac 1000 $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
b79fe189 1001
1426edac 1002 if ($weight <= 0) {
1003 continue;
1004 }
b79fe189 1005
d9ae2ab5 1006 if ($items[$itemid]->aggregationcoef == 0) {
1007 $weightsum += $weight;
1008 }
1009 $sum += $weight * $grade_value;
1426edac 1010 }
1011 if ($weightsum == 0) {
d9ae2ab5 1012 $agg_grade = $sum; // only extra credits
b79fe189 1013
1426edac 1014 } else {
1015 $agg_grade = $sum / $weightsum;
1016 }
bfe969e8
DW
1017 // Record the weights as used.
1018 if ($weights !== null) {
1019 foreach ($grade_values as $itemid=>$grade_value) {
852fae0b 1020 if ($weightsum > 0) {
bfe969e8 1021 $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
852fae0b 1022 $weights[$itemid] = $weight / $weightsum;
bfe969e8
DW
1023 } else {
1024 $weights[$itemid] = 0;
1025 }
1026 }
1027 }
1426edac 1028 break;
1029
c2efb501 1030 case GRADE_AGGREGATE_EXTRACREDIT_MEAN: // special average
9580a21f 1031 $num = 0;
d9ae2ab5 1032 $sum = null;
b79fe189 1033
1034 foreach ($grade_values as $itemid=>$grade_value) {
1035
eacd3700 1036 if ($items[$itemid]->aggregationcoef == 0) {
9580a21f 1037 $num += 1;
1038 $sum += $grade_value;
bfe969e8
DW
1039 if ($weights !== null) {
1040 $weights[$itemid] = 1;
1041 }
b79fe189 1042
eacd3700 1043 } else if ($items[$itemid]->aggregationcoef > 0) {
1044 $sum += $items[$itemid]->aggregationcoef * $grade_value;
bfe969e8 1045 if ($weights !== null) {
852fae0b 1046 $weights[$itemid] = 1;
bfe969e8
DW
1047 }
1048 }
1049 }
1050 if ($weights !== null && $num > 0) {
1051 foreach ($grade_values as $itemid=>$grade_value) {
1052 if ($weights[$itemid]) {
1053 $weights[$itemid] = 1.0 / $num;
1054 }
9580a21f 1055 }
1056 }
b79fe189 1057
9580a21f 1058 if ($num == 0) {
9c8d38fa 1059 $agg_grade = $sum; // only extra credits or wrong coefs
b79fe189 1060
9580a21f 1061 } else {
9c8d38fa 1062 $agg_grade = $sum / $num;
9580a21f 1063 }
1064 break;
1065
5232d3f2
DW
1066 case GRADE_AGGREGATE_SUM: // Add up all the items.
1067 $num = count($grade_values);
d57ea599 1068 $sum = 0;
a2c13f68 1069 $sumweights = 0;
a2c13f68
DW
1070 $grademin = 0;
1071 $grademax = 0;
1072 foreach ($grade_values as $itemid => $gradevalue) {
5a59aeb1 1073 // We need to check if the grademax/min was adjusted per user because of excluded items.
057063b1 1074 $usergrademin = $items[$itemid]->grademin;
5a59aeb1
DW
1075 $usergrademax = $items[$itemid]->grademax;
1076 if (isset($grademinoverrides[$itemid])) {
1077 $usergrademin = $grademinoverrides[$itemid];
1078 }
1079 if (isset($grademaxoverrides[$itemid])) {
1080 $usergrademax = $grademaxoverrides[$itemid];
1081 }
a2c13f68 1082
64055d50
FM
1083 // Ignore extra credit and items with a weight of 0.
1084 if ($items[$itemid]->aggregationcoef <= 0 && $items[$itemid]->aggregationcoef2 > 0) {
0b2e8ae0
FM
1085 $grademin += $usergrademin;
1086 $grademax += $usergrademax;
a2c13f68 1087 $sumweights += $items[$itemid]->aggregationcoef2;
aa705529
JO
1088 }
1089 }
057063b1
DW
1090 $userweights = array();
1091 $totaloverriddenweight = 0;
1092 $totaloverriddengrademax = 0;
1093 // We first need to rescale all manually assigned weights down by the
1094 // percentage of weights missing from the category.
1095 foreach ($grade_values as $itemid => $gradevalue) {
1096 if ($items[$itemid]->weightoverride) {
64055d50
FM
1097 if ($items[$itemid]->aggregationcoef2 <= 0) {
1098 // Records the weight of 0 and continue.
1099 $userweights[$itemid] = 0;
1100 continue;
1101 }
057063b1
DW
1102 $userweights[$itemid] = $items[$itemid]->aggregationcoef2 / $sumweights;
1103 $totaloverriddenweight += $userweights[$itemid];
1104 $usergrademax = $items[$itemid]->grademax;
1105 if (isset($grademaxoverrides[$itemid])) {
1106 $usergrademax = $grademaxoverrides[$itemid];
1107 }
1108 $totaloverriddengrademax += $usergrademax;
1109 }
1110 }
1111 $nonoverriddenpoints = $grademax - $totaloverriddengrademax;
1112
1113 // Then we need to recalculate the automatic weights.
1114 foreach ($grade_values as $itemid => $gradevalue) {
1115 if (!$items[$itemid]->weightoverride) {
64055d50
FM
1116 $usergrademax = $items[$itemid]->grademax;
1117 if (isset($grademaxoverrides[$itemid])) {
1118 $usergrademax = $grademaxoverrides[$itemid];
1119 }
057063b1 1120 if ($nonoverriddenpoints > 0) {
057063b1
DW
1121 $userweights[$itemid] = ($usergrademax/$nonoverriddenpoints) * (1 - $totaloverriddenweight);
1122 } else {
1123 $userweights[$itemid] = 0;
64055d50
FM
1124 if ($items[$itemid]->aggregationcoef2 > 0) {
1125 // Items with a weight of 0 should not count for the grade max,
1126 // though this only applies if the weight was changed to 0.
1127 $grademax -= $usergrademax;
1128 }
057063b1
DW
1129 }
1130 }
a2c13f68 1131 }
057063b1
DW
1132
1133 // We can use our freshly corrected weights below.
a2c13f68 1134 foreach ($grade_values as $itemid => $gradevalue) {
057063b1 1135 $sum += $gradevalue * $userweights[$itemid] * $grademax;
a2c13f68 1136 if ($weights !== null) {
057063b1 1137 $weights[$itemid] = $userweights[$itemid];
a2c13f68
DW
1138 }
1139 }
1140 if ($grademax > 0) {
1141 $agg_grade = $sum / $grademax; // Re-normalize score.
1142 } else {
1143 // Every item in the category is extra credit.
1144 $agg_grade = $sum;
1145 $grademax = $sum;
1146 }
b50b12b3 1147
5232d3f2
DW
1148 break;
1149
c2efb501 1150 case GRADE_AGGREGATE_MEAN: // Arithmetic average of all grade items (if ungraded aggregated, NULL counted as minimum)
ac9b0805 1151 default:
9580a21f 1152 $num = count($grade_values);
1153 $sum = array_sum($grade_values);
9c8d38fa 1154 $agg_grade = $sum / $num;
bfe969e8
DW
1155 // Record the weights evenly.
1156 if ($weights !== null && $num > 0) {
1157 foreach ($grade_values as $itemid=>$grade_value) {
1158 $weights[$itemid] = 1.0 / $num;
1159 }
1160 }
b8ff92b6 1161 break;
1162 }
1163
5232d3f2
DW
1164 return array('grade' => $agg_grade, 'grademin' => $grademin, 'grademax' => $grademax);
1165 }
1166
1167 /**
1168 * Internal function that calculates the aggregated grade for this grade category
1169 *
1170 * Must be public as it is used by grade_grade::get_hiding_affected()
1171 *
1172 * @deprecated since Moodle 2.8
1173 * @param array $grade_values An array of values to be aggregated
1174 * @param array $items The array of grade_items
1175 * @return float The aggregate grade for this grade category
1176 */
1177 public function aggregate_values($grade_values, $items) {
1178 debugging('grade_category::aggregate_values() is deprecated.
1179 Call grade_category::aggregate_values_and_adjust_bounds() instead.', DEBUG_DEVELOPER);
1180 $result = $this->aggregate_values_and_adjust_bounds($grade_values, $items);
1181 return $result['grade'];
0aa32279 1182 }
0758a08e 1183
3a03653e 1184 /**
fcf6e015 1185 * Some aggregation types may need to update their max grade.
a153c9f2 1186 *
64055d50
FM
1187 * This must be executed after updating the weights as it relies on them.
1188 *
fcf6e015 1189 * @return void
3a03653e 1190 */
fcf6e015
FM
1191 private function auto_update_max() {
1192 global $DB;
3a03653e 1193 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
1194 // not needed at all
1195 return;
1196 }
1197
fcf6e015
FM
1198 // Find grade items of immediate children (category or grade items) and force site settings.
1199 $this->load_grade_item();
1200 $depends_on = $this->grade_item->depends_on();
1201
1202 $items = false;
1203 if (!empty($depends_on)) {
1204 list($usql, $params) = $DB->get_in_or_equal($depends_on);
1205 $sql = "SELECT *
1206 FROM {grade_items}
1207 WHERE id $usql";
1208 $items = $DB->get_records_sql($sql, $params);
1209 }
1210
3a03653e 1211 if (!$items) {
b79fe189 1212
3a03653e 1213 if ($this->grade_item->grademax != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
1214 $this->grade_item->grademax = 0;
1215 $this->grade_item->grademin = 0;
1216 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
1217 $this->grade_item->update('aggregation');
1218 }
1219 return;
1220 }
1221
d57ea599 1222 //find max grade possible
59080eee 1223 $maxes = array();
b79fe189 1224
3a03653e 1225 foreach ($items as $item) {
b79fe189 1226
d57ea599
JO
1227 if ($item->aggregationcoef > 0) {
1228 // extra credit from this activity - does not affect total
1229 continue;
64055d50
FM
1230 } else if ($item->aggregationcoef2 <= 0) {
1231 // Items with a weight of 0 do not affect the total.
1232 continue;
3a03653e 1233 }
11eca362 1234
d57ea599
JO
1235 if ($item->gradetype == GRADE_TYPE_VALUE) {
1236 $maxes[$item->id] = $item->grademax;
1237
1238 } else if ($item->gradetype == GRADE_TYPE_SCALE) {
1239 $maxes[$item->id] = $item->grademax; // 0 = nograde, 1 = first scale item, 2 = second scale item
1240 }
1241 }
4272386a
FM
1242
1243 if ($this->can_apply_limit_rules()) {
1244 // Apply droplow and keephigh.
1245 $this->apply_limit_rules($maxes, $items);
1246 }
59080eee 1247 $max = array_sum($maxes);
3a03653e 1248
59080eee 1249 // update db if anything changed
1250 if ($this->grade_item->grademax != $max or $this->grade_item->grademin != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
3a03653e 1251 $this->grade_item->grademax = $max;
1252 $this->grade_item->grademin = 0;
1253 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
1254 $this->grade_item->update('aggregation');
1255 }
1256 }
1257
a2f1f65d
AD
1258 /**
1259 * Recalculate the weights of the grade items in this category.
fcf6e015 1260 *
64055d50
FM
1261 * The category total is not updated here, a further call to
1262 * {@link self::auto_update_max()} is required.
1263 *
fcf6e015 1264 * @return void
a2f1f65d
AD
1265 */
1266 private function auto_update_weights() {
1267 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
1268 // This is only required if we are using natural weights.
1269 return;
1270 }
1271 $children = $this->get_children();
1272
519429b2 1273 $gradeitem = null;
a2f1f65d
AD
1274
1275 // Calculate the sum of the grademax's of all the items within this category.
f70da024 1276 $totalnonoverriddengrademax = 0;
11c93e28 1277 $totalgrademax = 0;
45da5361
AD
1278
1279 // Out of 1, how much weight has been manually overriden by a user?
1280 $totaloverriddenweight = 0;
1281 $totaloverriddengrademax = 0;
519429b2
AG
1282
1283 // Has every assessment in this category been overridden?
f70da024 1284 $automaticgradeitemspresent = false;
519429b2
AG
1285 // Does the grade item require normalising?
1286 $requiresnormalising = false;
1287
1288 // This array keeps track of the id and weight of every grade item that has been overridden.
1289 $overridearray = array();
a2f1f65d 1290 foreach ($children as $sortorder => $child) {
519429b2 1291 $gradeitem = null;
a2f1f65d
AD
1292
1293 if ($child['type'] == 'item') {
519429b2 1294 $gradeitem = $child['object'];
a2f1f65d 1295 } else if ($child['type'] == 'category') {
519429b2
AG
1296 $gradeitem = $child['object']->load_grade_item();
1297 }
1298
1299 // Record the ID and the weight for this grade item.
1300 $overridearray[$gradeitem->id] = array();
11c93e28 1301 $overridearray[$gradeitem->id]['extracredit'] = intval($gradeitem->aggregationcoef);
519429b2 1302 $overridearray[$gradeitem->id]['weight'] = $gradeitem->aggregationcoef2;
11c93e28 1303 $overridearray[$gradeitem->id]['weightoverride'] = intval($gradeitem->weightoverride);
519429b2
AG
1304 // If this item has had its weight overridden then set the flag to true, but
1305 // only if all previous items were also overridden. Note that extra credit items
1306 // are counted as overridden grade items.
f70da024
AG
1307 if (!$gradeitem->weightoverride && $gradeitem->aggregationcoef == 0) {
1308 $automaticgradeitemspresent = true;
1309 }
45da5361 1310
f70da024 1311 if ($gradeitem->aggregationcoef > 0) {
64055d50
FM
1312 // An extra credit grade item doesn't contribute to $totaloverriddengrademax.
1313 continue;
11c93e28 1314 } else if ($gradeitem->weightoverride > 0 && $gradeitem->aggregationcoef2 <= 0) {
64055d50 1315 // An overriden item that defines a weight of 0 does not contribute to $totaloverriddengrademax.
b14c5870
AD
1316 continue;
1317 }
1318
11c93e28
DW
1319 $totalgrademax += $gradeitem->grademax;
1320 if ($gradeitem->weightoverride > 0) {
519429b2
AG
1321 $totaloverriddenweight += $gradeitem->aggregationcoef2;
1322 $totaloverriddengrademax += $gradeitem->grademax;
1323 }
1324 }
1325
1326 // Initialise this variable (used to keep track of the weight override total).
1327 $normalisetotal = 0;
1328 // 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
1329 // other weights to zero and normalise the others.
1330 $overriddentotal = 0;
f70da024
AG
1331 // If the overridden weight total is higher than 1 then set the other untouched weights to zero.
1332 $setotherweightstozero = false;
519429b2
AG
1333 // Total up all of the weights.
1334 foreach ($overridearray as $gradeitemdetail) {
1335 // If the grade item has extra credit, then don't add it to the normalisetotal.
11c93e28 1336 if (!$gradeitemdetail['extracredit']) {
519429b2
AG
1337 $normalisetotal += $gradeitemdetail['weight'];
1338 }
11c93e28 1339 if ($gradeitemdetail['weightoverride'] && !$gradeitemdetail['extracredit']) {
519429b2
AG
1340 // Add overriden weights up to see if they are greater than 1.
1341 $overriddentotal += $gradeitemdetail['weight'];
45da5361 1342 }
a2f1f65d 1343 }
f70da024 1344 if ($overriddentotal > 1) {
519429b2
AG
1345 // Make sure that this catergory of weights gets normalised.
1346 $requiresnormalising = true;
1347 // The normalised weights are only the overridden weights, so we just use the total of those.
1348 $normalisetotal = $overriddentotal;
519429b2
AG
1349 }
1350
11c93e28 1351 $totalnonoverriddengrademax = $totalgrademax - $totaloverriddengrademax;
45da5361 1352
a2f1f65d
AD
1353 reset($children);
1354 foreach ($children as $sortorder => $child) {
519429b2 1355 $gradeitem = null;
a2f1f65d
AD
1356
1357 if ($child['type'] == 'item') {
519429b2 1358 $gradeitem = $child['object'];
a2f1f65d 1359 } else if ($child['type'] == 'category') {
519429b2
AG
1360 $gradeitem = $child['object']->load_grade_item();
1361 }
1362
f70da024
AG
1363 if (!$gradeitem->weightoverride) {
1364 // Calculations with a grade maximum of zero will cause problems. Just set the weight to zero.
1365 if ($totaloverriddenweight >= 1 || $totalnonoverriddengrademax == 0 || $gradeitem->grademax == 0) {
64055d50 1366 // There is no more weight to distribute.
f70da024 1367 $gradeitem->aggregationcoef2 = 0;
64055d50
FM
1368 } else {
1369 // Calculate this item's weight as a percentage of the non-overridden total grade maxes
1370 // then convert it to a proportion of the available non-overriden weight.
f70da024
AG
1371 $gradeitem->aggregationcoef2 = ($gradeitem->grademax/$totalnonoverriddengrademax) *
1372 (1 - $totaloverriddenweight);
64055d50 1373 }
f70da024 1374 $gradeitem->update();
11c93e28
DW
1375 } else if ((!$automaticgradeitemspresent && $normalisetotal != 1) || ($requiresnormalising)) {
1376 // Just divide the overriden weight for this item against the total weight override of all
1377 // items in this category.
1378 if ($normalisetotal == 0) {
1379 $gradeitem->aggregationcoef2 = 0;
1380 } else {
1381 $gradeitem->aggregationcoef2 = $overridearray[$gradeitem->id]['weight'] / $normalisetotal;
1382 }
1383 // Update the grade item to reflect these changes.
1384 $gradeitem->update();
45da5361 1385 }
a2f1f65d
AD
1386 }
1387 }
1388
adc2f286 1389 /**
a153c9f2 1390 * Given an array of grade values (numerical indices) applies droplow or keephigh rules to limit the final array.
b79fe189 1391 *
a153c9f2 1392 * @param array $grade_values itemid=>$grade_value float
b79fe189 1393 * @param array $items grade item objects
adc2f286 1394 * @return array Limited grades.
1395 */
a9e38ac8 1396 public function apply_limit_rules(&$grade_values, $items) {
1397 $extraused = $this->is_extracredit_used();
1398
adc2f286 1399 if (!empty($this->droplow)) {
a9e38ac8 1400 asort($grade_values, SORT_NUMERIC);
1401 $dropped = 0;
b79fe189 1402
fb80cb2a
AD
1403 // If we have fewer grade items available to drop than $this->droplow, use this flag to escape the loop
1404 // May occur because of "extra credit" or if droplow is higher than the number of grade items
1405 $droppedsomething = true;
b79fe189 1406
fb80cb2a
AD
1407 while ($dropped < $this->droplow && $droppedsomething) {
1408 $droppedsomething = false;
b79fe189 1409
fb80cb2a 1410 $grade_keys = array_keys($grade_values);
aee968da
AD
1411 $gradekeycount = count($grade_keys);
1412
1413 if ($gradekeycount === 0) {
fb80cb2a
AD
1414 //We've dropped all grade items
1415 break;
1416 }
b79fe189 1417
fb80cb2a
AD
1418 $originalindex = $founditemid = $foundmax = null;
1419
1420 // Find the first remaining grade item that is available to be dropped
1421 foreach ($grade_keys as $gradekeyindex=>$gradekey) {
1422 if (!$extraused || $items[$gradekey]->aggregationcoef <= 0) {
1423 // Found a non-extra credit grade item that is eligible to be dropped
1424 $originalindex = $gradekeyindex;
1425 $founditemid = $grade_keys[$originalindex];
1426 $foundmax = $items[$founditemid]->grademax;
1427 break;
a9e38ac8 1428 }
fb80cb2a 1429 }
b79fe189 1430
fb80cb2a
AD
1431 if (empty($founditemid)) {
1432 // No grade items available to drop
a9e38ac8 1433 break;
59080eee 1434 }
fb80cb2a
AD
1435
1436 // Now iterate over the remaining grade items
1437 // We're looking for other grade items with the same grade value but a higher grademax
1438 $i = 1;
aee968da 1439 while ($originalindex + $i < $gradekeycount) {
52929486 1440
fb80cb2a 1441 $possibleitemid = $grade_keys[$originalindex+$i];
52929486
AD
1442 $i++;
1443
fb80cb2a
AD
1444 if ($grade_values[$founditemid] != $grade_values[$possibleitemid]) {
1445 // The next grade item has a different grade value. Stop looking.
1446 break;
1447 }
1448
1449 if ($extraused && $items[$possibleitemid]->aggregationcoef > 0) {
1450 // Don't drop extra credit grade items. Continue the search.
1451 continue;
1452 }
1453
1454 if ($foundmax < $items[$possibleitemid]->grademax) {
1455 // Found a grade item with the same grade value and a higher grademax
1456 $foundmax = $items[$possibleitemid]->grademax;
1457 $founditemid = $possibleitemid;
1458 // Continue searching to see if there is an even higher grademax
1459 }
fb80cb2a
AD
1460 }
1461
1462 // Now drop whatever grade item we have found
1463 unset($grade_values[$founditemid]);
1464 $dropped++;
1465 $droppedsomething = true;
adc2f286 1466 }
a9e38ac8 1467
1468 } else if (!empty($this->keephigh)) {
1469 arsort($grade_values, SORT_NUMERIC);
1470 $kept = 0;
b79fe189 1471
a9e38ac8 1472 foreach ($grade_values as $itemid=>$value) {
b79fe189 1473
a9e38ac8 1474 if ($extraused and $items[$itemid]->aggregationcoef > 0) {
1475 // we keep all extra credits
b79fe189 1476
a9e38ac8 1477 } else if ($kept < $this->keephigh) {
1478 $kept++;
b79fe189 1479
a9e38ac8 1480 } else {
1481 unset($grade_values[$itemid]);
1482 }
adc2f286 1483 }
1484 }
0aa32279 1485 }
1486
4272386a
FM
1487 /**
1488 * Returns whether or not we can apply the limit rules.
1489 *
1490 * There are cases where drop lowest or keep highest should not be used
1491 * at all. This method will determine whether or not this logic can be
1492 * applied considering the current setup of the category.
1493 *
1494 * @return bool
1495 */
1496 public function can_apply_limit_rules() {
1497 if ($this->canapplylimitrules !== null) {
1498 return $this->canapplylimitrules;
1499 }
1500
1501 // Set it to be supported by default.
1502 $this->canapplylimitrules = true;
1503
1504 // Natural aggregation.
1505 if ($this->aggregation == GRADE_AGGREGATE_SUM) {
1506 $canapply = true;
1507
1508 // Check until one child breaks the rules.
1509 $gradeitems = $this->get_children();
1510 $validitems = 0;
1511 $lastweight = null;
1512 $lastmaxgrade = null;
1513 foreach ($gradeitems as $gradeitem) {
1514 $gi = $gradeitem['object'];
1515
1516 if ($gradeitem['type'] == 'category') {
1517 // Sub categories are not allowed because they can have dynamic weights/maxgrades.
1518 $canapply = false;
1519 break;
1520 }
1521
1522 if ($gi->aggregationcoef > 0) {
1523 // Extra credit items are not allowed.
1524 $canapply = false;
1525 break;
1526 }
1527
1528 if ($lastweight !== null && $lastweight != $gi->aggregationcoef2) {
1529 // One of the weight differs from another item.
1530 $canapply = false;
1531 break;
1532 }
1533
1534 if ($lastmaxgrade !== null && $lastmaxgrade != $gi->grademax) {
1535 // One of the max grade differ from another item. This is not allowed for now
1536 // because we could be end up with different max grade between users for this category.
1537 $canapply = false;
1538 break;
1539 }
1540
1541 $lastweight = $gi->aggregationcoef2;
1542 $lastmaxgrade = $gi->grademax;
1543 }
1544
1545 $this->canapplylimitrules = $canapply;
1546 }
1547
1548 return $this->canapplylimitrules;
1549 }
1550
793253ae 1551 /**
1552 * Returns true if category uses extra credit of any kind
b79fe189 1553 *
a153c9f2 1554 * @return bool True if extra credit used
793253ae 1555 */
134c514b
RT
1556 public function is_extracredit_used() {
1557 return self::aggregation_uses_extracredit($this->aggregation);
1558 }
1559
1560 /**
1561 * Returns true if aggregation passed is using extracredit.
1562 *
1563 * @param int $aggregation Aggregation const.
1564 * @return bool True if extra credit used
1565 */
1566 public static function aggregation_uses_extracredit($aggregation) {
1567 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1568 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1569 or $aggregation == GRADE_AGGREGATE_SUM);
793253ae 1570 }
1571
9580a21f 1572 /**
f7d515b6 1573 * Returns true if category uses special aggregation coefficient
b79fe189 1574 *
a153c9f2 1575 * @return bool True if an aggregation coefficient is being used
9580a21f 1576 */
4e9ca991 1577 public function is_aggregationcoef_used() {
134c514b
RT
1578 return self::aggregation_uses_aggregationcoef($this->aggregation);
1579
1580 }
1581
1582 /**
1583 * Returns true if aggregation uses aggregationcoef
1584 *
1585 * @param int $aggregation Aggregation const.
1586 * @return bool True if an aggregation coefficient is being used
1587 */
1588 public static function aggregation_uses_aggregationcoef($aggregation) {
1589 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN
1590 or $aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1591 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1592 or $aggregation == GRADE_AGGREGATE_SUM);
ba74762b 1593
9580a21f 1594 }
1595
653a8648 1596 /**
a153c9f2 1597 * Recursive function to find which weight/extra credit field to use in the grade item form.
b79fe189 1598 *
a153c9f2 1599 * Inherits from a parent category if that category has aggregatesubcats set to true.
b79fe189 1600 *
a153c9f2 1601 * @param string $first Whether or not this is the first item in the recursion
b79fe189 1602 * @return string
653a8648 1603 */
1604 public function get_coefstring($first=true) {
1605 if (!is_null($this->coefstring)) {
1606 return $this->coefstring;
1607 }
1608
1609 $overriding_coefstring = null;
1610
1611 // Stop recursing upwards if this category aggregates subcats or has no parent
1612 if (!$first && !$this->aggregatesubcats) {
b79fe189 1613
121d8006 1614 if ($parent_category = $this->load_parent_category()) {
653a8648 1615 return $parent_category->get_coefstring(false);
b79fe189 1616
653a8648 1617 } else {
1618 return null;
1619 }
b79fe189 1620
1621 } else if ($first) {
1622
653a8648 1623 if (!$this->aggregatesubcats) {
b79fe189 1624
121d8006 1625 if ($parent_category = $this->load_parent_category()) {
653a8648 1626 $overriding_coefstring = $parent_category->get_coefstring(false);
1627 }
1628 }
1629 }
1630
1631 // If an overriding coefstring has trickled down from one of the parent categories, return it. Otherwise, return self.
1632 if (!is_null($overriding_coefstring)) {
1633 return $overriding_coefstring;
1634 }
1635
1636 // No parent category is overriding this category's aggregation, return its string
1637 if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
1638 $this->coefstring = 'aggregationcoefweight';
b79fe189 1639
d9ae2ab5 1640 } else if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2) {
1641 $this->coefstring = 'aggregationcoefextrasum';
b79fe189 1642
653a8648 1643 } else if ($this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
3869ab1a 1644 $this->coefstring = 'aggregationcoefextraweight';
b79fe189 1645
653a8648 1646 } else if ($this->aggregation == GRADE_AGGREGATE_SUM) {
b6a1e366 1647 $this->coefstring = 'aggregationcoefextraweightsum';
b79fe189 1648
653a8648 1649 } else {
1650 $this->coefstring = 'aggregationcoef';
1651 }
1652 return $this->coefstring;
1653 }
1654
1c307f21 1655 /**
b3ac6c3e 1656 * Returns tree with all grade_items and categories as elements
b79fe189 1657 *
1658 * @param int $courseid The course ID
a153c9f2 1659 * @param bool $include_category_items as category children
b3ac6c3e 1660 * @return array
1c307f21 1661 */
da3801e8 1662 public static function fetch_course_tree($courseid, $include_category_items=false) {
f3ac8eb4 1663 $course_category = grade_category::fetch_course_category($courseid);
514a3467 1664 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
1665 'children'=>$course_category->get_children($include_category_items));
b146d984
AD
1666
1667 $course_category->sortorder = $course_category->get_sortorder();
e2bb3c92
PS
1668 $sortorder = $course_category->get_sortorder();
1669 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 1670 }
1671
b79fe189 1672 /**
a153c9f2 1673 * An internal function that recursively sorts grade categories within a course
b79fe189 1674 *
1675 * @param array $category_array The seed of the recursion
a153c9f2
AD
1676 * @param int $sortorder The current sortorder
1677 * @return array An array containing 'object', 'type', 'depth' and optionally 'children'
b79fe189 1678 */
1679 static private function _fetch_course_tree_recursion($category_array, &$sortorder) {
b3ac6c3e 1680 // update the sortorder in db if needed
b146d984
AD
1681 //NOTE: This leads to us resetting sort orders every time the categories and items page is viewed :(
1682 //if ($category_array['object']->sortorder != $sortorder) {
1683 //$category_array['object']->set_sortorder($sortorder);
1684 //}
ce385eb4 1685
7bac3777
AD
1686 if (isset($category_array['object']->gradetype) && $category_array['object']->gradetype==GRADE_TYPE_NONE) {
1687 return null;
1688 }
1689
314c4336 1690 // store the grade_item or grade_category instance with extra info
1691 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 1692
1693 // reuse final grades if there
1694 if (array_key_exists('finalgrades', $category_array)) {
1695 $result['finalgrades'] = $category_array['finalgrades'];
1696 }
1697
1698 // recursively resort children
1699 if (!empty($category_array['children'])) {
1700 $result['children'] = array();
29d509f5 1701 //process the category item first
7bac3777 1702 $child = null;
b79fe189 1703
1704 foreach ($category_array['children'] as $oldorder=>$child_array) {
1705
314c4336 1706 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
7bac3777
AD
1707 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1708 if (!empty($child)) {
1709 $result['children'][$sortorder] = $child;
1710 }
29d509f5 1711 }
2b0f65e2 1712 }
b79fe189 1713
1714 foreach ($category_array['children'] as $oldorder=>$child_array) {
1715
29d509f5 1716 if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
7bac3777
AD
1717 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1718 if (!empty($child)) {
1719 $result['children'][++$sortorder] = $child;
1720 }
b3ac6c3e 1721 }
1722 }
1723 }
1724
1725 return $result;
ce385eb4 1726 }
7c8a963f 1727
1728 /**
4a490db0 1729 * Fetches and returns all the children categories and/or grade_items belonging to this category.
1730 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 1731 * as well as all levels (0). The elements are indexed by sort order.
b79fe189 1732 *
1733 * @param bool $include_category_items Whether or not to include category grade_items in the children array
7c8a963f 1734 * @return array Array of child objects (grade_category and grade_item).
1735 */
da3801e8 1736 public function get_children($include_category_items=false) {
1737 global $DB;
b3ac6c3e 1738
1739 // This function must be as fast as possible ;-)
1740 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
1741 // we have to limit the number of queries though, because it will be used often in grade reports
1742
da3801e8 1743 $cats = $DB->get_records('grade_categories', array('courseid' => $this->courseid));
1744 $items = $DB->get_records('grade_items', array('courseid' => $this->courseid));
4a490db0 1745
b3ac6c3e 1746 // init children array first
1747 foreach ($cats as $catid=>$cat) {
1748 $cats[$catid]->children = array();
27f95e9b 1749 }
4a490db0 1750
b3ac6c3e 1751 //first attach items to cats and add category sortorder
1752 foreach ($items as $item) {
b79fe189 1753
b3ac6c3e 1754 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
1755 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 1756
b3ac6c3e 1757 if (!$include_category_items) {
1758 continue;
1759 }
1760 $categoryid = $item->iteminstance;
b79fe189 1761
b3ac6c3e 1762 } else {
1763 $categoryid = $item->categoryid;
63354ab5
AD
1764 if (empty($categoryid)) {
1765 debugging('Found a grade item that isnt in a category');
1766 }
b3ac6c3e 1767 }
1768
1769 // prevent problems with duplicate sortorders in db
1770 $sortorder = $item->sortorder;
b79fe189 1771
63354ab5
AD
1772 while (array_key_exists($categoryid, $cats)
1773 && array_key_exists($sortorder, $cats[$categoryid]->children)) {
1774
b3ac6c3e 1775 $sortorder++;
1776 }
1777
1778 $cats[$categoryid]->children[$sortorder] = $item;
1779
1780 }
1781
1782 // now find the requested category and connect categories as children
1783 $category = false;
b79fe189 1784
b3ac6c3e 1785 foreach ($cats as $catid=>$cat) {
b79fe189 1786
ec3717e1 1787 if (empty($cat->parent)) {
b79fe189 1788
ec3717e1 1789 if ($cat->path !== '/'.$cat->id.'/') {
1790 $grade_category = new grade_category($cat, false);
1791 $grade_category->path = '/'.$cat->id.'/';
1792 $grade_category->depth = 1;
1793 $grade_category->update('system');
1794 return $this->get_children($include_category_items);
1795 }
b79fe189 1796
ec3717e1 1797 } else {
b79fe189 1798
ec3717e1 1799 if (empty($cat->path) or !preg_match('|/'.$cat->parent.'/'.$cat->id.'/$|', $cat->path)) {
1800 //fix paths and depts
1801 static $recursioncounter = 0; // prevents infinite recursion
1802 $recursioncounter++;
b79fe189 1803
da3801e8 1804 if ($recursioncounter < 5) {
ec3717e1 1805 // fix paths and depths!
1806 $grade_category = new grade_category($cat, false);
1807 $grade_category->depth = 0;
1808 $grade_category->path = null;
1809 $grade_category->update('system');
1810 return $this->get_children($include_category_items);
1811 }
da3801e8 1812 }
b3ac6c3e 1813 // prevent problems with duplicate sortorders in db
1814 $sortorder = $cat->sortorder;
b79fe189 1815
1816 while (array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 1817 //debugging("$sortorder exists in cat loop");
b3ac6c3e 1818 $sortorder++;
1819 }
1820
65370356 1821 $cats[$cat->parent]->children[$sortorder] = &$cats[$catid];
b3ac6c3e 1822 }
f3ac8eb4 1823
b3ac6c3e 1824 if ($catid == $this->id) {
1825 $category = &$cats[$catid];
1826 }
1827 }
1828
1829 unset($items); // not needed
1830 unset($cats); // not needed
1831
f3ac8eb4 1832 $children_array = grade_category::_get_children_recursion($category);
b3ac6c3e 1833
1834 ksort($children_array);
1835
1836 return $children_array;
1837
1838 }
1839
b79fe189 1840 /**
1841 * Private method used to retrieve all children of this category recursively
1842 *
1843 * @param grade_category $category Source of current recursion
a153c9f2 1844 * @return array An array of child grade categories
b79fe189 1845 */
22a9b6d8 1846 private static function _get_children_recursion($category) {
b3ac6c3e 1847
1848 $children_array = array();
b79fe189 1849 foreach ($category->children as $sortorder=>$child) {
1850
b3ac6c3e 1851 if (array_key_exists('itemtype', $child)) {
f3ac8eb4 1852 $grade_item = new grade_item($child, false);
b79fe189 1853
4faf5f99 1854 if (in_array($grade_item->itemtype, array('course', 'category'))) {
1855 $type = $grade_item->itemtype.'item';
1856 $depth = $category->depth;
b79fe189 1857
314c4336 1858 } else {
1859 $type = 'item';
1860 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 1861 }
4faf5f99 1862 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 1863
7c8a963f 1864 } else {
f3ac8eb4 1865 $children = grade_category::_get_children_recursion($child);
1866 $grade_category = new grade_category($child, false);
b79fe189 1867
b3ac6c3e 1868 if (empty($children)) {
314c4336 1869 $children = array();
7c8a963f 1870 }
4faf5f99 1871 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
314c4336 1872 }
27f95e9b 1873 }
1874
b3ac6c3e 1875 // sort the array
1876 ksort($children_array);
1877
27f95e9b 1878 return $children_array;
1879 }
4a490db0 1880
f151b073 1881 /**
a4d76049 1882 * Uses {@link get_grade_item()} to load or create a grade_item, then saves it as $this->grade_item.
a153c9f2
AD
1883 *
1884 * @return grade_item
f151b073 1885 */
da3801e8 1886 public function load_grade_item() {
ac9b0805 1887 if (empty($this->grade_item)) {
1888 $this->grade_item = $this->get_grade_item();
1889 }
ab53054f 1890 return $this->grade_item;
1891 }
4a490db0 1892
ab53054f 1893 /**
a153c9f2
AD
1894 * Retrieves this grade categories' associated grade_item from the database
1895 *
1896 * If no grade_item exists yet, creates one.
1897 *
1898 * @return grade_item
ab53054f 1899 */
da3801e8 1900 public function get_grade_item() {
c91ed4be 1901 if (empty($this->id)) {
1902 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
1903 return false;
1904 }
1905
b3ac6c3e 1906 if (empty($this->parent)) {
1907 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
1908
1909 } else {
1910 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
1911 }
4ac209d5 1912
f3ac8eb4 1913 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 1914 // create a new one
f3ac8eb4 1915 $grade_item = new grade_item($params, false);
b8ff92b6 1916 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 1917 $grade_item->insert('system');
4a490db0 1918
b79fe189 1919 } else if (count($grade_items) == 1) {
b8ff92b6 1920 // found existing one
1921 $grade_item = reset($grade_items);
4a490db0 1922
b8ff92b6 1923 } else {
1924 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 1925 // return first one
1926 $grade_item = reset($grade_items);
2c72af1f 1927 }
1928
ab53054f 1929 return $grade_item;
f151b073 1930 }
8c846243 1931
1932 /**
a153c9f2
AD
1933 * Uses $this->parent to instantiate $this->parent_category based on the referenced record in the DB
1934 *
1935 * @return grade_category The parent category
8c846243 1936 */
da3801e8 1937 public function load_parent_category() {
8c846243 1938 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 1939 $this->parent_category = $this->get_parent_category();
8c846243 1940 }
1941 return $this->parent_category;
4a490db0 1942 }
1943
ab53054f 1944 /**
a153c9f2
AD
1945 * Uses $this->parent to instantiate and return a grade_category object
1946 *
1947 * @return grade_category Returns the parent category or null if this category has no parent
ab53054f 1948 */
da3801e8 1949 public function get_parent_category() {
ab53054f 1950 if (!empty($this->parent)) {
f3ac8eb4 1951 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 1952 return $parent_category;
ab53054f 1953 } else {
1954 return null;
1955 }
1956 }
1957
2186f72c 1958 /**
a153c9f2 1959 * Returns the most descriptive field for this grade category
b79fe189 1960 *
2186f72c 1961 * @return string name
1962 */
da3801e8 1963 public function get_name() {
1964 global $DB;
8f6fdf43 1965 // For a course category, we return the course name if the fullname is set to '?' in the DB (empty in the category edit form)
1966 if (empty($this->parent) && $this->fullname == '?') {
da3801e8 1967 $course = $DB->get_record('course', array('id'=> $this->courseid));
410753fb 1968 return format_string($course->fullname);
b79fe189 1969
314c4336 1970 } else {
1971 return $this->fullname;
1972 }
2186f72c 1973 }
c91ed4be 1974
65c2ac93
DW
1975 /**
1976 * Describe the aggregation settings for this category so the reports make more sense.
1977 *
1978 * @return string description
1979 */
1980 public function get_description() {
1981 $allhelp = array();
2be0d5c3
MG
1982 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
1983 $aggrstrings = grade_helper::get_aggregation_strings();
1984 $allhelp[] = $aggrstrings[$this->aggregation];
1985 }
65c2ac93 1986
ded8ea8f 1987 if ($this->droplow && $this->can_apply_limit_rules()) {
65c2ac93
DW
1988 $allhelp[] = get_string('droplowestvalues', 'grades', $this->droplow);
1989 }
ded8ea8f 1990 if ($this->keephigh && $this->can_apply_limit_rules()) {
65c2ac93
DW
1991 $allhelp[] = get_string('keephighestvalues', 'grades', $this->keephigh);
1992 }
1993 if (!$this->aggregateonlygraded) {
1994 $allhelp[] = get_string('aggregatenotonlygraded', 'grades');
1995 }
1996 if ($this->aggregatesubcats) {
1997 $allhelp[] = get_string('aggregatesubcatsshort', 'grades');
1998 }
2be0d5c3
MG
1999 if ($allhelp) {
2000 return implode('. ', $allhelp) . '.';
2001 }
2002 return '';
65c2ac93
DW
2003 }
2004
0fc7f624 2005 /**
a153c9f2 2006 * Sets this category's parent id
b79fe189 2007 *
a153c9f2
AD
2008 * @param int $parentid The ID of the category that is the new parent to $this
2009 * @param string $source From where was the object updated (mod/forum, manual, etc.)
2010 * @return bool success
0fc7f624 2011 */
da3801e8 2012 public function set_parent($parentid, $source=null) {
f13002d5 2013 if ($this->parent == $parentid) {
2014 return true;
2015 }
2016
2017 if ($parentid == $this->id) {
2f137aa1 2018 print_error('cannotassignselfasparent');
f13002d5 2019 }
2020
2021 if (empty($this->parent) and $this->is_course_category()) {
2f137aa1 2022 print_error('cannothaveparentcate');
b3ac6c3e 2023 }
f13002d5 2024
2025 // find parent and check course id
f3ac8eb4 2026 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 2027 return false;
2028 }
2029
f8e6e4db 2030 $this->force_regrading();
b3ac6c3e 2031
2032 // set new parent category
f8e6e4db 2033 $this->parent = $parent_category->id;
2034 $this->parent_category =& $parent_category;
b3ac6c3e 2035 $this->path = null; // remove old path and depth - will be recalculated in update()
ec3717e1 2036 $this->depth = 0; // remove old path and depth - will be recalculated in update()
f8e6e4db 2037 $this->update($source);
b3ac6c3e 2038
15b462da 2039 return $this->update($source);
b3ac6c3e 2040 }
2041
2042 /**
a153c9f2 2043 * Returns the final grade values for this grade category.
b79fe189 2044 *
a153c9f2 2045 * @param int $userid Optional user ID to retrieve a single user's final grade
b3ac6c3e 2046 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
2047 */
b79fe189 2048 public function get_final($userid=null) {
b3ac6c3e 2049 $this->load_grade_item();
2050 return $this->grade_item->get_final($userid);
0fc7f624 2051 }
4a490db0 2052
0fc7f624 2053 /**
a153c9f2
AD
2054 * Returns the sortorder of the grade categories' associated grade_item
2055 *
2056 * This method is also available in grade_item for cases where the object type is not known.
b79fe189 2057 *
0fc7f624 2058 * @return int Sort order
2059 */
da3801e8 2060 public function get_sortorder() {
b3ac6c3e 2061 $this->load_grade_item();
2062 return $this->grade_item->get_sortorder();
0fc7f624 2063 }
2064
be7c0693 2065 /**
a153c9f2
AD
2066 * Returns the idnumber of the grade categories' associated grade_item.
2067 *
2068 * This method is also available in grade_item for cases where the object type is not known.
b79fe189 2069 *
be7c0693 2070 * @return string idnumber
2071 */
da3801e8 2072 public function get_idnumber() {
be7c0693 2073 $this->load_grade_item();
2074 return $this->grade_item->get_idnumber();
2075 }
2076
0fc7f624 2077 /**
a153c9f2
AD
2078 * Sets the sortorder variable for this category.
2079 *
4a490db0 2080 * This method is also available in grade_item, for cases where the object type is not know.
b79fe189 2081 *
2082 * @param int $sortorder The sortorder to assign to this category
0fc7f624 2083 */
da3801e8 2084 public function set_sortorder($sortorder) {
b3ac6c3e 2085 $this->load_grade_item();
2086 $this->grade_item->set_sortorder($sortorder);
2087 }
2088
6639ead3 2089 /**
a153c9f2 2090 * Move this category after the given sortorder
b79fe189 2091 *
a153c9f2 2092 * Does not change the parent
b79fe189 2093 *
a153c9f2 2094 * @param int $sortorder to place after.
b79fe189 2095 * @return void
6639ead3 2096 */
da3801e8 2097 public function move_after_sortorder($sortorder) {
f13002d5 2098 $this->load_grade_item();
2099 $this->grade_item->move_after_sortorder($sortorder);
2100 }
2101
b3ac6c3e 2102 /**
f13002d5 2103 * Return true if this is the top most category that represents the total course grade.
b79fe189 2104 *
a153c9f2 2105 * @return bool
b3ac6c3e 2106 */
da3801e8 2107 public function is_course_category() {
b3ac6c3e 2108 $this->load_grade_item();
2109 return $this->grade_item->is_course_item();
2110 }
2111
2112 /**
a153c9f2 2113 * Return the course level grade_category object
b79fe189 2114 *
2115 * @param int $courseid The Course ID
a153c9f2 2116 * @return grade_category Returns the course level grade_category instance
b3ac6c3e 2117 */
22a9b6d8 2118 public static function fetch_course_category($courseid) {
a4503119 2119 if (empty($courseid)) {
2120 debugging('Missing course id!');
2121 return false;
2122 }
b3ac6c3e 2123
2124 // course category has no parent
f3ac8eb4 2125 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
b3ac6c3e 2126 return $course_category;
2127 }
2128
2129 // create a new one
f3ac8eb4 2130 $course_category = new grade_category();
b3ac6c3e 2131 $course_category->insert_course_category($courseid);
2132
2133 return $course_category;
0fc7f624 2134 }
4ac209d5 2135
79eabc2a 2136 /**
2137 * Is grading object editable?
b79fe189 2138 *
a153c9f2 2139 * @return bool
79eabc2a 2140 */
da3801e8 2141 public function is_editable() {
79eabc2a 2142 return true;
2143 }
2144
5fad5061 2145 /**
a153c9f2
AD
2146 * Returns the locked state/date of the grade categories' associated grade_item.
2147 *
2148 * This method is also available in grade_item, for cases where the object type is not known.
2149 *
2150 * @return bool
5fad5061 2151 */
da3801e8 2152 public function is_locked() {
5fad5061 2153 $this->load_grade_item();
22e23c78 2154 return $this->grade_item->is_locked();
5fad5061 2155 }
2156
2157 /**
2158 * Sets the grade_item's locked variable and updates the grade_item.
a153c9f2
AD
2159 *
2160 * Calls set_locked() on the categories' grade_item
b79fe189 2161 *
2162 * @param int $lockedstate 0, 1 or a timestamp int(10) after which date the item will be locked.
2163 * @param bool $cascade lock/unlock child objects too
2164 * @param bool $refresh refresh grades when unlocking
a153c9f2 2165 * @return bool success if category locked (not all children mayb be locked though)
5fad5061 2166 */
da3801e8 2167 public function set_locked($lockedstate, $cascade=false, $refresh=true) {
5fad5061 2168 $this->load_grade_item();
2b0f65e2 2169
fb0e3570 2170 $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
2171
2172 if ($cascade) {
2173 //process all children - items and categories
f3ac8eb4 2174 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
b79fe189 2175
2176 foreach ($children as $child) {
fb0e3570 2177 $child->set_locked($lockedstate, true, false);
b79fe189 2178
fb0e3570 2179 if (empty($lockedstate) and $refresh) {
2180 //refresh when unlocking
2181 $child->refresh_grades();
2182 }
2b0f65e2 2183 }
7a7a53d3 2184 }
b79fe189 2185
f3ac8eb4 2186 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 2187
2188 foreach ($children as $child) {
fb0e3570 2189 $child->set_locked($lockedstate, true, true);
2190 }
7a7a53d3 2191 }
2192 }
2b0f65e2 2193
b121b544 2194 return $result;
5fad5061 2195 }
4a490db0 2196
a153c9f2
AD
2197 /**
2198 * Overrides grade_object::set_properties() to add special handling for changes to category aggregation types
2199 *
2200 * @param stdClass $instance the object to set the properties on
2201 * @param array|stdClass $params Either an associative array or an object containing property name, property value pairs
2202 */
79b260cc
AD
2203 public static function set_properties(&$instance, $params) {
2204 global $DB;
2205
2206 parent::set_properties($instance, $params);
2207
c1024411 2208 //if they've changed aggregation type we made need to do some fiddling to provide appropriate defaults
79b260cc
AD
2209 if (!empty($params->aggregation)) {
2210
2211 //weight and extra credit share a column :( Would like a default of 1 for weight and 0 for extra credit
2212 //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 2213 if (self::aggregation_uses_aggregationcoef($params->aggregation)) {
79b260cc 2214 $sql = $defaultaggregationcoef = null;
7ad5a627 2215
134c514b 2216 if (!self::aggregation_uses_extracredit($params->aggregation)) {
79b260cc
AD
2217 //if all items in this category have aggregation coefficient of 0 we can change it to 1 ie evenly weighted
2218 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=0";
2219 $defaultaggregationcoef = 1;
134c514b 2220 } else {
79b260cc
AD
2221 //if all items in this category have aggregation coefficient of 1 we can change it to 0 ie no extra credit
2222 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=1";
2223 $defaultaggregationcoef = 0;
2224 }
2225
2226 $params = array('categoryid'=>$instance->id);
2227 $count = $DB->count_records_sql($sql, $params);
2228 if ($count===0) { //category is either empty or all items are set to a default value so we can switch defaults
2229 $params['aggregationcoef'] = $defaultaggregationcoef;
2230 $DB->execute("update {grade_items} set aggregationcoef=:aggregationcoef where categoryid=:categoryid",$params);
2231 }
2232 }
2233 }
2234 }
2235
5fad5061 2236 /**
4a490db0 2237 * Sets the grade_item's hidden variable and updates the grade_item.
a153c9f2
AD
2238 *
2239 * Overrides grade_item::set_hidden() to add cascading of the hidden value to grade items in this grade category
2240 *
2241 * @param int $hidden 0 mean always visible, 1 means always hidden and a number > 1 is a timestamp to hide until
2242 * @param bool $cascade apply to child objects too
5fad5061 2243 */
da3801e8 2244 public function set_hidden($hidden, $cascade=false) {
5fad5061 2245 $this->load_grade_item();
a25bb902 2246 //this hides the associated grade item (the course total)
1762a264 2247 $this->grade_item->set_hidden($hidden, $cascade);
a25bb902
AD
2248 //this hides the category itself and everything it contains
2249 parent::set_hidden($hidden, $cascade);
b79fe189 2250
f60c61b1 2251 if ($cascade) {
b79fe189 2252
f3ac8eb4 2253 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
b79fe189 2254
2255 foreach ($children as $child) {
39873128
TH
2256 if ($child->can_control_visibility()) {
2257 $child->set_hidden($hidden, $cascade);
2258 }
f60c61b1 2259 }
f13002d5 2260 }
b79fe189 2261
f3ac8eb4 2262 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 2263
2264 foreach ($children as $child) {
f60c61b1 2265 $child->set_hidden($hidden, $cascade);
2266 }
f13002d5 2267 }
2268 }
d90aa634
AD
2269
2270 //if marking category visible make sure parent category is visible MDL-21367
93fad868 2271 if( !$hidden ) {
d90aa634
AD
2272 $category_array = grade_category::fetch_all(array('id'=>$this->parent));
2273 if ($category_array && array_key_exists($this->parent, $category_array)) {
2274 $category = $category_array[$this->parent];
93fad868
SH
2275 //call set_hidden on the category regardless of whether it is hidden as its parent might be hidden
2276 //if($category->is_hidden()) {
2277 $category->set_hidden($hidden, false);
2278 //}
d90aa634
AD
2279 }
2280 }
5fad5061 2281 }
89a5f827 2282
190af29f 2283 /**
2284 * Applies default settings on this category
a153c9f2
AD
2285 *
2286 * @return bool True if anything changed
190af29f 2287 */
da3801e8 2288 public function apply_default_settings() {
190af29f 2289 global $CFG;
2290
2291 foreach ($this->forceable as $property) {
b79fe189 2292
190af29f 2293 if (isset($CFG->{"grade_$property"})) {
b79fe189 2294
190af29f 2295 if ($CFG->{"grade_$property"} == -1) {
2296 continue; //temporary bc before version bump
2297 }
2298 $this->$property = $CFG->{"grade_$property"};
2299 }
2300 }
2301 }
2302
89a5f827 2303 /**
2304 * Applies forced settings on this category
a153c9f2
AD
2305 *
2306 * @return bool True if anything changed
89a5f827 2307 */
da3801e8 2308 public function apply_forced_settings() {
89a5f827 2309 global $CFG;
2310
2311 $updated = false;
b79fe189 2312
89a5f827 2313 foreach ($this->forceable as $property) {
b79fe189 2314
2315 if (isset($CFG->{"grade_$property"}) and isset($CFG->{"grade_{$property}_flag"}) and
2316 ((int) $CFG->{"grade_{$property}_flag"} & 1)) {
2317
190af29f 2318 if ($CFG->{"grade_$property"} == -1) {
2319 continue; //temporary bc before version bump
2320 }
89a5f827 2321 $this->$property = $CFG->{"grade_$property"};
2322 $updated = true;
2323 }
2324 }
2325
2326 return $updated;
2327 }
2328
2329 /**
2330 * Notification of change in forced category settings.
b79fe189 2331 *
a153c9f2 2332 * Causes all course and category grade items to be marked as needing to be updated
89a5f827 2333 */
da3801e8 2334 public static function updated_forced_settings() {
5b0af8c5 2335 global $CFG, $DB;
2336 $params = array(1, 'course', 'category');
2337 $sql = "UPDATE {grade_items} SET needsupdate=? WHERE itemtype=? or itemtype=?";
2338 $DB->execute($sql, $params);
89a5f827 2339 }
4a490db0 2340}