MDL-29877 core_grade:add some upgrade code to fix broken grade items introduced by...
[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
cfe170e4
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
cfe170e4
AD
885 while ($dropped < $this->droplow && $droppedsomething) {
886 $droppedsomething = false;
b79fe189 887
cfe170e4 888 $grade_keys = array_keys($grade_values);
b10a4673
AD
889 $gradekeycount = count($grade_keys);
890
891 if ($gradekeycount === 0) {
cfe170e4
AD
892 //We've dropped all grade items
893 break;
894 }
b79fe189 895
cfe170e4
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 }
cfe170e4 907 }
b79fe189 908
cfe170e4
AD
909 if (empty($founditemid)) {
910 // No grade items available to drop
a9e38ac8 911 break;
59080eee 912 }
cfe170e4
AD
913
914 $i = 1;
b10a4673 915 while ($originalindex + $i < $gradekeycount) {
410d0dc2 916
cfe170e4 917 $possibleitemid = $grade_keys[$originalindex+$i];
410d0dc2
AD
918 $i++;
919
cfe170e4
AD
920 if ($grade_values[$founditemid] != $grade_values[$possibleitemid]) {
921 // The next grade item has a different grade. Stop looking.
922 break;
923 }
924
925 if ($extraused && $items[$possibleitemid]->aggregationcoef > 0) {
926 // Don't drop extra credit grade items. Continue the search.
927 continue;
928 }
929
930 if ($foundmax < $items[$possibleitemid]->grademax) {
931 // Found a grade item with the same grade and a higher grademax
932 $foundmax = $items[$possibleitemid]->grademax;
933 $founditemid = $possibleitemid;
934 // Continue searching to see if there is an even higher grademax...
935 }
cfe170e4
AD
936 }
937
938 // Now drop whatever grade item we have found
939 unset($grade_values[$founditemid]);
940 $dropped++;
941 $droppedsomething = true;
adc2f286 942 }
a9e38ac8 943
944 } else if (!empty($this->keephigh)) {
945 arsort($grade_values, SORT_NUMERIC);
946 $kept = 0;
b79fe189 947
a9e38ac8 948 foreach ($grade_values as $itemid=>$value) {
b79fe189 949
a9e38ac8 950 if ($extraused and $items[$itemid]->aggregationcoef > 0) {
951 // we keep all extra credits
b79fe189 952
a9e38ac8 953 } else if ($kept < $this->keephigh) {
954 $kept++;
b79fe189 955
a9e38ac8 956 } else {
957 unset($grade_values[$itemid]);
958 }
adc2f286 959 }
960 }
0aa32279 961 }
962
793253ae 963 /**
964 * Returns true if category uses extra credit of any kind
b79fe189 965 *
a153c9f2 966 * @return bool True if extra credit used
793253ae 967 */
968 function is_extracredit_used() {
969 return ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
970 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
971 or $this->aggregation == GRADE_AGGREGATE_SUM);
972 }
973
9580a21f 974 /**
f7d515b6 975 * Returns true if category uses special aggregation coefficient
b79fe189 976 *
a153c9f2 977 * @return bool True if an aggregation coefficient is being used
9580a21f 978 */
4e9ca991 979 public function is_aggregationcoef_used() {
c2efb501 980 return ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN
d9ae2ab5 981 or $this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
2e0d37fe 982 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
983 or $this->aggregation == GRADE_AGGREGATE_SUM);
ba74762b 984
9580a21f 985 }
986
653a8648 987 /**
a153c9f2 988 * Recursive function to find which weight/extra credit field to use in the grade item form.
b79fe189 989 *
a153c9f2 990 * Inherits from a parent category if that category has aggregatesubcats set to true.
b79fe189 991 *
a153c9f2 992 * @param string $first Whether or not this is the first item in the recursion
b79fe189 993 * @return string
653a8648 994 */
995 public function get_coefstring($first=true) {
996 if (!is_null($this->coefstring)) {
997 return $this->coefstring;
998 }
999
1000 $overriding_coefstring = null;
1001
1002 // Stop recursing upwards if this category aggregates subcats or has no parent
1003 if (!$first && !$this->aggregatesubcats) {
b79fe189 1004
121d8006 1005 if ($parent_category = $this->load_parent_category()) {
653a8648 1006 return $parent_category->get_coefstring(false);
b79fe189 1007
653a8648 1008 } else {
1009 return null;
1010 }
b79fe189 1011
1012 } else if ($first) {
1013
653a8648 1014 if (!$this->aggregatesubcats) {
b79fe189 1015
121d8006 1016 if ($parent_category = $this->load_parent_category()) {
653a8648 1017 $overriding_coefstring = $parent_category->get_coefstring(false);
1018 }
1019 }
1020 }
1021
1022 // If an overriding coefstring has trickled down from one of the parent categories, return it. Otherwise, return self.
1023 if (!is_null($overriding_coefstring)) {
1024 return $overriding_coefstring;
1025 }
1026
1027 // No parent category is overriding this category's aggregation, return its string
1028 if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
1029 $this->coefstring = 'aggregationcoefweight';
b79fe189 1030
d9ae2ab5 1031 } else if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2) {
1032 $this->coefstring = 'aggregationcoefextrasum';
b79fe189 1033
653a8648 1034 } else if ($this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
3869ab1a 1035 $this->coefstring = 'aggregationcoefextraweight';
b79fe189 1036
653a8648 1037 } else if ($this->aggregation == GRADE_AGGREGATE_SUM) {
1038 $this->coefstring = 'aggregationcoefextrasum';
b79fe189 1039
653a8648 1040 } else {
1041 $this->coefstring = 'aggregationcoef';
1042 }
1043 return $this->coefstring;
1044 }
1045
1c307f21 1046 /**
b3ac6c3e 1047 * Returns tree with all grade_items and categories as elements
b79fe189 1048 *
1049 * @param int $courseid The course ID
a153c9f2 1050 * @param bool $include_category_items as category children
b3ac6c3e 1051 * @return array
1c307f21 1052 */
da3801e8 1053 public static function fetch_course_tree($courseid, $include_category_items=false) {
f3ac8eb4 1054 $course_category = grade_category::fetch_course_category($courseid);
514a3467 1055 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
1056 'children'=>$course_category->get_children($include_category_items));
b146d984
AD
1057
1058 $course_category->sortorder = $course_category->get_sortorder();
e2bb3c92
PS
1059 $sortorder = $course_category->get_sortorder();
1060 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 1061 }
1062
b79fe189 1063 /**
a153c9f2 1064 * An internal function that recursively sorts grade categories within a course
b79fe189 1065 *
1066 * @param array $category_array The seed of the recursion
a153c9f2
AD
1067 * @param int $sortorder The current sortorder
1068 * @return array An array containing 'object', 'type', 'depth' and optionally 'children'
b79fe189 1069 */
1070 static private function _fetch_course_tree_recursion($category_array, &$sortorder) {
b3ac6c3e 1071 // update the sortorder in db if needed
b146d984
AD
1072 //NOTE: This leads to us resetting sort orders every time the categories and items page is viewed :(
1073 //if ($category_array['object']->sortorder != $sortorder) {
1074 //$category_array['object']->set_sortorder($sortorder);
1075 //}
ce385eb4 1076
7bac3777
AD
1077 if (isset($category_array['object']->gradetype) && $category_array['object']->gradetype==GRADE_TYPE_NONE) {
1078 return null;
1079 }
1080
314c4336 1081 // store the grade_item or grade_category instance with extra info
1082 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 1083
1084 // reuse final grades if there
1085 if (array_key_exists('finalgrades', $category_array)) {
1086 $result['finalgrades'] = $category_array['finalgrades'];
1087 }
1088
1089 // recursively resort children
1090 if (!empty($category_array['children'])) {
1091 $result['children'] = array();
29d509f5 1092 //process the category item first
7bac3777 1093 $child = null;
b79fe189 1094
1095 foreach ($category_array['children'] as $oldorder=>$child_array) {
1096
314c4336 1097 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
7bac3777
AD
1098 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1099 if (!empty($child)) {
1100 $result['children'][$sortorder] = $child;
1101 }
29d509f5 1102 }
2b0f65e2 1103 }
b79fe189 1104
1105 foreach ($category_array['children'] as $oldorder=>$child_array) {
1106
29d509f5 1107 if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
7bac3777
AD
1108 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1109 if (!empty($child)) {
1110 $result['children'][++$sortorder] = $child;
1111 }
b3ac6c3e 1112 }
1113 }
1114 }
1115
1116 return $result;
ce385eb4 1117 }
7c8a963f 1118
1119 /**
4a490db0 1120 * Fetches and returns all the children categories and/or grade_items belonging to this category.
1121 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 1122 * as well as all levels (0). The elements are indexed by sort order.
b79fe189 1123 *
1124 * @param bool $include_category_items Whether or not to include category grade_items in the children array
7c8a963f 1125 * @return array Array of child objects (grade_category and grade_item).
1126 */
da3801e8 1127 public function get_children($include_category_items=false) {
1128 global $DB;
b3ac6c3e 1129
1130 // This function must be as fast as possible ;-)
1131 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
1132 // we have to limit the number of queries though, because it will be used often in grade reports
1133
da3801e8 1134 $cats = $DB->get_records('grade_categories', array('courseid' => $this->courseid));
1135 $items = $DB->get_records('grade_items', array('courseid' => $this->courseid));
4a490db0 1136
b3ac6c3e 1137 // init children array first
1138 foreach ($cats as $catid=>$cat) {
1139 $cats[$catid]->children = array();
27f95e9b 1140 }
4a490db0 1141
b3ac6c3e 1142 //first attach items to cats and add category sortorder
1143 foreach ($items as $item) {
b79fe189 1144
b3ac6c3e 1145 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
1146 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 1147
b3ac6c3e 1148 if (!$include_category_items) {
1149 continue;
1150 }
1151 $categoryid = $item->iteminstance;
b79fe189 1152
b3ac6c3e 1153 } else {
1154 $categoryid = $item->categoryid;
aeacefdb
AD
1155 if (empty($categoryid)) {
1156 debugging('Found a grade item that isnt in a category');
1157 }
b3ac6c3e 1158 }
1159
1160 // prevent problems with duplicate sortorders in db
1161 $sortorder = $item->sortorder;
b79fe189 1162
aeacefdb
AD
1163 while (array_key_exists($categoryid, $cats)
1164 && array_key_exists($sortorder, $cats[$categoryid]->children)) {
1165
b3ac6c3e 1166 $sortorder++;
1167 }
1168
1169 $cats[$categoryid]->children[$sortorder] = $item;
1170
1171 }
1172
1173 // now find the requested category and connect categories as children
1174 $category = false;
b79fe189 1175
b3ac6c3e 1176 foreach ($cats as $catid=>$cat) {
b79fe189 1177
ec3717e1 1178 if (empty($cat->parent)) {
b79fe189 1179
ec3717e1 1180 if ($cat->path !== '/'.$cat->id.'/') {
1181 $grade_category = new grade_category($cat, false);
1182 $grade_category->path = '/'.$cat->id.'/';
1183 $grade_category->depth = 1;
1184 $grade_category->update('system');
1185 return $this->get_children($include_category_items);
1186 }
b79fe189 1187
ec3717e1 1188 } else {
b79fe189 1189
ec3717e1 1190 if (empty($cat->path) or !preg_match('|/'.$cat->parent.'/'.$cat->id.'/$|', $cat->path)) {
1191 //fix paths and depts
1192 static $recursioncounter = 0; // prevents infinite recursion
1193 $recursioncounter++;
b79fe189 1194
da3801e8 1195 if ($recursioncounter < 5) {
ec3717e1 1196 // fix paths and depths!
1197 $grade_category = new grade_category($cat, false);
1198 $grade_category->depth = 0;
1199 $grade_category->path = null;
1200 $grade_category->update('system');
1201 return $this->get_children($include_category_items);
1202 }
da3801e8 1203 }
b3ac6c3e 1204 // prevent problems with duplicate sortorders in db
1205 $sortorder = $cat->sortorder;
b79fe189 1206
1207 while (array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 1208 //debugging("$sortorder exists in cat loop");
b3ac6c3e 1209 $sortorder++;
1210 }
1211
65370356 1212 $cats[$cat->parent]->children[$sortorder] = &$cats[$catid];
b3ac6c3e 1213 }
f3ac8eb4 1214
b3ac6c3e 1215 if ($catid == $this->id) {
1216 $category = &$cats[$catid];
1217 }
1218 }
1219
1220 unset($items); // not needed
1221 unset($cats); // not needed
1222
f3ac8eb4 1223 $children_array = grade_category::_get_children_recursion($category);
b3ac6c3e 1224
1225 ksort($children_array);
1226
1227 return $children_array;
1228
1229 }
1230
b79fe189 1231 /**
1232 * Private method used to retrieve all children of this category recursively
1233 *
1234 * @param grade_category $category Source of current recursion
a153c9f2 1235 * @return array An array of child grade categories
b79fe189 1236 */
22a9b6d8 1237 private static function _get_children_recursion($category) {
b3ac6c3e 1238
1239 $children_array = array();
b79fe189 1240 foreach ($category->children as $sortorder=>$child) {
1241
b3ac6c3e 1242 if (array_key_exists('itemtype', $child)) {
f3ac8eb4 1243 $grade_item = new grade_item($child, false);
b79fe189 1244
4faf5f99 1245 if (in_array($grade_item->itemtype, array('course', 'category'))) {
1246 $type = $grade_item->itemtype.'item';
1247 $depth = $category->depth;
b79fe189 1248
314c4336 1249 } else {
1250 $type = 'item';
1251 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 1252 }
4faf5f99 1253 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 1254
7c8a963f 1255 } else {
f3ac8eb4 1256 $children = grade_category::_get_children_recursion($child);
1257 $grade_category = new grade_category($child, false);
b79fe189 1258
b3ac6c3e 1259 if (empty($children)) {
314c4336 1260 $children = array();
7c8a963f 1261 }
4faf5f99 1262 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
314c4336 1263 }
27f95e9b 1264 }
1265
b3ac6c3e 1266 // sort the array
1267 ksort($children_array);
1268
27f95e9b 1269 return $children_array;
1270 }
4a490db0 1271
f151b073 1272 /**
a4d76049 1273 * Uses {@link get_grade_item()} to load or create a grade_item, then saves it as $this->grade_item.
a153c9f2
AD
1274 *
1275 * @return grade_item
f151b073 1276 */
da3801e8 1277 public function load_grade_item() {
ac9b0805 1278 if (empty($this->grade_item)) {
1279 $this->grade_item = $this->get_grade_item();
1280 }
ab53054f 1281 return $this->grade_item;
1282 }
4a490db0 1283
ab53054f 1284 /**
a153c9f2
AD
1285 * Retrieves this grade categories' associated grade_item from the database
1286 *
1287 * If no grade_item exists yet, creates one.
1288 *
1289 * @return grade_item
ab53054f 1290 */
da3801e8 1291 public function get_grade_item() {
c91ed4be 1292 if (empty($this->id)) {
1293 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
1294 return false;
1295 }
1296
b3ac6c3e 1297 if (empty($this->parent)) {
1298 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
1299
1300 } else {
1301 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
1302 }
4ac209d5 1303
f3ac8eb4 1304 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 1305 // create a new one
f3ac8eb4 1306 $grade_item = new grade_item($params, false);
b8ff92b6 1307 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 1308 $grade_item->insert('system');
4a490db0 1309
b79fe189 1310 } else if (count($grade_items) == 1) {
b8ff92b6 1311 // found existing one
1312 $grade_item = reset($grade_items);
4a490db0 1313
b8ff92b6 1314 } else {
1315 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 1316 // return first one
1317 $grade_item = reset($grade_items);
2c72af1f 1318 }
1319
ab53054f 1320 return $grade_item;
f151b073 1321 }
8c846243 1322
1323 /**
a153c9f2
AD
1324 * Uses $this->parent to instantiate $this->parent_category based on the referenced record in the DB
1325 *
1326 * @return grade_category The parent category
8c846243 1327 */
da3801e8 1328 public function load_parent_category() {
8c846243 1329 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 1330 $this->parent_category = $this->get_parent_category();
8c846243 1331 }
1332 return $this->parent_category;
4a490db0 1333 }
1334
ab53054f 1335 /**
a153c9f2
AD
1336 * Uses $this->parent to instantiate and return a grade_category object
1337 *
1338 * @return grade_category Returns the parent category or null if this category has no parent
ab53054f 1339 */
da3801e8 1340 public function get_parent_category() {
ab53054f 1341 if (!empty($this->parent)) {
f3ac8eb4 1342 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 1343 return $parent_category;
ab53054f 1344 } else {
1345 return null;
1346 }
1347 }
1348
2186f72c 1349 /**
a153c9f2 1350 * Returns the most descriptive field for this grade category
b79fe189 1351 *
2186f72c 1352 * @return string name
1353 */
da3801e8 1354 public function get_name() {
1355 global $DB;
8f6fdf43 1356 // For a course category, we return the course name if the fullname is set to '?' in the DB (empty in the category edit form)
1357 if (empty($this->parent) && $this->fullname == '?') {
da3801e8 1358 $course = $DB->get_record('course', array('id'=> $this->courseid));
410753fb 1359 return format_string($course->fullname);
b79fe189 1360
314c4336 1361 } else {
1362 return $this->fullname;
1363 }
2186f72c 1364 }
c91ed4be 1365
0fc7f624 1366 /**
a153c9f2 1367 * Sets this category's parent id
b79fe189 1368 *
a153c9f2
AD
1369 * @param int $parentid The ID of the category that is the new parent to $this
1370 * @param string $source From where was the object updated (mod/forum, manual, etc.)
1371 * @return bool success
0fc7f624 1372 */
da3801e8 1373 public function set_parent($parentid, $source=null) {
f13002d5 1374 if ($this->parent == $parentid) {
1375 return true;
1376 }
1377
1378 if ($parentid == $this->id) {
2f137aa1 1379 print_error('cannotassignselfasparent');
f13002d5 1380 }
1381
1382 if (empty($this->parent) and $this->is_course_category()) {
2f137aa1 1383 print_error('cannothaveparentcate');
b3ac6c3e 1384 }
f13002d5 1385
1386 // find parent and check course id
f3ac8eb4 1387 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 1388 return false;
1389 }
1390
f8e6e4db 1391 $this->force_regrading();
b3ac6c3e 1392
1393 // set new parent category
f8e6e4db 1394 $this->parent = $parent_category->id;
1395 $this->parent_category =& $parent_category;
b3ac6c3e 1396 $this->path = null; // remove old path and depth - will be recalculated in update()
ec3717e1 1397 $this->depth = 0; // remove old path and depth - will be recalculated in update()
f8e6e4db 1398 $this->update($source);
b3ac6c3e 1399
15b462da 1400 return $this->update($source);
b3ac6c3e 1401 }
1402
1403 /**
a153c9f2 1404 * Returns the final grade values for this grade category.
b79fe189 1405 *
a153c9f2 1406 * @param int $userid Optional user ID to retrieve a single user's final grade
b3ac6c3e 1407 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
1408 */
b79fe189 1409 public function get_final($userid=null) {
b3ac6c3e 1410 $this->load_grade_item();
1411 return $this->grade_item->get_final($userid);
0fc7f624 1412 }
4a490db0 1413
0fc7f624 1414 /**
a153c9f2
AD
1415 * Returns the sortorder of the grade categories' associated grade_item
1416 *
1417 * This method is also available in grade_item for cases where the object type is not known.
b79fe189 1418 *
0fc7f624 1419 * @return int Sort order
1420 */
da3801e8 1421 public function get_sortorder() {
b3ac6c3e 1422 $this->load_grade_item();
1423 return $this->grade_item->get_sortorder();
0fc7f624 1424 }
1425
be7c0693 1426 /**
a153c9f2
AD
1427 * Returns the idnumber of the grade categories' associated grade_item.
1428 *
1429 * This method is also available in grade_item for cases where the object type is not known.
b79fe189 1430 *
be7c0693 1431 * @return string idnumber
1432 */
da3801e8 1433 public function get_idnumber() {
be7c0693 1434 $this->load_grade_item();
1435 return $this->grade_item->get_idnumber();
1436 }
1437
0fc7f624 1438 /**
a153c9f2
AD
1439 * Sets the sortorder variable for this category.
1440 *
4a490db0 1441 * This method is also available in grade_item, for cases where the object type is not know.
b79fe189 1442 *
1443 * @param int $sortorder The sortorder to assign to this category
0fc7f624 1444 */
da3801e8 1445 public function set_sortorder($sortorder) {
b3ac6c3e 1446 $this->load_grade_item();
1447 $this->grade_item->set_sortorder($sortorder);
1448 }
1449
6639ead3 1450 /**
a153c9f2 1451 * Move this category after the given sortorder
b79fe189 1452 *
a153c9f2 1453 * Does not change the parent
b79fe189 1454 *
a153c9f2 1455 * @param int $sortorder to place after.
b79fe189 1456 * @return void
6639ead3 1457 */
da3801e8 1458 public function move_after_sortorder($sortorder) {
f13002d5 1459 $this->load_grade_item();
1460 $this->grade_item->move_after_sortorder($sortorder);
1461 }
1462
b3ac6c3e 1463 /**
f13002d5 1464 * Return true if this is the top most category that represents the total course grade.
b79fe189 1465 *
a153c9f2 1466 * @return bool
b3ac6c3e 1467 */
da3801e8 1468 public function is_course_category() {
b3ac6c3e 1469 $this->load_grade_item();
1470 return $this->grade_item->is_course_item();
1471 }
1472
1473 /**
a153c9f2 1474 * Return the course level grade_category object
b79fe189 1475 *
1476 * @param int $courseid The Course ID
a153c9f2 1477 * @return grade_category Returns the course level grade_category instance
b3ac6c3e 1478 */
22a9b6d8 1479 public static function fetch_course_category($courseid) {
a4503119 1480 if (empty($courseid)) {
1481 debugging('Missing course id!');
1482 return false;
1483 }
b3ac6c3e 1484
1485 // course category has no parent
f3ac8eb4 1486 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
b3ac6c3e 1487 return $course_category;
1488 }
1489
1490 // create a new one
f3ac8eb4 1491 $course_category = new grade_category();
b3ac6c3e 1492 $course_category->insert_course_category($courseid);
1493
1494 return $course_category;
0fc7f624 1495 }
4ac209d5 1496
79eabc2a 1497 /**
1498 * Is grading object editable?
b79fe189 1499 *
a153c9f2 1500 * @return bool
79eabc2a 1501 */
da3801e8 1502 public function is_editable() {
79eabc2a 1503 return true;
1504 }
1505
5fad5061 1506 /**
a153c9f2
AD
1507 * Returns the locked state/date of the grade categories' associated grade_item.
1508 *
1509 * This method is also available in grade_item, for cases where the object type is not known.
1510 *
1511 * @return bool
5fad5061 1512 */
da3801e8 1513 public function is_locked() {
5fad5061 1514 $this->load_grade_item();
22e23c78 1515 return $this->grade_item->is_locked();
5fad5061 1516 }
1517
1518 /**
1519 * Sets the grade_item's locked variable and updates the grade_item.
a153c9f2
AD
1520 *
1521 * Calls set_locked() on the categories' grade_item
b79fe189 1522 *
1523 * @param int $lockedstate 0, 1 or a timestamp int(10) after which date the item will be locked.
1524 * @param bool $cascade lock/unlock child objects too
1525 * @param bool $refresh refresh grades when unlocking
a153c9f2 1526 * @return bool success if category locked (not all children mayb be locked though)
5fad5061 1527 */
da3801e8 1528 public function set_locked($lockedstate, $cascade=false, $refresh=true) {
5fad5061 1529 $this->load_grade_item();
2b0f65e2 1530
fb0e3570 1531 $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
1532
1533 if ($cascade) {
1534 //process all children - items and categories
f3ac8eb4 1535 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
b79fe189 1536
1537 foreach ($children as $child) {
fb0e3570 1538 $child->set_locked($lockedstate, true, false);
b79fe189 1539
fb0e3570 1540 if (empty($lockedstate) and $refresh) {
1541 //refresh when unlocking
1542 $child->refresh_grades();
1543 }
2b0f65e2 1544 }
7a7a53d3 1545 }
b79fe189 1546
f3ac8eb4 1547 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 1548
1549 foreach ($children as $child) {
fb0e3570 1550 $child->set_locked($lockedstate, true, true);
1551 }
7a7a53d3 1552 }
1553 }
2b0f65e2 1554
b121b544 1555 return $result;
5fad5061 1556 }
4a490db0 1557
a153c9f2
AD
1558 /**
1559 * Overrides grade_object::set_properties() to add special handling for changes to category aggregation types
1560 *
1561 * @param stdClass $instance the object to set the properties on
1562 * @param array|stdClass $params Either an associative array or an object containing property name, property value pairs
1563 */
79b260cc
AD
1564 public static function set_properties(&$instance, $params) {
1565 global $DB;
1566
1567 parent::set_properties($instance, $params);
1568
c1024411 1569 //if they've changed aggregation type we made need to do some fiddling to provide appropriate defaults
79b260cc
AD
1570 if (!empty($params->aggregation)) {
1571
1572 //weight and extra credit share a column :( Would like a default of 1 for weight and 0 for extra credit
1573 //Flip from the default of 0 to 1 (or vice versa) if ALL items in the category are still set to the old default.
1574 if ($params->aggregation==GRADE_AGGREGATE_WEIGHTED_MEAN || $params->aggregation==GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
1575 $sql = $defaultaggregationcoef = null;
7ad5a627 1576
79b260cc
AD
1577 if ($params->aggregation==GRADE_AGGREGATE_WEIGHTED_MEAN) {
1578 //if all items in this category have aggregation coefficient of 0 we can change it to 1 ie evenly weighted
1579 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=0";
1580 $defaultaggregationcoef = 1;
1581 } else if ($params->aggregation==GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
1582 //if all items in this category have aggregation coefficient of 1 we can change it to 0 ie no extra credit
1583 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=1";
1584 $defaultaggregationcoef = 0;
1585 }
1586
1587 $params = array('categoryid'=>$instance->id);
1588 $count = $DB->count_records_sql($sql, $params);
1589 if ($count===0) { //category is either empty or all items are set to a default value so we can switch defaults
1590 $params['aggregationcoef'] = $defaultaggregationcoef;
1591 $DB->execute("update {grade_items} set aggregationcoef=:aggregationcoef where categoryid=:categoryid",$params);
1592 }
1593 }
1594 }
1595 }
1596
5fad5061 1597 /**
4a490db0 1598 * Sets the grade_item's hidden variable and updates the grade_item.
a153c9f2
AD
1599 *
1600 * Overrides grade_item::set_hidden() to add cascading of the hidden value to grade items in this grade category
1601 *
1602 * @param int $hidden 0 mean always visible, 1 means always hidden and a number > 1 is a timestamp to hide until
1603 * @param bool $cascade apply to child objects too
5fad5061 1604 */
da3801e8 1605 public function set_hidden($hidden, $cascade=false) {
5fad5061 1606 $this->load_grade_item();
a25bb902 1607 //this hides the associated grade item (the course total)
1762a264 1608 $this->grade_item->set_hidden($hidden, $cascade);
a25bb902
AD
1609 //this hides the category itself and everything it contains
1610 parent::set_hidden($hidden, $cascade);
b79fe189 1611
f60c61b1 1612 if ($cascade) {
b79fe189 1613
f3ac8eb4 1614 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
b79fe189 1615
1616 foreach ($children as $child) {
f60c61b1 1617 $child->set_hidden($hidden, $cascade);
1618 }
f13002d5 1619 }
b79fe189 1620
f3ac8eb4 1621 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 1622
1623 foreach ($children as $child) {
f60c61b1 1624 $child->set_hidden($hidden, $cascade);
1625 }
f13002d5 1626 }
1627 }
d90aa634
AD
1628
1629 //if marking category visible make sure parent category is visible MDL-21367
1630 if( !$hidden ) {
1631 $category_array = grade_category::fetch_all(array('id'=>$this->parent));
1632 if ($category_array && array_key_exists($this->parent, $category_array)) {
1633 $category = $category_array[$this->parent];
1634 //call set_hidden on the category regardless of whether it is hidden as its parent might be hidden
1635 //if($category->is_hidden()) {
1636 $category->set_hidden($hidden, false);
1637 //}
1638 }
1639 }
5fad5061 1640 }
89a5f827 1641
190af29f 1642 /**
1643 * Applies default settings on this category
a153c9f2
AD
1644 *
1645 * @return bool True if anything changed
190af29f 1646 */
da3801e8 1647 public function apply_default_settings() {
190af29f 1648 global $CFG;
1649
1650 foreach ($this->forceable as $property) {
b79fe189 1651
190af29f 1652 if (isset($CFG->{"grade_$property"})) {
b79fe189 1653
190af29f 1654 if ($CFG->{"grade_$property"} == -1) {
1655 continue; //temporary bc before version bump
1656 }
1657 $this->$property = $CFG->{"grade_$property"};
1658 }
1659 }
1660 }
1661
89a5f827 1662 /**
1663 * Applies forced settings on this category
a153c9f2
AD
1664 *
1665 * @return bool True if anything changed
89a5f827 1666 */
da3801e8 1667 public function apply_forced_settings() {
89a5f827 1668 global $CFG;
1669
1670 $updated = false;
b79fe189 1671
89a5f827 1672 foreach ($this->forceable as $property) {
b79fe189 1673
1674 if (isset($CFG->{"grade_$property"}) and isset($CFG->{"grade_{$property}_flag"}) and
1675 ((int) $CFG->{"grade_{$property}_flag"} & 1)) {
1676
190af29f 1677 if ($CFG->{"grade_$property"} == -1) {
1678 continue; //temporary bc before version bump
1679 }
89a5f827 1680 $this->$property = $CFG->{"grade_$property"};
1681 $updated = true;
1682 }
1683 }
1684
1685 return $updated;
1686 }
1687
1688 /**
1689 * Notification of change in forced category settings.
b79fe189 1690 *
a153c9f2 1691 * Causes all course and category grade items to be marked as needing to be updated
89a5f827 1692 */
da3801e8 1693 public static function updated_forced_settings() {
5b0af8c5 1694 global $CFG, $DB;
1695 $params = array(1, 'course', 'category');
1696 $sql = "UPDATE {grade_items} SET needsupdate=? WHERE itemtype=? or itemtype=?";
1697 $DB->execute($sql, $params);
89a5f827 1698 }
4a490db0 1699}