MDL-46139 Grades: Language change "weight -> calculated weight"
[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
0e999796
AD
572 $minvisible = (bool) get_config('moodle', 'grade_report_showmin');
573
b79fe189 574 // normalize the grades first - all will have value 0...1
d5f0aa01 575 // ungraded items are not used in aggregation
23207a1a 576 foreach ($grade_values as $itemid=>$v) {
b79fe189 577
b8ff92b6 578 if (is_null($v)) {
579 // null means no grade
23207a1a 580 unset($grade_values[$itemid]);
581 continue;
b79fe189 582
23207a1a 583 } else if (in_array($itemid, $excluded)) {
584 unset($grade_values[$itemid]);
b8ff92b6 585 continue;
0aa32279 586 }
0e999796
AD
587 // If grademin is hidden, set it to 0.
588 if (!$minvisible and $items[$itemid]->gradetype != GRADE_TYPE_SCALE) {
589 $items[$itemid]->grademin = 0;
590 }
9a68cffc 591 $grade_values[$itemid] = grade_grade::standardise_score($v, $items[$itemid]->grademin, $items[$itemid]->grademax, 0, 1);
0aa32279 592 }
dda0c7e6 593
eacd3700 594 // use min grade if grade missing for these types
c2efb501 595 if (!$this->aggregateonlygraded) {
b79fe189 596
597 foreach ($items as $itemid=>$value) {
598
c2efb501 599 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
600 $grade_values[$itemid] = 0;
eacd3700 601 }
c2efb501 602 }
eacd3700 603 }
604
605 // limit and sort
a9e38ac8 606 $this->apply_limit_rules($grade_values, $items);
9580a21f 607 asort($grade_values, SORT_NUMERIC);
4a490db0 608
d5f0aa01 609 // let's see we have still enough grades to do any statistics
9580a21f 610 if (count($grade_values) == 0) {
ac9b0805 611 // not enough attempts yet
f8e6e4db 612 $grade->finalgrade = null;
b79fe189 613
66690b69 614 if (!is_null($oldfinalgrade)) {
0758a08e 615 $grade->update('aggregation');
b8ff92b6 616 }
617 return;
618 }
2df71235 619
d297269d 620 // do the maths
5232d3f2
DW
621 $result = $this->aggregate_values_and_adjust_bounds($grade_values, $items);
622 $agg_grade = $result['grade'];
d297269d 623
0e999796
AD
624 if (!$minvisible and $this->grade_item->gradetype != GRADE_TYPE_SCALE) {
625 $this->grade_item->grademin = 0;
626 }
627
0758a08e 628 // recalculate the grade back to requested range
5232d3f2 629 $finalgrade = grade_grade::standardise_score($agg_grade, 0, 1, $result['grademin'], $result['grademax']);
d297269d 630
653a8648 631 $grade->finalgrade = $this->grade_item->bounded_grade($finalgrade);
d297269d 632
633 // update in db if changed
25bcd908 634 if (grade_floats_different($grade->finalgrade, $oldfinalgrade)) {
0758a08e 635 $grade->update('aggregation');
d297269d 636 }
637
638 return;
639 }
640
89a5f827 641 /**
5232d3f2 642 * Internal function that calculates the aggregated grade and new min/max for this grade category
b79fe189 643 *
a153c9f2 644 * Must be public as it is used by grade_grade::get_hiding_affected()
b79fe189 645 *
a153c9f2
AD
646 * @param array $grade_values An array of values to be aggregated
647 * @param array $items The array of grade_items
d6caf637 648 * @since Moodle 2.6.5, 2.7.2
5232d3f2
DW
649 * @return array containing values for:
650 * 'grade' => the new calculated grade
651 * 'grademin' => the new calculated min grade for the category
652 * 'grademax' => the new calculated max grade for the category
89a5f827 653 */
5232d3f2
DW
654 public function aggregate_values_and_adjust_bounds($grade_values, $items) {
655 $category_item = $this->get_grade_item();
656 $grademin = $category_item->grademin;
657 $grademax = $category_item->grademax;
658
b8ff92b6 659 switch ($this->aggregation) {
b79fe189 660
c2efb501 661 case GRADE_AGGREGATE_MEDIAN: // Middle point value in the set: ignores frequencies
9580a21f 662 $num = count($grade_values);
c186c7b2 663 $grades = array_values($grade_values);
b79fe189 664
c186c7b2 665 if ($num % 2 == 0) {
9c8d38fa 666 $agg_grade = ($grades[intval($num/2)-1] + $grades[intval($num/2)]) / 2;
b79fe189 667
b8ff92b6 668 } else {
9c8d38fa 669 $agg_grade = $grades[intval(($num/2)-0.5)];
b8ff92b6 670 }
671 break;
ac9b0805 672
c2efb501 673 case GRADE_AGGREGATE_MIN:
9c8d38fa 674 $agg_grade = reset($grade_values);
b8ff92b6 675 break;
676
c2efb501 677 case GRADE_AGGREGATE_MAX:
9c8d38fa 678 $agg_grade = array_pop($grade_values);
b8ff92b6 679 break;
680
c2efb501 681 case GRADE_AGGREGATE_MODE: // the most common value, average used if multimode
0198929c 682 // array_count_values only counts INT and STRING, so if grades are floats we must convert them to string
683 $converted_grade_values = array();
684
685 foreach ($grade_values as $k => $gv) {
b79fe189 686
0198929c 687 if (!is_int($gv) && !is_string($gv)) {
688 $converted_grade_values[$k] = (string) $gv;
b79fe189 689
0198929c 690 } else {
691 $converted_grade_values[$k] = $gv;
692 }
693 }
694
695 $freq = array_count_values($converted_grade_values);
95affb8a 696 arsort($freq); // sort by frequency keeping keys
697 $top = reset($freq); // highest frequency count
698 $modes = array_keys($freq, $top); // search for all modes (have the same highest count)
f7d515b6 699 rsort($modes, SORT_NUMERIC); // get highest mode
9c8d38fa 700 $agg_grade = reset($modes);
d5fab31f 701 break;
95affb8a 702
1426edac 703 case GRADE_AGGREGATE_WEIGHTED_MEAN: // Weighted average of all existing final grades, weight specified in coef
9580a21f 704 $weightsum = 0;
705 $sum = 0;
b79fe189 706
707 foreach ($grade_values as $itemid=>$grade_value) {
708
eacd3700 709 if ($items[$itemid]->aggregationcoef <= 0) {
9580a21f 710 continue;
711 }
eacd3700 712 $weightsum += $items[$itemid]->aggregationcoef;
713 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 714 }
b79fe189 715
9580a21f 716 if ($weightsum == 0) {
9c8d38fa 717 $agg_grade = null;
b79fe189 718
9580a21f 719 } else {
9c8d38fa 720 $agg_grade = $sum / $weightsum;
9580a21f 721 }
722 break;
723
d9ae2ab5 724 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
725 // Weighted average of all existing final grades with optional extra credit flag,
f7d515b6 726 // weight is the range of grade (usually grademax)
1426edac 727 $weightsum = 0;
d9ae2ab5 728 $sum = null;
b79fe189 729
730 foreach ($grade_values as $itemid=>$grade_value) {
1426edac 731 $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
b79fe189 732
1426edac 733 if ($weight <= 0) {
734 continue;
735 }
b79fe189 736
d9ae2ab5 737 if ($items[$itemid]->aggregationcoef == 0) {
738 $weightsum += $weight;
739 }
740 $sum += $weight * $grade_value;
1426edac 741 }
b79fe189 742
1426edac 743 if ($weightsum == 0) {
d9ae2ab5 744 $agg_grade = $sum; // only extra credits
b79fe189 745
1426edac 746 } else {
747 $agg_grade = $sum / $weightsum;
748 }
749 break;
750
c2efb501 751 case GRADE_AGGREGATE_EXTRACREDIT_MEAN: // special average
9580a21f 752 $num = 0;
d9ae2ab5 753 $sum = null;
b79fe189 754
755 foreach ($grade_values as $itemid=>$grade_value) {
756
eacd3700 757 if ($items[$itemid]->aggregationcoef == 0) {
9580a21f 758 $num += 1;
759 $sum += $grade_value;
b79fe189 760
eacd3700 761 } else if ($items[$itemid]->aggregationcoef > 0) {
762 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 763 }
764 }
b79fe189 765
9580a21f 766 if ($num == 0) {
9c8d38fa 767 $agg_grade = $sum; // only extra credits or wrong coefs
b79fe189 768
9580a21f 769 } else {
9c8d38fa 770 $agg_grade = $sum / $num;
9580a21f 771 }
772 break;
773
5232d3f2
DW
774 case GRADE_AGGREGATE_SUM: // Add up all the items.
775 $num = count($grade_values);
5232d3f2
DW
776 // Excluded items can affect the grademax for this grade_item.
777 $grademin = 0;
778 $grademax = 0;
b50b12b3 779 $sum = 0;
5232d3f2 780 foreach ($grade_values as $itemid => $grade_value) {
b50b12b3 781 $sum += $grade_value * ($items[$itemid]->grademax - $items[$itemid]->grademin);
5232d3f2
DW
782 $grademin += $items[$itemid]->grademin;
783 $grademax += $items[$itemid]->grademax;
784 }
b50b12b3
DW
785
786 $agg_grade = $sum / ($grademax - $grademin);
5232d3f2
DW
787 break;
788
c2efb501 789 case GRADE_AGGREGATE_MEAN: // Arithmetic average of all grade items (if ungraded aggregated, NULL counted as minimum)
ac9b0805 790 default:
9580a21f 791 $num = count($grade_values);
792 $sum = array_sum($grade_values);
9c8d38fa 793 $agg_grade = $sum / $num;
b8ff92b6 794 break;
795 }
796
5232d3f2
DW
797 return array('grade' => $agg_grade, 'grademin' => $grademin, 'grademax' => $grademax);
798 }
799
800 /**
801 * Internal function that calculates the aggregated grade for this grade category
802 *
803 * Must be public as it is used by grade_grade::get_hiding_affected()
804 *
805 * @deprecated since Moodle 2.8
806 * @param array $grade_values An array of values to be aggregated
807 * @param array $items The array of grade_items
808 * @return float The aggregate grade for this grade category
809 */
810 public function aggregate_values($grade_values, $items) {
811 debugging('grade_category::aggregate_values() is deprecated.
812 Call grade_category::aggregate_values_and_adjust_bounds() instead.', DEBUG_DEVELOPER);
813 $result = $this->aggregate_values_and_adjust_bounds($grade_values, $items);
814 return $result['grade'];
0aa32279 815 }
0758a08e 816
3a03653e 817 /**
a153c9f2
AD
818 * Some aggregation types may automatically update max grade
819 *
3a03653e 820 * @param array $items sub items
3a03653e 821 */
822 private function auto_update_max($items) {
823 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
824 // not needed at all
825 return;
826 }
827
828 if (!$items) {
b79fe189 829
3a03653e 830 if ($this->grade_item->grademax != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
831 $this->grade_item->grademax = 0;
832 $this->grade_item->grademin = 0;
833 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
834 $this->grade_item->update('aggregation');
835 }
836 return;
837 }
838
59080eee 839 //find max grade possible
840 $maxes = array();
b79fe189 841
3a03653e 842 foreach ($items as $item) {
b79fe189 843
3a03653e 844 if ($item->aggregationcoef > 0) {
845 // extra credit from this activity - does not affect total
846 continue;
847 }
b79fe189 848
3a03653e 849 if ($item->gradetype == GRADE_TYPE_VALUE) {
b9b199be 850 $maxes[$item->id] = $item->grademax;
b79fe189 851
3a03653e 852 } else if ($item->gradetype == GRADE_TYPE_SCALE) {
b9b199be 853 $maxes[$item->id] = $item->grademax; // 0 = nograde, 1 = first scale item, 2 = second scale item
3a03653e 854 }
855 }
59080eee 856 // apply droplow and keephigh
a9e38ac8 857 $this->apply_limit_rules($maxes, $items);
59080eee 858 $max = array_sum($maxes);
3a03653e 859
59080eee 860 // update db if anything changed
861 if ($this->grade_item->grademax != $max or $this->grade_item->grademin != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
3a03653e 862 $this->grade_item->grademax = $max;
863 $this->grade_item->grademin = 0;
864 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
865 $this->grade_item->update('aggregation');
866 }
867 }
868
0758a08e 869 /**
a153c9f2 870 * Internal function for category grades summing
b79fe189 871 *
a153c9f2
AD
872 * @param grade_grade $grade The grade item
873 * @param float $oldfinalgrade Old Final grade
874 * @param array $items Grade items
875 * @param array $grade_values Grade values
876 * @param array $excluded Excluded
0758a08e 877 */
da3801e8 878 private function sum_grades(&$grade, $oldfinalgrade, $items, $grade_values, $excluded) {
653a8648 879 if (empty($items)) {
880 return null;
881 }
882
c1024411 883 // ungraded and excluded items are not used in aggregation
0758a08e 884 foreach ($grade_values as $itemid=>$v) {
b79fe189 885
0758a08e 886 if (is_null($v)) {
887 unset($grade_values[$itemid]);
b79fe189 888
0758a08e 889 } else if (in_array($itemid, $excluded)) {
890 unset($grade_values[$itemid]);
891 }
892 }
893
d28f25a4 894 // use 0 if grade missing, droplow used and aggregating all items
895 if (!$this->aggregateonlygraded and !empty($this->droplow)) {
b79fe189 896
897 foreach ($items as $itemid=>$value) {
898
d28f25a4 899 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
900 $grade_values[$itemid] = 0;
901 }
902 }
903 }
904
a9e38ac8 905 $this->apply_limit_rules($grade_values, $items);
0758a08e 906
907 $sum = array_sum($grade_values);
653a8648 908 $grade->finalgrade = $this->grade_item->bounded_grade($sum);
0758a08e 909
910 // update in db if changed
25bcd908 911 if (grade_floats_different($grade->finalgrade, $oldfinalgrade)) {
0758a08e 912 $grade->update('aggregation');
913 }
914
915 return;
916 }
917
adc2f286 918 /**
a153c9f2 919 * Given an array of grade values (numerical indices) applies droplow or keephigh rules to limit the final array.
b79fe189 920 *
a153c9f2 921 * @param array $grade_values itemid=>$grade_value float
b79fe189 922 * @param array $items grade item objects
adc2f286 923 * @return array Limited grades.
924 */
a9e38ac8 925 public function apply_limit_rules(&$grade_values, $items) {
926 $extraused = $this->is_extracredit_used();
927
adc2f286 928 if (!empty($this->droplow)) {
a9e38ac8 929 asort($grade_values, SORT_NUMERIC);
930 $dropped = 0;
b79fe189 931
fb80cb2a
AD
932 // If we have fewer grade items available to drop than $this->droplow, use this flag to escape the loop
933 // May occur because of "extra credit" or if droplow is higher than the number of grade items
934 $droppedsomething = true;
b79fe189 935
fb80cb2a
AD
936 while ($dropped < $this->droplow && $droppedsomething) {
937 $droppedsomething = false;
b79fe189 938
fb80cb2a 939 $grade_keys = array_keys($grade_values);
aee968da
AD
940 $gradekeycount = count($grade_keys);
941
942 if ($gradekeycount === 0) {
fb80cb2a
AD
943 //We've dropped all grade items
944 break;
945 }
b79fe189 946
fb80cb2a
AD
947 $originalindex = $founditemid = $foundmax = null;
948
949 // Find the first remaining grade item that is available to be dropped
950 foreach ($grade_keys as $gradekeyindex=>$gradekey) {
951 if (!$extraused || $items[$gradekey]->aggregationcoef <= 0) {
952 // Found a non-extra credit grade item that is eligible to be dropped
953 $originalindex = $gradekeyindex;
954 $founditemid = $grade_keys[$originalindex];
955 $foundmax = $items[$founditemid]->grademax;
956 break;
a9e38ac8 957 }
fb80cb2a 958 }
b79fe189 959
fb80cb2a
AD
960 if (empty($founditemid)) {
961 // No grade items available to drop
a9e38ac8 962 break;
59080eee 963 }
fb80cb2a
AD
964
965 // Now iterate over the remaining grade items
966 // We're looking for other grade items with the same grade value but a higher grademax
967 $i = 1;
aee968da 968 while ($originalindex + $i < $gradekeycount) {
52929486 969
fb80cb2a 970 $possibleitemid = $grade_keys[$originalindex+$i];
52929486
AD
971 $i++;
972
fb80cb2a
AD
973 if ($grade_values[$founditemid] != $grade_values[$possibleitemid]) {
974 // The next grade item has a different grade value. Stop looking.
975 break;
976 }
977
978 if ($extraused && $items[$possibleitemid]->aggregationcoef > 0) {
979 // Don't drop extra credit grade items. Continue the search.
980 continue;
981 }
982
983 if ($foundmax < $items[$possibleitemid]->grademax) {
984 // Found a grade item with the same grade value and a higher grademax
985 $foundmax = $items[$possibleitemid]->grademax;
986 $founditemid = $possibleitemid;
987 // Continue searching to see if there is an even higher grademax
988 }
fb80cb2a
AD
989 }
990
991 // Now drop whatever grade item we have found
992 unset($grade_values[$founditemid]);
993 $dropped++;
994 $droppedsomething = true;
adc2f286 995 }
a9e38ac8 996
997 } else if (!empty($this->keephigh)) {
998 arsort($grade_values, SORT_NUMERIC);
999 $kept = 0;
b79fe189 1000
a9e38ac8 1001 foreach ($grade_values as $itemid=>$value) {
b79fe189 1002
a9e38ac8 1003 if ($extraused and $items[$itemid]->aggregationcoef > 0) {
1004 // we keep all extra credits
b79fe189 1005
a9e38ac8 1006 } else if ($kept < $this->keephigh) {
1007 $kept++;
b79fe189 1008
a9e38ac8 1009 } else {
1010 unset($grade_values[$itemid]);
1011 }
adc2f286 1012 }
1013 }
0aa32279 1014 }
1015
793253ae 1016 /**
1017 * Returns true if category uses extra credit of any kind
b79fe189 1018 *
a153c9f2 1019 * @return bool True if extra credit used
793253ae 1020 */
134c514b
RT
1021 public function is_extracredit_used() {
1022 return self::aggregation_uses_extracredit($this->aggregation);
1023 }
1024
1025 /**
1026 * Returns true if aggregation passed is using extracredit.
1027 *
1028 * @param int $aggregation Aggregation const.
1029 * @return bool True if extra credit used
1030 */
1031 public static function aggregation_uses_extracredit($aggregation) {
1032 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1033 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1034 or $aggregation == GRADE_AGGREGATE_SUM);
793253ae 1035 }
1036
9580a21f 1037 /**
f7d515b6 1038 * Returns true if category uses special aggregation coefficient
b79fe189 1039 *
a153c9f2 1040 * @return bool True if an aggregation coefficient is being used
9580a21f 1041 */
4e9ca991 1042 public function is_aggregationcoef_used() {
134c514b
RT
1043 return self::aggregation_uses_aggregationcoef($this->aggregation);
1044
1045 }
1046
1047 /**
1048 * Returns true if aggregation uses aggregationcoef
1049 *
1050 * @param int $aggregation Aggregation const.
1051 * @return bool True if an aggregation coefficient is being used
1052 */
1053 public static function aggregation_uses_aggregationcoef($aggregation) {
1054 return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN
1055 or $aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1056 or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1057 or $aggregation == GRADE_AGGREGATE_SUM);
ba74762b 1058
9580a21f 1059 }
1060
653a8648 1061 /**
a153c9f2 1062 * Recursive function to find which weight/extra credit field to use in the grade item form.
b79fe189 1063 *
a153c9f2 1064 * Inherits from a parent category if that category has aggregatesubcats set to true.
b79fe189 1065 *
a153c9f2 1066 * @param string $first Whether or not this is the first item in the recursion
b79fe189 1067 * @return string
653a8648 1068 */
1069 public function get_coefstring($first=true) {
1070 if (!is_null($this->coefstring)) {
1071 return $this->coefstring;
1072 }
1073
1074 $overriding_coefstring = null;
1075
1076 // Stop recursing upwards if this category aggregates subcats or has no parent
1077 if (!$first && !$this->aggregatesubcats) {
b79fe189 1078
121d8006 1079 if ($parent_category = $this->load_parent_category()) {
653a8648 1080 return $parent_category->get_coefstring(false);
b79fe189 1081
653a8648 1082 } else {
1083 return null;
1084 }
b79fe189 1085
1086 } else if ($first) {
1087
653a8648 1088 if (!$this->aggregatesubcats) {
b79fe189 1089
121d8006 1090 if ($parent_category = $this->load_parent_category()) {
653a8648 1091 $overriding_coefstring = $parent_category->get_coefstring(false);
1092 }
1093 }
1094 }
1095
1096 // If an overriding coefstring has trickled down from one of the parent categories, return it. Otherwise, return self.
1097 if (!is_null($overriding_coefstring)) {
1098 return $overriding_coefstring;
1099 }
1100
1101 // No parent category is overriding this category's aggregation, return its string
1102 if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
1103 $this->coefstring = 'aggregationcoefweight';
b79fe189 1104
d9ae2ab5 1105 } else if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2) {
1106 $this->coefstring = 'aggregationcoefextrasum';
b79fe189 1107
653a8648 1108 } else if ($this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
3869ab1a 1109 $this->coefstring = 'aggregationcoefextraweight';
b79fe189 1110
653a8648 1111 } else if ($this->aggregation == GRADE_AGGREGATE_SUM) {
1112 $this->coefstring = 'aggregationcoefextrasum';
b79fe189 1113
653a8648 1114 } else {
1115 $this->coefstring = 'aggregationcoef';
1116 }
1117 return $this->coefstring;
1118 }
1119
1c307f21 1120 /**
b3ac6c3e 1121 * Returns tree with all grade_items and categories as elements
b79fe189 1122 *
1123 * @param int $courseid The course ID
a153c9f2 1124 * @param bool $include_category_items as category children
b3ac6c3e 1125 * @return array
1c307f21 1126 */
da3801e8 1127 public static function fetch_course_tree($courseid, $include_category_items=false) {
f3ac8eb4 1128 $course_category = grade_category::fetch_course_category($courseid);
514a3467 1129 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
1130 'children'=>$course_category->get_children($include_category_items));
b146d984
AD
1131
1132 $course_category->sortorder = $course_category->get_sortorder();
e2bb3c92
PS
1133 $sortorder = $course_category->get_sortorder();
1134 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 1135 }
1136
b79fe189 1137 /**
a153c9f2 1138 * An internal function that recursively sorts grade categories within a course
b79fe189 1139 *
1140 * @param array $category_array The seed of the recursion
a153c9f2
AD
1141 * @param int $sortorder The current sortorder
1142 * @return array An array containing 'object', 'type', 'depth' and optionally 'children'
b79fe189 1143 */
1144 static private function _fetch_course_tree_recursion($category_array, &$sortorder) {
b3ac6c3e 1145 // update the sortorder in db if needed
b146d984
AD
1146 //NOTE: This leads to us resetting sort orders every time the categories and items page is viewed :(
1147 //if ($category_array['object']->sortorder != $sortorder) {
1148 //$category_array['object']->set_sortorder($sortorder);
1149 //}
ce385eb4 1150
7bac3777
AD
1151 if (isset($category_array['object']->gradetype) && $category_array['object']->gradetype==GRADE_TYPE_NONE) {
1152 return null;
1153 }
1154
314c4336 1155 // store the grade_item or grade_category instance with extra info
1156 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 1157
1158 // reuse final grades if there
1159 if (array_key_exists('finalgrades', $category_array)) {
1160 $result['finalgrades'] = $category_array['finalgrades'];
1161 }
1162
1163 // recursively resort children
1164 if (!empty($category_array['children'])) {
1165 $result['children'] = array();
29d509f5 1166 //process the category item first
7bac3777 1167 $child = null;
b79fe189 1168
1169 foreach ($category_array['children'] as $oldorder=>$child_array) {
1170
314c4336 1171 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
7bac3777
AD
1172 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1173 if (!empty($child)) {
1174 $result['children'][$sortorder] = $child;
1175 }
29d509f5 1176 }
2b0f65e2 1177 }
b79fe189 1178
1179 foreach ($category_array['children'] as $oldorder=>$child_array) {
1180
29d509f5 1181 if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
7bac3777
AD
1182 $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
1183 if (!empty($child)) {
1184 $result['children'][++$sortorder] = $child;
1185 }
b3ac6c3e 1186 }
1187 }
1188 }
1189
1190 return $result;
ce385eb4 1191 }
7c8a963f 1192
1193 /**
4a490db0 1194 * Fetches and returns all the children categories and/or grade_items belonging to this category.
1195 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 1196 * as well as all levels (0). The elements are indexed by sort order.
b79fe189 1197 *
1198 * @param bool $include_category_items Whether or not to include category grade_items in the children array
7c8a963f 1199 * @return array Array of child objects (grade_category and grade_item).
1200 */
da3801e8 1201 public function get_children($include_category_items=false) {
1202 global $DB;
b3ac6c3e 1203
1204 // This function must be as fast as possible ;-)
1205 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
1206 // we have to limit the number of queries though, because it will be used often in grade reports
1207
da3801e8 1208 $cats = $DB->get_records('grade_categories', array('courseid' => $this->courseid));
1209 $items = $DB->get_records('grade_items', array('courseid' => $this->courseid));
4a490db0 1210
b3ac6c3e 1211 // init children array first
1212 foreach ($cats as $catid=>$cat) {
1213 $cats[$catid]->children = array();
27f95e9b 1214 }
4a490db0 1215
b3ac6c3e 1216 //first attach items to cats and add category sortorder
1217 foreach ($items as $item) {
b79fe189 1218
b3ac6c3e 1219 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
1220 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 1221
b3ac6c3e 1222 if (!$include_category_items) {
1223 continue;
1224 }
1225 $categoryid = $item->iteminstance;
b79fe189 1226
b3ac6c3e 1227 } else {
1228 $categoryid = $item->categoryid;
63354ab5
AD
1229 if (empty($categoryid)) {
1230 debugging('Found a grade item that isnt in a category');
1231 }
b3ac6c3e 1232 }
1233
1234 // prevent problems with duplicate sortorders in db
1235 $sortorder = $item->sortorder;
b79fe189 1236
63354ab5
AD
1237 while (array_key_exists($categoryid, $cats)
1238 && array_key_exists($sortorder, $cats[$categoryid]->children)) {
1239
b3ac6c3e 1240 $sortorder++;
1241 }
1242
1243 $cats[$categoryid]->children[$sortorder] = $item;
1244
1245 }
1246
1247 // now find the requested category and connect categories as children
1248 $category = false;
b79fe189 1249
b3ac6c3e 1250 foreach ($cats as $catid=>$cat) {
b79fe189 1251
ec3717e1 1252 if (empty($cat->parent)) {
b79fe189 1253
ec3717e1 1254 if ($cat->path !== '/'.$cat->id.'/') {
1255 $grade_category = new grade_category($cat, false);
1256 $grade_category->path = '/'.$cat->id.'/';
1257 $grade_category->depth = 1;
1258 $grade_category->update('system');
1259 return $this->get_children($include_category_items);
1260 }
b79fe189 1261
ec3717e1 1262 } else {
b79fe189 1263
ec3717e1 1264 if (empty($cat->path) or !preg_match('|/'.$cat->parent.'/'.$cat->id.'/$|', $cat->path)) {
1265 //fix paths and depts
1266 static $recursioncounter = 0; // prevents infinite recursion
1267 $recursioncounter++;
b79fe189 1268
da3801e8 1269 if ($recursioncounter < 5) {
ec3717e1 1270 // fix paths and depths!
1271 $grade_category = new grade_category($cat, false);
1272 $grade_category->depth = 0;
1273 $grade_category->path = null;
1274 $grade_category->update('system');
1275 return $this->get_children($include_category_items);
1276 }
da3801e8 1277 }
b3ac6c3e 1278 // prevent problems with duplicate sortorders in db
1279 $sortorder = $cat->sortorder;
b79fe189 1280
1281 while (array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 1282 //debugging("$sortorder exists in cat loop");
b3ac6c3e 1283 $sortorder++;
1284 }
1285
65370356 1286 $cats[$cat->parent]->children[$sortorder] = &$cats[$catid];
b3ac6c3e 1287 }
f3ac8eb4 1288
b3ac6c3e 1289 if ($catid == $this->id) {
1290 $category = &$cats[$catid];
1291 }
1292 }
1293
1294 unset($items); // not needed
1295 unset($cats); // not needed
1296
f3ac8eb4 1297 $children_array = grade_category::_get_children_recursion($category);
b3ac6c3e 1298
1299 ksort($children_array);
1300
1301 return $children_array;
1302
1303 }
1304
b79fe189 1305 /**
1306 * Private method used to retrieve all children of this category recursively
1307 *
1308 * @param grade_category $category Source of current recursion
a153c9f2 1309 * @return array An array of child grade categories
b79fe189 1310 */
22a9b6d8 1311 private static function _get_children_recursion($category) {
b3ac6c3e 1312
1313 $children_array = array();
b79fe189 1314 foreach ($category->children as $sortorder=>$child) {
1315
b3ac6c3e 1316 if (array_key_exists('itemtype', $child)) {
f3ac8eb4 1317 $grade_item = new grade_item($child, false);
b79fe189 1318
4faf5f99 1319 if (in_array($grade_item->itemtype, array('course', 'category'))) {
1320 $type = $grade_item->itemtype.'item';
1321 $depth = $category->depth;
b79fe189 1322
314c4336 1323 } else {
1324 $type = 'item';
1325 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 1326 }
4faf5f99 1327 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 1328
7c8a963f 1329 } else {
f3ac8eb4 1330 $children = grade_category::_get_children_recursion($child);
1331 $grade_category = new grade_category($child, false);
b79fe189 1332
b3ac6c3e 1333 if (empty($children)) {
314c4336 1334 $children = array();
7c8a963f 1335 }
4faf5f99 1336 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
314c4336 1337 }
27f95e9b 1338 }
1339
b3ac6c3e 1340 // sort the array
1341 ksort($children_array);
1342
27f95e9b 1343 return $children_array;
1344 }
4a490db0 1345
f151b073 1346 /**
a4d76049 1347 * Uses {@link get_grade_item()} to load or create a grade_item, then saves it as $this->grade_item.
a153c9f2
AD
1348 *
1349 * @return grade_item
f151b073 1350 */
da3801e8 1351 public function load_grade_item() {
ac9b0805 1352 if (empty($this->grade_item)) {
1353 $this->grade_item = $this->get_grade_item();
1354 }
ab53054f 1355 return $this->grade_item;
1356 }
4a490db0 1357
ab53054f 1358 /**
a153c9f2
AD
1359 * Retrieves this grade categories' associated grade_item from the database
1360 *
1361 * If no grade_item exists yet, creates one.
1362 *
1363 * @return grade_item
ab53054f 1364 */
da3801e8 1365 public function get_grade_item() {
c91ed4be 1366 if (empty($this->id)) {
1367 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
1368 return false;
1369 }
1370
b3ac6c3e 1371 if (empty($this->parent)) {
1372 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
1373
1374 } else {
1375 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
1376 }
4ac209d5 1377
f3ac8eb4 1378 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 1379 // create a new one
f3ac8eb4 1380 $grade_item = new grade_item($params, false);
b8ff92b6 1381 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 1382 $grade_item->insert('system');
4a490db0 1383
b79fe189 1384 } else if (count($grade_items) == 1) {
b8ff92b6 1385 // found existing one
1386 $grade_item = reset($grade_items);
4a490db0 1387
b8ff92b6 1388 } else {
1389 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 1390 // return first one
1391 $grade_item = reset($grade_items);
2c72af1f 1392 }
1393
ab53054f 1394 return $grade_item;
f151b073 1395 }
8c846243 1396
1397 /**
a153c9f2
AD
1398 * Uses $this->parent to instantiate $this->parent_category based on the referenced record in the DB
1399 *
1400 * @return grade_category The parent category
8c846243 1401 */
da3801e8 1402 public function load_parent_category() {
8c846243 1403 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 1404 $this->parent_category = $this->get_parent_category();
8c846243 1405 }
1406 return $this->parent_category;
4a490db0 1407 }
1408
ab53054f 1409 /**
a153c9f2
AD
1410 * Uses $this->parent to instantiate and return a grade_category object
1411 *
1412 * @return grade_category Returns the parent category or null if this category has no parent
ab53054f 1413 */
da3801e8 1414 public function get_parent_category() {
ab53054f 1415 if (!empty($this->parent)) {
f3ac8eb4 1416 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 1417 return $parent_category;
ab53054f 1418 } else {
1419 return null;
1420 }
1421 }
1422
2186f72c 1423 /**
a153c9f2 1424 * Returns the most descriptive field for this grade category
b79fe189 1425 *
2186f72c 1426 * @return string name
1427 */
da3801e8 1428 public function get_name() {
1429 global $DB;
8f6fdf43 1430 // For a course category, we return the course name if the fullname is set to '?' in the DB (empty in the category edit form)
1431 if (empty($this->parent) && $this->fullname == '?') {
da3801e8 1432 $course = $DB->get_record('course', array('id'=> $this->courseid));
410753fb 1433 return format_string($course->fullname);
b79fe189 1434
314c4336 1435 } else {
1436 return $this->fullname;
1437 }
2186f72c 1438 }
c91ed4be 1439
0fc7f624 1440 /**
a153c9f2 1441 * Sets this category's parent id
b79fe189 1442 *
a153c9f2
AD
1443 * @param int $parentid The ID of the category that is the new parent to $this
1444 * @param string $source From where was the object updated (mod/forum, manual, etc.)
1445 * @return bool success
0fc7f624 1446 */
da3801e8 1447 public function set_parent($parentid, $source=null) {
f13002d5 1448 if ($this->parent == $parentid) {
1449 return true;
1450 }
1451
1452 if ($parentid == $this->id) {
2f137aa1 1453 print_error('cannotassignselfasparent');
f13002d5 1454 }
1455
1456 if (empty($this->parent) and $this->is_course_category()) {
2f137aa1 1457 print_error('cannothaveparentcate');
b3ac6c3e 1458 }
f13002d5 1459
1460 // find parent and check course id
f3ac8eb4 1461 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 1462 return false;
1463 }
1464
f8e6e4db 1465 $this->force_regrading();
b3ac6c3e 1466
1467 // set new parent category
f8e6e4db 1468 $this->parent = $parent_category->id;
1469 $this->parent_category =& $parent_category;
b3ac6c3e 1470 $this->path = null; // remove old path and depth - will be recalculated in update()
ec3717e1 1471 $this->depth = 0; // remove old path and depth - will be recalculated in update()
f8e6e4db 1472 $this->update($source);
b3ac6c3e 1473
15b462da 1474 return $this->update($source);
b3ac6c3e 1475 }
1476
1477 /**
a153c9f2 1478 * Returns the final grade values for this grade category.
b79fe189 1479 *
a153c9f2 1480 * @param int $userid Optional user ID to retrieve a single user's final grade
b3ac6c3e 1481 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
1482 */
b79fe189 1483 public function get_final($userid=null) {
b3ac6c3e 1484 $this->load_grade_item();
1485 return $this->grade_item->get_final($userid);
0fc7f624 1486 }
4a490db0 1487
0fc7f624 1488 /**
a153c9f2
AD
1489 * Returns the sortorder of the grade categories' associated grade_item
1490 *
1491 * This method is also available in grade_item for cases where the object type is not known.
b79fe189 1492 *
0fc7f624 1493 * @return int Sort order
1494 */
da3801e8 1495 public function get_sortorder() {
b3ac6c3e 1496 $this->load_grade_item();
1497 return $this->grade_item->get_sortorder();
0fc7f624 1498 }
1499
be7c0693 1500 /**
a153c9f2
AD
1501 * Returns the idnumber of the grade categories' associated grade_item.
1502 *
1503 * This method is also available in grade_item for cases where the object type is not known.
b79fe189 1504 *
be7c0693 1505 * @return string idnumber
1506 */
da3801e8 1507 public function get_idnumber() {
be7c0693 1508 $this->load_grade_item();
1509 return $this->grade_item->get_idnumber();
1510 }
1511
0fc7f624 1512 /**
a153c9f2
AD
1513 * Sets the sortorder variable for this category.
1514 *
4a490db0 1515 * This method is also available in grade_item, for cases where the object type is not know.
b79fe189 1516 *
1517 * @param int $sortorder The sortorder to assign to this category
0fc7f624 1518 */
da3801e8 1519 public function set_sortorder($sortorder) {
b3ac6c3e 1520 $this->load_grade_item();
1521 $this->grade_item->set_sortorder($sortorder);
1522 }
1523
6639ead3 1524 /**
a153c9f2 1525 * Move this category after the given sortorder
b79fe189 1526 *
a153c9f2 1527 * Does not change the parent
b79fe189 1528 *
a153c9f2 1529 * @param int $sortorder to place after.
b79fe189 1530 * @return void
6639ead3 1531 */
da3801e8 1532 public function move_after_sortorder($sortorder) {
f13002d5 1533 $this->load_grade_item();
1534 $this->grade_item->move_after_sortorder($sortorder);
1535 }
1536
b3ac6c3e 1537 /**
f13002d5 1538 * Return true if this is the top most category that represents the total course grade.
b79fe189 1539 *
a153c9f2 1540 * @return bool
b3ac6c3e 1541 */
da3801e8 1542 public function is_course_category() {
b3ac6c3e 1543 $this->load_grade_item();
1544 return $this->grade_item->is_course_item();
1545 }
1546
1547 /**
a153c9f2 1548 * Return the course level grade_category object
b79fe189 1549 *
1550 * @param int $courseid The Course ID
a153c9f2 1551 * @return grade_category Returns the course level grade_category instance
b3ac6c3e 1552 */
22a9b6d8 1553 public static function fetch_course_category($courseid) {
a4503119 1554 if (empty($courseid)) {
1555 debugging('Missing course id!');
1556 return false;
1557 }
b3ac6c3e 1558
1559 // course category has no parent
f3ac8eb4 1560 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
b3ac6c3e 1561 return $course_category;
1562 }
1563
1564 // create a new one
f3ac8eb4 1565 $course_category = new grade_category();
b3ac6c3e 1566 $course_category->insert_course_category($courseid);
1567
1568 return $course_category;
0fc7f624 1569 }
4ac209d5 1570
79eabc2a 1571 /**
1572 * Is grading object editable?
b79fe189 1573 *
a153c9f2 1574 * @return bool
79eabc2a 1575 */
da3801e8 1576 public function is_editable() {
79eabc2a 1577 return true;
1578 }
1579
5fad5061 1580 /**
a153c9f2
AD
1581 * Returns the locked state/date of the grade categories' associated grade_item.
1582 *
1583 * This method is also available in grade_item, for cases where the object type is not known.
1584 *
1585 * @return bool
5fad5061 1586 */
da3801e8 1587 public function is_locked() {
5fad5061 1588 $this->load_grade_item();
22e23c78 1589 return $this->grade_item->is_locked();
5fad5061 1590 }
1591
1592 /**
1593 * Sets the grade_item's locked variable and updates the grade_item.
a153c9f2
AD
1594 *
1595 * Calls set_locked() on the categories' grade_item
b79fe189 1596 *
1597 * @param int $lockedstate 0, 1 or a timestamp int(10) after which date the item will be locked.
1598 * @param bool $cascade lock/unlock child objects too
1599 * @param bool $refresh refresh grades when unlocking
a153c9f2 1600 * @return bool success if category locked (not all children mayb be locked though)
5fad5061 1601 */
da3801e8 1602 public function set_locked($lockedstate, $cascade=false, $refresh=true) {
5fad5061 1603 $this->load_grade_item();
2b0f65e2 1604
fb0e3570 1605 $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
1606
1607 if ($cascade) {
1608 //process all children - items and categories
f3ac8eb4 1609 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
b79fe189 1610
1611 foreach ($children as $child) {
fb0e3570 1612 $child->set_locked($lockedstate, true, false);
b79fe189 1613
fb0e3570 1614 if (empty($lockedstate) and $refresh) {
1615 //refresh when unlocking
1616 $child->refresh_grades();
1617 }
2b0f65e2 1618 }
7a7a53d3 1619 }
b79fe189 1620
f3ac8eb4 1621 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 1622
1623 foreach ($children as $child) {
fb0e3570 1624 $child->set_locked($lockedstate, true, true);
1625 }
7a7a53d3 1626 }
1627 }
2b0f65e2 1628
b121b544 1629 return $result;
5fad5061 1630 }
4a490db0 1631
a153c9f2
AD
1632 /**
1633 * Overrides grade_object::set_properties() to add special handling for changes to category aggregation types
1634 *
1635 * @param stdClass $instance the object to set the properties on
1636 * @param array|stdClass $params Either an associative array or an object containing property name, property value pairs
1637 */
79b260cc
AD
1638 public static function set_properties(&$instance, $params) {
1639 global $DB;
1640
1641 parent::set_properties($instance, $params);
1642
c1024411 1643 //if they've changed aggregation type we made need to do some fiddling to provide appropriate defaults
79b260cc
AD
1644 if (!empty($params->aggregation)) {
1645
1646 //weight and extra credit share a column :( Would like a default of 1 for weight and 0 for extra credit
1647 //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 1648 if (self::aggregation_uses_aggregationcoef($params->aggregation)) {
79b260cc 1649 $sql = $defaultaggregationcoef = null;
7ad5a627 1650
134c514b 1651 if (!self::aggregation_uses_extracredit($params->aggregation)) {
79b260cc
AD
1652 //if all items in this category have aggregation coefficient of 0 we can change it to 1 ie evenly weighted
1653 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=0";
1654 $defaultaggregationcoef = 1;
134c514b 1655 } else {
79b260cc
AD
1656 //if all items in this category have aggregation coefficient of 1 we can change it to 0 ie no extra credit
1657 $sql = "select count(id) from {grade_items} where categoryid=:categoryid and aggregationcoef!=1";
1658 $defaultaggregationcoef = 0;
1659 }
1660
1661 $params = array('categoryid'=>$instance->id);
1662 $count = $DB->count_records_sql($sql, $params);
1663 if ($count===0) { //category is either empty or all items are set to a default value so we can switch defaults
1664 $params['aggregationcoef'] = $defaultaggregationcoef;
1665 $DB->execute("update {grade_items} set aggregationcoef=:aggregationcoef where categoryid=:categoryid",$params);
1666 }
1667 }
1668 }
1669 }
1670
5fad5061 1671 /**
4a490db0 1672 * Sets the grade_item's hidden variable and updates the grade_item.
a153c9f2
AD
1673 *
1674 * Overrides grade_item::set_hidden() to add cascading of the hidden value to grade items in this grade category
1675 *
1676 * @param int $hidden 0 mean always visible, 1 means always hidden and a number > 1 is a timestamp to hide until
1677 * @param bool $cascade apply to child objects too
5fad5061 1678 */
da3801e8 1679 public function set_hidden($hidden, $cascade=false) {
5fad5061 1680 $this->load_grade_item();
a25bb902 1681 //this hides the associated grade item (the course total)
1762a264 1682 $this->grade_item->set_hidden($hidden, $cascade);
a25bb902
AD
1683 //this hides the category itself and everything it contains
1684 parent::set_hidden($hidden, $cascade);
b79fe189 1685
f60c61b1 1686 if ($cascade) {
b79fe189 1687
f3ac8eb4 1688 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
b79fe189 1689
1690 foreach ($children as $child) {
39873128
TH
1691 if ($child->can_control_visibility()) {
1692 $child->set_hidden($hidden, $cascade);
1693 }
f60c61b1 1694 }
f13002d5 1695 }
b79fe189 1696
f3ac8eb4 1697 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
b79fe189 1698
1699 foreach ($children as $child) {
f60c61b1 1700 $child->set_hidden($hidden, $cascade);
1701 }
f13002d5 1702 }
1703 }
d90aa634
AD
1704
1705 //if marking category visible make sure parent category is visible MDL-21367
1706 if( !$hidden ) {
1707 $category_array = grade_category::fetch_all(array('id'=>$this->parent));
1708 if ($category_array && array_key_exists($this->parent, $category_array)) {
1709 $category = $category_array[$this->parent];
1710 //call set_hidden on the category regardless of whether it is hidden as its parent might be hidden
1711 //if($category->is_hidden()) {
1712 $category->set_hidden($hidden, false);
1713 //}
1714 }
1715 }
5fad5061 1716 }
89a5f827 1717
190af29f 1718 /**
1719 * Applies default settings on this category
a153c9f2
AD
1720 *
1721 * @return bool True if anything changed
190af29f 1722 */
da3801e8 1723 public function apply_default_settings() {
190af29f 1724 global $CFG;
1725
1726 foreach ($this->forceable as $property) {
b79fe189 1727
190af29f 1728 if (isset($CFG->{"grade_$property"})) {
b79fe189 1729
190af29f 1730 if ($CFG->{"grade_$property"} == -1) {
1731 continue; //temporary bc before version bump
1732 }
1733 $this->$property = $CFG->{"grade_$property"};
1734 }
1735 }
1736 }
1737
89a5f827 1738 /**
1739 * Applies forced settings on this category
a153c9f2
AD
1740 *
1741 * @return bool True if anything changed
89a5f827 1742 */
da3801e8 1743 public function apply_forced_settings() {
89a5f827 1744 global $CFG;
1745
1746 $updated = false;
b79fe189 1747
89a5f827 1748 foreach ($this->forceable as $property) {
b79fe189 1749
1750 if (isset($CFG->{"grade_$property"}) and isset($CFG->{"grade_{$property}_flag"}) and
1751 ((int) $CFG->{"grade_{$property}_flag"} & 1)) {
1752
190af29f 1753 if ($CFG->{"grade_$property"} == -1) {
1754 continue; //temporary bc before version bump
1755 }
89a5f827 1756 $this->$property = $CFG->{"grade_$property"};
1757 $updated = true;
1758 }
1759 }
1760
1761 return $updated;
1762 }
1763
1764 /**
1765 * Notification of change in forced category settings.
b79fe189 1766 *
a153c9f2 1767 * Causes all course and category grade items to be marked as needing to be updated
89a5f827 1768 */
da3801e8 1769 public static function updated_forced_settings() {
5b0af8c5 1770 global $CFG, $DB;
1771 $params = array(1, 'course', 'category');
1772 $sql = "UPDATE {grade_items} SET needsupdate=? WHERE itemtype=? or itemtype=?";
1773 $DB->execute($sql, $params);
89a5f827 1774 }
4a490db0 1775}