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