MDL-47064 core_grades: fix the calculation of contribution towards total
[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() {
432 $this->auto_update_max();
433 $this->auto_update_weights();
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) {
e171963b 567 global $CFG;
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();
572 $usedweights = array();
573
b8ff92b6 574 if (empty($userid)) {
f8e6e4db 575 //ignore first call
b8ff92b6 576 return;
577 }
4a490db0 578
f8e6e4db 579 if ($oldgrade) {
66690b69 580 $oldfinalgrade = $oldgrade->finalgrade;
f3ac8eb4 581 $grade = new grade_grade($oldgrade, false);
f8e6e4db 582 $grade->grade_item =& $this->grade_item;
b8ff92b6 583
f8e6e4db 584 } else {
585 // insert final grade - it will be needed later anyway
f3ac8eb4 586 $grade = new grade_grade(array('itemid'=>$this->grade_item->id, 'userid'=>$userid), false);
f8e6e4db 587 $grade->grade_item =& $this->grade_item;
f1ad9e04 588 $grade->insert('system');
589 $oldfinalgrade = null;
f8e6e4db 590 }
f1ad9e04 591
c86caae7 592 // no need to recalculate locked or overridden grades
593 if ($grade->is_locked() or $grade->is_overridden()) {
2cc4b0f9 594 return;
ac9b0805 595 }
596
f8e6e4db 597 // can not use own final category grade in calculation
9580a21f 598 unset($grade_values[$this->grade_item->id]);
f8e6e4db 599
0758a08e 600 // if no grades calculation possible or grading not allowed clear final grade
9580a21f 601 if (empty($grade_values) or empty($items) or ($this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE)) {
f8e6e4db 602 $grade->finalgrade = null;
b79fe189 603
66690b69 604 if (!is_null($oldfinalgrade)) {
0758a08e 605 $grade->update('aggregation');
f8e6e4db 606 }
bfe969e8
DW
607 $dropped = $grade_values;
608 $this->set_usedinaggregation($userid, $usedweights, $novalue, $dropped);
b8ff92b6 609 return;
610 }
0758a08e 611
0e999796
AD
612 $minvisible = (bool) get_config('moodle', 'grade_report_showmin');
613
b79fe189 614 // normalize the grades first - all will have value 0...1
d5f0aa01 615 // ungraded items are not used in aggregation
825fba1c
FM
616 foreach ($grade_values as $itemid=>$v) {
617 // Natural weighting currently cannot exclude empty grades, or grades from excluded items.
618 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
aa705529
JO
619 if (is_null($v)) {
620 // null means no grade
621 unset($grade_values[$itemid]);
622 $novalue[$itemid] = 0;
623 continue;
aa705529
JO
624 } else if (in_array($itemid, $excluded)) {
625 unset($grade_values[$itemid]);
626 $dropped[$itemid] = 0;
627 continue;
628 }
0e999796 629 }
5a59aeb1
DW
630 // Check for user specific grade min/max overrides.
631 $usergrademin = $items[$itemid]->grademin;
632 $usergrademax = $items[$itemid]->grademax;
633 if (isset($grademinoverrides[$itemid])) {
634 $usergrademin = $grademinoverrides[$itemid];
635 }
636 if (isset($grademaxoverrides[$itemid])) {
637 $usergrademax = $grademaxoverrides[$itemid];
638 }
639 $grade_values[$itemid] = grade_grade::standardise_score($v, $usergrademin, $usergrademax, 0, 1);
0aa32279 640 }
eacd3700 641 // use min grade if grade missing for these types
c2efb501 642 if (!$this->aggregateonlygraded) {
b79fe189 643
644 foreach ($items as $itemid=>$value) {
645
c2efb501 646 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
647 $grade_values[$itemid] = 0;
eacd3700 648 }
c2efb501 649 }
eacd3700 650 }
651
652 // limit and sort
bfe969e8 653 $allvalues = $grade_values;
4272386a
FM
654 if ($this->can_apply_limit_rules()) {
655 $this->apply_limit_rules($grade_values, $items);
656 }
bfe969e8
DW
657
658 $moredropped = array_diff($allvalues, $grade_values);
659 foreach ($moredropped as $drop => $unused) {
660 $dropped[$drop] = 0;
661 }
9580a21f 662 asort($grade_values, SORT_NUMERIC);
4a490db0 663
d5f0aa01 664 // let's see we have still enough grades to do any statistics
9580a21f 665 if (count($grade_values) == 0) {
ac9b0805 666 // not enough attempts yet
f8e6e4db 667 $grade->finalgrade = null;
b79fe189 668
66690b69 669 if (!is_null($oldfinalgrade)) {
0758a08e 670 $grade->update('aggregation');
b8ff92b6 671 }
bfe969e8 672 $this->set_usedinaggregation($userid, $usedweights, $novalue, $dropped);
b8ff92b6 673 return;
674 }
2df71235 675
d297269d 676 // do the maths
5a59aeb1
DW
677 $result = $this->aggregate_values_and_adjust_bounds($grade_values,
678 $items,
679 $usedweights,
680 $grademinoverrides,
681 $grademaxoverrides);
5232d3f2 682 $agg_grade = $result['grade'];
d297269d 683
825fba1c
FM
684 // Recalculate the grade back to requested range.
685 $finalgrade = grade_grade::standardise_score($agg_grade, 0, 1, $result['grademin'], $result['grademax']);
d297269d 686
653a8648 687 $grade->finalgrade = $this->grade_item->bounded_grade($finalgrade);
90cc8ce7 688 $oldrawgrademax = $grade->rawgrademax;
5a59aeb1 689 $grade->rawgrademax = $result['grademax'];
d297269d 690
691 // update in db if changed
90cc8ce7
DW
692 if (grade_floats_different($grade->finalgrade, $oldfinalgrade) ||
693 grade_floats_different($grade->rawgrademax, $oldrawgrademax)) {
0758a08e 694 $grade->update('aggregation');
d297269d 695 }
696
bfe969e8
DW
697 $this->set_usedinaggregation($userid, $usedweights, $novalue, $dropped);
698
d297269d 699 return;
700 }
701
bfe969e8
DW
702 /**
703 * Set the flags on the grade_grade items to indicate how individual grades are used
704 * in the aggregation.
705 *
706 * @param int $userid The user we have aggregated the grades for.
707 * @param array $usedweights An array with keys for each of the grade_item columns included in the aggregation. The value are the relative weight.
708 * @param array $novalue An array with keys for each of the grade_item columns skipped because
709 * they had no value in the aggregation
710 * @param array $dropped An array with keys for each of the grade_item columns dropped
711 * because of any drop lowest/highest settings in the aggregation
712 */
713 private function set_usedinaggregation($userid, $usedweights, $novalue, $dropped) {
714 global $DB;
715
716 // Included.
717 if (!empty($usedweights)) {
718 // The usedweights items are updated individually to record the weights.
719 foreach ($usedweights as $gradeitemid => $contribution) {
bfe969e8 720 $DB->set_field_select('grade_grades',
a1740d7b 721 'aggregationweight',
bfe969e8
DW
722 $contribution,
723 "itemid = :itemid AND userid = :userid",
724 array('itemid'=>$gradeitemid, 'userid'=>$userid));
725 }
a1740d7b
DW
726
727 // Now set the status flag for all these weights.
728 list($itemsql, $itemlist) = $DB->get_in_or_equal(array_keys($usedweights), SQL_PARAMS_NAMED, 'g');
729 $itemlist['userid'] = $userid;
730
731 $DB->set_field_select('grade_grades',
732 'aggregationstatus',
733 'used',
734 "itemid $itemsql AND userid = :userid",
735 $itemlist);
bfe969e8
DW
736 }
737
738 // No value.
739 if (!empty($novalue)) {
740 list($itemsql, $itemlist) = $DB->get_in_or_equal(array_keys($novalue), SQL_PARAMS_NAMED, 'g');
741
742 $itemlist['userid'] = $userid;
743
744 $DB->set_field_select('grade_grades',
a1740d7b 745 'aggregationstatus',
bfe969e8
DW
746 'novalue',
747 "itemid $itemsql AND userid = :userid",
748 $itemlist);
749 }
750
751 // Dropped.
752 if (!empty($dropped)) {
753 list($itemsql, $itemlist) = $DB->get_in_or_equal(array_keys($dropped), SQL_PARAMS_NAMED, 'g');
754
755 $itemlist['userid'] = $userid;
756
757 $DB->set_field_select('grade_grades',
a1740d7b 758 'aggregationstatus',
bfe969e8
DW
759 'dropped',
760 "itemid $itemsql AND userid = :userid",
761 $itemlist);
762 }
763 }
764
89a5f827 765 /**
5232d3f2 766 * Internal function that calculates the aggregated grade and new min/max for this grade category
b79fe189 767 *
a153c9f2 768 * Must be public as it is used by grade_grade::get_hiding_affected()
b79fe189 769 *
a153c9f2
AD
770 * @param array $grade_values An array of values to be aggregated
771 * @param array $items The array of grade_items
d6caf637 772 * @since Moodle 2.6.5, 2.7.2
bfe969e8
DW
773 * @param array & $weights If provided, will be filled with the normalized weights
774 * for each grade_item as used in the aggregation.
5a59aeb1
DW
775 * @param array $grademinoverrides User specific grademin values if different to the grade_item grademin (key is itemid)
776 * @param array $grademaxoverrides User specific grademax values if different to the grade_item grademax (key is itemid)
5232d3f2
DW
777 * @return array containing values for:
778 * 'grade' => the new calculated grade
779 * 'grademin' => the new calculated min grade for the category
780 * 'grademax' => the new calculated max grade for the category
89a5f827 781 */
5a59aeb1
DW
782 public function aggregate_values_and_adjust_bounds($grade_values,
783 $items,
784 & $weights = null,
785 $grademinoverrides = array(),
786 $grademaxoverrides = array()) {
5232d3f2
DW
787 $category_item = $this->get_grade_item();
788 $grademin = $category_item->grademin;
789 $grademax = $category_item->grademax;
790
b8ff92b6 791 switch ($this->aggregation) {
b79fe189 792
c2efb501 793 case GRADE_AGGREGATE_MEDIAN: // Middle point value in the set: ignores frequencies
9580a21f 794 $num = count($grade_values);
c186c7b2 795 $grades = array_values($grade_values);
b79fe189 796
c186c7b2 797 if ($num % 2 == 0) {
9c8d38fa 798 $agg_grade = ($grades[intval($num/2)-1] + $grades[intval($num/2)]) / 2;
b79fe189 799
b8ff92b6 800 } else {
9c8d38fa 801 $agg_grade = $grades[intval(($num/2)-0.5)];
b8ff92b6 802 }
bfe969e8
DW
803
804 // Record the weights evenly.
805 if ($weights !== null && $num > 0) {
806 foreach ($grade_values as $itemid=>$grade_value) {
807 $weights[$itemid] = 1.0 / $num;
808 }
809 }
b8ff92b6 810 break;
ac9b0805 811
c2efb501 812 case GRADE_AGGREGATE_MIN:
9c8d38fa 813 $agg_grade = reset($grade_values);
bfe969e8
DW
814 // Record the weights as used.
815 if ($weights !== null) {
816 foreach ($grade_values as $itemid=>$grade_value) {
817 $weights[$itemid] = 0;
818 }
819 }
820 // Set the first item to 1.
821 $itemids = array_keys($grade_values);
822 $weights[reset($itemids)] = 1;
b8ff92b6 823 break;
824
c2efb501 825 case GRADE_AGGREGATE_MAX:
bfe969e8
DW
826 // Record the weights as used.
827 if ($weights !== null) {
828 foreach ($grade_values as $itemid=>$grade_value) {
829 $weights[$itemid] = 0;
830 }
831 }
832 // Set the last item to 1.
833 $itemids = array_keys($grade_values);
834 $weights[end($itemids)] = 1;
835 $agg_grade = end($grade_values);
b8ff92b6 836 break;
837
bfe969e8 838 case GRADE_AGGREGATE_MODE: // the most common value
0198929c 839 // array_count_values only counts INT and STRING, so if grades are floats we must convert them to string
840 $converted_grade_values = array();
841
842 foreach ($grade_values as $k => $gv) {
b79fe189 843
0198929c 844 if (!is_int($gv) && !is_string($gv)) {
845 $converted_grade_values[$k] = (string) $gv;
b79fe189 846
0198929c 847 } else {
848 $converted_grade_values[$k] = $gv;
849 }
bfe969e8
DW
850 if ($weights !== null) {
851 $weights[$k] = 0;
852 }
0198929c 853 }
854
855 $freq = array_count_values($converted_grade_values);
95affb8a 856 arsort($freq); // sort by frequency keeping keys
857 $top = reset($freq); // highest frequency count
858 $modes = array_keys($freq, $top); // search for all modes (have the same highest count)
f7d515b6 859 rsort($modes, SORT_NUMERIC); // get highest mode
9c8d38fa 860 $agg_grade = reset($modes);
bfe969e8
DW
861 // Record the weights as used.
862 if ($weights !== null && $top > 0) {
863 foreach ($grade_values as $k => $gv) {
864 if ($gv == $agg_grade) {
865 $weights[$k] = 1.0 / $top;
866 }
867 }
868 }
d5fab31f 869 break;
95affb8a 870
1426edac 871 case GRADE_AGGREGATE_WEIGHTED_MEAN: // Weighted average of all existing final grades, weight specified in coef
9580a21f 872 $weightsum = 0;
873 $sum = 0;
b79fe189 874
875 foreach ($grade_values as $itemid=>$grade_value) {
876
eacd3700 877 if ($items[$itemid]->aggregationcoef <= 0) {
9580a21f 878 continue;
879 }
eacd3700 880 $weightsum += $items[$itemid]->aggregationcoef;
881 $sum += $items[$itemid]->aggregationcoef * $grade_value;
bfe969e8
DW
882 if ($weights !== null) {
883 $weights[$itemid] = $items[$itemid]->aggregationcoef;
884 }
9580a21f 885 }
886 if ($weightsum == 0) {
9c8d38fa 887 $agg_grade = null;
b79fe189 888
9580a21f 889 } else {
9c8d38fa 890 $agg_grade = $sum / $weightsum;
bfe969e8
DW
891 if ($weights !== null) {
892 // Normalise the weights.
893 foreach ($weights as $itemid => $weight) {
894 $weights[$itemid] = $weight / $weightsum;
895 }
896 }
897
9580a21f 898 }
899 break;
900
d9ae2ab5 901 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
902 // Weighted average of all existing final grades with optional extra credit flag,
f7d515b6 903 // weight is the range of grade (usually grademax)
1426edac 904 $weightsum = 0;
d9ae2ab5 905 $sum = null;
b79fe189 906
907 foreach ($grade_values as $itemid=>$grade_value) {
1426edac 908 $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
b79fe189 909
1426edac 910 if ($weight <= 0) {
911 continue;
912 }
b79fe189 913
d9ae2ab5 914 if ($items[$itemid]->aggregationcoef == 0) {
915 $weightsum += $weight;
916 }
917 $sum += $weight * $grade_value;
1426edac 918 }
919 if ($weightsum == 0) {
d9ae2ab5 920 $agg_grade = $sum; // only extra credits
b79fe189 921
1426edac 922 } else {
923 $agg_grade = $sum / $weightsum;
924 }
bfe969e8
DW
925 // Record the weights as used.
926 if ($weights !== null) {
927 foreach ($grade_values as $itemid=>$grade_value) {
928 if ($items[$itemid]->aggregationcoef == 0 && $weightsum > 0) {
929 $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
930 $weights[$itemid] = ($items[$itemid]->grademax - $items[$itemid]->grademin) / $weightsum;
931 } else {
932 $weights[$itemid] = 0;
933 }
934 }
935 }
1426edac 936 break;
937
c2efb501 938 case GRADE_AGGREGATE_EXTRACREDIT_MEAN: // special average
9580a21f 939 $num = 0;
d9ae2ab5 940 $sum = null;
b79fe189 941
942 foreach ($grade_values as $itemid=>$grade_value) {
943
eacd3700 944 if ($items[$itemid]->aggregationcoef == 0) {
9580a21f 945 $num += 1;
946 $sum += $grade_value;
bfe969e8
DW
947 if ($weights !== null) {
948 $weights[$itemid] = 1;
949 }
b79fe189 950
eacd3700 951 } else if ($items[$itemid]->aggregationcoef > 0) {
952 $sum += $items[$itemid]->aggregationcoef * $grade_value;
bfe969e8
DW
953 if ($weights !== null) {
954 $weights[$itemid] = 0;
955 }
956 }
957 }
958 if ($weights !== null && $num > 0) {
959 foreach ($grade_values as $itemid=>$grade_value) {
960 if ($weights[$itemid]) {
961 $weights[$itemid] = 1.0 / $num;
962 }
9580a21f 963 }
964 }
b79fe189 965
9580a21f 966 if ($num == 0) {
9c8d38fa 967 $agg_grade = $sum; // only extra credits or wrong coefs
b79fe189 968
9580a21f 969 } else {
9c8d38fa 970 $agg_grade = $sum / $num;
9580a21f 971 }
972 break;
973
5232d3f2
DW
974 case GRADE_AGGREGATE_SUM: // Add up all the items.
975 $num = count($grade_values);
d57ea599 976 $sum = 0;
a2c13f68 977 $sumweights = 0;
a2c13f68
DW
978 $grademin = 0;
979 $grademax = 0;
980 foreach ($grade_values as $itemid => $gradevalue) {
5a59aeb1 981 // We need to check if the grademax/min was adjusted per user because of excluded items.
057063b1 982 $usergrademin = $items[$itemid]->grademin;
5a59aeb1
DW
983 $usergrademax = $items[$itemid]->grademax;
984 if (isset($grademinoverrides[$itemid])) {
985 $usergrademin = $grademinoverrides[$itemid];
986 }
987 if (isset($grademaxoverrides[$itemid])) {
988 $usergrademax = $grademaxoverrides[$itemid];
989 }
057063b1 990 $gradeitemrange = $usergrademax - $usergrademin;
a2c13f68
DW
991
992 // Extra credit.
1577229f 993 if (!($items[$itemid]->aggregationcoef > 0)) {
a2c13f68
DW
994 $grademax += $gradeitemrange;
995 $sumweights += $items[$itemid]->aggregationcoef2;
aa705529
JO
996 }
997 }
057063b1
DW
998 $userweights = array();
999 $totaloverriddenweight = 0;
1000 $totaloverriddengrademax = 0;
1001 // We first need to rescale all manually assigned weights down by the
1002 // percentage of weights missing from the category.
1003 foreach ($grade_values as $itemid => $gradevalue) {
1004 if ($items[$itemid]->weightoverride) {
1005 $userweights[$itemid] = $items[$itemid]->aggregationcoef2 / $sumweights;
1006 $totaloverriddenweight += $userweights[$itemid];
1007 $usergrademax = $items[$itemid]->grademax;
1008 if (isset($grademaxoverrides[$itemid])) {
1009 $usergrademax = $grademaxoverrides[$itemid];
1010 }
1011 $totaloverriddengrademax += $usergrademax;
1012 }
1013 }
1014 $nonoverriddenpoints = $grademax - $totaloverriddengrademax;
1015
1016 // Then we need to recalculate the automatic weights.
1017 foreach ($grade_values as $itemid => $gradevalue) {
1018 if (!$items[$itemid]->weightoverride) {
1019 if ($nonoverriddenpoints > 0) {
1020 $usergrademax = $items[$itemid]->grademax;
1021 if (isset($grademaxoverrides[$itemid])) {
1022 $usergrademax = $grademaxoverrides[$itemid];
1023 }
1024 $userweights[$itemid] = ($usergrademax/$nonoverriddenpoints) * (1 - $totaloverriddenweight);
1025 } else {
1026 $userweights[$itemid] = 0;
1027 }
1028 }
a2c13f68 1029 }
057063b1
DW
1030
1031 // We can use our freshly corrected weights below.
a2c13f68 1032 foreach ($grade_values as $itemid => $gradevalue) {
057063b1 1033 $sum += $gradevalue * $userweights[$itemid] * $grademax;
a2c13f68 1034 if ($weights !== null) {
057063b1 1035 $weights[$itemid] = $userweights[$itemid];
a2c13f68
DW
1036 }
1037 }
1038 if ($grademax > 0) {
1039 $agg_grade = $sum / $grademax; // Re-normalize score.
1040 } else {
1041 // Every item in the category is extra credit.
1042 $agg_grade = $sum;
1043 $grademax = $sum;
1044 }
b50b12b3 1045
5232d3f2
DW
1046 break;
1047
c2efb501 1048 case GRADE_AGGREGATE_MEAN: // Arithmetic average of all grade items (if ungraded aggregated, NULL counted as minimum)
ac9b0805 1049 default:
9580a21f 1050 $num = count($grade_values);
1051 $sum = array_sum($grade_values);
9c8d38fa 1052 $agg_grade = $sum / $num;
bfe969e8
DW
1053 // Record the weights evenly.
1054 if ($weights !== null && $num > 0) {
1055 foreach ($grade_values as $itemid=>$grade_value) {
1056 $weights[$itemid] = 1.0 / $num;
1057 }
1058 }
b8ff92b6 1059 break;
1060 }
1061
5232d3f2
DW
1062 return array('grade' => $agg_grade, 'grademin' => $grademin, 'grademax' => $grademax);
1063 }
1064
1065 /**
1066 * Internal function that calculates the aggregated grade for this grade category
1067 *
1068 * Must be public as it is used by grade_grade::get_hiding_affected()
1069 *
1070 * @deprecated since Moodle 2.8
1071 * @param array $grade_values An array of values to be aggregated
1072 * @param array $items The array of grade_items
1073 * @return float The aggregate grade for this grade category
1074 */
1075 public function aggregate_values($grade_values, $items) {
1076 debugging('grade_category::aggregate_values() is deprecated.
1077 Call grade_category::aggregate_values_and_adjust_bounds() instead.', DEBUG_DEVELOPER);
1078 $result = $this->aggregate_values_and_adjust_bounds($grade_values, $items);
1079 return $result['grade'];
0aa32279 1080 }
0758a08e 1081
3a03653e 1082 /**
fcf6e015 1083 * Some aggregation types may need to update their max grade.
a153c9f2 1084 *
fcf6e015 1085 * @return void
3a03653e 1086 */
fcf6e015
FM
1087 private function auto_update_max() {
1088 global $DB;
3a03653e 1089 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
1090 // not needed at all
1091 return;
1092 }
1093
fcf6e015
FM
1094 // Find grade items of immediate children (category or grade items) and force site settings.
1095 $this->load_grade_item();
1096 $depends_on = $this->grade_item->depends_on();
1097
1098 $items = false;
1099 if (!empty($depends_on)) {
1100 list($usql, $params) = $DB->get_in_or_equal($depends_on);
1101 $sql = "SELECT *
1102 FROM {grade_items}
1103 WHERE id $usql";
1104 $items = $DB->get_records_sql($sql, $params);
1105 }
1106
3a03653e 1107 if (!$items) {
b79fe189 1108
3a03653e 1109 if ($this->grade_item->grademax != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
1110 $this->grade_item->grademax = 0;
1111 $this->grade_item->grademin = 0;
1112 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
1113 $this->grade_item->update('aggregation');
1114 }
1115 return;
1116 }
1117
d57ea599 1118 //find max grade possible
59080eee 1119 $maxes = array();
b79fe189 1120
3a03653e 1121 foreach ($items as $item) {
b79fe189 1122
d57ea599
JO
1123 if ($item->aggregationcoef > 0) {
1124 // extra credit from this activity - does not affect total
1125 continue;
3a03653e 1126 }
11eca362 1127
d57ea599
JO
1128 if ($item->gradetype == GRADE_TYPE_VALUE) {
1129 $maxes[$item->id] = $item->grademax;
1130
1131 } else if ($item->gradetype == GRADE_TYPE_SCALE) {
1132 $maxes[$item->id] = $item->grademax; // 0 = nograde, 1 = first scale item, 2 = second scale item
1133 }
1134 }
4272386a
FM
1135
1136 if ($this->can_apply_limit_rules()) {
1137 // Apply droplow and keephigh.
1138 $this->apply_limit_rules($maxes, $items);
1139 }
59080eee 1140 $max = array_sum($maxes);
3a03653e 1141
59080eee 1142 // update db if anything changed
1143 if ($this->grade_item->grademax != $max or $this->grade_item->grademin != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
3a03653e 1144 $this->grade_item->grademax = $max;
1145 $this->grade_item->grademin = 0;
1146 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
1147 $this->grade_item->update('aggregation');
1148 }
1149 }
1150
a2f1f65d
AD
1151 /**
1152 * Recalculate the weights of the grade items in this category.
fcf6e015
FM
1153 *
1154 * @return void
a2f1f65d
AD
1155 */
1156 private function auto_update_weights() {
1157 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
1158 // This is only required if we are using natural weights.
1159 return;
1160 }
1161 $children = $this->get_children();
1162
1163 $grade_item = null;
1164
1165 // Calculate the sum of the grademax's of all the items within this category.
1166 $totalgrademax = 0;
45da5361
AD
1167
1168 // Out of 1, how much weight has been manually overriden by a user?
1169 $totaloverriddenweight = 0;
1170 $totaloverriddengrademax = 0;
a2f1f65d
AD
1171 foreach ($children as $sortorder => $child) {
1172 $grade_item = null;
1173
1174 if ($child['type'] == 'item') {
1175 $grade_item = $child['object'];
1176 } else if ($child['type'] == 'category') {
1177 $grade_item = $child['object']->load_grade_item();
1178 }
45da5361 1179
b14c5870
AD
1180 // An extra credit grade item doesn't contribute to $totaloverriddengrademax.
1181 if ($grade_item->aggregationcoef > 0) {
1182 continue;
1183 }
1184
a2f1f65d 1185 $totalgrademax += $grade_item->grademax;
45da5361
AD
1186 if ($grade_item->weightoverride) {
1187 $totaloverriddenweight += $grade_item->aggregationcoef2;
1188 $totaloverriddengrademax += $grade_item->grademax;
1189 }
a2f1f65d
AD
1190 }
1191
45da5361
AD
1192 $totalgrademax -= $totaloverriddengrademax;
1193
a2f1f65d
AD
1194 reset($children);
1195 foreach ($children as $sortorder => $child) {
1196 $grade_item = null;
1197
1198 if ($child['type'] == 'item') {
1199 $grade_item = $child['object'];
1200 } else if ($child['type'] == 'category') {
1201 $grade_item = $child['object']->load_grade_item();
1202 }
45da5361
AD
1203 if (!$grade_item->weightoverride) {
1204 // Calculate this item's weight as a percentage of the non-overridden total grade maxes
1205 // then convert it to a proportion of the available non-overriden weight.
1206 $grade_item->aggregationcoef2 = ($grade_item->grademax/$totalgrademax) * (1 - $totaloverriddenweight);
1207 $grade_item->update();
1208 }
a2f1f65d
AD
1209 }
1210 }
1211
adc2f286 1212 /**
a153c9f2 1213 * Given an array of grade values (numerical indices) applies droplow or keephigh rules to limit the final array.
b79fe189 1214 *
a153c9f2 1215 * @param array $grade_values itemid=>$grade_value float
b79fe189 1216 * @param array $items grade item objects
adc2f286 1217 * @return array Limited grades.
1218 */
a9e38ac8 1219 public function apply_limit_rules(&$grade_values, $items) {
1220 $extraused = $this->is_extracredit_used();
1221
adc2f286 1222 if (!empty($this->droplow)) {
a9e38ac8 1223 asort($grade_values, SORT_NUMERIC);
1224 $dropped = 0;
b79fe189 1225
fb80cb2a
AD
1226 // If we have fewer grade items available to drop than $this->droplow, use this flag to escape the loop
1227 // May occur because of "extra credit" or if droplow is higher than the number of grade items
1228 $droppedsomething = true;
b79fe189 1229
fb80cb2a
AD
1230 while ($dropped < $this->droplow && $droppedsomething) {
1231 $droppedsomething = false;
b79fe189 1232
fb80cb2a 1233 $grade_keys = array_keys($grade_values);
aee968da
AD
1234 $gradekeycount = count($grade_keys);
1235
1236 if ($gradekeycount === 0) {
fb80cb2a
AD
1237 //We've dropped all grade items
1238 break;
1239 }
b79fe189 1240
fb80cb2a
AD
1241 $originalindex = $founditemid = $foundmax = null;
1242
1243 // Find the first remaining grade item that is available to be dropped
1244 foreach ($grade_keys as $gradekeyindex=>$gradekey) {
1245 if (!$extraused || $items[$gradekey]->aggregationcoef <= 0) {
1246 // Found a non-extra credit grade item that is eligible to be dropped
1247 $originalindex = $gradekeyindex;
1248 $founditemid = $grade_keys[$originalindex];
1249 $foundmax = $items[$founditemid]->grademax;
1250 break;
a9e38ac8 1251 }
fb80cb2a 1252 }
b79fe189 1253
fb80cb2a
AD
1254 if (empty($founditemid)) {
1255 // No grade items available to drop
a9e38ac8 1256 break;
59080eee 1257 }
fb80cb2a
AD
1258
1259 // Now iterate over the remaining grade items
1260 // We're looking for other grade items with the same grade value but a higher grademax
1261 $i = 1;
aee968da 1262 while ($originalindex + $i < $gradekeycount) {
52929486 1263
fb80cb2a 1264 $possibleitemid = $grade_keys[$originalindex+$i];
52929486
AD
1265 $i++;
1266
fb80cb2a
AD
1267 if ($grade_values[$founditemid] != $grade_values[$possibleitemid]) {
1268 // The next grade item has a different grade value. Stop looking.
1269 break;
1270 }
1271
1272 if ($extraused && $items[$possibleitemid]->aggregationcoef > 0) {
1273 // Don't drop extra credit grade items. Continue the search.
1274 continue;
1275 }
1276
1277 if ($foundmax < $items[$possibleitemid]->grademax) {
1278 // Found a grade item with the same grade value and a higher grademax
1279 $foundmax = $items[$possibleitemid]->grademax;
1280 $founditemid = $possibleitemid;
1281 // Continue searching to see if there is an even higher grademax
1282 }
fb80cb2a
AD
1283 }
1284
1285 // Now drop whatever grade item we have found
1286 unset($grade_values[$founditemid]);
1287 $dropped++;
1288 $droppedsomething = true;
adc2f286 1289 }
a9e38ac8 1290
1291 } else if (!empty($this->keephigh)) {
1292 arsort($grade_values, SORT_NUMERIC);
1293 $kept = 0;
b79fe189 1294
a9e38ac8 1295 foreach ($grade_values as $itemid=>$value) {
b79fe189 1296
a9e38ac8 1297 if ($extraused and $items[$itemid]->aggregationcoef > 0) {
1298 // we keep all extra credits
b79fe189 1299
a9e38ac8 1300 } else if ($kept < $this->keephigh) {
1301 $kept++;
b79fe189 1302
a9e38ac8 1303 } else {
1304 unset($grade_values[$itemid]);
1305 }
adc2f286 1306 }
1307 }
0aa32279 1308 }
1309
4272386a
FM
1310 /**
1311 * Returns whether or not we can apply the limit rules.
1312 *
1313 * There are cases where drop lowest or keep highest should not be used
1314 * at all. This method will determine whether or not this logic can be
1315 * applied considering the current setup of the category.
1316 *
1317 * @return bool
1318 */
1319 public function can_apply_limit_rules() {
1320 if ($this->canapplylimitrules !== null) {
1321 return $this->canapplylimitrules;
1322 }
1323
1324 // Set it to be supported by default.
1325 $this->canapplylimitrules = true;
1326
1327 // Natural aggregation.
1328 if ($this->aggregation == GRADE_AGGREGATE_SUM) {
1329 $canapply = true;
1330
1331 // Check until one child breaks the rules.
1332 $gradeitems = $this->get_children();
1333 $validitems = 0;
1334 $lastweight = null;
1335 $lastmaxgrade = null;
1336 foreach ($gradeitems as $gradeitem) {
1337 $gi = $gradeitem['object'];
1338
1339 if ($gradeitem['type'] == 'category') {
1340 // Sub categories are not allowed because they can have dynamic weights/maxgrades.
1341 $canapply = false;
1342 break;
1343 }
1344
1345 if ($gi->aggregationcoef > 0) {
1346 // Extra credit items are not allowed.
1347 $canapply = false;
1348 break;
1349 }
1350
1351 if ($lastweight !== null && $lastweight != $gi->aggregationcoef2) {
1352 // One of the weight differs from another item.
1353 $canapply = false;
1354 break;
1355 }
1356
1357 if ($lastmaxgrade !== null && $lastmaxgrade != $gi->grademax) {
1358 // One of the max grade differ from another item. This is not allowed for now
1359 // because we could be end up with different max grade between users for this category.
1360 $canapply = false;
1361 break;
1362 }
1363
1364 $lastweight = $gi->aggregationcoef2;
1365 $lastmaxgrade = $gi->grademax;
1366 }
1367
1368 $this->canapplylimitrules = $canapply;
1369 }
1370
1371 return $this->canapplylimitrules;
1372 }
1373
793253ae 1374 /**
1375 * Returns true if category uses extra credit of any kind
b79fe189 1376 *
a153c9f2 1377 * @return bool True if extra credit used
793253ae 1378 */
134c514b
RT
1379 public function is_extracredit_used() {
1380 return self::aggregation_uses_extracredit($this->aggregation);
1381 }
1382
1383 /**
1384 * Returns true if aggregation passed is using extracredit.
1385 *
1386 * @param int $aggregation Aggregation const.
1387 * @return bool True if extra credit used
1388 */
1389 public static function aggregation_uses_extracredit($aggregation) {
1390 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1391 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1392 or $aggregation == GRADE_AGGREGATE_SUM);
793253ae 1393 }
1394
9580a21f 1395 /**
f7d515b6 1396 * Returns true if category uses special aggregation coefficient
b79fe189 1397 *
a153c9f2 1398 * @return bool True if an aggregation coefficient is being used
9580a21f 1399 */
4e9ca991 1400 public function is_aggregationcoef_used() {
134c514b
RT
1401 return self::aggregation_uses_aggregationcoef($this->aggregation);
1402
1403 }
1404
1405 /**
1406 * Returns true if aggregation uses aggregationcoef
1407 *
1408 * @param int $aggregation Aggregation const.
1409 * @return bool True if an aggregation coefficient is being used
1410 */
1411 public static function aggregation_uses_aggregationcoef($aggregation) {
1412 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN
1413 or $aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1414 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1415 or $aggregation == GRADE_AGGREGATE_SUM);
ba74762b 1416
9580a21f 1417 }
1418
653a8648 1419 /**
a153c9f2 1420 * Recursive function to find which weight/extra credit field to use in the grade item form.
b79fe189 1421 *
a153c9f2 1422 * Inherits from a parent category if that category has aggregatesubcats set to true.
b79fe189 1423 *
a153c9f2 1424 * @param string $first Whether or not this is the first item in the recursion
b79fe189 1425 * @return string
653a8648 1426 */
1427 public function get_coefstring($first=true) {
1428 if (!is_null($this->coefstring)) {
1429 return $this->coefstring;
1430 }
1431
1432 $overriding_coefstring = null;
1433
1434 // Stop recursing upwards if this category aggregates subcats or has no parent
1435 if (!$first && !$this->aggregatesubcats) {
b79fe189 1436
121d8006 1437 if ($parent_category = $this->load_parent_category()) {
653a8648 1438 return $parent_category->get_coefstring(false);
b79fe189 1439
653a8648 1440 } else {
1441 return null;
1442 }
b79fe189 1443
1444 } else if ($first) {
1445
653a8648 1446 if (!$this->aggregatesubcats) {
b79fe189 1447
121d8006 1448 if ($parent_category = $this->load_parent_category()) {
653a8648 1449 $overriding_coefstring = $parent_category->get_coefstring(false);
1450 }
1451 }
1452 }
1453
1454 // If an overriding coefstring has trickled down from one of the parent categories, return it. Otherwise, return self.
1455 if (!is_null($overriding_coefstring)) {
1456 return $overriding_coefstring;
1457 }
1458
1459 // No parent category is overriding this category's aggregation, return its string
1460 if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
1461 $this->coefstring = 'aggregationcoefweight';
b79fe189 1462
d9ae2ab5 1463 } else if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2) {
1464 $this->coefstring = 'aggregationcoefextrasum';
b79fe189 1465
653a8648 1466 } else if ($this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
3869ab1a 1467 $this->coefstring = 'aggregationcoefextraweight';
b79fe189 1468
653a8648 1469 } else if ($this->aggregation == GRADE_AGGREGATE_SUM) {
b6a1e366 1470 $this->coefstring = 'aggregationcoefextraweightsum';
b79fe189 1471
653a8648 1472 } else {
1473 $this->coefstring = 'aggregationcoef';
1474 }
1475 return $this->coefstring;
1476 }
1477
1c307f21 1478 /**
b3ac6c3e 1479 * Returns tree with all grade_items and categories as elements
b79fe189 1480 *
1481 * @param int $courseid The course ID
a153c9f2 1482 * @param bool $include_category_items as category children
b3ac6c3e 1483 * @return array
1c307f21 1484 */
da3801e8 1485 public static function fetch_course_tree($courseid, $include_category_items=false) {
f3ac8eb4 1486 $course_category = grade_category::fetch_course_category($courseid);
514a3467 1487 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
1488 'children'=>$course_category->get_children($include_category_items));
b146d984
AD
1489
1490 $course_category->sortorder = $course_category->get_sortorder();
e2bb3c92
PS
1491 $sortorder = $course_category->get_sortorder();
1492 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 1493 }
1494
b79fe189 1495 /**
a153c9f2 1496 * An internal function that recursively sorts grade categories within a course
b79fe189 1497 *
1498 * @param array $category_array The seed of the recursion
a153c9f2
AD
1499 * @param int $sortorder The current sortorder
1500 * @return array An array containing 'object', 'type', 'depth' and optionally 'children'
b79fe189 1501 */
1502 static private function _fetch_course_tree_recursion($category_array, &$sortorder) {
b3ac6c3e 1503 // update the sortorder in db if needed
b146d984
AD
1504 //NOTE: This leads to us resetting sort orders every time the categories and items page is viewed :(
1505 //if ($category_array['object']->sortorder != $sortorder) {
1506 //$category_array['object']->set_sortorder($sortorder);
1507 //}
ce385eb4 1508
7bac3777
AD
1509 if (isset($category_array['object']->gradetype) && $category_array['object']->gradetype==GRADE_TYPE_NONE) {
1510 return null;
1511 }
1512
314c4336 1513 // store the grade_item or grade_category instance with extra info
1514 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 1515
1516 // reuse final grades if there
1517 if (array_key_exists('finalgrades', $category_array)) {
1518 $result['finalgrades'] = $category_array['finalgrades'];
1519 }
1520
1521 // recursively resort children
1522 if (!empty($category_array['children'])) {
1523 $result['children'] = array();
29d509f5 1524 //process the category item first
7bac3777 1525 $child = null;
b79fe189 1526
1527 foreach ($category_array['children'] as $oldorder=>$child_array) {
1528
314c4336 1529 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
7bac3777
AD
1530 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1531 if (!empty($child)) {
1532 $result['children'][$sortorder] = $child;
1533 }
29d509f5 1534 }
2b0f65e2 1535 }
b79fe189 1536
1537 foreach ($category_array['children'] as $oldorder=>$child_array) {
1538
29d509f5 1539 if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
7bac3777
AD
1540 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1541 if (!empty($child)) {
1542 $result['children'][++$sortorder] = $child;
1543 }
b3ac6c3e 1544 }
1545 }
1546 }
1547
1548 return $result;
ce385eb4 1549 }
7c8a963f 1550
1551 /**
4a490db0 1552 * Fetches and returns all the children categories and/or grade_items belonging to this category.
1553 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 1554 * as well as all levels (0). The elements are indexed by sort order.
b79fe189 1555 *
1556 * @param bool $include_category_items Whether or not to include category grade_items in the children array
7c8a963f 1557 * @return array Array of child objects (grade_category and grade_item).
1558 */
da3801e8 1559 public function get_children($include_category_items=false) {
1560 global $DB;
b3ac6c3e 1561
1562 // This function must be as fast as possible ;-)
1563 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
1564 // we have to limit the number of queries though, because it will be used often in grade reports
1565
da3801e8 1566 $cats = $DB->get_records('grade_categories', array('courseid' => $this->courseid));
1567 $items = $DB->get_records('grade_items', array('courseid' => $this->courseid));
4a490db0 1568
b3ac6c3e 1569 // init children array first
1570 foreach ($cats as $catid=>$cat) {
1571 $cats[$catid]->children = array();
27f95e9b 1572 }
4a490db0 1573
b3ac6c3e 1574 //first attach items to cats and add category sortorder
1575 foreach ($items as $item) {
b79fe189 1576
b3ac6c3e 1577 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
1578 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 1579
b3ac6c3e 1580 if (!$include_category_items) {
1581 continue;
1582 }
1583 $categoryid = $item->iteminstance;
b79fe189 1584
b3ac6c3e 1585 } else {
1586 $categoryid = $item->categoryid;
63354ab5
AD
1587 if (empty($categoryid)) {
1588 debugging('Found a grade item that isnt in a category');
1589 }
b3ac6c3e 1590 }
1591
1592 // prevent problems with duplicate sortorders in db
1593 $sortorder = $item->sortorder;
b79fe189 1594
63354ab5
AD
1595 while (array_key_exists($categoryid, $cats)
1596 && array_key_exists($sortorder, $cats[$categoryid]->children)) {
1597
b3ac6c3e 1598 $sortorder++;
1599 }
1600
1601 $cats[$categoryid]->children[$sortorder] = $item;
1602
1603 }
1604
1605 // now find the requested category and connect categories as children
1606 $category = false;
b79fe189 1607
b3ac6c3e 1608 foreach ($cats as $catid=>$cat) {
b79fe189 1609
ec3717e1 1610 if (empty($cat->parent)) {
b79fe189 1611
ec3717e1 1612 if ($cat->path !== '/'.$cat->id.'/') {
1613 $grade_category = new grade_category($cat, false);
1614 $grade_category->path = '/'.$cat->id.'/';
1615 $grade_category->depth = 1;
1616 $grade_category->update('system');
1617 return $this->get_children($include_category_items);
1618 }
b79fe189 1619
ec3717e1 1620 } else {
b79fe189 1621
ec3717e1 1622 if (empty($cat->path) or !preg_match('|/'.$cat->parent.'/'.$cat->id.'/$|', $cat->path)) {
1623 //fix paths and depts
1624 static $recursioncounter = 0; // prevents infinite recursion
1625 $recursioncounter++;
b79fe189 1626
da3801e8 1627 if ($recursioncounter < 5) {
ec3717e1 1628 // fix paths and depths!
1629 $grade_category = new grade_category($cat, false);
1630 $grade_category->depth = 0;
1631 $grade_category->path = null;
1632 $grade_category->update('system');
1633 return $this->get_children($include_category_items);
1634 }
da3801e8 1635 }
b3ac6c3e 1636 // prevent problems with duplicate sortorders in db
1637 $sortorder = $cat->sortorder;
b79fe189 1638
1639 while (array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 1640 //debugging("$sortorder exists in cat loop");
b3ac6c3e 1641 $sortorder++;
1642 }
1643
65370356 1644 $cats[$cat->parent]->children[$sortorder] = &$cats[$catid];
b3ac6c3e 1645 }
f3ac8eb4 1646
b3ac6c3e 1647 if ($catid == $this->id) {
1648 $category = &$cats[$catid];
1649 }
1650 }
1651
1652 unset($items); // not needed
1653 unset($cats); // not needed
1654
f3ac8eb4 1655 $children_array = grade_category::_get_children_recursion($category);
b3ac6c3e 1656
1657 ksort($children_array);
1658
1659 return $children_array;
1660
1661 }
1662
b79fe189 1663 /**
1664 * Private method used to retrieve all children of this category recursively
1665 *
1666 * @param grade_category $category Source of current recursion
a153c9f2 1667 * @return array An array of child grade categories
b79fe189 1668 */
22a9b6d8 1669 private static function _get_children_recursion($category) {
b3ac6c3e 1670
1671 $children_array = array();
b79fe189 1672 foreach ($category->children as $sortorder=>$child) {
1673
b3ac6c3e 1674 if (array_key_exists('itemtype', $child)) {
f3ac8eb4 1675 $grade_item = new grade_item($child, false);
b79fe189 1676
4faf5f99 1677 if (in_array($grade_item->itemtype, array('course', 'category'))) {
1678 $type = $grade_item->itemtype.'item';
1679 $depth = $category->depth;
b79fe189 1680
314c4336 1681 } else {
1682 $type = 'item';
1683 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 1684 }
4faf5f99 1685 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 1686
7c8a963f 1687 } else {
f3ac8eb4 1688 $children = grade_category::_get_children_recursion($child);
1689 $grade_category = new grade_category($child, false);
b79fe189 1690
b3ac6c3e 1691 if (empty($children)) {
314c4336 1692 $children = array();
7c8a963f 1693 }
4faf5f99 1694 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
314c4336 1695 }
27f95e9b 1696 }
1697
b3ac6c3e 1698 // sort the array
1699 ksort($children_array);
1700
27f95e9b 1701 return $children_array;
1702 }
4a490db0 1703
f151b073 1704 /**
a4d76049 1705 * Uses {@link get_grade_item()} to load or create a grade_item, then saves it as $this->grade_item.
a153c9f2
AD
1706 *
1707 * @return grade_item
f151b073 1708 */
da3801e8 1709 public function load_grade_item() {
ac9b0805 1710 if (empty($this->grade_item)) {
1711 $this->grade_item = $this->get_grade_item();
1712 }
ab53054f 1713 return $this->grade_item;
1714 }
4a490db0 1715
ab53054f 1716 /**
a153c9f2
AD
1717 * Retrieves this grade categories' associated grade_item from the database
1718 *
1719 * If no grade_item exists yet, creates one.
1720 *
1721 * @return grade_item
ab53054f 1722 */
da3801e8 1723 public function get_grade_item() {
c91ed4be 1724 if (empty($this->id)) {
1725 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
1726 return false;
1727 }
1728
b3ac6c3e 1729 if (empty($this->parent)) {
1730 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
1731
1732 } else {
1733 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
1734 }
4ac209d5 1735
f3ac8eb4 1736 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 1737 // create a new one
f3ac8eb4 1738 $grade_item = new grade_item($params, false);
b8ff92b6 1739 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 1740 $grade_item->insert('system');
4a490db0 1741
b79fe189 1742 } else if (count($grade_items) == 1) {
b8ff92b6 1743 // found existing one
1744 $grade_item = reset($grade_items);
4a490db0 1745
b8ff92b6 1746 } else {
1747 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 1748 // return first one
1749 $grade_item = reset($grade_items);
2c72af1f 1750 }
1751
ab53054f 1752 return $grade_item;
f151b073 1753 }
8c846243 1754
1755 /**
a153c9f2
AD
1756 * Uses $this->parent to instantiate $this->parent_category based on the referenced record in the DB
1757 *
1758 * @return grade_category The parent category
8c846243 1759 */
da3801e8 1760 public function load_parent_category() {
8c846243 1761 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 1762 $this->parent_category = $this->get_parent_category();
8c846243 1763 }
1764 return $this->parent_category;
4a490db0 1765 }
1766
ab53054f 1767 /**
a153c9f2
AD
1768 * Uses $this->parent to instantiate and return a grade_category object
1769 *
1770 * @return grade_category Returns the parent category or null if this category has no parent
ab53054f 1771 */
da3801e8 1772 public function get_parent_category() {
ab53054f 1773 if (!empty($this->parent)) {
f3ac8eb4 1774 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 1775 return $parent_category;
ab53054f 1776 } else {
1777 return null;
1778 }
1779 }
1780
2186f72c 1781 /**
a153c9f2 1782 * Returns the most descriptive field for this grade category
b79fe189 1783 *
2186f72c 1784 * @return string name
1785 */
da3801e8 1786 public function get_name() {
1787 global $DB;
8f6fdf43 1788 // For a course category, we return the course name if the fullname is set to '?' in the DB (empty in the category edit form)
1789 if (empty($this->parent) && $this->fullname == '?') {
da3801e8 1790 $course = $DB->get_record('course', array('id'=> $this->courseid));
410753fb 1791 return format_string($course->fullname);
b79fe189 1792
314c4336 1793 } else {
1794 return $this->fullname;
1795 }
2186f72c 1796 }
c91ed4be 1797
65c2ac93
DW
1798 /**
1799 * Describe the aggregation settings for this category so the reports make more sense.
1800 *
1801 * @return string description
1802 */
1803 public function get_description() {
1804 $allhelp = array();
1805 $aggrstrings = grade_helper::get_aggregation_strings();
1806 $allhelp[] = $aggrstrings[$this->aggregation];
1807
ded8ea8f 1808 if ($this->droplow && $this->can_apply_limit_rules()) {
65c2ac93
DW
1809 $allhelp[] = get_string('droplowestvalues', 'grades', $this->droplow);
1810 }
ded8ea8f 1811 if ($this->keephigh && $this->can_apply_limit_rules()) {
65c2ac93
DW
1812 $allhelp[] = get_string('keephighestvalues', 'grades', $this->keephigh);
1813 }
1814 if (!$this->aggregateonlygraded) {
1815 $allhelp[] = get_string('aggregatenotonlygraded', 'grades');
1816 }
1817 if ($this->aggregatesubcats) {
1818 $allhelp[] = get_string('aggregatesubcatsshort', 'grades');
1819 }
1820 return implode('. ', $allhelp) . '.';
1821 }
1822
0fc7f624 1823 /**
a153c9f2 1824 * Sets this category's parent id
b79fe189 1825 *
a153c9f2
AD
1826 * @param int $parentid The ID of the category that is the new parent to $this
1827 * @param string $source From where was the object updated (mod/forum, manual, etc.)
1828 * @return bool success
0fc7f624 1829 */
da3801e8 1830 public function set_parent($parentid, $source=null) {
f13002d5 1831 if ($this->parent == $parentid) {
1832 return true;
1833 }
1834
1835 if ($parentid == $this->id) {
2f137aa1 1836 print_error('cannotassignselfasparent');
f13002d5 1837 }
1838
1839 if (empty($this->parent) and $this->is_course_category()) {
2f137aa1 1840 print_error('cannothaveparentcate');
b3ac6c3e 1841 }
f13002d5 1842
1843 // find parent and check course id
f3ac8eb4 1844 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 1845 return false;
1846 }
1847
f8e6e4db 1848 $this->force_regrading();
b3ac6c3e 1849
1850 // set new parent category
f8e6e4db 1851 $this->parent = $parent_category->id;
1852 $this->parent_category =& $parent_category;
b3ac6c3e 1853 $this->path = null; // remove old path and depth - will be recalculated in update()
ec3717e1 1854 $this->depth = 0; // remove old path and depth - will be recalculated in update()
f8e6e4db 1855 $this->update($source);
b3ac6c3e 1856
15b462da 1857 return $this->update($source);
b3ac6c3e 1858 }
1859
1860 /**
a153c9f2 1861 * Returns the final grade values for this grade category.
b79fe189 1862 *
a153c9f2 1863 * @param int $userid Optional user ID to retrieve a single user's final grade
b3ac6c3e 1864 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
1865 */
b79fe189 1866 public function get_final($userid=null) {
b3ac6c3e 1867 $this->load_grade_item();
1868 return $this->grade_item->get_final($userid);
0fc7f624 1869 }
4a490db0 1870
0fc7f624 1871 /**
a153c9f2
AD
1872 * Returns the sortorder of the grade categories' associated grade_item
1873 *
1874 * This method is also available in grade_item for cases where the object type is not known.
b79fe189 1875 *
0fc7f624 1876 * @return int Sort order
1877 */
da3801e8 1878 public function get_sortorder() {
b3ac6c3e 1879 $this->load_grade_item();
1880 return $this->grade_item->get_sortorder();
0fc7f624 1881 }
1882
be7c0693 1883 /**
a153c9f2
AD
1884 * Returns the idnumber of the grade categories' associated grade_item.
1885 *
1886 * This method is also available in grade_item for cases where the object type is not known.
b79fe189 1887 *
be7c0693 1888 * @return string idnumber
1889 */
da3801e8 1890 public function get_idnumber() {
be7c0693 1891 $this->load_grade_item();
1892 return $this->grade_item->get_idnumber();
1893 }
1894
0fc7f624 1895 /**
a153c9f2
AD
1896 * Sets the sortorder variable for this category.
1897 *
4a490db0 1898 * This method is also available in grade_item, for cases where the object type is not know.
b79fe189 1899 *
1900 * @param int $sortorder The sortorder to assign to this category
0fc7f624 1901 */
da3801e8 1902 public function set_sortorder($sortorder) {
b3ac6c3e 1903 $this->load_grade_item();
1904 $this->grade_item->set_sortorder($sortorder);
1905 }
1906
6639ead3 1907 /**
a153c9f2 1908 * Move this category after the given sortorder
b79fe189 1909 *
a153c9f2 1910 * Does not change the parent
b79fe189 1911 *
a153c9f2 1912 * @param int $sortorder to place after.
b79fe189 1913 * @return void
6639ead3 1914 */
da3801e8 1915 public function move_after_sortorder($sortorder) {
f13002d5 1916 $this->load_grade_item();
1917 $this->grade_item->move_after_sortorder($sortorder);
1918 }
1919
b3ac6c3e 1920 /**
f13002d5 1921 * Return true if this is the top most category that represents the total course grade.
b79fe189 1922 *
a153c9f2 1923 * @return bool
b3ac6c3e 1924 */
da3801e8 1925 public function is_course_category() {
b3ac6c3e 1926 $this->load_grade_item();
1927 return $this->grade_item->is_course_item();
1928 }
1929
1930 /**
a153c9f2 1931 * Return the course level grade_category object
b79fe189 1932 *
1933 * @param int $courseid The Course ID
a153c9f2 1934 * @return grade_category Returns the course level grade_category instance
b3ac6c3e 1935 */
22a9b6d8 1936 public static function fetch_course_category($courseid) {
a4503119 1937 if (empty($courseid)) {
1938 debugging('Missing course id!');
1939 return false;
1940 }
b3ac6c3e 1941
1942 // course category has no parent
f3ac8eb4 1943 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
b3ac6c3e 1944 return $course_category;
1945 }
1946
1947 // create a new one
f3ac8eb4 1948 $course_category = new grade_category();
b3ac6c3e 1949 $course_category->insert_course_category($courseid);
1950
1951 return $course_category;
0fc7f624 1952 }
4ac209d5 1953
79eabc2a 1954 /**
1955 * Is grading object editable?
b79fe189 1956 *
a153c9f2 1957 * @return bool
79eabc2a 1958 */
da3801e8 1959 public function is_editable() {
79eabc2a 1960 return true;
1961 }
1962
5fad5061 1963 /**
a153c9f2
AD
1964 * Returns the locked state/date of the grade categories' associated grade_item.
1965 *
1966 * This method is also available in grade_item, for cases where the object type is not known.
1967 *
1968 * @return bool
5fad5061 1969 */
da3801e8 1970 public function is_locked() {
5fad5061 1971 $this->load_grade_item();
22e23c78 1972 return $this->grade_item->is_locked();
5fad5061 1973 }
1974
1975 /**
1976 * Sets the grade_item's locked variable and updates the grade_item.
a153c9f2
AD
1977 *
1978 * Calls set_locked() on the categories' grade_item
b79fe189 1979 *
1980 * @param int $lockedstate 0, 1 or a timestamp int(10) after which date the item will be locked.
1981 * @param bool $cascade lock/unlock child objects too
1982 * @param bool $refresh refresh grades when unlocking
a153c9f2 1983 * @return bool success if category locked (not all children mayb be locked though)
5fad5061 1984 */
da3801e8 1985 public function set_locked($lockedstate, $cascade=false, $refresh=true) {
5fad5061 1986 $this->load_grade_item();
2b0f65e2 1987
fb0e3570 1988 $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
1989
1990 if ($cascade) {
1991 //process all children - items and categories
f3ac8eb4 1992 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
b79fe189 1993
1994 foreach ($children as $child) {
fb0e3570 1995 $child->set_locked($lockedstate, true, false);
b79fe189 1996
fb0e3570 1997 if (empty($lockedstate) and $refresh) {
1998 //refresh when unlocking
1999 $child->refresh_grades();
2000 }
2b0f65e2 2001 }
7a7a53d3 2002 }
b79fe189 2003
f3ac8eb4 2004 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 2005
2006 foreach ($children as $child) {
fb0e3570 2007 $child->set_locked($lockedstate, true, true);
2008 }
7a7a53d3 2009 }
2010 }
2b0f65e2 2011
b121b544 2012 return $result;
5fad5061 2013 }
4a490db0 2014
a153c9f2
AD
2015 /**
2016 * Overrides grade_object::set_properties() to add special handling for changes to category aggregation types
2017 *
2018 * @param stdClass $instance the object to set the properties on
2019 * @param array|stdClass $params Either an associative array or an object containing property name, property value pairs
2020 */
79b260cc
AD
2021 public static function set_properties(&$instance, $params) {
2022 global $DB;
2023
2024 parent::set_properties($instance, $params);
2025
c1024411 2026 //if they've changed aggregation type we made need to do some fiddling to provide appropriate defaults
79b260cc
AD
2027 if (!empty($params->aggregation)) {
2028
2029 //weight and extra credit share a column :( Would like a default of 1 for weight and 0 for extra credit
2030 //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 2031 if (self::aggregation_uses_aggregationcoef($params->aggregation)) {
79b260cc 2032 $sql = $defaultaggregationcoef = null;
7ad5a627 2033
134c514b 2034 if (!self::aggregation_uses_extracredit($params->aggregation)) {
79b260cc
AD
2035 //if all items in this category have aggregation coefficient of 0 we can change it to 1 ie evenly weighted
2036 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=0";
2037 $defaultaggregationcoef = 1;
134c514b 2038 } else {
79b260cc
AD
2039 //if all items in this category have aggregation coefficient of 1 we can change it to 0 ie no extra credit
2040 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=1";
2041 $defaultaggregationcoef = 0;
2042 }
2043
2044 $params = array('categoryid'=>$instance->id);
2045 $count = $DB->count_records_sql($sql, $params);
2046 if ($count===0) { //category is either empty or all items are set to a default value so we can switch defaults
2047 $params['aggregationcoef'] = $defaultaggregationcoef;
2048 $DB->execute("update {grade_items} set aggregationcoef=:aggregationcoef where categoryid=:categoryid",$params);
2049 }
2050 }
2051 }
2052 }
2053
5fad5061 2054 /**
4a490db0 2055 * Sets the grade_item's hidden variable and updates the grade_item.
a153c9f2
AD
2056 *
2057 * Overrides grade_item::set_hidden() to add cascading of the hidden value to grade items in this grade category
2058 *
2059 * @param int $hidden 0 mean always visible, 1 means always hidden and a number > 1 is a timestamp to hide until
2060 * @param bool $cascade apply to child objects too
5fad5061 2061 */
da3801e8 2062 public function set_hidden($hidden, $cascade=false) {
5fad5061 2063 $this->load_grade_item();
a25bb902 2064 //this hides the associated grade item (the course total)
1762a264 2065 $this->grade_item->set_hidden($hidden, $cascade);
a25bb902
AD
2066 //this hides the category itself and everything it contains
2067 parent::set_hidden($hidden, $cascade);
b79fe189 2068
f60c61b1 2069 if ($cascade) {
b79fe189 2070
f3ac8eb4 2071 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
b79fe189 2072
2073 foreach ($children as $child) {
39873128
TH
2074 if ($child->can_control_visibility()) {
2075 $child->set_hidden($hidden, $cascade);
2076 }
f60c61b1 2077 }
f13002d5 2078 }
b79fe189 2079
f3ac8eb4 2080 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 2081
2082 foreach ($children as $child) {
f60c61b1 2083 $child->set_hidden($hidden, $cascade);
2084 }
f13002d5 2085 }
2086 }
d90aa634
AD
2087
2088 //if marking category visible make sure parent category is visible MDL-21367
2089 if( !$hidden ) {
2090 $category_array = grade_category::fetch_all(array('id'=>$this->parent));
2091 if ($category_array && array_key_exists($this->parent, $category_array)) {
2092 $category = $category_array[$this->parent];
2093 //call set_hidden on the category regardless of whether it is hidden as its parent might be hidden
2094 //if($category->is_hidden()) {
2095 $category->set_hidden($hidden, false);
2096 //}
2097 }
2098 }
5fad5061 2099 }
89a5f827 2100
190af29f 2101 /**
2102 * Applies default settings on this category
a153c9f2
AD
2103 *
2104 * @return bool True if anything changed
190af29f 2105 */
da3801e8 2106 public function apply_default_settings() {
190af29f 2107 global $CFG;
2108
2109 foreach ($this->forceable as $property) {
b79fe189 2110
190af29f 2111 if (isset($CFG->{"grade_$property"})) {
b79fe189 2112
190af29f 2113 if ($CFG->{"grade_$property"} == -1) {
2114 continue; //temporary bc before version bump
2115 }
2116 $this->$property = $CFG->{"grade_$property"};
2117 }
2118 }
2119 }
2120
89a5f827 2121 /**
2122 * Applies forced settings on this category
a153c9f2
AD
2123 *
2124 * @return bool True if anything changed
89a5f827 2125 */
da3801e8 2126 public function apply_forced_settings() {
89a5f827 2127 global $CFG;
2128
2129 $updated = false;
b79fe189 2130
89a5f827 2131 foreach ($this->forceable as $property) {
b79fe189 2132
2133 if (isset($CFG->{"grade_$property"}) and isset($CFG->{"grade_{$property}_flag"}) and
2134 ((int) $CFG->{"grade_{$property}_flag"} & 1)) {
2135
190af29f 2136 if ($CFG->{"grade_$property"} == -1) {
2137 continue; //temporary bc before version bump
2138 }
89a5f827 2139 $this->$property = $CFG->{"grade_$property"};
2140 $updated = true;
2141 }
2142 }
2143
2144 return $updated;
2145 }
2146
2147 /**
2148 * Notification of change in forced category settings.
b79fe189 2149 *
a153c9f2 2150 * Causes all course and category grade items to be marked as needing to be updated
89a5f827 2151 */
da3801e8 2152 public static function updated_forced_settings() {
5b0af8c5 2153 global $CFG, $DB;
2154 $params = array(1, 'course', 'category');
2155 $sql = "UPDATE {grade_items} SET needsupdate=? WHERE itemtype=? or itemtype=?";
2156 $DB->execute($sql, $params);
89a5f827 2157 }
4a490db0 2158}