MDL-35984 grade: Add behat tests for grade aggregations
[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
e5c674f1 163 /**
164 * Builds this category's path string based on its parents (if any) and its own id number.
165 * This is typically done just before inserting this object in the DB for the first time,
ce385eb4 166 * or when a new parent is added or changed. It is a recursive function: once the calling
167 * object no longer has a parent, the path is complete.
168 *
a153c9f2
AD
169 * @param grade_category $grade_category A Grade_Category object
170 * @return string The category's path string
e5c674f1 171 */
22a9b6d8 172 public static function build_path($grade_category) {
da3801e8 173 global $DB;
174
ce385eb4 175 if (empty($grade_category->parent)) {
c2efb501 176 return '/'.$grade_category->id.'/';
b79fe189 177
ce385eb4 178 } else {
da3801e8 179 $parent = $DB->get_record('grade_categories', array('id' => $grade_category->parent));
9a68cffc 180 return grade_category::build_path($parent).$grade_category->id.'/';
ce385eb4 181 }
e5c674f1 182 }
183
8a31e65c 184 /**
f92dcad8 185 * Finds and returns a grade_category instance based on params.
8a31e65c 186 *
f92dcad8 187 * @param array $params associative arrays varname=>value
a153c9f2 188 * @return grade_category The retrieved grade_category instance or false if none found.
f92dcad8 189 */
da3801e8 190 public static function fetch($params) {
f3ac8eb4 191 return grade_object::fetch_helper('grade_categories', 'grade_category', $params);
f92dcad8 192 }
193
194 /**
195 * Finds and returns all grade_category instances based on params.
f92dcad8 196 *
197 * @param array $params associative arrays varname=>value
198 * @return array array of grade_category insatnces or false if none found.
199 */
da3801e8 200 public static function fetch_all($params) {
f3ac8eb4 201 return grade_object::fetch_all_helper('grade_categories', 'grade_category', $params);
ce385eb4 202 }
203
8f4a626d 204 /**
2cc4b0f9 205 * In addition to update() as defined in grade_object, call force_regrading of parent categories, if applicable.
a153c9f2 206 *
aaff71da 207 * @param string $source from where was the object updated (mod/forum, manual, etc.)
a153c9f2 208 * @return bool success
8f4a626d 209 */
da3801e8 210 public function update($source=null) {
b3ac6c3e 211 // load the grade item or create a new one
212 $this->load_grade_item();
213
214 // force recalculation of path;
215 if (empty($this->path)) {
9a68cffc 216 $this->path = grade_category::build_path($this);
c2efb501 217 $this->depth = substr_count($this->path, '/') - 1;
1909a127 218 $updatechildren = true;
b79fe189 219
1909a127 220 } else {
221 $updatechildren = false;
4a490db0 222 }
0fc7f624 223
89a5f827 224 $this->apply_forced_settings();
225
b79fe189 226 // these are exclusive
89a5f827 227 if ($this->droplow > 0) {
228 $this->keephigh = 0;
b79fe189 229
89a5f827 230 } else if ($this->keephigh > 0) {
231 $this->droplow = 0;
232 }
4a490db0 233
b3ac6c3e 234 // Recalculate grades if needed
235 if ($this->qualifies_for_regrading()) {
f8e6e4db 236 $this->force_regrading();
4a490db0 237 }
f8e6e4db 238
ced5ee59 239 $this->timemodified = time();
240
1909a127 241 $result = parent::update($source);
242
243 // now update paths in all child categories
244 if ($result and $updatechildren) {
b79fe189 245
1909a127 246 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 247
1909a127 248 foreach ($children as $child) {
1909a127 249 $child->path = null;
250 $child->depth = 0;
251 $child->update($source);
da3801e8 252 }
1909a127 253 }
254 }
255
256 return $result;
8f4a626d 257 }
4a490db0 258
8f4a626d 259 /**
2cc4b0f9 260 * If parent::delete() is successful, send force_regrading message to parent category.
a153c9f2 261 *
aaff71da 262 * @param string $source from where was the object deleted (mod/forum, manual, etc.)
a153c9f2 263 * @return bool success
8f4a626d 264 */
da3801e8 265 public function delete($source=null) {
f13002d5 266 $grade_item = $this->load_grade_item();
4a490db0 267
f615fbab 268 if ($this->is_course_category()) {
b79fe189 269
f3ac8eb4 270 if ($categories = grade_category::fetch_all(array('courseid'=>$this->courseid))) {
b79fe189 271
f615fbab 272 foreach ($categories as $category) {
b79fe189 273
f615fbab 274 if ($category->id == $this->id) {
275 continue; // do not delete course category yet
276 }
277 $category->delete($source);
278 }
aaff71da 279 }
2b0f65e2 280
f3ac8eb4 281 if ($items = grade_item::fetch_all(array('courseid'=>$this->courseid))) {
b79fe189 282
f615fbab 283 foreach ($items as $item) {
b79fe189 284
f615fbab 285 if ($item->id == $grade_item->id) {
286 continue; // do not delete course item yet
287 }
288 $item->delete($source);
289 }
290 }
291
292 } else {
293 $this->force_regrading();
2b0f65e2 294
f615fbab 295 $parent = $this->load_parent_category();
2b0f65e2 296
f615fbab 297 // Update children's categoryid/parent field first
f3ac8eb4 298 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
f615fbab 299 foreach ($children as $child) {
300 $child->set_parent($parent->id);
301 }
302 }
b79fe189 303
f3ac8eb4 304 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
f615fbab 305 foreach ($children as $child) {
306 $child->set_parent($parent->id);
307 }
aaff71da 308 }
309 }
f13002d5 310
aaff71da 311 // first delete the attached grade item and grades
312 $grade_item->delete($source);
f13002d5 313
314 // delete category itself
aaff71da 315 return parent::delete($source);
8f4a626d 316 }
4a490db0 317
ce385eb4 318 /**
319 * In addition to the normal insert() defined in grade_object, this method sets the depth
a153c9f2
AD
320 * and path for this object, and update the record accordingly.
321 *
322 * We do this here instead of in the constructor as they both need to know the record's
323 * ID number, which only gets created at insertion time.
f151b073 324 * This method also creates an associated grade_item if this wasn't done during construction.
a153c9f2 325 *
aaff71da 326 * @param string $source from where was the object inserted (mod/forum, manual, etc.)
327 * @return int PK ID if successful, false otherwise
ce385eb4 328 */
da3801e8 329 public function insert($source=null) {
b3ac6c3e 330
331 if (empty($this->courseid)) {
2f137aa1 332 print_error('cannotinsertgrade');
b8ff92b6 333 }
4a490db0 334
b3ac6c3e 335 if (empty($this->parent)) {
f3ac8eb4 336 $course_category = grade_category::fetch_course_category($this->courseid);
b3ac6c3e 337 $this->parent = $course_category->id;
ce385eb4 338 }
4a490db0 339
b3ac6c3e 340 $this->path = null;
341
ced5ee59 342 $this->timecreated = $this->timemodified = time();
343
aaff71da 344 if (!parent::insert($source)) {
b3ac6c3e 345 debugging("Could not insert this category: " . print_r($this, true));
346 return false;
347 }
348
f8e6e4db 349 $this->force_regrading();
350
b3ac6c3e 351 // build path and depth
aaff71da 352 $this->update($source);
4a490db0 353
aaff71da 354 return $this->id;
b3ac6c3e 355 }
356
f2c88356 357 /**
f615fbab 358 * Internal function - used only from fetch_course_category()
359 * Normal insert() can not be used for course category
b79fe189 360 *
361 * @param int $courseid The course ID
a153c9f2 362 * @return int The ID of the new course category
f2c88356 363 */
da3801e8 364 public function insert_course_category($courseid) {
1f0e4921 365 $this->courseid = $courseid;
8f6fdf43 366 $this->fullname = '?';
1f0e4921 367 $this->path = null;
368 $this->parent = null;
0c87b5aa 369 $this->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2;
4a490db0 370
190af29f 371 $this->apply_default_settings();
89a5f827 372 $this->apply_forced_settings();
373
ced5ee59 374 $this->timecreated = $this->timemodified = time();
375
aaff71da 376 if (!parent::insert('system')) {
b3ac6c3e 377 debugging("Could not insert this category: " . print_r($this, true));
378 return false;
f151b073 379 }
4a490db0 380
b3ac6c3e 381 // build path and depth
aaff71da 382 $this->update('system');
b3ac6c3e 383
aaff71da 384 return $this->id;
ce385eb4 385 }
4a490db0 386
8f4a626d 387 /**
388 * Compares the values held by this object with those of the matching record in DB, and returns
389 * whether or not these differences are sufficient to justify an update of all parent objects.
a153c9f2
AD
390 * This assumes that this object has an ID number and a matching record in DB. If not, it will return false.
391 *
392 * @return bool
8f4a626d 393 */
da3801e8 394 public function qualifies_for_regrading() {
8f4a626d 395 if (empty($this->id)) {
6639ead3 396 debugging("Can not regrade non existing category");
8f4a626d 397 return false;
398 }
f3ac8eb4 399
400 $db_item = grade_category::fetch(array('id'=>$this->id));
4a490db0 401
c2efb501 402 $aggregationdiff = $db_item->aggregation != $this->aggregation;
403 $keephighdiff = $db_item->keephigh != $this->keephigh;
404 $droplowdiff = $db_item->droplow != $this->droplow;
405 $aggonlygrddiff = $db_item->aggregateonlygraded != $this->aggregateonlygraded;
406 $aggoutcomesdiff = $db_item->aggregateoutcomes != $this->aggregateoutcomes;
407 $aggsubcatsdiff = $db_item->aggregatesubcats != $this->aggregatesubcats;
8f4a626d 408
c2efb501 409 return ($aggregationdiff || $keephighdiff || $droplowdiff || $aggonlygrddiff || $aggoutcomesdiff || $aggsubcatsdiff);
8f4a626d 410 }
8c846243 411
412 /**
a153c9f2 413 * Marks this grade categories' associated grade item as needing regrading
8c846243 414 */
da3801e8 415 public function force_regrading() {
f8e6e4db 416 $grade_item = $this->load_grade_item();
417 $grade_item->force_regrading();
8c846243 418 }
419
0aa32279 420 /**
0758a08e 421 * Generates and saves final grades in associated category grade item.
1994d890 422 * These immediate children must already have their own final grades.
0758a08e 423 * The category's aggregation method is used to generate final grades.
ac9b0805 424 *
a153c9f2 425 * Please note that category grade is either calculated or aggregated, not both at the same time.
ac9b0805 426 *
c86caae7 427 * This method must be used ONLY from grade_item::regrade_final_grades(),
ac9b0805 428 * because the calculation must be done in correct order!
b8ff92b6 429 *
4a490db0 430 * Steps to follow:
ac9b0805 431 * 1. Get final grades from immediate children
2df71235 432 * 3. Aggregate these grades
0758a08e 433 * 4. Save them in final grades of associated category grade item
b79fe189 434 *
a153c9f2 435 * @param int $userid The user ID if final grade generation should be limited to a single user
b79fe189 436 * @return bool
0aa32279 437 */
da3801e8 438 public function generate_grades($userid=null) {
439 global $CFG, $DB;
4a490db0 440
ac9b0805 441 $this->load_grade_item();
2cc4b0f9 442
443 if ($this->grade_item->is_locked()) {
444 return true; // no need to recalculate locked items
445 }
446
89a5f827 447 // find grade items of immediate children (category or grade items) and force site settings
61c33818 448 $depends_on = $this->grade_item->depends_on();
b3ac6c3e 449
f8e6e4db 450 if (empty($depends_on)) {
451 $items = false;
b79fe189 452
f8e6e4db 453 } else {
5b0af8c5 454 list($usql, $params) = $DB->get_in_or_equal($depends_on);
f8e6e4db 455 $sql = "SELECT *
5b0af8c5 456 FROM {grade_items}
457 WHERE id $usql";
458 $items = $DB->get_records_sql($sql, $params);
f8e6e4db 459 }
4a490db0 460
3a03653e 461 // needed mostly for SUM agg type
462 $this->auto_update_max($items);
463
5b0af8c5 464 $grade_inst = new grade_grade();
465 $fields = 'g.'.implode(',g.', $grade_inst->required_fields);
466
467 // where to look for final grades - include grade of this item too, we will store the results there
468 $gis = array_merge($depends_on, array($this->grade_item->id));
469 list($usql, $params) = $DB->get_in_or_equal($gis);
470
f8e6e4db 471 if ($userid) {
5b0af8c5 472 $usersql = "AND g.userid=?";
473 $params[] = $userid;
b79fe189 474
f8e6e4db 475 } else {
476 $usersql = "";
b8ff92b6 477 }
4a490db0 478
3f2b0c8a 479 $sql = "SELECT $fields
5b0af8c5 480 FROM {grade_grades} g, {grade_items} gi
481 WHERE gi.id = g.itemid AND gi.id $usql $usersql
ac9b0805 482 ORDER BY g.userid";
b8ff92b6 483
9580a21f 484 // group the results by userid and aggregate the grades for this user
1b42e677
EL
485 $rs = $DB->get_recordset_sql($sql, $params);
486 if ($rs->valid()) {
03cedd62 487 $prevuser = 0;
488 $grade_values = array();
489 $excluded = array();
490 $oldgrade = null;
b79fe189 491
da3801e8 492 foreach ($rs as $used) {
b79fe189 493
03cedd62 494 if ($used->userid != $prevuser) {
495 $this->aggregate_grades($prevuser, $items, $grade_values, $oldgrade, $excluded);
496 $prevuser = $used->userid;
497 $grade_values = array();
498 $excluded = array();
499 $oldgrade = null;
500 }
501 $grade_values[$used->itemid] = $used->finalgrade;
b79fe189 502
03cedd62 503 if ($used->excluded) {
504 $excluded[] = $used->itemid;
505 }
b79fe189 506
03cedd62 507 if ($this->grade_item->id == $used->itemid) {
508 $oldgrade = $used;
2df71235 509 }
b8ff92b6 510 }
03cedd62 511 $this->aggregate_grades($prevuser, $items, $grade_values, $oldgrade, $excluded);//the last one
b8ff92b6 512 }
1b42e677 513 $rs->close();
b8ff92b6 514
b8ff92b6 515 return true;
516 }
517
518 /**
a153c9f2 519 * Internal function for grade category grade aggregation
ced5ee59 520 *
b79fe189 521 * @param int $userid The User ID
522 * @param array $items Grade items
523 * @param array $grade_values Array of grade values
524 * @param object $oldgrade Old grade
22a9b6d8 525 * @param array $excluded Excluded
b8ff92b6 526 */
da3801e8 527 private function aggregate_grades($userid, $items, $grade_values, $oldgrade, $excluded) {
e171963b 528 global $CFG;
b8ff92b6 529 if (empty($userid)) {
f8e6e4db 530 //ignore first call
b8ff92b6 531 return;
532 }
4a490db0 533
f8e6e4db 534 if ($oldgrade) {
66690b69 535 $oldfinalgrade = $oldgrade->finalgrade;
f3ac8eb4 536 $grade = new grade_grade($oldgrade, false);
f8e6e4db 537 $grade->grade_item =& $this->grade_item;
b8ff92b6 538
f8e6e4db 539 } else {
540 // insert final grade - it will be needed later anyway
f3ac8eb4 541 $grade = new grade_grade(array('itemid'=>$this->grade_item->id, 'userid'=>$userid), false);
f8e6e4db 542 $grade->grade_item =& $this->grade_item;
f1ad9e04 543 $grade->insert('system');
544 $oldfinalgrade = null;
f8e6e4db 545 }
f1ad9e04 546
c86caae7 547 // no need to recalculate locked or overridden grades
548 if ($grade->is_locked() or $grade->is_overridden()) {
2cc4b0f9 549 return;
ac9b0805 550 }
551
f8e6e4db 552 // can not use own final category grade in calculation
9580a21f 553 unset($grade_values[$this->grade_item->id]);
f8e6e4db 554
f1ad9e04 555
b79fe189 556 // sum is a special aggregation types - it adjusts the min max, does not use relative values
f1ad9e04 557 if ($this->aggregation == GRADE_AGGREGATE_SUM) {
558 $this->sum_grades($grade, $oldfinalgrade, $items, $grade_values, $excluded);
559 return;
560 }
561
0758a08e 562 // if no grades calculation possible or grading not allowed clear final grade
9580a21f 563 if (empty($grade_values) or empty($items) or ($this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE)) {
f8e6e4db 564 $grade->finalgrade = null;
b79fe189 565
66690b69 566 if (!is_null($oldfinalgrade)) {
0758a08e 567 $grade->update('aggregation');
f8e6e4db 568 }
b8ff92b6 569 return;
570 }
0758a08e 571
b79fe189 572 // normalize the grades first - all will have value 0...1
d5f0aa01 573 // ungraded items are not used in aggregation
23207a1a 574 foreach ($grade_values as $itemid=>$v) {
b79fe189 575
b8ff92b6 576 if (is_null($v)) {
577 // null means no grade
23207a1a 578 unset($grade_values[$itemid]);
579 continue;
b79fe189 580
23207a1a 581 } else if (in_array($itemid, $excluded)) {
582 unset($grade_values[$itemid]);
b8ff92b6 583 continue;
0aa32279 584 }
9a68cffc 585 $grade_values[$itemid] = grade_grade::standardise_score($v, $items[$itemid]->grademin, $items[$itemid]->grademax, 0, 1);
0aa32279 586 }
dda0c7e6 587
eacd3700 588 // use min grade if grade missing for these types
c2efb501 589 if (!$this->aggregateonlygraded) {
b79fe189 590
591 foreach ($items as $itemid=>$value) {
592
c2efb501 593 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
594 $grade_values[$itemid] = 0;
eacd3700 595 }
c2efb501 596 }
eacd3700 597 }
598
599 // limit and sort
a9e38ac8 600 $this->apply_limit_rules($grade_values, $items);
9580a21f 601 asort($grade_values, SORT_NUMERIC);
4a490db0 602
d5f0aa01 603 // let's see we have still enough grades to do any statistics
9580a21f 604 if (count($grade_values) == 0) {
ac9b0805 605 // not enough attempts yet
f8e6e4db 606 $grade->finalgrade = null;
b79fe189 607
66690b69 608 if (!is_null($oldfinalgrade)) {
0758a08e 609 $grade->update('aggregation');
b8ff92b6 610 }
611 return;
612 }
2df71235 613
d297269d 614 // do the maths
615 $agg_grade = $this->aggregate_values($grade_values, $items);
616
0758a08e 617 // recalculate the grade back to requested range
9a68cffc 618 $finalgrade = grade_grade::standardise_score($agg_grade, 0, 1, $this->grade_item->grademin, $this->grade_item->grademax);
d297269d 619
653a8648 620 $grade->finalgrade = $this->grade_item->bounded_grade($finalgrade);
d297269d 621
622 // update in db if changed
25bcd908 623 if (grade_floats_different($grade->finalgrade, $oldfinalgrade)) {
0758a08e 624 $grade->update('aggregation');
d297269d 625 }
626
627 return;
628 }
629
89a5f827 630 /**
a153c9f2 631 * Internal function that calculates the aggregated grade for this grade category
b79fe189 632 *
a153c9f2 633 * Must be public as it is used by grade_grade::get_hiding_affected()
b79fe189 634 *
a153c9f2
AD
635 * @param array $grade_values An array of values to be aggregated
636 * @param array $items The array of grade_items
637 * @return float The aggregate grade for this grade category
89a5f827 638 */
54c4a2cb 639 public function aggregate_values($grade_values, $items) {
b8ff92b6 640 switch ($this->aggregation) {
b79fe189 641
c2efb501 642 case GRADE_AGGREGATE_MEDIAN: // Middle point value in the set: ignores frequencies
9580a21f 643 $num = count($grade_values);
c186c7b2 644 $grades = array_values($grade_values);
b79fe189 645
c186c7b2 646 if ($num % 2 == 0) {
9c8d38fa 647 $agg_grade = ($grades[intval($num/2)-1] + $grades[intval($num/2)]) / 2;
b79fe189 648
b8ff92b6 649 } else {
9c8d38fa 650 $agg_grade = $grades[intval(($num/2)-0.5)];
b8ff92b6 651 }
652 break;
ac9b0805 653
c2efb501 654 case GRADE_AGGREGATE_MIN:
9c8d38fa 655 $agg_grade = reset($grade_values);
b8ff92b6 656 break;
657
c2efb501 658 case GRADE_AGGREGATE_MAX:
9c8d38fa 659 $agg_grade = array_pop($grade_values);
b8ff92b6 660 break;
661
c2efb501 662 case GRADE_AGGREGATE_MODE: // the most common value, average used if multimode
0198929c 663 // array_count_values only counts INT and STRING, so if grades are floats we must convert them to string
664 $converted_grade_values = array();
665
666 foreach ($grade_values as $k => $gv) {
b79fe189 667
0198929c 668 if (!is_int($gv) && !is_string($gv)) {
669 $converted_grade_values[$k] = (string) $gv;
b79fe189 670
0198929c 671 } else {
672 $converted_grade_values[$k] = $gv;
673 }
674 }
675
676 $freq = array_count_values($converted_grade_values);
95affb8a 677 arsort($freq); // sort by frequency keeping keys
678 $top = reset($freq); // highest frequency count
679 $modes = array_keys($freq, $top); // search for all modes (have the same highest count)
f7d515b6 680 rsort($modes, SORT_NUMERIC); // get highest mode
9c8d38fa 681 $agg_grade = reset($modes);
d5fab31f 682 break;
95affb8a 683
1426edac 684 case GRADE_AGGREGATE_WEIGHTED_MEAN: // Weighted average of all existing final grades, weight specified in coef
9580a21f 685 $weightsum = 0;
686 $sum = 0;
b79fe189 687
688 foreach ($grade_values as $itemid=>$grade_value) {
689
eacd3700 690 if ($items[$itemid]->aggregationcoef <= 0) {
9580a21f 691 continue;
692 }
eacd3700 693 $weightsum += $items[$itemid]->aggregationcoef;
694 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 695 }
b79fe189 696
9580a21f 697 if ($weightsum == 0) {
9c8d38fa 698 $agg_grade = null;
b79fe189 699
9580a21f 700 } else {
9c8d38fa 701 $agg_grade = $sum / $weightsum;
9580a21f 702 }
703 break;
704
d9ae2ab5 705 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
706 // Weighted average of all existing final grades with optional extra credit flag,
f7d515b6 707 // weight is the range of grade (usually grademax)
1426edac 708 $weightsum = 0;
d9ae2ab5 709 $sum = null;
b79fe189 710
711 foreach ($grade_values as $itemid=>$grade_value) {
1426edac 712 $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
b79fe189 713
1426edac 714 if ($weight <= 0) {
715 continue;
716 }
b79fe189 717
d9ae2ab5 718 if ($items[$itemid]->aggregationcoef == 0) {
719 $weightsum += $weight;
720 }
721 $sum += $weight * $grade_value;
1426edac 722 }
b79fe189 723
1426edac 724 if ($weightsum == 0) {
d9ae2ab5 725 $agg_grade = $sum; // only extra credits
b79fe189 726
1426edac 727 } else {
728 $agg_grade = $sum / $weightsum;
729 }
730 break;
731
c2efb501 732 case GRADE_AGGREGATE_EXTRACREDIT_MEAN: // special average
9580a21f 733 $num = 0;
d9ae2ab5 734 $sum = null;
b79fe189 735
736 foreach ($grade_values as $itemid=>$grade_value) {
737
eacd3700 738 if ($items[$itemid]->aggregationcoef == 0) {
9580a21f 739 $num += 1;
740 $sum += $grade_value;
b79fe189 741
eacd3700 742 } else if ($items[$itemid]->aggregationcoef > 0) {
743 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 744 }
745 }
b79fe189 746
9580a21f 747 if ($num == 0) {
9c8d38fa 748 $agg_grade = $sum; // only extra credits or wrong coefs
b79fe189 749
9580a21f 750 } else {
9c8d38fa 751 $agg_grade = $sum / $num;
9580a21f 752 }
753 break;
754
c2efb501 755 case GRADE_AGGREGATE_MEAN: // Arithmetic average of all grade items (if ungraded aggregated, NULL counted as minimum)
ac9b0805 756 default:
9580a21f 757 $num = count($grade_values);
758 $sum = array_sum($grade_values);
9c8d38fa 759 $agg_grade = $sum / $num;
b8ff92b6 760 break;
761 }
762
d297269d 763 return $agg_grade;
0aa32279 764 }
0758a08e 765
3a03653e 766 /**
a153c9f2
AD
767 * Some aggregation types may automatically update max grade
768 *
3a03653e 769 * @param array $items sub items
3a03653e 770 */
771 private function auto_update_max($items) {
772 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
773 // not needed at all
774 return;
775 }
776
777 if (!$items) {
b79fe189 778
3a03653e 779 if ($this->grade_item->grademax != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
780 $this->grade_item->grademax = 0;
781 $this->grade_item->grademin = 0;
782 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
783 $this->grade_item->update('aggregation');
784 }
785 return;
786 }
787
59080eee 788 //find max grade possible
789 $maxes = array();
b79fe189 790
3a03653e 791 foreach ($items as $item) {
b79fe189 792
3a03653e 793 if ($item->aggregationcoef > 0) {
794 // extra credit from this activity - does not affect total
795 continue;
796 }
b79fe189 797
3a03653e 798 if ($item->gradetype == GRADE_TYPE_VALUE) {
b9b199be 799 $maxes[$item->id] = $item->grademax;
b79fe189 800
3a03653e 801 } else if ($item->gradetype == GRADE_TYPE_SCALE) {
b9b199be 802 $maxes[$item->id] = $item->grademax; // 0 = nograde, 1 = first scale item, 2 = second scale item
3a03653e 803 }
804 }
59080eee 805 // apply droplow and keephigh
a9e38ac8 806 $this->apply_limit_rules($maxes, $items);
59080eee 807 $max = array_sum($maxes);
3a03653e 808
59080eee 809 // update db if anything changed
810 if ($this->grade_item->grademax != $max or $this->grade_item->grademin != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
3a03653e 811 $this->grade_item->grademax = $max;
812 $this->grade_item->grademin = 0;
813 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
814 $this->grade_item->update('aggregation');
815 }
816 }
817
0758a08e 818 /**
a153c9f2 819 * Internal function for category grades summing
b79fe189 820 *
a153c9f2
AD
821 * @param grade_grade $grade The grade item
822 * @param float $oldfinalgrade Old Final grade
823 * @param array $items Grade items
824 * @param array $grade_values Grade values
825 * @param array $excluded Excluded
0758a08e 826 */
da3801e8 827 private function sum_grades(&$grade, $oldfinalgrade, $items, $grade_values, $excluded) {
653a8648 828 if (empty($items)) {
829 return null;
830 }
831
c1024411 832 // ungraded and excluded items are not used in aggregation
0758a08e 833 foreach ($grade_values as $itemid=>$v) {
b79fe189 834
0758a08e 835 if (is_null($v)) {
836 unset($grade_values[$itemid]);
b79fe189 837
0758a08e 838 } else if (in_array($itemid, $excluded)) {
839 unset($grade_values[$itemid]);
840 }
841 }
842
d28f25a4 843 // use 0 if grade missing, droplow used and aggregating all items
844 if (!$this->aggregateonlygraded and !empty($this->droplow)) {
b79fe189 845
846 foreach ($items as $itemid=>$value) {
847
d28f25a4 848 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
849 $grade_values[$itemid] = 0;
850 }
851 }
852 }
853
a9e38ac8 854 $this->apply_limit_rules($grade_values, $items);
0758a08e 855
856 $sum = array_sum($grade_values);
653a8648 857 $grade->finalgrade = $this->grade_item->bounded_grade($sum);
0758a08e 858
859 // update in db if changed
25bcd908 860 if (grade_floats_different($grade->finalgrade, $oldfinalgrade)) {
0758a08e 861 $grade->update('aggregation');
862 }
863
864 return;
865 }
866
adc2f286 867 /**
a153c9f2 868 * Given an array of grade values (numerical indices) applies droplow or keephigh rules to limit the final array.
b79fe189 869 *
a153c9f2 870 * @param array $grade_values itemid=>$grade_value float
b79fe189 871 * @param array $items grade item objects
adc2f286 872 * @return array Limited grades.
873 */
a9e38ac8 874 public function apply_limit_rules(&$grade_values, $items) {
875 $extraused = $this->is_extracredit_used();
876
adc2f286 877 if (!empty($this->droplow)) {
a9e38ac8 878 asort($grade_values, SORT_NUMERIC);
879 $dropped = 0;
b79fe189 880
fb80cb2a
AD
881 // If we have fewer grade items available to drop than $this->droplow, use this flag to escape the loop
882 // May occur because of "extra credit" or if droplow is higher than the number of grade items
883 $droppedsomething = true;
b79fe189 884
fb80cb2a
AD
885 while ($dropped < $this->droplow && $droppedsomething) {
886 $droppedsomething = false;
b79fe189 887
fb80cb2a 888 $grade_keys = array_keys($grade_values);
aee968da
AD
889 $gradekeycount = count($grade_keys);
890
891 if ($gradekeycount === 0) {
fb80cb2a
AD
892 //We've dropped all grade items
893 break;
894 }
b79fe189 895
fb80cb2a
AD
896 $originalindex = $founditemid = $foundmax = null;
897
898 // Find the first remaining grade item that is available to be dropped
899 foreach ($grade_keys as $gradekeyindex=>$gradekey) {
900 if (!$extraused || $items[$gradekey]->aggregationcoef <= 0) {
901 // Found a non-extra credit grade item that is eligible to be dropped
902 $originalindex = $gradekeyindex;
903 $founditemid = $grade_keys[$originalindex];
904 $foundmax = $items[$founditemid]->grademax;
905 break;
a9e38ac8 906 }
fb80cb2a 907 }
b79fe189 908
fb80cb2a
AD
909 if (empty($founditemid)) {
910 // No grade items available to drop
a9e38ac8 911 break;
59080eee 912 }
fb80cb2a
AD
913
914 // Now iterate over the remaining grade items
915 // We're looking for other grade items with the same grade value but a higher grademax
916 $i = 1;
aee968da 917 while ($originalindex + $i < $gradekeycount) {
52929486 918
fb80cb2a 919 $possibleitemid = $grade_keys[$originalindex+$i];
52929486
AD
920 $i++;
921
fb80cb2a
AD
922 if ($grade_values[$founditemid] != $grade_values[$possibleitemid]) {
923 // The next grade item has a different grade value. Stop looking.
924 break;
925 }
926
927 if ($extraused && $items[$possibleitemid]->aggregationcoef > 0) {
928 // Don't drop extra credit grade items. Continue the search.
929 continue;
930 }
931
932 if ($foundmax < $items[$possibleitemid]->grademax) {
933 // Found a grade item with the same grade value and a higher grademax
934 $foundmax = $items[$possibleitemid]->grademax;
935 $founditemid = $possibleitemid;
936 // Continue searching to see if there is an even higher grademax
937 }
fb80cb2a
AD
938 }
939
940 // Now drop whatever grade item we have found
941 unset($grade_values[$founditemid]);
942 $dropped++;
943 $droppedsomething = true;
adc2f286 944 }
a9e38ac8 945
946 } else if (!empty($this->keephigh)) {
947 arsort($grade_values, SORT_NUMERIC);
948 $kept = 0;
b79fe189 949
a9e38ac8 950 foreach ($grade_values as $itemid=>$value) {
b79fe189 951
a9e38ac8 952 if ($extraused and $items[$itemid]->aggregationcoef > 0) {
953 // we keep all extra credits
b79fe189 954
a9e38ac8 955 } else if ($kept < $this->keephigh) {
956 $kept++;
b79fe189 957
a9e38ac8 958 } else {
959 unset($grade_values[$itemid]);
960 }
adc2f286 961 }
962 }
0aa32279 963 }
964
793253ae 965 /**
966 * Returns true if category uses extra credit of any kind
b79fe189 967 *
a153c9f2 968 * @return bool True if extra credit used
793253ae 969 */
134c514b
RT
970 public function is_extracredit_used() {
971 return self::aggregation_uses_extracredit($this->aggregation);
972 }
973
974 /**
975 * Returns true if aggregation passed is using extracredit.
976 *
977 * @param int $aggregation Aggregation const.
978 * @return bool True if extra credit used
979 */
980 public static function aggregation_uses_extracredit($aggregation) {
981 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
982 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
983 or $aggregation == GRADE_AGGREGATE_SUM);
793253ae 984 }
985
9580a21f 986 /**
f7d515b6 987 * Returns true if category uses special aggregation coefficient
b79fe189 988 *
a153c9f2 989 * @return bool True if an aggregation coefficient is being used
9580a21f 990 */
4e9ca991 991 public function is_aggregationcoef_used() {
134c514b
RT
992 return self::aggregation_uses_aggregationcoef($this->aggregation);
993
994 }
995
996 /**
997 * Returns true if aggregation uses aggregationcoef
998 *
999 * @param int $aggregation Aggregation const.
1000 * @return bool True if an aggregation coefficient is being used
1001 */
1002 public static function aggregation_uses_aggregationcoef($aggregation) {
1003 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN
1004 or $aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1005 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1006 or $aggregation == GRADE_AGGREGATE_SUM);
ba74762b 1007
9580a21f 1008 }
1009
653a8648 1010 /**
a153c9f2 1011 * Recursive function to find which weight/extra credit field to use in the grade item form.
b79fe189 1012 *
a153c9f2 1013 * Inherits from a parent category if that category has aggregatesubcats set to true.
b79fe189 1014 *
a153c9f2 1015 * @param string $first Whether or not this is the first item in the recursion
b79fe189 1016 * @return string
653a8648 1017 */
1018 public function get_coefstring($first=true) {
1019 if (!is_null($this->coefstring)) {
1020 return $this->coefstring;
1021 }
1022
1023 $overriding_coefstring = null;
1024
1025 // Stop recursing upwards if this category aggregates subcats or has no parent
1026 if (!$first && !$this->aggregatesubcats) {
b79fe189 1027
121d8006 1028 if ($parent_category = $this->load_parent_category()) {
653a8648 1029 return $parent_category->get_coefstring(false);
b79fe189 1030
653a8648 1031 } else {
1032 return null;
1033 }
b79fe189 1034
1035 } else if ($first) {
1036
653a8648 1037 if (!$this->aggregatesubcats) {
b79fe189 1038
121d8006 1039 if ($parent_category = $this->load_parent_category()) {
653a8648 1040 $overriding_coefstring = $parent_category->get_coefstring(false);
1041 }
1042 }
1043 }
1044
1045 // If an overriding coefstring has trickled down from one of the parent categories, return it. Otherwise, return self.
1046 if (!is_null($overriding_coefstring)) {
1047 return $overriding_coefstring;
1048 }
1049
1050 // No parent category is overriding this category's aggregation, return its string
1051 if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
1052 $this->coefstring = 'aggregationcoefweight';
b79fe189 1053
d9ae2ab5 1054 } else if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2) {
1055 $this->coefstring = 'aggregationcoefextrasum';
b79fe189 1056
653a8648 1057 } else if ($this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
3869ab1a 1058 $this->coefstring = 'aggregationcoefextraweight';
b79fe189 1059
653a8648 1060 } else if ($this->aggregation == GRADE_AGGREGATE_SUM) {
1061 $this->coefstring = 'aggregationcoefextrasum';
b79fe189 1062
653a8648 1063 } else {
1064 $this->coefstring = 'aggregationcoef';
1065 }
1066 return $this->coefstring;
1067 }
1068
1c307f21 1069 /**
b3ac6c3e 1070 * Returns tree with all grade_items and categories as elements
b79fe189 1071 *
1072 * @param int $courseid The course ID
a153c9f2 1073 * @param bool $include_category_items as category children
b3ac6c3e 1074 * @return array
1c307f21 1075 */
da3801e8 1076 public static function fetch_course_tree($courseid, $include_category_items=false) {
f3ac8eb4 1077 $course_category = grade_category::fetch_course_category($courseid);
514a3467 1078 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
1079 'children'=>$course_category->get_children($include_category_items));
b146d984
AD
1080
1081 $course_category->sortorder = $course_category->get_sortorder();
e2bb3c92
PS
1082 $sortorder = $course_category->get_sortorder();
1083 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 1084 }
1085
b79fe189 1086 /**
a153c9f2 1087 * An internal function that recursively sorts grade categories within a course
b79fe189 1088 *
1089 * @param array $category_array The seed of the recursion
a153c9f2
AD
1090 * @param int $sortorder The current sortorder
1091 * @return array An array containing 'object', 'type', 'depth' and optionally 'children'
b79fe189 1092 */
1093 static private function _fetch_course_tree_recursion($category_array, &$sortorder) {
b3ac6c3e 1094 // update the sortorder in db if needed
b146d984
AD
1095 //NOTE: This leads to us resetting sort orders every time the categories and items page is viewed :(
1096 //if ($category_array['object']->sortorder != $sortorder) {
1097 //$category_array['object']->set_sortorder($sortorder);
1098 //}
ce385eb4 1099
7bac3777
AD
1100 if (isset($category_array['object']->gradetype) && $category_array['object']->gradetype==GRADE_TYPE_NONE) {
1101 return null;
1102 }
1103
314c4336 1104 // store the grade_item or grade_category instance with extra info
1105 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 1106
1107 // reuse final grades if there
1108 if (array_key_exists('finalgrades', $category_array)) {
1109 $result['finalgrades'] = $category_array['finalgrades'];
1110 }
1111
1112 // recursively resort children
1113 if (!empty($category_array['children'])) {
1114 $result['children'] = array();
29d509f5 1115 //process the category item first
7bac3777 1116 $child = null;
b79fe189 1117
1118 foreach ($category_array['children'] as $oldorder=>$child_array) {
1119
314c4336 1120 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
7bac3777
AD
1121 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1122 if (!empty($child)) {
1123 $result['children'][$sortorder] = $child;
1124 }
29d509f5 1125 }
2b0f65e2 1126 }
b79fe189 1127
1128 foreach ($category_array['children'] as $oldorder=>$child_array) {
1129
29d509f5 1130 if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
7bac3777
AD
1131 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1132 if (!empty($child)) {
1133 $result['children'][++$sortorder] = $child;
1134 }
b3ac6c3e 1135 }
1136 }
1137 }
1138
1139 return $result;
ce385eb4 1140 }
7c8a963f 1141
1142 /**
4a490db0 1143 * Fetches and returns all the children categories and/or grade_items belonging to this category.
1144 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 1145 * as well as all levels (0). The elements are indexed by sort order.
b79fe189 1146 *
1147 * @param bool $include_category_items Whether or not to include category grade_items in the children array
7c8a963f 1148 * @return array Array of child objects (grade_category and grade_item).
1149 */
da3801e8 1150 public function get_children($include_category_items=false) {
1151 global $DB;
b3ac6c3e 1152
1153 // This function must be as fast as possible ;-)
1154 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
1155 // we have to limit the number of queries though, because it will be used often in grade reports
1156
da3801e8 1157 $cats = $DB->get_records('grade_categories', array('courseid' => $this->courseid));
1158 $items = $DB->get_records('grade_items', array('courseid' => $this->courseid));
4a490db0 1159
b3ac6c3e 1160 // init children array first
1161 foreach ($cats as $catid=>$cat) {
1162 $cats[$catid]->children = array();
27f95e9b 1163 }
4a490db0 1164
b3ac6c3e 1165 //first attach items to cats and add category sortorder
1166 foreach ($items as $item) {
b79fe189 1167
b3ac6c3e 1168 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
1169 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 1170
b3ac6c3e 1171 if (!$include_category_items) {
1172 continue;
1173 }
1174 $categoryid = $item->iteminstance;
b79fe189 1175
b3ac6c3e 1176 } else {
1177 $categoryid = $item->categoryid;
63354ab5
AD
1178 if (empty($categoryid)) {
1179 debugging('Found a grade item that isnt in a category');
1180 }
b3ac6c3e 1181 }
1182
1183 // prevent problems with duplicate sortorders in db
1184 $sortorder = $item->sortorder;
b79fe189 1185
63354ab5
AD
1186 while (array_key_exists($categoryid, $cats)
1187 && array_key_exists($sortorder, $cats[$categoryid]->children)) {
1188
b3ac6c3e 1189 $sortorder++;
1190 }
1191
1192 $cats[$categoryid]->children[$sortorder] = $item;
1193
1194 }
1195
1196 // now find the requested category and connect categories as children
1197 $category = false;
b79fe189 1198
b3ac6c3e 1199 foreach ($cats as $catid=>$cat) {
b79fe189 1200
ec3717e1 1201 if (empty($cat->parent)) {
b79fe189 1202
ec3717e1 1203 if ($cat->path !== '/'.$cat->id.'/') {
1204 $grade_category = new grade_category($cat, false);
1205 $grade_category->path = '/'.$cat->id.'/';
1206 $grade_category->depth = 1;
1207 $grade_category->update('system');
1208 return $this->get_children($include_category_items);
1209 }
b79fe189 1210
ec3717e1 1211 } else {
b79fe189 1212
ec3717e1 1213 if (empty($cat->path) or !preg_match('|/'.$cat->parent.'/'.$cat->id.'/$|', $cat->path)) {
1214 //fix paths and depts
1215 static $recursioncounter = 0; // prevents infinite recursion
1216 $recursioncounter++;
b79fe189 1217
da3801e8 1218 if ($recursioncounter < 5) {
ec3717e1 1219 // fix paths and depths!
1220 $grade_category = new grade_category($cat, false);
1221 $grade_category->depth = 0;
1222 $grade_category->path = null;
1223 $grade_category->update('system');
1224 return $this->get_children($include_category_items);
1225 }
da3801e8 1226 }
b3ac6c3e 1227 // prevent problems with duplicate sortorders in db
1228 $sortorder = $cat->sortorder;
b79fe189 1229
1230 while (array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 1231 //debugging("$sortorder exists in cat loop");
b3ac6c3e 1232 $sortorder++;
1233 }
1234
65370356 1235 $cats[$cat->parent]->children[$sortorder] = &$cats[$catid];
b3ac6c3e 1236 }
f3ac8eb4 1237
b3ac6c3e 1238 if ($catid == $this->id) {
1239 $category = &$cats[$catid];
1240 }
1241 }
1242
1243 unset($items); // not needed
1244 unset($cats); // not needed
1245
f3ac8eb4 1246 $children_array = grade_category::_get_children_recursion($category);
b3ac6c3e 1247
1248 ksort($children_array);
1249
1250 return $children_array;
1251
1252 }
1253
b79fe189 1254 /**
1255 * Private method used to retrieve all children of this category recursively
1256 *
1257 * @param grade_category $category Source of current recursion
a153c9f2 1258 * @return array An array of child grade categories
b79fe189 1259 */
22a9b6d8 1260 private static function _get_children_recursion($category) {
b3ac6c3e 1261
1262 $children_array = array();
b79fe189 1263 foreach ($category->children as $sortorder=>$child) {
1264
b3ac6c3e 1265 if (array_key_exists('itemtype', $child)) {
f3ac8eb4 1266 $grade_item = new grade_item($child, false);
b79fe189 1267
4faf5f99 1268 if (in_array($grade_item->itemtype, array('course', 'category'))) {
1269 $type = $grade_item->itemtype.'item';
1270 $depth = $category->depth;
b79fe189 1271
314c4336 1272 } else {
1273 $type = 'item';
1274 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 1275 }
4faf5f99 1276 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 1277
7c8a963f 1278 } else {
f3ac8eb4 1279 $children = grade_category::_get_children_recursion($child);
1280 $grade_category = new grade_category($child, false);
b79fe189 1281
b3ac6c3e 1282 if (empty($children)) {
314c4336 1283 $children = array();
7c8a963f 1284 }
4faf5f99 1285 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
314c4336 1286 }
27f95e9b 1287 }
1288
b3ac6c3e 1289 // sort the array
1290 ksort($children_array);
1291
27f95e9b 1292 return $children_array;
1293 }
4a490db0 1294
f151b073 1295 /**
a4d76049 1296 * Uses {@link get_grade_item()} to load or create a grade_item, then saves it as $this->grade_item.
a153c9f2
AD
1297 *
1298 * @return grade_item
f151b073 1299 */
da3801e8 1300 public function load_grade_item() {
ac9b0805 1301 if (empty($this->grade_item)) {
1302 $this->grade_item = $this->get_grade_item();
1303 }
ab53054f 1304 return $this->grade_item;
1305 }
4a490db0 1306
ab53054f 1307 /**
a153c9f2
AD
1308 * Retrieves this grade categories' associated grade_item from the database
1309 *
1310 * If no grade_item exists yet, creates one.
1311 *
1312 * @return grade_item
ab53054f 1313 */
da3801e8 1314 public function get_grade_item() {
c91ed4be 1315 if (empty($this->id)) {
1316 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
1317 return false;
1318 }
1319
b3ac6c3e 1320 if (empty($this->parent)) {
1321 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
1322
1323 } else {
1324 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
1325 }
4ac209d5 1326
f3ac8eb4 1327 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 1328 // create a new one
f3ac8eb4 1329 $grade_item = new grade_item($params, false);
b8ff92b6 1330 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 1331 $grade_item->insert('system');
4a490db0 1332
b79fe189 1333 } else if (count($grade_items) == 1) {
b8ff92b6 1334 // found existing one
1335 $grade_item = reset($grade_items);
4a490db0 1336
b8ff92b6 1337 } else {
1338 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 1339 // return first one
1340 $grade_item = reset($grade_items);
2c72af1f 1341 }
1342
ab53054f 1343 return $grade_item;
f151b073 1344 }
8c846243 1345
1346 /**
a153c9f2
AD
1347 * Uses $this->parent to instantiate $this->parent_category based on the referenced record in the DB
1348 *
1349 * @return grade_category The parent category
8c846243 1350 */
da3801e8 1351 public function load_parent_category() {
8c846243 1352 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 1353 $this->parent_category = $this->get_parent_category();
8c846243 1354 }
1355 return $this->parent_category;
4a490db0 1356 }
1357
ab53054f 1358 /**
a153c9f2
AD
1359 * Uses $this->parent to instantiate and return a grade_category object
1360 *
1361 * @return grade_category Returns the parent category or null if this category has no parent
ab53054f 1362 */
da3801e8 1363 public function get_parent_category() {
ab53054f 1364 if (!empty($this->parent)) {
f3ac8eb4 1365 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 1366 return $parent_category;
ab53054f 1367 } else {
1368 return null;
1369 }
1370 }
1371
2186f72c 1372 /**
a153c9f2 1373 * Returns the most descriptive field for this grade category
b79fe189 1374 *
2186f72c 1375 * @return string name
1376 */
da3801e8 1377 public function get_name() {
1378 global $DB;
8f6fdf43 1379 // For a course category, we return the course name if the fullname is set to '?' in the DB (empty in the category edit form)
1380 if (empty($this->parent) && $this->fullname == '?') {
da3801e8 1381 $course = $DB->get_record('course', array('id'=> $this->courseid));
410753fb 1382 return format_string($course->fullname);
b79fe189 1383
314c4336 1384 } else {
1385 return $this->fullname;
1386 }
2186f72c 1387 }
c91ed4be 1388
0fc7f624 1389 /**
a153c9f2 1390 * Sets this category's parent id
b79fe189 1391 *
a153c9f2
AD
1392 * @param int $parentid The ID of the category that is the new parent to $this
1393 * @param string $source From where was the object updated (mod/forum, manual, etc.)
1394 * @return bool success
0fc7f624 1395 */
da3801e8 1396 public function set_parent($parentid, $source=null) {
f13002d5 1397 if ($this->parent == $parentid) {
1398 return true;
1399 }
1400
1401 if ($parentid == $this->id) {
2f137aa1 1402 print_error('cannotassignselfasparent');
f13002d5 1403 }
1404
1405 if (empty($this->parent) and $this->is_course_category()) {
2f137aa1 1406 print_error('cannothaveparentcate');
b3ac6c3e 1407 }
f13002d5 1408
1409 // find parent and check course id
f3ac8eb4 1410 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 1411 return false;
1412 }
1413
f8e6e4db 1414 $this->force_regrading();
b3ac6c3e 1415
1416 // set new parent category
f8e6e4db 1417 $this->parent = $parent_category->id;
1418 $this->parent_category =& $parent_category;
b3ac6c3e 1419 $this->path = null; // remove old path and depth - will be recalculated in update()
ec3717e1 1420 $this->depth = 0; // remove old path and depth - will be recalculated in update()
f8e6e4db 1421 $this->update($source);
b3ac6c3e 1422
15b462da 1423 return $this->update($source);
b3ac6c3e 1424 }
1425
1426 /**
a153c9f2 1427 * Returns the final grade values for this grade category.
b79fe189 1428 *
a153c9f2 1429 * @param int $userid Optional user ID to retrieve a single user's final grade
b3ac6c3e 1430 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
1431 */
b79fe189 1432 public function get_final($userid=null) {
b3ac6c3e 1433 $this->load_grade_item();
1434 return $this->grade_item->get_final($userid);
0fc7f624 1435 }
4a490db0 1436
0fc7f624 1437 /**
a153c9f2
AD
1438 * Returns the sortorder of the grade categories' associated grade_item
1439 *
1440 * This method is also available in grade_item for cases where the object type is not known.
b79fe189 1441 *
0fc7f624 1442 * @return int Sort order
1443 */
da3801e8 1444 public function get_sortorder() {
b3ac6c3e 1445 $this->load_grade_item();
1446 return $this->grade_item->get_sortorder();
0fc7f624 1447 }
1448
be7c0693 1449 /**
a153c9f2
AD
1450 * Returns the idnumber of the grade categories' associated grade_item.
1451 *
1452 * This method is also available in grade_item for cases where the object type is not known.
b79fe189 1453 *
be7c0693 1454 * @return string idnumber
1455 */
da3801e8 1456 public function get_idnumber() {
be7c0693 1457 $this->load_grade_item();
1458 return $this->grade_item->get_idnumber();
1459 }
1460
0fc7f624 1461 /**
a153c9f2
AD
1462 * Sets the sortorder variable for this category.
1463 *
4a490db0 1464 * This method is also available in grade_item, for cases where the object type is not know.
b79fe189 1465 *
1466 * @param int $sortorder The sortorder to assign to this category
0fc7f624 1467 */
da3801e8 1468 public function set_sortorder($sortorder) {
b3ac6c3e 1469 $this->load_grade_item();
1470 $this->grade_item->set_sortorder($sortorder);
1471 }
1472
6639ead3 1473 /**
a153c9f2 1474 * Move this category after the given sortorder
b79fe189 1475 *
a153c9f2 1476 * Does not change the parent
b79fe189 1477 *
a153c9f2 1478 * @param int $sortorder to place after.
b79fe189 1479 * @return void
6639ead3 1480 */
da3801e8 1481 public function move_after_sortorder($sortorder) {
f13002d5 1482 $this->load_grade_item();
1483 $this->grade_item->move_after_sortorder($sortorder);
1484 }
1485
b3ac6c3e 1486 /**
f13002d5 1487 * Return true if this is the top most category that represents the total course grade.
b79fe189 1488 *
a153c9f2 1489 * @return bool
b3ac6c3e 1490 */
da3801e8 1491 public function is_course_category() {
b3ac6c3e 1492 $this->load_grade_item();
1493 return $this->grade_item->is_course_item();
1494 }
1495
1496 /**
a153c9f2 1497 * Return the course level grade_category object
b79fe189 1498 *
1499 * @param int $courseid The Course ID
a153c9f2 1500 * @return grade_category Returns the course level grade_category instance
b3ac6c3e 1501 */
22a9b6d8 1502 public static function fetch_course_category($courseid) {
a4503119 1503 if (empty($courseid)) {
1504 debugging('Missing course id!');
1505 return false;
1506 }
b3ac6c3e 1507
1508 // course category has no parent
f3ac8eb4 1509 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
b3ac6c3e 1510 return $course_category;
1511 }
1512
1513 // create a new one
f3ac8eb4 1514 $course_category = new grade_category();
b3ac6c3e 1515 $course_category->insert_course_category($courseid);
1516
1517 return $course_category;
0fc7f624 1518 }
4ac209d5 1519
79eabc2a 1520 /**
1521 * Is grading object editable?
b79fe189 1522 *
a153c9f2 1523 * @return bool
79eabc2a 1524 */
da3801e8 1525 public function is_editable() {
79eabc2a 1526 return true;
1527 }
1528
5fad5061 1529 /**
a153c9f2
AD
1530 * Returns the locked state/date of the grade categories' associated grade_item.
1531 *
1532 * This method is also available in grade_item, for cases where the object type is not known.
1533 *
1534 * @return bool
5fad5061 1535 */
da3801e8 1536 public function is_locked() {
5fad5061 1537 $this->load_grade_item();
22e23c78 1538 return $this->grade_item->is_locked();
5fad5061 1539 }
1540
1541 /**
1542 * Sets the grade_item's locked variable and updates the grade_item.
a153c9f2
AD
1543 *
1544 * Calls set_locked() on the categories' grade_item
b79fe189 1545 *
1546 * @param int $lockedstate 0, 1 or a timestamp int(10) after which date the item will be locked.
1547 * @param bool $cascade lock/unlock child objects too
1548 * @param bool $refresh refresh grades when unlocking
a153c9f2 1549 * @return bool success if category locked (not all children mayb be locked though)
5fad5061 1550 */
da3801e8 1551 public function set_locked($lockedstate, $cascade=false, $refresh=true) {
5fad5061 1552 $this->load_grade_item();
2b0f65e2 1553
fb0e3570 1554 $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
1555
1556 if ($cascade) {
1557 //process all children - items and categories
f3ac8eb4 1558 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
b79fe189 1559
1560 foreach ($children as $child) {
fb0e3570 1561 $child->set_locked($lockedstate, true, false);
b79fe189 1562
fb0e3570 1563 if (empty($lockedstate) and $refresh) {
1564 //refresh when unlocking
1565 $child->refresh_grades();
1566 }
2b0f65e2 1567 }
7a7a53d3 1568 }
b79fe189 1569
f3ac8eb4 1570 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 1571
1572 foreach ($children as $child) {
fb0e3570 1573 $child->set_locked($lockedstate, true, true);
1574 }
7a7a53d3 1575 }
1576 }
2b0f65e2 1577
b121b544 1578 return $result;
5fad5061 1579 }
4a490db0 1580
a153c9f2
AD
1581 /**
1582 * Overrides grade_object::set_properties() to add special handling for changes to category aggregation types
1583 *
1584 * @param stdClass $instance the object to set the properties on
1585 * @param array|stdClass $params Either an associative array or an object containing property name, property value pairs
1586 */
79b260cc
AD
1587 public static function set_properties(&$instance, $params) {
1588 global $DB;
1589
1590 parent::set_properties($instance, $params);
1591
c1024411 1592 //if they've changed aggregation type we made need to do some fiddling to provide appropriate defaults
79b260cc
AD
1593 if (!empty($params->aggregation)) {
1594
1595 //weight and extra credit share a column :( Would like a default of 1 for weight and 0 for extra credit
1596 //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 1597 if (self::aggregation_uses_aggregationcoef($params->aggregation)) {
79b260cc 1598 $sql = $defaultaggregationcoef = null;
7ad5a627 1599
134c514b 1600 if (!self::aggregation_uses_extracredit($params->aggregation)) {
79b260cc
AD
1601 //if all items in this category have aggregation coefficient of 0 we can change it to 1 ie evenly weighted
1602 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=0";
1603 $defaultaggregationcoef = 1;
134c514b 1604 } else {
79b260cc
AD
1605 //if all items in this category have aggregation coefficient of 1 we can change it to 0 ie no extra credit
1606 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=1";
1607 $defaultaggregationcoef = 0;
1608 }
1609
1610 $params = array('categoryid'=>$instance->id);
1611 $count = $DB->count_records_sql($sql, $params);
1612 if ($count===0) { //category is either empty or all items are set to a default value so we can switch defaults
1613 $params['aggregationcoef'] = $defaultaggregationcoef;
1614 $DB->execute("update {grade_items} set aggregationcoef=:aggregationcoef where categoryid=:categoryid",$params);
1615 }
1616 }
1617 }
1618 }
1619
5fad5061 1620 /**
4a490db0 1621 * Sets the grade_item's hidden variable and updates the grade_item.
a153c9f2
AD
1622 *
1623 * Overrides grade_item::set_hidden() to add cascading of the hidden value to grade items in this grade category
1624 *
1625 * @param int $hidden 0 mean always visible, 1 means always hidden and a number > 1 is a timestamp to hide until
1626 * @param bool $cascade apply to child objects too
5fad5061 1627 */
da3801e8 1628 public function set_hidden($hidden, $cascade=false) {
5fad5061 1629 $this->load_grade_item();
a25bb902 1630 //this hides the associated grade item (the course total)
1762a264 1631 $this->grade_item->set_hidden($hidden, $cascade);
a25bb902
AD
1632 //this hides the category itself and everything it contains
1633 parent::set_hidden($hidden, $cascade);
b79fe189 1634
f60c61b1 1635 if ($cascade) {
b79fe189 1636
f3ac8eb4 1637 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
b79fe189 1638
1639 foreach ($children as $child) {
39873128
TH
1640 if ($child->can_control_visibility()) {
1641 $child->set_hidden($hidden, $cascade);
1642 }
f60c61b1 1643 }
f13002d5 1644 }
b79fe189 1645
f3ac8eb4 1646 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 1647
1648 foreach ($children as $child) {
f60c61b1 1649 $child->set_hidden($hidden, $cascade);
1650 }
f13002d5 1651 }
1652 }
d90aa634
AD
1653
1654 //if marking category visible make sure parent category is visible MDL-21367
1655 if( !$hidden ) {
1656 $category_array = grade_category::fetch_all(array('id'=>$this->parent));
1657 if ($category_array && array_key_exists($this->parent, $category_array)) {
1658 $category = $category_array[$this->parent];
1659 //call set_hidden on the category regardless of whether it is hidden as its parent might be hidden
1660 //if($category->is_hidden()) {
1661 $category->set_hidden($hidden, false);
1662 //}
1663 }
1664 }
5fad5061 1665 }
89a5f827 1666
190af29f 1667 /**
1668 * Applies default settings on this category
a153c9f2
AD
1669 *
1670 * @return bool True if anything changed
190af29f 1671 */
da3801e8 1672 public function apply_default_settings() {
190af29f 1673 global $CFG;
1674
1675 foreach ($this->forceable as $property) {
b79fe189 1676
190af29f 1677 if (isset($CFG->{"grade_$property"})) {
b79fe189 1678
190af29f 1679 if ($CFG->{"grade_$property"} == -1) {
1680 continue; //temporary bc before version bump
1681 }
1682 $this->$property = $CFG->{"grade_$property"};
1683 }
1684 }
1685 }
1686
89a5f827 1687 /**
1688 * Applies forced settings on this category
a153c9f2
AD
1689 *
1690 * @return bool True if anything changed
89a5f827 1691 */
da3801e8 1692 public function apply_forced_settings() {
89a5f827 1693 global $CFG;
1694
1695 $updated = false;
b79fe189 1696
89a5f827 1697 foreach ($this->forceable as $property) {
b79fe189 1698
1699 if (isset($CFG->{"grade_$property"}) and isset($CFG->{"grade_{$property}_flag"}) and
1700 ((int) $CFG->{"grade_{$property}_flag"} & 1)) {
1701
190af29f 1702 if ($CFG->{"grade_$property"} == -1) {
1703 continue; //temporary bc before version bump
1704 }
89a5f827 1705 $this->$property = $CFG->{"grade_$property"};
1706 $updated = true;
1707 }
1708 }
1709
1710 return $updated;
1711 }
1712
1713 /**
1714 * Notification of change in forced category settings.
b79fe189 1715 *
a153c9f2 1716 * Causes all course and category grade items to be marked as needing to be updated
89a5f827 1717 */
da3801e8 1718 public static function updated_forced_settings() {
5b0af8c5 1719 global $CFG, $DB;
1720 $params = array(1, 'course', 'category');
1721 $sql = "UPDATE {grade_items} SET needsupdate=? WHERE itemtype=? or itemtype=?";
1722 $DB->execute($sql, $params);
89a5f827 1723 }
4a490db0 1724}