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