MDL-40697 core_grades: trigger the user_graded event
[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 */
da3801e8 93 public $aggregation = GRADE_AGGREGATE_MEAN;
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();
11c93e28
DW
1376 } else if ((!$automaticgradeitemspresent && $normalisetotal != 1) || ($requiresnormalising)) {
1377 // Just divide the overriden weight for this item against the total weight override of all
1378 // items in this category.
1379 if ($normalisetotal == 0) {
1380 $gradeitem->aggregationcoef2 = 0;
1381 } else {
1382 $gradeitem->aggregationcoef2 = $overridearray[$gradeitem->id]['weight'] / $normalisetotal;
1383 }
1384 // Update the grade item to reflect these changes.
1385 $gradeitem->update();
45da5361 1386 }
a2f1f65d
AD
1387 }
1388 }
1389
adc2f286 1390 /**
a153c9f2 1391 * Given an array of grade values (numerical indices) applies droplow or keephigh rules to limit the final array.
b79fe189 1392 *
a153c9f2 1393 * @param array $grade_values itemid=>$grade_value float
b79fe189 1394 * @param array $items grade item objects
adc2f286 1395 * @return array Limited grades.
1396 */
a9e38ac8 1397 public function apply_limit_rules(&$grade_values, $items) {
1398 $extraused = $this->is_extracredit_used();
1399
adc2f286 1400 if (!empty($this->droplow)) {
a9e38ac8 1401 asort($grade_values, SORT_NUMERIC);
1402 $dropped = 0;
b79fe189 1403
fb80cb2a
AD
1404 // If we have fewer grade items available to drop than $this->droplow, use this flag to escape the loop
1405 // May occur because of "extra credit" or if droplow is higher than the number of grade items
1406 $droppedsomething = true;
b79fe189 1407
fb80cb2a
AD
1408 while ($dropped < $this->droplow && $droppedsomething) {
1409 $droppedsomething = false;
b79fe189 1410
fb80cb2a 1411 $grade_keys = array_keys($grade_values);
aee968da
AD
1412 $gradekeycount = count($grade_keys);
1413
1414 if ($gradekeycount === 0) {
fb80cb2a
AD
1415 //We've dropped all grade items
1416 break;
1417 }
b79fe189 1418
fb80cb2a
AD
1419 $originalindex = $founditemid = $foundmax = null;
1420
1421 // Find the first remaining grade item that is available to be dropped
1422 foreach ($grade_keys as $gradekeyindex=>$gradekey) {
1423 if (!$extraused || $items[$gradekey]->aggregationcoef <= 0) {
1424 // Found a non-extra credit grade item that is eligible to be dropped
1425 $originalindex = $gradekeyindex;
1426 $founditemid = $grade_keys[$originalindex];
1427 $foundmax = $items[$founditemid]->grademax;
1428 break;
a9e38ac8 1429 }
fb80cb2a 1430 }
b79fe189 1431
fb80cb2a
AD
1432 if (empty($founditemid)) {
1433 // No grade items available to drop
a9e38ac8 1434 break;
59080eee 1435 }
fb80cb2a
AD
1436
1437 // Now iterate over the remaining grade items
1438 // We're looking for other grade items with the same grade value but a higher grademax
1439 $i = 1;
aee968da 1440 while ($originalindex + $i < $gradekeycount) {
52929486 1441
fb80cb2a 1442 $possibleitemid = $grade_keys[$originalindex+$i];
52929486
AD
1443 $i++;
1444
fb80cb2a
AD
1445 if ($grade_values[$founditemid] != $grade_values[$possibleitemid]) {
1446 // The next grade item has a different grade value. Stop looking.
1447 break;
1448 }
1449
1450 if ($extraused && $items[$possibleitemid]->aggregationcoef > 0) {
1451 // Don't drop extra credit grade items. Continue the search.
1452 continue;
1453 }
1454
1455 if ($foundmax < $items[$possibleitemid]->grademax) {
1456 // Found a grade item with the same grade value and a higher grademax
1457 $foundmax = $items[$possibleitemid]->grademax;
1458 $founditemid = $possibleitemid;
1459 // Continue searching to see if there is an even higher grademax
1460 }
fb80cb2a
AD
1461 }
1462
1463 // Now drop whatever grade item we have found
1464 unset($grade_values[$founditemid]);
1465 $dropped++;
1466 $droppedsomething = true;
adc2f286 1467 }
a9e38ac8 1468
1469 } else if (!empty($this->keephigh)) {
1470 arsort($grade_values, SORT_NUMERIC);
1471 $kept = 0;
b79fe189 1472
a9e38ac8 1473 foreach ($grade_values as $itemid=>$value) {
b79fe189 1474
a9e38ac8 1475 if ($extraused and $items[$itemid]->aggregationcoef > 0) {
1476 // we keep all extra credits
b79fe189 1477
a9e38ac8 1478 } else if ($kept < $this->keephigh) {
1479 $kept++;
b79fe189 1480
a9e38ac8 1481 } else {
1482 unset($grade_values[$itemid]);
1483 }
adc2f286 1484 }
1485 }
0aa32279 1486 }
1487
4272386a
FM
1488 /**
1489 * Returns whether or not we can apply the limit rules.
1490 *
1491 * There are cases where drop lowest or keep highest should not be used
1492 * at all. This method will determine whether or not this logic can be
1493 * applied considering the current setup of the category.
1494 *
1495 * @return bool
1496 */
1497 public function can_apply_limit_rules() {
1498 if ($this->canapplylimitrules !== null) {
1499 return $this->canapplylimitrules;
1500 }
1501
1502 // Set it to be supported by default.
1503 $this->canapplylimitrules = true;
1504
1505 // Natural aggregation.
1506 if ($this->aggregation == GRADE_AGGREGATE_SUM) {
1507 $canapply = true;
1508
1509 // Check until one child breaks the rules.
1510 $gradeitems = $this->get_children();
1511 $validitems = 0;
1512 $lastweight = null;
1513 $lastmaxgrade = null;
1514 foreach ($gradeitems as $gradeitem) {
1515 $gi = $gradeitem['object'];
1516
1517 if ($gradeitem['type'] == 'category') {
1518 // Sub categories are not allowed because they can have dynamic weights/maxgrades.
1519 $canapply = false;
1520 break;
1521 }
1522
1523 if ($gi->aggregationcoef > 0) {
1524 // Extra credit items are not allowed.
1525 $canapply = false;
1526 break;
1527 }
1528
1529 if ($lastweight !== null && $lastweight != $gi->aggregationcoef2) {
1530 // One of the weight differs from another item.
1531 $canapply = false;
1532 break;
1533 }
1534
1535 if ($lastmaxgrade !== null && $lastmaxgrade != $gi->grademax) {
1536 // One of the max grade differ from another item. This is not allowed for now
1537 // because we could be end up with different max grade between users for this category.
1538 $canapply = false;
1539 break;
1540 }
1541
1542 $lastweight = $gi->aggregationcoef2;
1543 $lastmaxgrade = $gi->grademax;
1544 }
1545
1546 $this->canapplylimitrules = $canapply;
1547 }
1548
1549 return $this->canapplylimitrules;
1550 }
1551
793253ae 1552 /**
1553 * Returns true if category uses extra credit of any kind
b79fe189 1554 *
a153c9f2 1555 * @return bool True if extra credit used
793253ae 1556 */
134c514b
RT
1557 public function is_extracredit_used() {
1558 return self::aggregation_uses_extracredit($this->aggregation);
1559 }
1560
1561 /**
1562 * Returns true if aggregation passed is using extracredit.
1563 *
1564 * @param int $aggregation Aggregation const.
1565 * @return bool True if extra credit used
1566 */
1567 public static function aggregation_uses_extracredit($aggregation) {
1568 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1569 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1570 or $aggregation == GRADE_AGGREGATE_SUM);
793253ae 1571 }
1572
9580a21f 1573 /**
f7d515b6 1574 * Returns true if category uses special aggregation coefficient
b79fe189 1575 *
a153c9f2 1576 * @return bool True if an aggregation coefficient is being used
9580a21f 1577 */
4e9ca991 1578 public function is_aggregationcoef_used() {
134c514b
RT
1579 return self::aggregation_uses_aggregationcoef($this->aggregation);
1580
1581 }
1582
1583 /**
1584 * Returns true if aggregation uses aggregationcoef
1585 *
1586 * @param int $aggregation Aggregation const.
1587 * @return bool True if an aggregation coefficient is being used
1588 */
1589 public static function aggregation_uses_aggregationcoef($aggregation) {
1590 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN
1591 or $aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1592 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1593 or $aggregation == GRADE_AGGREGATE_SUM);
ba74762b 1594
9580a21f 1595 }
1596
653a8648 1597 /**
a153c9f2 1598 * Recursive function to find which weight/extra credit field to use in the grade item form.
b79fe189 1599 *
a153c9f2 1600 * Inherits from a parent category if that category has aggregatesubcats set to true.
b79fe189 1601 *
a153c9f2 1602 * @param string $first Whether or not this is the first item in the recursion
b79fe189 1603 * @return string
653a8648 1604 */
1605 public function get_coefstring($first=true) {
1606 if (!is_null($this->coefstring)) {
1607 return $this->coefstring;
1608 }
1609
1610 $overriding_coefstring = null;
1611
1612 // Stop recursing upwards if this category aggregates subcats or has no parent
1613 if (!$first && !$this->aggregatesubcats) {
b79fe189 1614
121d8006 1615 if ($parent_category = $this->load_parent_category()) {
653a8648 1616 return $parent_category->get_coefstring(false);
b79fe189 1617
653a8648 1618 } else {
1619 return null;
1620 }
b79fe189 1621
1622 } else if ($first) {
1623
653a8648 1624 if (!$this->aggregatesubcats) {
b79fe189 1625
121d8006 1626 if ($parent_category = $this->load_parent_category()) {
653a8648 1627 $overriding_coefstring = $parent_category->get_coefstring(false);
1628 }
1629 }
1630 }
1631
1632 // If an overriding coefstring has trickled down from one of the parent categories, return it. Otherwise, return self.
1633 if (!is_null($overriding_coefstring)) {
1634 return $overriding_coefstring;
1635 }
1636
1637 // No parent category is overriding this category's aggregation, return its string
1638 if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
1639 $this->coefstring = 'aggregationcoefweight';
b79fe189 1640
d9ae2ab5 1641 } else if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2) {
1642 $this->coefstring = 'aggregationcoefextrasum';
b79fe189 1643
653a8648 1644 } else if ($this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
3869ab1a 1645 $this->coefstring = 'aggregationcoefextraweight';
b79fe189 1646
653a8648 1647 } else if ($this->aggregation == GRADE_AGGREGATE_SUM) {
b6a1e366 1648 $this->coefstring = 'aggregationcoefextraweightsum';
b79fe189 1649
653a8648 1650 } else {
1651 $this->coefstring = 'aggregationcoef';
1652 }
1653 return $this->coefstring;
1654 }
1655
1c307f21 1656 /**
b3ac6c3e 1657 * Returns tree with all grade_items and categories as elements
b79fe189 1658 *
1659 * @param int $courseid The course ID
a153c9f2 1660 * @param bool $include_category_items as category children
b3ac6c3e 1661 * @return array
1c307f21 1662 */
da3801e8 1663 public static function fetch_course_tree($courseid, $include_category_items=false) {
f3ac8eb4 1664 $course_category = grade_category::fetch_course_category($courseid);
514a3467 1665 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
1666 'children'=>$course_category->get_children($include_category_items));
b146d984
AD
1667
1668 $course_category->sortorder = $course_category->get_sortorder();
e2bb3c92
PS
1669 $sortorder = $course_category->get_sortorder();
1670 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 1671 }
1672
b79fe189 1673 /**
a153c9f2 1674 * An internal function that recursively sorts grade categories within a course
b79fe189 1675 *
1676 * @param array $category_array The seed of the recursion
a153c9f2
AD
1677 * @param int $sortorder The current sortorder
1678 * @return array An array containing 'object', 'type', 'depth' and optionally 'children'
b79fe189 1679 */
1680 static private function _fetch_course_tree_recursion($category_array, &$sortorder) {
b3ac6c3e 1681 // update the sortorder in db if needed
b146d984
AD
1682 //NOTE: This leads to us resetting sort orders every time the categories and items page is viewed :(
1683 //if ($category_array['object']->sortorder != $sortorder) {
1684 //$category_array['object']->set_sortorder($sortorder);
1685 //}
ce385eb4 1686
7bac3777
AD
1687 if (isset($category_array['object']->gradetype) && $category_array['object']->gradetype==GRADE_TYPE_NONE) {
1688 return null;
1689 }
1690
314c4336 1691 // store the grade_item or grade_category instance with extra info
1692 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 1693
1694 // reuse final grades if there
1695 if (array_key_exists('finalgrades', $category_array)) {
1696 $result['finalgrades'] = $category_array['finalgrades'];
1697 }
1698
1699 // recursively resort children
1700 if (!empty($category_array['children'])) {
1701 $result['children'] = array();
29d509f5 1702 //process the category item first
7bac3777 1703 $child = null;
b79fe189 1704
1705 foreach ($category_array['children'] as $oldorder=>$child_array) {
1706
314c4336 1707 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
7bac3777
AD
1708 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1709 if (!empty($child)) {
1710 $result['children'][$sortorder] = $child;
1711 }
29d509f5 1712 }
2b0f65e2 1713 }
b79fe189 1714
1715 foreach ($category_array['children'] as $oldorder=>$child_array) {
1716
29d509f5 1717 if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
7bac3777
AD
1718 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1719 if (!empty($child)) {
1720 $result['children'][++$sortorder] = $child;
1721 }
b3ac6c3e 1722 }
1723 }
1724 }
1725
1726 return $result;
ce385eb4 1727 }
7c8a963f 1728
1729 /**
4a490db0 1730 * Fetches and returns all the children categories and/or grade_items belonging to this category.
1731 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 1732 * as well as all levels (0). The elements are indexed by sort order.
b79fe189 1733 *
1734 * @param bool $include_category_items Whether or not to include category grade_items in the children array
7c8a963f 1735 * @return array Array of child objects (grade_category and grade_item).
1736 */
da3801e8 1737 public function get_children($include_category_items=false) {
1738 global $DB;
b3ac6c3e 1739
1740 // This function must be as fast as possible ;-)
1741 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
1742 // we have to limit the number of queries though, because it will be used often in grade reports
1743
da3801e8 1744 $cats = $DB->get_records('grade_categories', array('courseid' => $this->courseid));
1745 $items = $DB->get_records('grade_items', array('courseid' => $this->courseid));
4a490db0 1746
b3ac6c3e 1747 // init children array first
1748 foreach ($cats as $catid=>$cat) {
1749 $cats[$catid]->children = array();
27f95e9b 1750 }
4a490db0 1751
b3ac6c3e 1752 //first attach items to cats and add category sortorder
1753 foreach ($items as $item) {
b79fe189 1754
b3ac6c3e 1755 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
1756 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 1757
b3ac6c3e 1758 if (!$include_category_items) {
1759 continue;
1760 }
1761 $categoryid = $item->iteminstance;
b79fe189 1762
b3ac6c3e 1763 } else {
1764 $categoryid = $item->categoryid;
63354ab5
AD
1765 if (empty($categoryid)) {
1766 debugging('Found a grade item that isnt in a category');
1767 }
b3ac6c3e 1768 }
1769
1770 // prevent problems with duplicate sortorders in db
1771 $sortorder = $item->sortorder;
b79fe189 1772
63354ab5
AD
1773 while (array_key_exists($categoryid, $cats)
1774 && array_key_exists($sortorder, $cats[$categoryid]->children)) {
1775
b3ac6c3e 1776 $sortorder++;
1777 }
1778
1779 $cats[$categoryid]->children[$sortorder] = $item;
1780
1781 }
1782
1783 // now find the requested category and connect categories as children
1784 $category = false;
b79fe189 1785
b3ac6c3e 1786 foreach ($cats as $catid=>$cat) {
b79fe189 1787
ec3717e1 1788 if (empty($cat->parent)) {
b79fe189 1789
ec3717e1 1790 if ($cat->path !== '/'.$cat->id.'/') {
1791 $grade_category = new grade_category($cat, false);
1792 $grade_category->path = '/'.$cat->id.'/';
1793 $grade_category->depth = 1;
1794 $grade_category->update('system');
1795 return $this->get_children($include_category_items);
1796 }
b79fe189 1797
ec3717e1 1798 } else {
b79fe189 1799
ec3717e1 1800 if (empty($cat->path) or !preg_match('|/'.$cat->parent.'/'.$cat->id.'/$|', $cat->path)) {
1801 //fix paths and depts
1802 static $recursioncounter = 0; // prevents infinite recursion
1803 $recursioncounter++;
b79fe189 1804
da3801e8 1805 if ($recursioncounter < 5) {
ec3717e1 1806 // fix paths and depths!
1807 $grade_category = new grade_category($cat, false);
1808 $grade_category->depth = 0;
1809 $grade_category->path = null;
1810 $grade_category->update('system');
1811 return $this->get_children($include_category_items);
1812 }
da3801e8 1813 }
b3ac6c3e 1814 // prevent problems with duplicate sortorders in db
1815 $sortorder = $cat->sortorder;
b79fe189 1816
1817 while (array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 1818 //debugging("$sortorder exists in cat loop");
b3ac6c3e 1819 $sortorder++;
1820 }
1821
65370356 1822 $cats[$cat->parent]->children[$sortorder] = &$cats[$catid];
b3ac6c3e 1823 }
f3ac8eb4 1824
b3ac6c3e 1825 if ($catid == $this->id) {
1826 $category = &$cats[$catid];
1827 }
1828 }
1829
1830 unset($items); // not needed
1831 unset($cats); // not needed
1832
f3ac8eb4 1833 $children_array = grade_category::_get_children_recursion($category);
b3ac6c3e 1834
1835 ksort($children_array);
1836
1837 return $children_array;
1838
1839 }
1840
b79fe189 1841 /**
1842 * Private method used to retrieve all children of this category recursively
1843 *
1844 * @param grade_category $category Source of current recursion
a153c9f2 1845 * @return array An array of child grade categories
b79fe189 1846 */
22a9b6d8 1847 private static function _get_children_recursion($category) {
b3ac6c3e 1848
1849 $children_array = array();
b79fe189 1850 foreach ($category->children as $sortorder=>$child) {
1851
b3ac6c3e 1852 if (array_key_exists('itemtype', $child)) {
f3ac8eb4 1853 $grade_item = new grade_item($child, false);
b79fe189 1854
4faf5f99 1855 if (in_array($grade_item->itemtype, array('course', 'category'))) {
1856 $type = $grade_item->itemtype.'item';
1857 $depth = $category->depth;
b79fe189 1858
314c4336 1859 } else {
1860 $type = 'item';
1861 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 1862 }
4faf5f99 1863 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 1864
7c8a963f 1865 } else {
f3ac8eb4 1866 $children = grade_category::_get_children_recursion($child);
1867 $grade_category = new grade_category($child, false);
b79fe189 1868
b3ac6c3e 1869 if (empty($children)) {
314c4336 1870 $children = array();
7c8a963f 1871 }
4faf5f99 1872 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
314c4336 1873 }
27f95e9b 1874 }
1875
b3ac6c3e 1876 // sort the array
1877 ksort($children_array);
1878
27f95e9b 1879 return $children_array;
1880 }
4a490db0 1881
f151b073 1882 /**
a4d76049 1883 * Uses {@link get_grade_item()} to load or create a grade_item, then saves it as $this->grade_item.
a153c9f2
AD
1884 *
1885 * @return grade_item
f151b073 1886 */
da3801e8 1887 public function load_grade_item() {
ac9b0805 1888 if (empty($this->grade_item)) {
1889 $this->grade_item = $this->get_grade_item();
1890 }
ab53054f 1891 return $this->grade_item;
1892 }
4a490db0 1893
ab53054f 1894 /**
a153c9f2
AD
1895 * Retrieves this grade categories' associated grade_item from the database
1896 *
1897 * If no grade_item exists yet, creates one.
1898 *
1899 * @return grade_item
ab53054f 1900 */
da3801e8 1901 public function get_grade_item() {
c91ed4be 1902 if (empty($this->id)) {
1903 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
1904 return false;
1905 }
1906
b3ac6c3e 1907 if (empty($this->parent)) {
1908 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
1909
1910 } else {
1911 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
1912 }
4ac209d5 1913
f3ac8eb4 1914 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 1915 // create a new one
f3ac8eb4 1916 $grade_item = new grade_item($params, false);
b8ff92b6 1917 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 1918 $grade_item->insert('system');
4a490db0 1919
b79fe189 1920 } else if (count($grade_items) == 1) {
b8ff92b6 1921 // found existing one
1922 $grade_item = reset($grade_items);
4a490db0 1923
b8ff92b6 1924 } else {
1925 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 1926 // return first one
1927 $grade_item = reset($grade_items);
2c72af1f 1928 }
1929
ab53054f 1930 return $grade_item;
f151b073 1931 }
8c846243 1932
1933 /**
a153c9f2
AD
1934 * Uses $this->parent to instantiate $this->parent_category based on the referenced record in the DB
1935 *
1936 * @return grade_category The parent category
8c846243 1937 */
da3801e8 1938 public function load_parent_category() {
8c846243 1939 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 1940 $this->parent_category = $this->get_parent_category();
8c846243 1941 }
1942 return $this->parent_category;
4a490db0 1943 }
1944
ab53054f 1945 /**
a153c9f2
AD
1946 * Uses $this->parent to instantiate and return a grade_category object
1947 *
1948 * @return grade_category Returns the parent category or null if this category has no parent
ab53054f 1949 */
da3801e8 1950 public function get_parent_category() {
ab53054f 1951 if (!empty($this->parent)) {
f3ac8eb4 1952 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 1953 return $parent_category;
ab53054f 1954 } else {
1955 return null;
1956 }
1957 }
1958
2186f72c 1959 /**
a153c9f2 1960 * Returns the most descriptive field for this grade category
b79fe189 1961 *
2186f72c 1962 * @return string name
1963 */
da3801e8 1964 public function get_name() {
1965 global $DB;
8f6fdf43 1966 // For a course category, we return the course name if the fullname is set to '?' in the DB (empty in the category edit form)
1967 if (empty($this->parent) && $this->fullname == '?') {
da3801e8 1968 $course = $DB->get_record('course', array('id'=> $this->courseid));
410753fb 1969 return format_string($course->fullname);
b79fe189 1970
314c4336 1971 } else {
1972 return $this->fullname;
1973 }
2186f72c 1974 }
c91ed4be 1975
65c2ac93
DW
1976 /**
1977 * Describe the aggregation settings for this category so the reports make more sense.
1978 *
1979 * @return string description
1980 */
1981 public function get_description() {
1982 $allhelp = array();
1983 $aggrstrings = grade_helper::get_aggregation_strings();
1984 $allhelp[] = $aggrstrings[$this->aggregation];
1985
ded8ea8f 1986 if ($this->droplow && $this->can_apply_limit_rules()) {
65c2ac93
DW
1987 $allhelp[] = get_string('droplowestvalues', 'grades', $this->droplow);
1988 }
ded8ea8f 1989 if ($this->keephigh && $this->can_apply_limit_rules()) {
65c2ac93
DW
1990 $allhelp[] = get_string('keephighestvalues', 'grades', $this->keephigh);
1991 }
1992 if (!$this->aggregateonlygraded) {
1993 $allhelp[] = get_string('aggregatenotonlygraded', 'grades');
1994 }
1995 if ($this->aggregatesubcats) {
1996 $allhelp[] = get_string('aggregatesubcatsshort', 'grades');
1997 }
1998 return implode('. ', $allhelp) . '.';
1999 }
2000
0fc7f624 2001 /**
a153c9f2 2002 * Sets this category's parent id
b79fe189 2003 *
a153c9f2
AD
2004 * @param int $parentid The ID of the category that is the new parent to $this
2005 * @param string $source From where was the object updated (mod/forum, manual, etc.)
2006 * @return bool success
0fc7f624 2007 */
da3801e8 2008 public function set_parent($parentid, $source=null) {
f13002d5 2009 if ($this->parent == $parentid) {
2010 return true;
2011 }
2012
2013 if ($parentid == $this->id) {
2f137aa1 2014 print_error('cannotassignselfasparent');
f13002d5 2015 }
2016
2017 if (empty($this->parent) and $this->is_course_category()) {
2f137aa1 2018 print_error('cannothaveparentcate');
b3ac6c3e 2019 }
f13002d5 2020
2021 // find parent and check course id
f3ac8eb4 2022 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 2023 return false;
2024 }
2025
f8e6e4db 2026 $this->force_regrading();
b3ac6c3e 2027
2028 // set new parent category
f8e6e4db 2029 $this->parent = $parent_category->id;
2030 $this->parent_category =& $parent_category;
b3ac6c3e 2031 $this->path = null; // remove old path and depth - will be recalculated in update()
ec3717e1 2032 $this->depth = 0; // remove old path and depth - will be recalculated in update()
f8e6e4db 2033 $this->update($source);
b3ac6c3e 2034
15b462da 2035 return $this->update($source);
b3ac6c3e 2036 }
2037
2038 /**
a153c9f2 2039 * Returns the final grade values for this grade category.
b79fe189 2040 *
a153c9f2 2041 * @param int $userid Optional user ID to retrieve a single user's final grade
b3ac6c3e 2042 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
2043 */
b79fe189 2044 public function get_final($userid=null) {
b3ac6c3e 2045 $this->load_grade_item();
2046 return $this->grade_item->get_final($userid);
0fc7f624 2047 }
4a490db0 2048
0fc7f624 2049 /**
a153c9f2
AD
2050 * Returns the sortorder of the grade categories' associated grade_item
2051 *
2052 * This method is also available in grade_item for cases where the object type is not known.
b79fe189 2053 *
0fc7f624 2054 * @return int Sort order
2055 */
da3801e8 2056 public function get_sortorder() {
b3ac6c3e 2057 $this->load_grade_item();
2058 return $this->grade_item->get_sortorder();
0fc7f624 2059 }
2060
be7c0693 2061 /**
a153c9f2
AD
2062 * Returns the idnumber of the grade categories' associated grade_item.
2063 *
2064 * This method is also available in grade_item for cases where the object type is not known.
b79fe189 2065 *
be7c0693 2066 * @return string idnumber
2067 */
da3801e8 2068 public function get_idnumber() {
be7c0693 2069 $this->load_grade_item();
2070 return $this->grade_item->get_idnumber();
2071 }
2072
0fc7f624 2073 /**
a153c9f2
AD
2074 * Sets the sortorder variable for this category.
2075 *
4a490db0 2076 * This method is also available in grade_item, for cases where the object type is not know.
b79fe189 2077 *
2078 * @param int $sortorder The sortorder to assign to this category
0fc7f624 2079 */
da3801e8 2080 public function set_sortorder($sortorder) {
b3ac6c3e 2081 $this->load_grade_item();
2082 $this->grade_item->set_sortorder($sortorder);
2083 }
2084
6639ead3 2085 /**
a153c9f2 2086 * Move this category after the given sortorder
b79fe189 2087 *
a153c9f2 2088 * Does not change the parent
b79fe189 2089 *
a153c9f2 2090 * @param int $sortorder to place after.
b79fe189 2091 * @return void
6639ead3 2092 */
da3801e8 2093 public function move_after_sortorder($sortorder) {
f13002d5 2094 $this->load_grade_item();
2095 $this->grade_item->move_after_sortorder($sortorder);
2096 }
2097
b3ac6c3e 2098 /**
f13002d5 2099 * Return true if this is the top most category that represents the total course grade.
b79fe189 2100 *
a153c9f2 2101 * @return bool
b3ac6c3e 2102 */
da3801e8 2103 public function is_course_category() {
b3ac6c3e 2104 $this->load_grade_item();
2105 return $this->grade_item->is_course_item();
2106 }
2107
2108 /**
a153c9f2 2109 * Return the course level grade_category object
b79fe189 2110 *
2111 * @param int $courseid The Course ID
a153c9f2 2112 * @return grade_category Returns the course level grade_category instance
b3ac6c3e 2113 */
22a9b6d8 2114 public static function fetch_course_category($courseid) {
a4503119 2115 if (empty($courseid)) {
2116 debugging('Missing course id!');
2117 return false;
2118 }
b3ac6c3e 2119
2120 // course category has no parent
f3ac8eb4 2121 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
b3ac6c3e 2122 return $course_category;
2123 }
2124
2125 // create a new one
f3ac8eb4 2126 $course_category = new grade_category();
b3ac6c3e 2127 $course_category->insert_course_category($courseid);
2128
2129 return $course_category;
0fc7f624 2130 }
4ac209d5 2131
79eabc2a 2132 /**
2133 * Is grading object editable?
b79fe189 2134 *
a153c9f2 2135 * @return bool
79eabc2a 2136 */
da3801e8 2137 public function is_editable() {
79eabc2a 2138 return true;
2139 }
2140
5fad5061 2141 /**
a153c9f2
AD
2142 * Returns the locked state/date of the grade categories' associated grade_item.
2143 *
2144 * This method is also available in grade_item, for cases where the object type is not known.
2145 *
2146 * @return bool
5fad5061 2147 */
da3801e8 2148 public function is_locked() {
5fad5061 2149 $this->load_grade_item();
22e23c78 2150 return $this->grade_item->is_locked();
5fad5061 2151 }
2152
2153 /**
2154 * Sets the grade_item's locked variable and updates the grade_item.
a153c9f2
AD
2155 *
2156 * Calls set_locked() on the categories' grade_item
b79fe189 2157 *
2158 * @param int $lockedstate 0, 1 or a timestamp int(10) after which date the item will be locked.
2159 * @param bool $cascade lock/unlock child objects too
2160 * @param bool $refresh refresh grades when unlocking
a153c9f2 2161 * @return bool success if category locked (not all children mayb be locked though)
5fad5061 2162 */
da3801e8 2163 public function set_locked($lockedstate, $cascade=false, $refresh=true) {
5fad5061 2164 $this->load_grade_item();
2b0f65e2 2165
fb0e3570 2166 $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
2167
2168 if ($cascade) {
2169 //process all children - items and categories
f3ac8eb4 2170 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
b79fe189 2171
2172 foreach ($children as $child) {
fb0e3570 2173 $child->set_locked($lockedstate, true, false);
b79fe189 2174
fb0e3570 2175 if (empty($lockedstate) and $refresh) {
2176 //refresh when unlocking
2177 $child->refresh_grades();
2178 }
2b0f65e2 2179 }
7a7a53d3 2180 }
b79fe189 2181
f3ac8eb4 2182 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 2183
2184 foreach ($children as $child) {
fb0e3570 2185 $child->set_locked($lockedstate, true, true);
2186 }
7a7a53d3 2187 }
2188 }
2b0f65e2 2189
b121b544 2190 return $result;
5fad5061 2191 }
4a490db0 2192
a153c9f2
AD
2193 /**
2194 * Overrides grade_object::set_properties() to add special handling for changes to category aggregation types
2195 *
2196 * @param stdClass $instance the object to set the properties on
2197 * @param array|stdClass $params Either an associative array or an object containing property name, property value pairs
2198 */
79b260cc
AD
2199 public static function set_properties(&$instance, $params) {
2200 global $DB;
2201
2202 parent::set_properties($instance, $params);
2203
c1024411 2204 //if they've changed aggregation type we made need to do some fiddling to provide appropriate defaults
79b260cc
AD
2205 if (!empty($params->aggregation)) {
2206
2207 //weight and extra credit share a column :( Would like a default of 1 for weight and 0 for extra credit
2208 //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 2209 if (self::aggregation_uses_aggregationcoef($params->aggregation)) {
79b260cc 2210 $sql = $defaultaggregationcoef = null;
7ad5a627 2211
134c514b 2212 if (!self::aggregation_uses_extracredit($params->aggregation)) {
79b260cc
AD
2213 //if all items in this category have aggregation coefficient of 0 we can change it to 1 ie evenly weighted
2214 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=0";
2215 $defaultaggregationcoef = 1;
134c514b 2216 } else {
79b260cc
AD
2217 //if all items in this category have aggregation coefficient of 1 we can change it to 0 ie no extra credit
2218 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=1";
2219 $defaultaggregationcoef = 0;
2220 }
2221
2222 $params = array('categoryid'=>$instance->id);
2223 $count = $DB->count_records_sql($sql, $params);
2224 if ($count===0) { //category is either empty or all items are set to a default value so we can switch defaults
2225 $params['aggregationcoef'] = $defaultaggregationcoef;
2226 $DB->execute("update {grade_items} set aggregationcoef=:aggregationcoef where categoryid=:categoryid",$params);
2227 }
2228 }
2229 }
2230 }
2231
5fad5061 2232 /**
4a490db0 2233 * Sets the grade_item's hidden variable and updates the grade_item.
a153c9f2
AD
2234 *
2235 * Overrides grade_item::set_hidden() to add cascading of the hidden value to grade items in this grade category
2236 *
2237 * @param int $hidden 0 mean always visible, 1 means always hidden and a number > 1 is a timestamp to hide until
2238 * @param bool $cascade apply to child objects too
5fad5061 2239 */
da3801e8 2240 public function set_hidden($hidden, $cascade=false) {
5fad5061 2241 $this->load_grade_item();
a25bb902 2242 //this hides the associated grade item (the course total)
1762a264 2243 $this->grade_item->set_hidden($hidden, $cascade);
a25bb902
AD
2244 //this hides the category itself and everything it contains
2245 parent::set_hidden($hidden, $cascade);
b79fe189 2246
f60c61b1 2247 if ($cascade) {
b79fe189 2248
f3ac8eb4 2249 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
b79fe189 2250
2251 foreach ($children as $child) {
39873128
TH
2252 if ($child->can_control_visibility()) {
2253 $child->set_hidden($hidden, $cascade);
2254 }
f60c61b1 2255 }
f13002d5 2256 }
b79fe189 2257
f3ac8eb4 2258 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 2259
2260 foreach ($children as $child) {
f60c61b1 2261 $child->set_hidden($hidden, $cascade);
2262 }
f13002d5 2263 }
2264 }
d90aa634
AD
2265
2266 //if marking category visible make sure parent category is visible MDL-21367
93fad868 2267 if( !$hidden ) {
d90aa634
AD
2268 $category_array = grade_category::fetch_all(array('id'=>$this->parent));
2269 if ($category_array && array_key_exists($this->parent, $category_array)) {
2270 $category = $category_array[$this->parent];
93fad868
SH
2271 //call set_hidden on the category regardless of whether it is hidden as its parent might be hidden
2272 //if($category->is_hidden()) {
2273 $category->set_hidden($hidden, false);
2274 //}
d90aa634
AD
2275 }
2276 }
5fad5061 2277 }
89a5f827 2278
190af29f 2279 /**
2280 * Applies default settings on this category
a153c9f2
AD
2281 *
2282 * @return bool True if anything changed
190af29f 2283 */
da3801e8 2284 public function apply_default_settings() {
190af29f 2285 global $CFG;
2286
2287 foreach ($this->forceable as $property) {
b79fe189 2288
190af29f 2289 if (isset($CFG->{"grade_$property"})) {
b79fe189 2290
190af29f 2291 if ($CFG->{"grade_$property"} == -1) {
2292 continue; //temporary bc before version bump
2293 }
2294 $this->$property = $CFG->{"grade_$property"};
2295 }
2296 }
2297 }
2298
89a5f827 2299 /**
2300 * Applies forced settings on this category
a153c9f2
AD
2301 *
2302 * @return bool True if anything changed
89a5f827 2303 */
da3801e8 2304 public function apply_forced_settings() {
89a5f827 2305 global $CFG;
2306
2307 $updated = false;
b79fe189 2308
89a5f827 2309 foreach ($this->forceable as $property) {
b79fe189 2310
2311 if (isset($CFG->{"grade_$property"}) and isset($CFG->{"grade_{$property}_flag"}) and
2312 ((int) $CFG->{"grade_{$property}_flag"} & 1)) {
2313
190af29f 2314 if ($CFG->{"grade_$property"} == -1) {
2315 continue; //temporary bc before version bump
2316 }
89a5f827 2317 $this->$property = $CFG->{"grade_$property"};
2318 $updated = true;
2319 }
2320 }
2321
2322 return $updated;
2323 }
2324
2325 /**
2326 * Notification of change in forced category settings.
b79fe189 2327 *
a153c9f2 2328 * Causes all course and category grade items to be marked as needing to be updated
89a5f827 2329 */
da3801e8 2330 public static function updated_forced_settings() {
5b0af8c5 2331 global $CFG, $DB;
2332 $params = array(1, 'course', 'category');
2333 $sql = "UPDATE {grade_items} SET needsupdate=? WHERE itemtype=? or itemtype=?";
2334 $DB->execute($sql, $params);
89a5f827 2335 }
4a490db0 2336}