MDL-18993 implemented frull support for droplow and keephigh in sum aggregation type
[moodle.git] / lib / grade / grade_category.php
CommitLineData
8a31e65c 1<?php // $Id$
2
3///////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Modular Object-Oriented Dynamic Learning Environment //
8// http://moodle.com //
9// //
1f0e4921 10// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
8a31e65c 11// //
12// This program is free software; you can redistribute it and/or modify //
13// it under the terms of the GNU General Public License as published by //
14// the Free Software Foundation; either version 2 of the License, or //
15// (at your option) any later version. //
16// //
17// This program is distributed in the hope that it will be useful, //
18// but WITHOUT ANY WARRANTY; without even the implied warranty of //
19// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20// GNU General Public License for more details: //
21// //
22// http://www.gnu.org/copyleft/gpl.html //
23// //
24///////////////////////////////////////////////////////////////////////////
25
26require_once('grade_object.php');
27
3058964f 28class grade_category extends grade_object {
8a31e65c 29 /**
7c8a963f 30 * The DB table.
8a31e65c 31 * @var string $table
32 */
da3801e8 33 public $table = 'grade_categories';
4a490db0 34
8a31e65c 35 /**
3f2b0c8a 36 * Array of required table fields, must start with 'id'.
37 * @var array $required_fields
8a31e65c 38 */
da3801e8 39 public $required_fields = array('id', 'courseid', 'parent', 'depth', 'path', 'fullname', 'aggregation',
3f2b0c8a 40 'keephigh', 'droplow', 'aggregateonlygraded', 'aggregateoutcomes',
41 'aggregatesubcats', 'timecreated', 'timemodified');
4a490db0 42
8a31e65c 43 /**
44 * The course this category belongs to.
45 * @var int $courseid
46 */
da3801e8 47 public $courseid;
4a490db0 48
8a31e65c 49 /**
50 * The category this category belongs to (optional).
4a490db0 51 * @var int $parent
8a31e65c 52 */
da3801e8 53 public $parent;
4a490db0 54
8c846243 55 /**
56 * The grade_category object referenced by $this->parent (PK).
57 * @var object $parent_category
58 */
da3801e8 59 public $parent_category;
27f95e9b 60
e5c674f1 61 /**
62 * The number of parents this category has.
63 * @var int $depth
64 */
da3801e8 65 public $depth = 0;
e5c674f1 66
67 /**
c2efb501 68 * Shows the hierarchical path for this category as /1/2/3/ (like course_categories), the last number being
e5c674f1 69 * this category's autoincrement ID number.
70 * @var string $path
71 */
da3801e8 72 public $path;
e5c674f1 73
8a31e65c 74 /**
75 * The name of this category.
76 * @var string $fullname
77 */
da3801e8 78 public $fullname;
4a490db0 79
8a31e65c 80 /**
81 * A constant pointing to one of the predefined aggregation strategies (none, mean, median, sum etc) .
4a490db0 82 * @var int $aggregation
8a31e65c 83 */
da3801e8 84 public $aggregation = GRADE_AGGREGATE_MEAN;
4a490db0 85
8a31e65c 86 /**
87 * Keep only the X highest items.
88 * @var int $keephigh
89 */
da3801e8 90 public $keephigh = 0;
4a490db0 91
8a31e65c 92 /**
93 * Drop the X lowest items.
94 * @var int $droplow
95 */
da3801e8 96 public $droplow = 0;
4a490db0 97
c2efb501 98 /**
99 * Aggregate only graded items
100 * @var int $aggregateonlygraded
101 */
da3801e8 102 public $aggregateonlygraded = 0;
c2efb501 103
29d509f5 104 /**
105 * Aggregate outcomes together with normal items
c2efb501 106 * @var int $aggregateoutcomes
29d509f5 107 */
da3801e8 108 public $aggregateoutcomes = 0;
29d509f5 109
c2efb501 110 /**
111 * Ignore subcategories when aggregating
112 * @var int $aggregatesubcats
113 */
da3801e8 114 public $aggregatesubcats = 0;
c2efb501 115
8a31e65c 116 /**
117 * Array of grade_items or grade_categories nested exactly 1 level below this category
118 * @var array $children
119 */
da3801e8 120 public $children;
8a31e65c 121
7c8a963f 122 /**
4a490db0 123 * A hierarchical array of all children below this category. This is stored separately from
7c8a963f 124 * $children because it is more memory-intensive and may not be used as often.
125 * @var array $all_children
126 */
da3801e8 127 public $all_children;
7c8a963f 128
f151b073 129 /**
130 * An associated grade_item object, with itemtype=category, used to calculate and cache a set of grade values
131 * for this category.
132 * @var object $grade_item
133 */
da3801e8 134 public $grade_item;
f151b073 135
b3ac6c3e 136 /**
137 * Temporary sortorder for speedup of children resorting
138 */
da3801e8 139 public $sortorder;
b3ac6c3e 140
89a5f827 141 /**
142 * List of options which can be "forced" from site settings.
143 */
da3801e8 144 public $forceable = array('aggregation', 'keephigh', 'droplow', 'aggregateonlygraded', 'aggregateoutcomes', 'aggregatesubcats');
89a5f827 145
653a8648 146 /**
147 * String representing the aggregation coefficient. Variable is used as cache.
148 */
149 var $coefstring = null;
150
e5c674f1 151 /**
152 * Builds this category's path string based on its parents (if any) and its own id number.
153 * This is typically done just before inserting this object in the DB for the first time,
ce385eb4 154 * or when a new parent is added or changed. It is a recursive function: once the calling
155 * object no longer has a parent, the path is complete.
156 *
157 * @static
158 * @param object $grade_category
159 * @return int The depth of this category (2 means there is one parent)
e5c674f1 160 */
da3801e8 161 public function build_path($grade_category) {
162 global $DB;
163
ce385eb4 164 if (empty($grade_category->parent)) {
c2efb501 165 return '/'.$grade_category->id.'/';
ce385eb4 166 } else {
da3801e8 167 $parent = $DB->get_record('grade_categories', array('id' => $grade_category->parent));
9a68cffc 168 return grade_category::build_path($parent).$grade_category->id.'/';
ce385eb4 169 }
e5c674f1 170 }
171
8a31e65c 172 /**
f92dcad8 173 * Finds and returns a grade_category instance based on params.
61c33818 174 * @static
8a31e65c 175 *
f92dcad8 176 * @param array $params associative arrays varname=>value
177 * @return object grade_category instance or false if none found.
178 */
da3801e8 179 public static function fetch($params) {
f3ac8eb4 180 return grade_object::fetch_helper('grade_categories', 'grade_category', $params);
f92dcad8 181 }
182
183 /**
184 * Finds and returns all grade_category instances based on params.
185 * @static
186 *
187 * @param array $params associative arrays varname=>value
188 * @return array array of grade_category insatnces or false if none found.
189 */
da3801e8 190 public static function fetch_all($params) {
f3ac8eb4 191 return grade_object::fetch_all_helper('grade_categories', 'grade_category', $params);
ce385eb4 192 }
193
8f4a626d 194 /**
2cc4b0f9 195 * In addition to update() as defined in grade_object, call force_regrading of parent categories, if applicable.
aaff71da 196 * @param string $source from where was the object updated (mod/forum, manual, etc.)
197 * @return boolean success
8f4a626d 198 */
da3801e8 199 public function update($source=null) {
b3ac6c3e 200 // load the grade item or create a new one
201 $this->load_grade_item();
202
203 // force recalculation of path;
204 if (empty($this->path)) {
9a68cffc 205 $this->path = grade_category::build_path($this);
c2efb501 206 $this->depth = substr_count($this->path, '/') - 1;
1909a127 207 $updatechildren = true;
208 } else {
209 $updatechildren = false;
4a490db0 210 }
0fc7f624 211
89a5f827 212 $this->apply_forced_settings();
213
214 // these are exclusive
215 if ($this->droplow > 0) {
216 $this->keephigh = 0;
217 } else if ($this->keephigh > 0) {
218 $this->droplow = 0;
219 }
4a490db0 220
b3ac6c3e 221 // Recalculate grades if needed
222 if ($this->qualifies_for_regrading()) {
f8e6e4db 223 $this->force_regrading();
4a490db0 224 }
f8e6e4db 225
ced5ee59 226 $this->timemodified = time();
227
1909a127 228 $result = parent::update($source);
229
230 // now update paths in all child categories
231 if ($result and $updatechildren) {
232 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
233 foreach ($children as $child) {
1909a127 234 $child->path = null;
235 $child->depth = 0;
236 $child->update($source);
da3801e8 237 }
1909a127 238 }
239 }
240
241 return $result;
8f4a626d 242 }
4a490db0 243
8f4a626d 244 /**
2cc4b0f9 245 * If parent::delete() is successful, send force_regrading message to parent category.
aaff71da 246 * @param string $source from where was the object deleted (mod/forum, manual, etc.)
247 * @return boolean success
8f4a626d 248 */
da3801e8 249 public function delete($source=null) {
f13002d5 250 $grade_item = $this->load_grade_item();
4a490db0 251
f615fbab 252 if ($this->is_course_category()) {
f3ac8eb4 253 if ($categories = grade_category::fetch_all(array('courseid'=>$this->courseid))) {
f615fbab 254 foreach ($categories as $category) {
255 if ($category->id == $this->id) {
256 continue; // do not delete course category yet
257 }
258 $category->delete($source);
259 }
aaff71da 260 }
2b0f65e2 261
f3ac8eb4 262 if ($items = grade_item::fetch_all(array('courseid'=>$this->courseid))) {
f615fbab 263 foreach ($items as $item) {
264 if ($item->id == $grade_item->id) {
265 continue; // do not delete course item yet
266 }
267 $item->delete($source);
268 }
269 }
270
271 } else {
272 $this->force_regrading();
2b0f65e2 273
f615fbab 274 $parent = $this->load_parent_category();
2b0f65e2 275
f615fbab 276 // Update children's categoryid/parent field first
f3ac8eb4 277 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
f615fbab 278 foreach ($children as $child) {
279 $child->set_parent($parent->id);
280 }
281 }
f3ac8eb4 282 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
f615fbab 283 foreach ($children as $child) {
284 $child->set_parent($parent->id);
285 }
aaff71da 286 }
287 }
f13002d5 288
aaff71da 289 // first delete the attached grade item and grades
290 $grade_item->delete($source);
f13002d5 291
292 // delete category itself
aaff71da 293 return parent::delete($source);
8f4a626d 294 }
4a490db0 295
ce385eb4 296 /**
297 * In addition to the normal insert() defined in grade_object, this method sets the depth
298 * and path for this object, and update the record accordingly. The reason why this must
299 * be done here instead of in the constructor, is that they both need to know the record's
4a490db0 300 * id number, which only gets created at insertion time.
f151b073 301 * This method also creates an associated grade_item if this wasn't done during construction.
aaff71da 302 * @param string $source from where was the object inserted (mod/forum, manual, etc.)
303 * @return int PK ID if successful, false otherwise
ce385eb4 304 */
da3801e8 305 public function insert($source=null) {
b3ac6c3e 306
307 if (empty($this->courseid)) {
2f137aa1 308 print_error('cannotinsertgrade');
b8ff92b6 309 }
4a490db0 310
b3ac6c3e 311 if (empty($this->parent)) {
f3ac8eb4 312 $course_category = grade_category::fetch_course_category($this->courseid);
b3ac6c3e 313 $this->parent = $course_category->id;
ce385eb4 314 }
4a490db0 315
b3ac6c3e 316 $this->path = null;
317
ced5ee59 318 $this->timecreated = $this->timemodified = time();
319
aaff71da 320 if (!parent::insert($source)) {
b3ac6c3e 321 debugging("Could not insert this category: " . print_r($this, true));
322 return false;
323 }
324
f8e6e4db 325 $this->force_regrading();
326
b3ac6c3e 327 // build path and depth
aaff71da 328 $this->update($source);
4a490db0 329
aaff71da 330 return $this->id;
b3ac6c3e 331 }
332
f2c88356 333 /**
f615fbab 334 * Internal function - used only from fetch_course_category()
335 * Normal insert() can not be used for course category
336 * @param int $courseid
337 * @return bool success
f2c88356 338 */
da3801e8 339 public function insert_course_category($courseid) {
1f0e4921 340 $this->courseid = $courseid;
8f6fdf43 341 $this->fullname = '?';
1f0e4921 342 $this->path = null;
343 $this->parent = null;
0c87b5aa 344 $this->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2;
4a490db0 345
190af29f 346 $this->apply_default_settings();
89a5f827 347 $this->apply_forced_settings();
348
ced5ee59 349 $this->timecreated = $this->timemodified = time();
350
aaff71da 351 if (!parent::insert('system')) {
b3ac6c3e 352 debugging("Could not insert this category: " . print_r($this, true));
353 return false;
f151b073 354 }
4a490db0 355
b3ac6c3e 356 // build path and depth
aaff71da 357 $this->update('system');
b3ac6c3e 358
aaff71da 359 return $this->id;
ce385eb4 360 }
4a490db0 361
8f4a626d 362 /**
363 * Compares the values held by this object with those of the matching record in DB, and returns
364 * whether or not these differences are sufficient to justify an update of all parent objects.
365 * This assumes that this object has an id number and a matching record in DB. If not, it will return false.
366 * @return boolean
367 */
da3801e8 368 public function qualifies_for_regrading() {
8f4a626d 369 if (empty($this->id)) {
6639ead3 370 debugging("Can not regrade non existing category");
8f4a626d 371 return false;
372 }
f3ac8eb4 373
374 $db_item = grade_category::fetch(array('id'=>$this->id));
4a490db0 375
c2efb501 376 $aggregationdiff = $db_item->aggregation != $this->aggregation;
377 $keephighdiff = $db_item->keephigh != $this->keephigh;
378 $droplowdiff = $db_item->droplow != $this->droplow;
379 $aggonlygrddiff = $db_item->aggregateonlygraded != $this->aggregateonlygraded;
380 $aggoutcomesdiff = $db_item->aggregateoutcomes != $this->aggregateoutcomes;
381 $aggsubcatsdiff = $db_item->aggregatesubcats != $this->aggregatesubcats;
8f4a626d 382
c2efb501 383 return ($aggregationdiff || $keephighdiff || $droplowdiff || $aggonlygrddiff || $aggoutcomesdiff || $aggsubcatsdiff);
8f4a626d 384 }
8c846243 385
386 /**
f8e6e4db 387 * Marks the category and course item as needing update - categories are always regraded.
388 * @return void
8c846243 389 */
da3801e8 390 public function force_regrading() {
f8e6e4db 391 $grade_item = $this->load_grade_item();
392 $grade_item->force_regrading();
8c846243 393 }
394
0aa32279 395 /**
0758a08e 396 * Generates and saves final grades in associated category grade item.
1994d890 397 * These immediate children must already have their own final grades.
0758a08e 398 * The category's aggregation method is used to generate final grades.
ac9b0805 399 *
400 * Please note that category grade is either calculated or aggregated - not both at the same time.
401 *
c86caae7 402 * This method must be used ONLY from grade_item::regrade_final_grades(),
ac9b0805 403 * because the calculation must be done in correct order!
b8ff92b6 404 *
4a490db0 405 * Steps to follow:
ac9b0805 406 * 1. Get final grades from immediate children
2df71235 407 * 3. Aggregate these grades
0758a08e 408 * 4. Save them in final grades of associated category grade item
0aa32279 409 */
da3801e8 410 public function generate_grades($userid=null) {
411 global $CFG, $DB;
4a490db0 412
ac9b0805 413 $this->load_grade_item();
2cc4b0f9 414
415 if ($this->grade_item->is_locked()) {
416 return true; // no need to recalculate locked items
417 }
418
89a5f827 419 // find grade items of immediate children (category or grade items) and force site settings
61c33818 420 $depends_on = $this->grade_item->depends_on();
b3ac6c3e 421
f8e6e4db 422 if (empty($depends_on)) {
423 $items = false;
424 } else {
5b0af8c5 425 list($usql, $params) = $DB->get_in_or_equal($depends_on);
f8e6e4db 426 $sql = "SELECT *
5b0af8c5 427 FROM {grade_items}
428 WHERE id $usql";
429 $items = $DB->get_records_sql($sql, $params);
f8e6e4db 430 }
4a490db0 431
3a03653e 432 // needed mostly for SUM agg type
433 $this->auto_update_max($items);
434
5b0af8c5 435 $grade_inst = new grade_grade();
436 $fields = 'g.'.implode(',g.', $grade_inst->required_fields);
437
438 // where to look for final grades - include grade of this item too, we will store the results there
439 $gis = array_merge($depends_on, array($this->grade_item->id));
440 list($usql, $params) = $DB->get_in_or_equal($gis);
441
f8e6e4db 442 if ($userid) {
5b0af8c5 443 $usersql = "AND g.userid=?";
444 $params[] = $userid;
f8e6e4db 445 } else {
446 $usersql = "";
b8ff92b6 447 }
4a490db0 448
3f2b0c8a 449 $sql = "SELECT $fields
5b0af8c5 450 FROM {grade_grades} g, {grade_items} gi
451 WHERE gi.id = g.itemid AND gi.id $usql $usersql
ac9b0805 452 ORDER BY g.userid";
b8ff92b6 453
9580a21f 454 // group the results by userid and aggregate the grades for this user
5b0af8c5 455 if ($rs = $DB->get_recordset_sql($sql, $params)) {
03cedd62 456 $prevuser = 0;
457 $grade_values = array();
458 $excluded = array();
459 $oldgrade = null;
da3801e8 460 foreach ($rs as $used) {
03cedd62 461 if ($used->userid != $prevuser) {
462 $this->aggregate_grades($prevuser, $items, $grade_values, $oldgrade, $excluded);
463 $prevuser = $used->userid;
464 $grade_values = array();
465 $excluded = array();
466 $oldgrade = null;
467 }
468 $grade_values[$used->itemid] = $used->finalgrade;
469 if ($used->excluded) {
470 $excluded[] = $used->itemid;
471 }
472 if ($this->grade_item->id == $used->itemid) {
473 $oldgrade = $used;
2df71235 474 }
b8ff92b6 475 }
da3801e8 476 $rs->close();
03cedd62 477 $this->aggregate_grades($prevuser, $items, $grade_values, $oldgrade, $excluded);//the last one
b8ff92b6 478 }
479
b8ff92b6 480 return true;
481 }
482
483 /**
ac9b0805 484 * internal function for category grades aggregation
ced5ee59 485 *
1994d890 486 * @param int $userid
487 * @param array $items
488 * @param array $grade_values
f1ad9e04 489 * @param object $oldgrade
1994d890 490 * @param bool $excluded
491 * @return boolean (just plain return;)
b8ff92b6 492 */
da3801e8 493 private function aggregate_grades($userid, $items, $grade_values, $oldgrade, $excluded) {
e171963b 494 global $CFG;
b8ff92b6 495 if (empty($userid)) {
f8e6e4db 496 //ignore first call
b8ff92b6 497 return;
498 }
4a490db0 499
f8e6e4db 500 if ($oldgrade) {
66690b69 501 $oldfinalgrade = $oldgrade->finalgrade;
f3ac8eb4 502 $grade = new grade_grade($oldgrade, false);
f8e6e4db 503 $grade->grade_item =& $this->grade_item;
b8ff92b6 504
f8e6e4db 505 } else {
506 // insert final grade - it will be needed later anyway
f3ac8eb4 507 $grade = new grade_grade(array('itemid'=>$this->grade_item->id, 'userid'=>$userid), false);
f8e6e4db 508 $grade->grade_item =& $this->grade_item;
f1ad9e04 509 $grade->insert('system');
510 $oldfinalgrade = null;
f8e6e4db 511 }
f1ad9e04 512
c86caae7 513 // no need to recalculate locked or overridden grades
514 if ($grade->is_locked() or $grade->is_overridden()) {
2cc4b0f9 515 return;
ac9b0805 516 }
517
f8e6e4db 518 // can not use own final category grade in calculation
9580a21f 519 unset($grade_values[$this->grade_item->id]);
f8e6e4db 520
f1ad9e04 521
522 /// sum is a special aggregation types - it adjusts the min max, does not use relative values
523 if ($this->aggregation == GRADE_AGGREGATE_SUM) {
524 $this->sum_grades($grade, $oldfinalgrade, $items, $grade_values, $excluded);
525 return;
526 }
527
0758a08e 528 // if no grades calculation possible or grading not allowed clear final grade
9580a21f 529 if (empty($grade_values) or empty($items) or ($this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE)) {
f8e6e4db 530 $grade->finalgrade = null;
66690b69 531 if (!is_null($oldfinalgrade)) {
0758a08e 532 $grade->update('aggregation');
f8e6e4db 533 }
b8ff92b6 534 return;
535 }
0758a08e 536
f8e6e4db 537 /// normalize the grades first - all will have value 0...1
d5f0aa01 538 // ungraded items are not used in aggregation
23207a1a 539 foreach ($grade_values as $itemid=>$v) {
b8ff92b6 540 if (is_null($v)) {
541 // null means no grade
23207a1a 542 unset($grade_values[$itemid]);
543 continue;
544 } else if (in_array($itemid, $excluded)) {
545 unset($grade_values[$itemid]);
b8ff92b6 546 continue;
0aa32279 547 }
9a68cffc 548 $grade_values[$itemid] = grade_grade::standardise_score($v, $items[$itemid]->grademin, $items[$itemid]->grademax, 0, 1);
0aa32279 549 }
dda0c7e6 550
eacd3700 551 // use min grade if grade missing for these types
c2efb501 552 if (!$this->aggregateonlygraded) {
553 foreach($items as $itemid=>$value) {
554 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
555 $grade_values[$itemid] = 0;
eacd3700 556 }
c2efb501 557 }
eacd3700 558 }
559
560 // limit and sort
9580a21f 561 $this->apply_limit_rules($grade_values);
562 asort($grade_values, SORT_NUMERIC);
4a490db0 563
d5f0aa01 564 // let's see we have still enough grades to do any statistics
9580a21f 565 if (count($grade_values) == 0) {
ac9b0805 566 // not enough attempts yet
f8e6e4db 567 $grade->finalgrade = null;
66690b69 568 if (!is_null($oldfinalgrade)) {
0758a08e 569 $grade->update('aggregation');
b8ff92b6 570 }
571 return;
572 }
2df71235 573
d297269d 574 // do the maths
575 $agg_grade = $this->aggregate_values($grade_values, $items);
576
0758a08e 577 // recalculate the grade back to requested range
9a68cffc 578 $finalgrade = grade_grade::standardise_score($agg_grade, 0, 1, $this->grade_item->grademin, $this->grade_item->grademax);
d297269d 579
653a8648 580 $grade->finalgrade = $this->grade_item->bounded_grade($finalgrade);
d297269d 581
582 // update in db if changed
25bcd908 583 if (grade_floats_different($grade->finalgrade, $oldfinalgrade)) {
0758a08e 584 $grade->update('aggregation');
d297269d 585 }
586
587 return;
588 }
589
89a5f827 590 /**
591 * Internal function - aggregation maths.
54c4a2cb 592 * Must be public: used by grade_grade::get_hiding_affected()
89a5f827 593 */
54c4a2cb 594 public function aggregate_values($grade_values, $items) {
b8ff92b6 595 switch ($this->aggregation) {
c2efb501 596 case GRADE_AGGREGATE_MEDIAN: // Middle point value in the set: ignores frequencies
9580a21f 597 $num = count($grade_values);
c186c7b2 598 $grades = array_values($grade_values);
599 if ($num % 2 == 0) {
9c8d38fa 600 $agg_grade = ($grades[intval($num/2)-1] + $grades[intval($num/2)]) / 2;
b8ff92b6 601 } else {
9c8d38fa 602 $agg_grade = $grades[intval(($num/2)-0.5)];
b8ff92b6 603 }
604 break;
ac9b0805 605
c2efb501 606 case GRADE_AGGREGATE_MIN:
9c8d38fa 607 $agg_grade = reset($grade_values);
b8ff92b6 608 break;
609
c2efb501 610 case GRADE_AGGREGATE_MAX:
9c8d38fa 611 $agg_grade = array_pop($grade_values);
b8ff92b6 612 break;
613
c2efb501 614 case GRADE_AGGREGATE_MODE: // the most common value, average used if multimode
0198929c 615 // array_count_values only counts INT and STRING, so if grades are floats we must convert them to string
616 $converted_grade_values = array();
617
618 foreach ($grade_values as $k => $gv) {
619 if (!is_int($gv) && !is_string($gv)) {
620 $converted_grade_values[$k] = (string) $gv;
621 } else {
622 $converted_grade_values[$k] = $gv;
623 }
624 }
625
626 $freq = array_count_values($converted_grade_values);
95affb8a 627 arsort($freq); // sort by frequency keeping keys
628 $top = reset($freq); // highest frequency count
629 $modes = array_keys($freq, $top); // search for all modes (have the same highest count)
630 rsort($modes, SORT_NUMERIC); // get highes mode
9c8d38fa 631 $agg_grade = reset($modes);
d5fab31f 632 break;
95affb8a 633
1426edac 634 case GRADE_AGGREGATE_WEIGHTED_MEAN: // Weighted average of all existing final grades, weight specified in coef
9580a21f 635 $weightsum = 0;
636 $sum = 0;
eacd3700 637 foreach($grade_values as $itemid=>$grade_value) {
638 if ($items[$itemid]->aggregationcoef <= 0) {
9580a21f 639 continue;
640 }
eacd3700 641 $weightsum += $items[$itemid]->aggregationcoef;
642 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 643 }
644 if ($weightsum == 0) {
9c8d38fa 645 $agg_grade = null;
9580a21f 646 } else {
9c8d38fa 647 $agg_grade = $sum / $weightsum;
9580a21f 648 }
649 break;
650
d9ae2ab5 651 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
652 // Weighted average of all existing final grades with optional extra credit flag,
653 // weight is the range of grade (ususally grademax)
1426edac 654 $weightsum = 0;
d9ae2ab5 655 $sum = null;
1426edac 656 foreach($grade_values as $itemid=>$grade_value) {
657 $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
658 if ($weight <= 0) {
659 continue;
660 }
d9ae2ab5 661 if ($items[$itemid]->aggregationcoef == 0) {
662 $weightsum += $weight;
663 }
664 $sum += $weight * $grade_value;
1426edac 665 }
666 if ($weightsum == 0) {
d9ae2ab5 667 $agg_grade = $sum; // only extra credits
1426edac 668 } else {
669 $agg_grade = $sum / $weightsum;
670 }
671 break;
672
c2efb501 673 case GRADE_AGGREGATE_EXTRACREDIT_MEAN: // special average
9580a21f 674 $num = 0;
d9ae2ab5 675 $sum = null;
eacd3700 676 foreach($grade_values as $itemid=>$grade_value) {
677 if ($items[$itemid]->aggregationcoef == 0) {
9580a21f 678 $num += 1;
679 $sum += $grade_value;
eacd3700 680 } else if ($items[$itemid]->aggregationcoef > 0) {
681 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 682 }
683 }
684 if ($num == 0) {
9c8d38fa 685 $agg_grade = $sum; // only extra credits or wrong coefs
9580a21f 686 } else {
9c8d38fa 687 $agg_grade = $sum / $num;
9580a21f 688 }
689 break;
690
c2efb501 691 case GRADE_AGGREGATE_MEAN: // Arithmetic average of all grade items (if ungraded aggregated, NULL counted as minimum)
ac9b0805 692 default:
9580a21f 693 $num = count($grade_values);
694 $sum = array_sum($grade_values);
9c8d38fa 695 $agg_grade = $sum / $num;
b8ff92b6 696 break;
697 }
698
d297269d 699 return $agg_grade;
0aa32279 700 }
0758a08e 701
3a03653e 702 /**
703 * Some aggregation tpyes may update max grade
704 * @param array $items sub items
705 * @return void
706 */
707 private function auto_update_max($items) {
708 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
709 // not needed at all
710 return;
711 }
712
713 if (!$items) {
714 if ($this->grade_item->grademax != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
715 $this->grade_item->grademax = 0;
716 $this->grade_item->grademin = 0;
717 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
718 $this->grade_item->update('aggregation');
719 }
720 return;
721 }
722
59080eee 723 //find max grade possible
724 $maxes = array();
3a03653e 725 foreach ($items as $item) {
726 if ($item->aggregationcoef > 0) {
727 // extra credit from this activity - does not affect total
728 continue;
729 }
730 if ($item->gradetype == GRADE_TYPE_VALUE) {
b9b199be 731 $maxes[$item->id] = $item->grademax;
3a03653e 732 } else if ($item->gradetype == GRADE_TYPE_SCALE) {
b9b199be 733 $maxes[$item->id] = $item->grademax; // 0 = nograde, 1 = first scale item, 2 = second scale item
3a03653e 734 }
735 }
59080eee 736 // apply droplow and keephigh
737 $this->apply_limit_rules($maxes);
738 $max = array_sum($maxes);
3a03653e 739
59080eee 740 // update db if anything changed
741 if ($this->grade_item->grademax != $max or $this->grade_item->grademin != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
3a03653e 742 $this->grade_item->grademax = $max;
743 $this->grade_item->grademin = 0;
744 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
745 $this->grade_item->update('aggregation');
746 }
747 }
748
0758a08e 749 /**
750 * internal function for category grades summing
751 *
f1ad9e04 752 * @param object $grade
0758a08e 753 * @param int $userid
f1ad9e04 754 * @param float $oldfinalgrade
0758a08e 755 * @param array $items
756 * @param array $grade_values
0758a08e 757 * @param bool $excluded
758 * @return boolean (just plain return;)
759 */
da3801e8 760 private function sum_grades(&$grade, $oldfinalgrade, $items, $grade_values, $excluded) {
653a8648 761 if (empty($items)) {
762 return null;
763 }
764
0758a08e 765 // ungraded and exluded items are not used in aggregation
766 foreach ($grade_values as $itemid=>$v) {
767 if (is_null($v)) {
768 unset($grade_values[$itemid]);
769 } else if (in_array($itemid, $excluded)) {
770 unset($grade_values[$itemid]);
771 }
772 }
773
d28f25a4 774 // use 0 if grade missing, droplow used and aggregating all items
775 if (!$this->aggregateonlygraded and !empty($this->droplow)) {
776 foreach($items as $itemid=>$value) {
777 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
778 $grade_values[$itemid] = 0;
779 }
780 }
781 }
782
0758a08e 783 $this->apply_limit_rules($grade_values);
784
785 $sum = array_sum($grade_values);
653a8648 786 $grade->finalgrade = $this->grade_item->bounded_grade($sum);
0758a08e 787
788 // update in db if changed
25bcd908 789 if (grade_floats_different($grade->finalgrade, $oldfinalgrade)) {
0758a08e 790 $grade->update('aggregation');
791 }
792
793 return;
794 }
795
adc2f286 796 /**
797 * Given an array of grade values (numerical indices), applies droplow or keephigh
798 * rules to limit the final array.
9580a21f 799 * @param array $grade_values
adc2f286 800 * @return array Limited grades.
801 */
da3801e8 802 public function apply_limit_rules(&$grade_values) {
9580a21f 803 arsort($grade_values, SORT_NUMERIC);
adc2f286 804 if (!empty($this->droplow)) {
805 for ($i = 0; $i < $this->droplow; $i++) {
59080eee 806 if (empty($grade_values)) {
807 // nothing to remove
808 return;
809 }
9580a21f 810 array_pop($grade_values);
adc2f286 811 }
4a490db0 812 } elseif (!empty($this->keephigh)) {
9580a21f 813 while (count($grade_values) > $this->keephigh) {
814 array_pop($grade_values);
adc2f286 815 }
816 }
0aa32279 817 }
818
9580a21f 819
820 /**
821 * Returns true if category uses special aggregation coeficient
822 * @return boolean true if coeficient used
823 */
4e9ca991 824 public function is_aggregationcoef_used() {
c2efb501 825 return ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN
d9ae2ab5 826 or $this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
2e0d37fe 827 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
828 or $this->aggregation == GRADE_AGGREGATE_SUM);
ba74762b 829
9580a21f 830 }
831
653a8648 832 /**
833 * Recursive function to find which weight/extra credit field to use in the grade item form. Inherits from a parent category
834 * if that category has aggregatesubcats set to true.
835 * @param string $coefstring
836 * @return string $coefstring
837 */
838 public function get_coefstring($first=true) {
839 if (!is_null($this->coefstring)) {
840 return $this->coefstring;
841 }
842
843 $overriding_coefstring = null;
844
845 // Stop recursing upwards if this category aggregates subcats or has no parent
846 if (!$first && !$this->aggregatesubcats) {
121d8006 847 if ($parent_category = $this->load_parent_category()) {
653a8648 848 return $parent_category->get_coefstring(false);
849 } else {
850 return null;
851 }
852 } elseif ($first) {
853 if (!$this->aggregatesubcats) {
121d8006 854 if ($parent_category = $this->load_parent_category()) {
653a8648 855 $overriding_coefstring = $parent_category->get_coefstring(false);
856 }
857 }
858 }
859
860 // If an overriding coefstring has trickled down from one of the parent categories, return it. Otherwise, return self.
861 if (!is_null($overriding_coefstring)) {
862 return $overriding_coefstring;
863 }
864
865 // No parent category is overriding this category's aggregation, return its string
866 if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
867 $this->coefstring = 'aggregationcoefweight';
d9ae2ab5 868 } else if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2) {
869 $this->coefstring = 'aggregationcoefextrasum';
653a8648 870 } else if ($this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
871 $this->coefstring = 'aggregationcoefextra';
872 } else if ($this->aggregation == GRADE_AGGREGATE_SUM) {
873 $this->coefstring = 'aggregationcoefextrasum';
874 } else {
875 $this->coefstring = 'aggregationcoef';
876 }
877 return $this->coefstring;
878 }
879
1c307f21 880 /**
b3ac6c3e 881 * Returns tree with all grade_items and categories as elements
882 * @static
883 * @param int $courseid
b3ac6c3e 884 * @param boolean $include_category_items as category children
885 * @return array
1c307f21 886 */
da3801e8 887 public static function fetch_course_tree($courseid, $include_category_items=false) {
f3ac8eb4 888 $course_category = grade_category::fetch_course_category($courseid);
514a3467 889 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
890 'children'=>$course_category->get_children($include_category_items));
891 $sortorder = 1;
892 $course_category->set_sortorder($sortorder);
893 $course_category->sortorder = $sortorder;
f3ac8eb4 894 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 895 }
896
da3801e8 897 private function _fetch_course_tree_recursion($category_array, &$sortorder) {
b3ac6c3e 898 // update the sortorder in db if needed
899 if ($category_array['object']->sortorder != $sortorder) {
900 $category_array['object']->set_sortorder($sortorder);
ce385eb4 901 }
ce385eb4 902
314c4336 903 // store the grade_item or grade_category instance with extra info
904 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 905
906 // reuse final grades if there
907 if (array_key_exists('finalgrades', $category_array)) {
908 $result['finalgrades'] = $category_array['finalgrades'];
909 }
910
911 // recursively resort children
912 if (!empty($category_array['children'])) {
913 $result['children'] = array();
29d509f5 914 //process the category item first
915 $cat_item_id = null;
b3ac6c3e 916 foreach($category_array['children'] as $oldorder=>$child_array) {
314c4336 917 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
f3ac8eb4 918 $result['children'][$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
29d509f5 919 }
2b0f65e2 920 }
29d509f5 921 foreach($category_array['children'] as $oldorder=>$child_array) {
922 if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
f3ac8eb4 923 $result['children'][++$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
b3ac6c3e 924 }
925 }
926 }
927
928 return $result;
ce385eb4 929 }
7c8a963f 930
931 /**
4a490db0 932 * Fetches and returns all the children categories and/or grade_items belonging to this category.
933 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 934 * as well as all levels (0). The elements are indexed by sort order.
7c8a963f 935 * @return array Array of child objects (grade_category and grade_item).
936 */
da3801e8 937 public function get_children($include_category_items=false) {
938 global $DB;
b3ac6c3e 939
940 // This function must be as fast as possible ;-)
941 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
942 // we have to limit the number of queries though, because it will be used often in grade reports
943
da3801e8 944 $cats = $DB->get_records('grade_categories', array('courseid' => $this->courseid));
945 $items = $DB->get_records('grade_items', array('courseid' => $this->courseid));
4a490db0 946
b3ac6c3e 947 // init children array first
948 foreach ($cats as $catid=>$cat) {
949 $cats[$catid]->children = array();
27f95e9b 950 }
4a490db0 951
b3ac6c3e 952 //first attach items to cats and add category sortorder
953 foreach ($items as $item) {
954 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
955 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 956
b3ac6c3e 957 if (!$include_category_items) {
958 continue;
959 }
960 $categoryid = $item->iteminstance;
961 } else {
962 $categoryid = $item->categoryid;
963 }
964
965 // prevent problems with duplicate sortorders in db
966 $sortorder = $item->sortorder;
967 while(array_key_exists($sortorder, $cats[$categoryid]->children)) {
f13002d5 968 //debugging("$sortorder exists in item loop");
b3ac6c3e 969 $sortorder++;
970 }
971
972 $cats[$categoryid]->children[$sortorder] = $item;
973
974 }
975
976 // now find the requested category and connect categories as children
977 $category = false;
978 foreach ($cats as $catid=>$cat) {
ec3717e1 979 if (empty($cat->parent)) {
980 if ($cat->path !== '/'.$cat->id.'/') {
981 $grade_category = new grade_category($cat, false);
982 $grade_category->path = '/'.$cat->id.'/';
983 $grade_category->depth = 1;
984 $grade_category->update('system');
985 return $this->get_children($include_category_items);
986 }
987 } else {
988 if (empty($cat->path) or !preg_match('|/'.$cat->parent.'/'.$cat->id.'/$|', $cat->path)) {
989 //fix paths and depts
990 static $recursioncounter = 0; // prevents infinite recursion
991 $recursioncounter++;
da3801e8 992 if ($recursioncounter < 5) {
ec3717e1 993 // fix paths and depths!
994 $grade_category = new grade_category($cat, false);
995 $grade_category->depth = 0;
996 $grade_category->path = null;
997 $grade_category->update('system');
998 return $this->get_children($include_category_items);
999 }
da3801e8 1000 }
b3ac6c3e 1001 // prevent problems with duplicate sortorders in db
1002 $sortorder = $cat->sortorder;
1003 while(array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 1004 //debugging("$sortorder exists in cat loop");
b3ac6c3e 1005 $sortorder++;
1006 }
1007
65370356 1008 $cats[$cat->parent]->children[$sortorder] = &$cats[$catid];
b3ac6c3e 1009 }
f3ac8eb4 1010
b3ac6c3e 1011 if ($catid == $this->id) {
1012 $category = &$cats[$catid];
1013 }
1014 }
1015
1016 unset($items); // not needed
1017 unset($cats); // not needed
1018
f3ac8eb4 1019 $children_array = grade_category::_get_children_recursion($category);
b3ac6c3e 1020
1021 ksort($children_array);
1022
1023 return $children_array;
1024
1025 }
1026
da3801e8 1027 private function _get_children_recursion($category) {
b3ac6c3e 1028
1029 $children_array = array();
1030 foreach($category->children as $sortorder=>$child) {
1031 if (array_key_exists('itemtype', $child)) {
f3ac8eb4 1032 $grade_item = new grade_item($child, false);
4faf5f99 1033 if (in_array($grade_item->itemtype, array('course', 'category'))) {
1034 $type = $grade_item->itemtype.'item';
1035 $depth = $category->depth;
314c4336 1036 } else {
1037 $type = 'item';
1038 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 1039 }
4faf5f99 1040 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 1041
7c8a963f 1042 } else {
f3ac8eb4 1043 $children = grade_category::_get_children_recursion($child);
1044 $grade_category = new grade_category($child, false);
b3ac6c3e 1045 if (empty($children)) {
314c4336 1046 $children = array();
7c8a963f 1047 }
4faf5f99 1048 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
314c4336 1049 }
27f95e9b 1050 }
1051
b3ac6c3e 1052 // sort the array
1053 ksort($children_array);
1054
27f95e9b 1055 return $children_array;
1056 }
4a490db0 1057
f151b073 1058 /**
ab53054f 1059 * Uses get_grade_item to load or create a grade_item, then saves it as $this->grade_item.
f151b073 1060 * @return object Grade_item
1061 */
da3801e8 1062 public function load_grade_item() {
ac9b0805 1063 if (empty($this->grade_item)) {
1064 $this->grade_item = $this->get_grade_item();
1065 }
ab53054f 1066 return $this->grade_item;
1067 }
4a490db0 1068
ab53054f 1069 /**
1070 * Retrieves from DB and instantiates the associated grade_item object.
1071 * If no grade_item exists yet, create one.
1072 * @return object Grade_item
1073 */
da3801e8 1074 public function get_grade_item() {
c91ed4be 1075 if (empty($this->id)) {
1076 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
1077 return false;
1078 }
1079
b3ac6c3e 1080 if (empty($this->parent)) {
1081 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
1082
1083 } else {
1084 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
1085 }
4ac209d5 1086
f3ac8eb4 1087 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 1088 // create a new one
f3ac8eb4 1089 $grade_item = new grade_item($params, false);
b8ff92b6 1090 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 1091 $grade_item->insert('system');
4a490db0 1092
b8ff92b6 1093 } else if (count($grade_items) == 1){
1094 // found existing one
1095 $grade_item = reset($grade_items);
4a490db0 1096
b8ff92b6 1097 } else {
1098 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 1099 // return first one
1100 $grade_item = reset($grade_items);
2c72af1f 1101 }
1102
ab53054f 1103 return $grade_item;
f151b073 1104 }
8c846243 1105
1106 /**
1107 * Uses $this->parent to instantiate $this->parent_category based on the
1108 * referenced record in the DB.
1109 * @return object Parent_category
1110 */
da3801e8 1111 public function load_parent_category() {
8c846243 1112 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 1113 $this->parent_category = $this->get_parent_category();
8c846243 1114 }
1115 return $this->parent_category;
4a490db0 1116 }
1117
ab53054f 1118 /**
1119 * Uses $this->parent to instantiate and return a grade_category object.
1120 * @return object Parent_category
1121 */
da3801e8 1122 public function get_parent_category() {
ab53054f 1123 if (!empty($this->parent)) {
f3ac8eb4 1124 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 1125 return $parent_category;
ab53054f 1126 } else {
1127 return null;
1128 }
1129 }
1130
2186f72c 1131 /**
4a490db0 1132 * Returns the most descriptive field for this object. This is a standard method used
2186f72c 1133 * when we do not know the exact type of an object.
1134 * @return string name
1135 */
da3801e8 1136 public function get_name() {
1137 global $DB;
8f6fdf43 1138 // For a course category, we return the course name if the fullname is set to '?' in the DB (empty in the category edit form)
1139 if (empty($this->parent) && $this->fullname == '?') {
da3801e8 1140 $course = $DB->get_record('course', array('id'=> $this->courseid));
410753fb 1141 return format_string($course->fullname);
314c4336 1142 } else {
1143 return $this->fullname;
1144 }
2186f72c 1145 }
c91ed4be 1146
0fc7f624 1147 /**
1148 * Sets this category's parent id. A generic method shared by objects that have a parent id of some kind.
f13002d5 1149 * @param int parentid
1150 * @return boolean success
0fc7f624 1151 */
da3801e8 1152 public function set_parent($parentid, $source=null) {
f13002d5 1153 if ($this->parent == $parentid) {
1154 return true;
1155 }
1156
1157 if ($parentid == $this->id) {
2f137aa1 1158 print_error('cannotassignselfasparent');
f13002d5 1159 }
1160
1161 if (empty($this->parent) and $this->is_course_category()) {
2f137aa1 1162 print_error('cannothaveparentcate');
b3ac6c3e 1163 }
f13002d5 1164
1165 // find parent and check course id
f3ac8eb4 1166 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 1167 return false;
1168 }
1169
f8e6e4db 1170 $this->force_regrading();
b3ac6c3e 1171
1172 // set new parent category
f8e6e4db 1173 $this->parent = $parent_category->id;
1174 $this->parent_category =& $parent_category;
b3ac6c3e 1175 $this->path = null; // remove old path and depth - will be recalculated in update()
ec3717e1 1176 $this->depth = 0; // remove old path and depth - will be recalculated in update()
f8e6e4db 1177 $this->update($source);
b3ac6c3e 1178
15b462da 1179 return $this->update($source);
b3ac6c3e 1180 }
1181
1182 /**
1183 * Returns the final values for this grade category.
1184 * @param int $userid Optional: to retrieve a single final grade
1185 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
1186 */
da3801e8 1187 public function get_final($userid=NULL) {
b3ac6c3e 1188 $this->load_grade_item();
1189 return $this->grade_item->get_final($userid);
0fc7f624 1190 }
4a490db0 1191
0fc7f624 1192 /**
4a490db0 1193 * Returns the sortorder of the associated grade_item. This method is also available in
5fad5061 1194 * grade_item, for cases where the object type is not known.
0fc7f624 1195 * @return int Sort order
1196 */
da3801e8 1197 public function get_sortorder() {
b3ac6c3e 1198 $this->load_grade_item();
1199 return $this->grade_item->get_sortorder();
0fc7f624 1200 }
1201
be7c0693 1202 /**
1203 * Returns the idnumber of the associated grade_item. This method is also available in
1204 * grade_item, for cases where the object type is not known.
1205 * @return string idnumber
1206 */
da3801e8 1207 public function get_idnumber() {
be7c0693 1208 $this->load_grade_item();
1209 return $this->grade_item->get_idnumber();
1210 }
1211
0fc7f624 1212 /**
b3ac6c3e 1213 * Sets sortorder variable for this category.
4a490db0 1214 * This method is also available in grade_item, for cases where the object type is not know.
0fc7f624 1215 * @param int $sortorder
1216 * @return void
1217 */
da3801e8 1218 public function set_sortorder($sortorder) {
b3ac6c3e 1219 $this->load_grade_item();
1220 $this->grade_item->set_sortorder($sortorder);
1221 }
1222
6639ead3 1223 /**
1224 * Move this category after the given sortorder - does not change the parent
1225 * @param int $sortorder to place after
1226 */
da3801e8 1227 public function move_after_sortorder($sortorder) {
f13002d5 1228 $this->load_grade_item();
1229 $this->grade_item->move_after_sortorder($sortorder);
1230 }
1231
b3ac6c3e 1232 /**
f13002d5 1233 * Return true if this is the top most category that represents the total course grade.
b3ac6c3e 1234 * @return boolean
1235 */
da3801e8 1236 public function is_course_category() {
b3ac6c3e 1237 $this->load_grade_item();
1238 return $this->grade_item->is_course_item();
1239 }
1240
1241 /**
1242 * Return the top most course category.
1243 * @static
1244 * @return object grade_category instance for course grade
1245 */
da3801e8 1246 public function fetch_course_category($courseid) {
a4503119 1247 if (empty($courseid)) {
1248 debugging('Missing course id!');
1249 return false;
1250 }
b3ac6c3e 1251
1252 // course category has no parent
f3ac8eb4 1253 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
b3ac6c3e 1254 return $course_category;
1255 }
1256
1257 // create a new one
f3ac8eb4 1258 $course_category = new grade_category();
b3ac6c3e 1259 $course_category->insert_course_category($courseid);
1260
1261 return $course_category;
0fc7f624 1262 }
4ac209d5 1263
79eabc2a 1264 /**
1265 * Is grading object editable?
1266 * @return boolean
1267 */
da3801e8 1268 public function is_editable() {
79eabc2a 1269 return true;
1270 }
1271
5fad5061 1272 /**
4a490db0 1273 * Returns the locked state/date of the associated grade_item. This method is also available in
1274 * grade_item, for cases where the object type is not known.
22e23c78 1275 * @return boolean
5fad5061 1276 */
da3801e8 1277 public function is_locked() {
5fad5061 1278 $this->load_grade_item();
22e23c78 1279 return $this->grade_item->is_locked();
5fad5061 1280 }
1281
1282 /**
1283 * Sets the grade_item's locked variable and updates the grade_item.
1284 * Method named after grade_item::set_locked().
1285 * @param int $locked 0, 1 or a timestamp int(10) after which date the item will be locked.
fb0e3570 1286 * @param boolean $cascade lock/unlock child objects too
2b0f65e2 1287 * @param boolean $refresh refresh grades when unlocking
9580a21f 1288 * @return boolean success if category locked (not all children mayb be locked though)
5fad5061 1289 */
da3801e8 1290 public function set_locked($lockedstate, $cascade=false, $refresh=true) {
5fad5061 1291 $this->load_grade_item();
2b0f65e2 1292
fb0e3570 1293 $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
1294
1295 if ($cascade) {
1296 //process all children - items and categories
f3ac8eb4 1297 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
fb0e3570 1298 foreach($children as $child) {
1299 $child->set_locked($lockedstate, true, false);
1300 if (empty($lockedstate) and $refresh) {
1301 //refresh when unlocking
1302 $child->refresh_grades();
1303 }
2b0f65e2 1304 }
7a7a53d3 1305 }
f3ac8eb4 1306 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
fb0e3570 1307 foreach($children as $child) {
1308 $child->set_locked($lockedstate, true, true);
1309 }
7a7a53d3 1310 }
1311 }
2b0f65e2 1312
b121b544 1313 return $result;
5fad5061 1314 }
4a490db0 1315
5fad5061 1316 /**
4a490db0 1317 * Returns the hidden state/date of the associated grade_item. This method is also available in
22e23c78 1318 * grade_item.
1319 * @return boolean
5fad5061 1320 */
da3801e8 1321 public function is_hidden() {
5fad5061 1322 $this->load_grade_item();
22e23c78 1323 return $this->grade_item->is_hidden();
5fad5061 1324 }
1325
597f50e6 1326 /**
1327 * Check grade hidden status. Uses data from both grade item and grade.
1328 * @return boolean true if hiddenuntil, false if not
1329 */
da3801e8 1330 public function is_hiddenuntil() {
597f50e6 1331 $this->load_grade_item();
1332 return $this->grade_item->is_hiddenuntil();
1333 }
1334
5fad5061 1335 /**
4a490db0 1336 * Sets the grade_item's hidden variable and updates the grade_item.
5fad5061 1337 * Method named after grade_item::set_hidden().
1338 * @param int $hidden 0, 1 or a timestamp int(10) after which date the item will be hidden.
f60c61b1 1339 * @param boolean $cascade apply to child objects too
5fad5061 1340 * @return void
1341 */
da3801e8 1342 public function set_hidden($hidden, $cascade=false) {
5fad5061 1343 $this->load_grade_item();
22e23c78 1344 $this->grade_item->set_hidden($hidden);
f60c61b1 1345 if ($cascade) {
f3ac8eb4 1346 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
f60c61b1 1347 foreach($children as $child) {
1348 $child->set_hidden($hidden, $cascade);
1349 }
f13002d5 1350 }
f3ac8eb4 1351 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
f60c61b1 1352 foreach($children as $child) {
1353 $child->set_hidden($hidden, $cascade);
1354 }
f13002d5 1355 }
1356 }
5fad5061 1357 }
89a5f827 1358
190af29f 1359 /**
1360 * Applies default settings on this category
1361 * @return bool true if anything changed
1362 */
da3801e8 1363 public function apply_default_settings() {
190af29f 1364 global $CFG;
1365
1366 foreach ($this->forceable as $property) {
1367 if (isset($CFG->{"grade_$property"})) {
1368 if ($CFG->{"grade_$property"} == -1) {
1369 continue; //temporary bc before version bump
1370 }
1371 $this->$property = $CFG->{"grade_$property"};
1372 }
1373 }
1374 }
1375
89a5f827 1376 /**
1377 * Applies forced settings on this category
1378 * @return bool true if anything changed
1379 */
da3801e8 1380 public function apply_forced_settings() {
89a5f827 1381 global $CFG;
1382
1383 $updated = false;
1384 foreach ($this->forceable as $property) {
190af29f 1385 if (isset($CFG->{"grade_$property"}) and isset($CFG->{"grade_{$property}_flag"}) and ((int)$CFG->{"grade_{$property}_flag"} & 1)) {
1386 if ($CFG->{"grade_$property"} == -1) {
1387 continue; //temporary bc before version bump
1388 }
89a5f827 1389 $this->$property = $CFG->{"grade_$property"};
1390 $updated = true;
1391 }
1392 }
1393
1394 return $updated;
1395 }
1396
1397 /**
1398 * Notification of change in forced category settings.
1399 * @static
1400 */
da3801e8 1401 public static function updated_forced_settings() {
5b0af8c5 1402 global $CFG, $DB;
1403 $params = array(1, 'course', 'category');
1404 $sql = "UPDATE {grade_items} SET needsupdate=? WHERE itemtype=? or itemtype=?";
1405 $DB->execute($sql, $params);
89a5f827 1406 }
4a490db0 1407}
8a31e65c 1408?>