quiz unit tests: remove dubious and failing test.
[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
1426edac 651 case GRADE_AGGREGATE_WEIGHTED_MEAN2: // Weighted average of all existing final grades, weight is the range of grade (ususally grademax)
652 $weightsum = 0;
653 $sum = 0;
654 foreach($grade_values as $itemid=>$grade_value) {
655 $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
656 if ($weight <= 0) {
657 continue;
658 }
659 $weightsum += $weight;
660 $sum += $weight * $grade_value;
661 }
662 if ($weightsum == 0) {
663 $agg_grade = null;
664 } else {
665 $agg_grade = $sum / $weightsum;
666 }
667 break;
668
c2efb501 669 case GRADE_AGGREGATE_EXTRACREDIT_MEAN: // special average
9580a21f 670 $num = 0;
671 $sum = 0;
eacd3700 672 foreach($grade_values as $itemid=>$grade_value) {
673 if ($items[$itemid]->aggregationcoef == 0) {
9580a21f 674 $num += 1;
675 $sum += $grade_value;
eacd3700 676 } else if ($items[$itemid]->aggregationcoef > 0) {
677 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 678 }
679 }
680 if ($num == 0) {
9c8d38fa 681 $agg_grade = $sum; // only extra credits or wrong coefs
9580a21f 682 } else {
9c8d38fa 683 $agg_grade = $sum / $num;
9580a21f 684 }
685 break;
686
c2efb501 687 case GRADE_AGGREGATE_MEAN: // Arithmetic average of all grade items (if ungraded aggregated, NULL counted as minimum)
ac9b0805 688 default:
9580a21f 689 $num = count($grade_values);
690 $sum = array_sum($grade_values);
9c8d38fa 691 $agg_grade = $sum / $num;
b8ff92b6 692 break;
693 }
694
d297269d 695 return $agg_grade;
0aa32279 696 }
0758a08e 697
3a03653e 698 /**
699 * Some aggregation tpyes may update max grade
700 * @param array $items sub items
701 * @return void
702 */
703 private function auto_update_max($items) {
704 if ($this->aggregation != GRADE_AGGREGATE_SUM) {
705 // not needed at all
706 return;
707 }
708
709 if (!$items) {
710 if ($this->grade_item->grademax != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
711 $this->grade_item->grademax = 0;
712 $this->grade_item->grademin = 0;
713 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
714 $this->grade_item->update('aggregation');
715 }
716 return;
717 }
718
719 $max = 0;
720
721 //find max grade
722 foreach ($items as $item) {
723 if ($item->aggregationcoef > 0) {
724 // extra credit from this activity - does not affect total
725 continue;
726 }
727 if ($item->gradetype == GRADE_TYPE_VALUE) {
728 $max += $item->grademax;
729 } else if ($item->gradetype == GRADE_TYPE_SCALE) {
730 $max += $item->grademax - 1; // scales min is 1
731 }
732 }
733
734 if ($this->grade_item->grademax != $max or $this->grade_item->grademin != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE){
735 $this->grade_item->grademax = $max;
736 $this->grade_item->grademin = 0;
737 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
738 $this->grade_item->update('aggregation');
739 }
740 }
741
0758a08e 742 /**
743 * internal function for category grades summing
744 *
f1ad9e04 745 * @param object $grade
0758a08e 746 * @param int $userid
f1ad9e04 747 * @param float $oldfinalgrade
0758a08e 748 * @param array $items
749 * @param array $grade_values
0758a08e 750 * @param bool $excluded
751 * @return boolean (just plain return;)
752 */
da3801e8 753 private function sum_grades(&$grade, $oldfinalgrade, $items, $grade_values, $excluded) {
653a8648 754 if (empty($items)) {
755 return null;
756 }
757
0758a08e 758 // ungraded and exluded items are not used in aggregation
759 foreach ($grade_values as $itemid=>$v) {
760 if (is_null($v)) {
761 unset($grade_values[$itemid]);
762 } else if (in_array($itemid, $excluded)) {
763 unset($grade_values[$itemid]);
764 }
765 }
766
d28f25a4 767 // use 0 if grade missing, droplow used and aggregating all items
768 if (!$this->aggregateonlygraded and !empty($this->droplow)) {
769 foreach($items as $itemid=>$value) {
770 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
771 $grade_values[$itemid] = 0;
772 }
773 }
774 }
775
0758a08e 776 $this->apply_limit_rules($grade_values);
777
778 $sum = array_sum($grade_values);
653a8648 779 $grade->finalgrade = $this->grade_item->bounded_grade($sum);
0758a08e 780
781 // update in db if changed
25bcd908 782 if (grade_floats_different($grade->finalgrade, $oldfinalgrade)) {
0758a08e 783 $grade->update('aggregation');
784 }
785
786 return;
787 }
788
adc2f286 789 /**
790 * Given an array of grade values (numerical indices), applies droplow or keephigh
791 * rules to limit the final array.
9580a21f 792 * @param array $grade_values
adc2f286 793 * @return array Limited grades.
794 */
da3801e8 795 public function apply_limit_rules(&$grade_values) {
9580a21f 796 arsort($grade_values, SORT_NUMERIC);
adc2f286 797 if (!empty($this->droplow)) {
798 for ($i = 0; $i < $this->droplow; $i++) {
9580a21f 799 array_pop($grade_values);
adc2f286 800 }
4a490db0 801 } elseif (!empty($this->keephigh)) {
9580a21f 802 while (count($grade_values) > $this->keephigh) {
803 array_pop($grade_values);
adc2f286 804 }
805 }
0aa32279 806 }
807
9580a21f 808
809 /**
810 * Returns true if category uses special aggregation coeficient
811 * @return boolean true if coeficient used
812 */
4e9ca991 813 public function is_aggregationcoef_used() {
c2efb501 814 return ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN
2e0d37fe 815 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
816 or $this->aggregation == GRADE_AGGREGATE_SUM);
ba74762b 817
9580a21f 818 }
819
653a8648 820 /**
821 * Recursive function to find which weight/extra credit field to use in the grade item form. Inherits from a parent category
822 * if that category has aggregatesubcats set to true.
823 * @param string $coefstring
824 * @return string $coefstring
825 */
826 public function get_coefstring($first=true) {
827 if (!is_null($this->coefstring)) {
828 return $this->coefstring;
829 }
830
831 $overriding_coefstring = null;
832
833 // Stop recursing upwards if this category aggregates subcats or has no parent
834 if (!$first && !$this->aggregatesubcats) {
121d8006 835 if ($parent_category = $this->load_parent_category()) {
653a8648 836 return $parent_category->get_coefstring(false);
837 } else {
838 return null;
839 }
840 } elseif ($first) {
841 if (!$this->aggregatesubcats) {
121d8006 842 if ($parent_category = $this->load_parent_category()) {
653a8648 843 $overriding_coefstring = $parent_category->get_coefstring(false);
844 }
845 }
846 }
847
848 // If an overriding coefstring has trickled down from one of the parent categories, return it. Otherwise, return self.
849 if (!is_null($overriding_coefstring)) {
850 return $overriding_coefstring;
851 }
852
853 // No parent category is overriding this category's aggregation, return its string
854 if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
855 $this->coefstring = 'aggregationcoefweight';
856 } else if ($this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
857 $this->coefstring = 'aggregationcoefextra';
858 } else if ($this->aggregation == GRADE_AGGREGATE_SUM) {
859 $this->coefstring = 'aggregationcoefextrasum';
860 } else {
861 $this->coefstring = 'aggregationcoef';
862 }
863 return $this->coefstring;
864 }
865
1c307f21 866 /**
b3ac6c3e 867 * Returns tree with all grade_items and categories as elements
868 * @static
869 * @param int $courseid
b3ac6c3e 870 * @param boolean $include_category_items as category children
871 * @return array
1c307f21 872 */
da3801e8 873 public static function fetch_course_tree($courseid, $include_category_items=false) {
f3ac8eb4 874 $course_category = grade_category::fetch_course_category($courseid);
514a3467 875 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
876 'children'=>$course_category->get_children($include_category_items));
877 $sortorder = 1;
878 $course_category->set_sortorder($sortorder);
879 $course_category->sortorder = $sortorder;
f3ac8eb4 880 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 881 }
882
da3801e8 883 private function _fetch_course_tree_recursion($category_array, &$sortorder) {
b3ac6c3e 884 // update the sortorder in db if needed
885 if ($category_array['object']->sortorder != $sortorder) {
886 $category_array['object']->set_sortorder($sortorder);
ce385eb4 887 }
ce385eb4 888
314c4336 889 // store the grade_item or grade_category instance with extra info
890 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 891
892 // reuse final grades if there
893 if (array_key_exists('finalgrades', $category_array)) {
894 $result['finalgrades'] = $category_array['finalgrades'];
895 }
896
897 // recursively resort children
898 if (!empty($category_array['children'])) {
899 $result['children'] = array();
29d509f5 900 //process the category item first
901 $cat_item_id = null;
b3ac6c3e 902 foreach($category_array['children'] as $oldorder=>$child_array) {
314c4336 903 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
f3ac8eb4 904 $result['children'][$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
29d509f5 905 }
2b0f65e2 906 }
29d509f5 907 foreach($category_array['children'] as $oldorder=>$child_array) {
908 if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
f3ac8eb4 909 $result['children'][++$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
b3ac6c3e 910 }
911 }
912 }
913
914 return $result;
ce385eb4 915 }
7c8a963f 916
917 /**
4a490db0 918 * Fetches and returns all the children categories and/or grade_items belonging to this category.
919 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 920 * as well as all levels (0). The elements are indexed by sort order.
7c8a963f 921 * @return array Array of child objects (grade_category and grade_item).
922 */
da3801e8 923 public function get_children($include_category_items=false) {
924 global $DB;
b3ac6c3e 925
926 // This function must be as fast as possible ;-)
927 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
928 // we have to limit the number of queries though, because it will be used often in grade reports
929
da3801e8 930 $cats = $DB->get_records('grade_categories', array('courseid' => $this->courseid));
931 $items = $DB->get_records('grade_items', array('courseid' => $this->courseid));
4a490db0 932
b3ac6c3e 933 // init children array first
934 foreach ($cats as $catid=>$cat) {
935 $cats[$catid]->children = array();
27f95e9b 936 }
4a490db0 937
b3ac6c3e 938 //first attach items to cats and add category sortorder
939 foreach ($items as $item) {
940 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
941 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 942
b3ac6c3e 943 if (!$include_category_items) {
944 continue;
945 }
946 $categoryid = $item->iteminstance;
947 } else {
948 $categoryid = $item->categoryid;
949 }
950
951 // prevent problems with duplicate sortorders in db
952 $sortorder = $item->sortorder;
953 while(array_key_exists($sortorder, $cats[$categoryid]->children)) {
f13002d5 954 //debugging("$sortorder exists in item loop");
b3ac6c3e 955 $sortorder++;
956 }
957
958 $cats[$categoryid]->children[$sortorder] = $item;
959
960 }
961
962 // now find the requested category and connect categories as children
963 $category = false;
964 foreach ($cats as $catid=>$cat) {
ec3717e1 965 if (empty($cat->parent)) {
966 if ($cat->path !== '/'.$cat->id.'/') {
967 $grade_category = new grade_category($cat, false);
968 $grade_category->path = '/'.$cat->id.'/';
969 $grade_category->depth = 1;
970 $grade_category->update('system');
971 return $this->get_children($include_category_items);
972 }
973 } else {
974 if (empty($cat->path) or !preg_match('|/'.$cat->parent.'/'.$cat->id.'/$|', $cat->path)) {
975 //fix paths and depts
976 static $recursioncounter = 0; // prevents infinite recursion
977 $recursioncounter++;
da3801e8 978 if ($recursioncounter < 5) {
ec3717e1 979 // fix paths and depths!
980 $grade_category = new grade_category($cat, false);
981 $grade_category->depth = 0;
982 $grade_category->path = null;
983 $grade_category->update('system');
984 return $this->get_children($include_category_items);
985 }
da3801e8 986 }
b3ac6c3e 987 // prevent problems with duplicate sortorders in db
988 $sortorder = $cat->sortorder;
989 while(array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 990 //debugging("$sortorder exists in cat loop");
b3ac6c3e 991 $sortorder++;
992 }
993
65370356 994 $cats[$cat->parent]->children[$sortorder] = &$cats[$catid];
b3ac6c3e 995 }
f3ac8eb4 996
b3ac6c3e 997 if ($catid == $this->id) {
998 $category = &$cats[$catid];
999 }
1000 }
1001
1002 unset($items); // not needed
1003 unset($cats); // not needed
1004
f3ac8eb4 1005 $children_array = grade_category::_get_children_recursion($category);
b3ac6c3e 1006
1007 ksort($children_array);
1008
1009 return $children_array;
1010
1011 }
1012
da3801e8 1013 private function _get_children_recursion($category) {
b3ac6c3e 1014
1015 $children_array = array();
1016 foreach($category->children as $sortorder=>$child) {
1017 if (array_key_exists('itemtype', $child)) {
f3ac8eb4 1018 $grade_item = new grade_item($child, false);
4faf5f99 1019 if (in_array($grade_item->itemtype, array('course', 'category'))) {
1020 $type = $grade_item->itemtype.'item';
1021 $depth = $category->depth;
314c4336 1022 } else {
1023 $type = 'item';
1024 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 1025 }
4faf5f99 1026 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 1027
7c8a963f 1028 } else {
f3ac8eb4 1029 $children = grade_category::_get_children_recursion($child);
1030 $grade_category = new grade_category($child, false);
b3ac6c3e 1031 if (empty($children)) {
314c4336 1032 $children = array();
7c8a963f 1033 }
4faf5f99 1034 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
314c4336 1035 }
27f95e9b 1036 }
1037
b3ac6c3e 1038 // sort the array
1039 ksort($children_array);
1040
27f95e9b 1041 return $children_array;
1042 }
4a490db0 1043
f151b073 1044 /**
ab53054f 1045 * Uses get_grade_item to load or create a grade_item, then saves it as $this->grade_item.
f151b073 1046 * @return object Grade_item
1047 */
da3801e8 1048 public function load_grade_item() {
ac9b0805 1049 if (empty($this->grade_item)) {
1050 $this->grade_item = $this->get_grade_item();
1051 }
ab53054f 1052 return $this->grade_item;
1053 }
4a490db0 1054
ab53054f 1055 /**
1056 * Retrieves from DB and instantiates the associated grade_item object.
1057 * If no grade_item exists yet, create one.
1058 * @return object Grade_item
1059 */
da3801e8 1060 public function get_grade_item() {
c91ed4be 1061 if (empty($this->id)) {
1062 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
1063 return false;
1064 }
1065
b3ac6c3e 1066 if (empty($this->parent)) {
1067 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
1068
1069 } else {
1070 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
1071 }
4ac209d5 1072
f3ac8eb4 1073 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 1074 // create a new one
f3ac8eb4 1075 $grade_item = new grade_item($params, false);
b8ff92b6 1076 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 1077 $grade_item->insert('system');
4a490db0 1078
b8ff92b6 1079 } else if (count($grade_items) == 1){
1080 // found existing one
1081 $grade_item = reset($grade_items);
4a490db0 1082
b8ff92b6 1083 } else {
1084 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 1085 // return first one
1086 $grade_item = reset($grade_items);
2c72af1f 1087 }
1088
ab53054f 1089 return $grade_item;
f151b073 1090 }
8c846243 1091
1092 /**
1093 * Uses $this->parent to instantiate $this->parent_category based on the
1094 * referenced record in the DB.
1095 * @return object Parent_category
1096 */
da3801e8 1097 public function load_parent_category() {
8c846243 1098 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 1099 $this->parent_category = $this->get_parent_category();
8c846243 1100 }
1101 return $this->parent_category;
4a490db0 1102 }
1103
ab53054f 1104 /**
1105 * Uses $this->parent to instantiate and return a grade_category object.
1106 * @return object Parent_category
1107 */
da3801e8 1108 public function get_parent_category() {
ab53054f 1109 if (!empty($this->parent)) {
f3ac8eb4 1110 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 1111 return $parent_category;
ab53054f 1112 } else {
1113 return null;
1114 }
1115 }
1116
2186f72c 1117 /**
4a490db0 1118 * Returns the most descriptive field for this object. This is a standard method used
2186f72c 1119 * when we do not know the exact type of an object.
1120 * @return string name
1121 */
da3801e8 1122 public function get_name() {
1123 global $DB;
8f6fdf43 1124 // For a course category, we return the course name if the fullname is set to '?' in the DB (empty in the category edit form)
1125 if (empty($this->parent) && $this->fullname == '?') {
da3801e8 1126 $course = $DB->get_record('course', array('id'=> $this->courseid));
410753fb 1127 return format_string($course->fullname);
314c4336 1128 } else {
1129 return $this->fullname;
1130 }
2186f72c 1131 }
c91ed4be 1132
0fc7f624 1133 /**
1134 * Sets this category's parent id. A generic method shared by objects that have a parent id of some kind.
f13002d5 1135 * @param int parentid
1136 * @return boolean success
0fc7f624 1137 */
da3801e8 1138 public function set_parent($parentid, $source=null) {
f13002d5 1139 if ($this->parent == $parentid) {
1140 return true;
1141 }
1142
1143 if ($parentid == $this->id) {
2f137aa1 1144 print_error('cannotassignselfasparent');
f13002d5 1145 }
1146
1147 if (empty($this->parent) and $this->is_course_category()) {
2f137aa1 1148 print_error('cannothaveparentcate');
b3ac6c3e 1149 }
f13002d5 1150
1151 // find parent and check course id
f3ac8eb4 1152 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 1153 return false;
1154 }
1155
f8e6e4db 1156 $this->force_regrading();
b3ac6c3e 1157
1158 // set new parent category
f8e6e4db 1159 $this->parent = $parent_category->id;
1160 $this->parent_category =& $parent_category;
b3ac6c3e 1161 $this->path = null; // remove old path and depth - will be recalculated in update()
ec3717e1 1162 $this->depth = 0; // remove old path and depth - will be recalculated in update()
f8e6e4db 1163 $this->update($source);
b3ac6c3e 1164
15b462da 1165 return $this->update($source);
b3ac6c3e 1166 }
1167
1168 /**
1169 * Returns the final values for this grade category.
1170 * @param int $userid Optional: to retrieve a single final grade
1171 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
1172 */
da3801e8 1173 public function get_final($userid=NULL) {
b3ac6c3e 1174 $this->load_grade_item();
1175 return $this->grade_item->get_final($userid);
0fc7f624 1176 }
4a490db0 1177
0fc7f624 1178 /**
4a490db0 1179 * Returns the sortorder of the associated grade_item. This method is also available in
5fad5061 1180 * grade_item, for cases where the object type is not known.
0fc7f624 1181 * @return int Sort order
1182 */
da3801e8 1183 public function get_sortorder() {
b3ac6c3e 1184 $this->load_grade_item();
1185 return $this->grade_item->get_sortorder();
0fc7f624 1186 }
1187
be7c0693 1188 /**
1189 * Returns the idnumber of the associated grade_item. This method is also available in
1190 * grade_item, for cases where the object type is not known.
1191 * @return string idnumber
1192 */
da3801e8 1193 public function get_idnumber() {
be7c0693 1194 $this->load_grade_item();
1195 return $this->grade_item->get_idnumber();
1196 }
1197
0fc7f624 1198 /**
b3ac6c3e 1199 * Sets sortorder variable for this category.
4a490db0 1200 * This method is also available in grade_item, for cases where the object type is not know.
0fc7f624 1201 * @param int $sortorder
1202 * @return void
1203 */
da3801e8 1204 public function set_sortorder($sortorder) {
b3ac6c3e 1205 $this->load_grade_item();
1206 $this->grade_item->set_sortorder($sortorder);
1207 }
1208
6639ead3 1209 /**
1210 * Move this category after the given sortorder - does not change the parent
1211 * @param int $sortorder to place after
1212 */
da3801e8 1213 public function move_after_sortorder($sortorder) {
f13002d5 1214 $this->load_grade_item();
1215 $this->grade_item->move_after_sortorder($sortorder);
1216 }
1217
b3ac6c3e 1218 /**
f13002d5 1219 * Return true if this is the top most category that represents the total course grade.
b3ac6c3e 1220 * @return boolean
1221 */
da3801e8 1222 public function is_course_category() {
b3ac6c3e 1223 $this->load_grade_item();
1224 return $this->grade_item->is_course_item();
1225 }
1226
1227 /**
1228 * Return the top most course category.
1229 * @static
1230 * @return object grade_category instance for course grade
1231 */
da3801e8 1232 public function fetch_course_category($courseid) {
a4503119 1233 if (empty($courseid)) {
1234 debugging('Missing course id!');
1235 return false;
1236 }
b3ac6c3e 1237
1238 // course category has no parent
f3ac8eb4 1239 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
b3ac6c3e 1240 return $course_category;
1241 }
1242
1243 // create a new one
f3ac8eb4 1244 $course_category = new grade_category();
b3ac6c3e 1245 $course_category->insert_course_category($courseid);
1246
1247 return $course_category;
0fc7f624 1248 }
4ac209d5 1249
79eabc2a 1250 /**
1251 * Is grading object editable?
1252 * @return boolean
1253 */
da3801e8 1254 public function is_editable() {
79eabc2a 1255 return true;
1256 }
1257
5fad5061 1258 /**
4a490db0 1259 * Returns the locked state/date of the associated grade_item. This method is also available in
1260 * grade_item, for cases where the object type is not known.
22e23c78 1261 * @return boolean
5fad5061 1262 */
da3801e8 1263 public function is_locked() {
5fad5061 1264 $this->load_grade_item();
22e23c78 1265 return $this->grade_item->is_locked();
5fad5061 1266 }
1267
1268 /**
1269 * Sets the grade_item's locked variable and updates the grade_item.
1270 * Method named after grade_item::set_locked().
1271 * @param int $locked 0, 1 or a timestamp int(10) after which date the item will be locked.
fb0e3570 1272 * @param boolean $cascade lock/unlock child objects too
2b0f65e2 1273 * @param boolean $refresh refresh grades when unlocking
9580a21f 1274 * @return boolean success if category locked (not all children mayb be locked though)
5fad5061 1275 */
da3801e8 1276 public function set_locked($lockedstate, $cascade=false, $refresh=true) {
5fad5061 1277 $this->load_grade_item();
2b0f65e2 1278
fb0e3570 1279 $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
1280
1281 if ($cascade) {
1282 //process all children - items and categories
f3ac8eb4 1283 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
fb0e3570 1284 foreach($children as $child) {
1285 $child->set_locked($lockedstate, true, false);
1286 if (empty($lockedstate) and $refresh) {
1287 //refresh when unlocking
1288 $child->refresh_grades();
1289 }
2b0f65e2 1290 }
7a7a53d3 1291 }
f3ac8eb4 1292 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
fb0e3570 1293 foreach($children as $child) {
1294 $child->set_locked($lockedstate, true, true);
1295 }
7a7a53d3 1296 }
1297 }
2b0f65e2 1298
b121b544 1299 return $result;
5fad5061 1300 }
4a490db0 1301
5fad5061 1302 /**
4a490db0 1303 * Returns the hidden state/date of the associated grade_item. This method is also available in
22e23c78 1304 * grade_item.
1305 * @return boolean
5fad5061 1306 */
da3801e8 1307 public function is_hidden() {
5fad5061 1308 $this->load_grade_item();
22e23c78 1309 return $this->grade_item->is_hidden();
5fad5061 1310 }
1311
597f50e6 1312 /**
1313 * Check grade hidden status. Uses data from both grade item and grade.
1314 * @return boolean true if hiddenuntil, false if not
1315 */
da3801e8 1316 public function is_hiddenuntil() {
597f50e6 1317 $this->load_grade_item();
1318 return $this->grade_item->is_hiddenuntil();
1319 }
1320
5fad5061 1321 /**
4a490db0 1322 * Sets the grade_item's hidden variable and updates the grade_item.
5fad5061 1323 * Method named after grade_item::set_hidden().
1324 * @param int $hidden 0, 1 or a timestamp int(10) after which date the item will be hidden.
f60c61b1 1325 * @param boolean $cascade apply to child objects too
5fad5061 1326 * @return void
1327 */
da3801e8 1328 public function set_hidden($hidden, $cascade=false) {
5fad5061 1329 $this->load_grade_item();
22e23c78 1330 $this->grade_item->set_hidden($hidden);
f60c61b1 1331 if ($cascade) {
f3ac8eb4 1332 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
f60c61b1 1333 foreach($children as $child) {
1334 $child->set_hidden($hidden, $cascade);
1335 }
f13002d5 1336 }
f3ac8eb4 1337 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
f60c61b1 1338 foreach($children as $child) {
1339 $child->set_hidden($hidden, $cascade);
1340 }
f13002d5 1341 }
1342 }
5fad5061 1343 }
89a5f827 1344
190af29f 1345 /**
1346 * Applies default settings on this category
1347 * @return bool true if anything changed
1348 */
da3801e8 1349 public function apply_default_settings() {
190af29f 1350 global $CFG;
1351
1352 foreach ($this->forceable as $property) {
1353 if (isset($CFG->{"grade_$property"})) {
1354 if ($CFG->{"grade_$property"} == -1) {
1355 continue; //temporary bc before version bump
1356 }
1357 $this->$property = $CFG->{"grade_$property"};
1358 }
1359 }
1360 }
1361
89a5f827 1362 /**
1363 * Applies forced settings on this category
1364 * @return bool true if anything changed
1365 */
da3801e8 1366 public function apply_forced_settings() {
89a5f827 1367 global $CFG;
1368
1369 $updated = false;
1370 foreach ($this->forceable as $property) {
190af29f 1371 if (isset($CFG->{"grade_$property"}) and isset($CFG->{"grade_{$property}_flag"}) and ((int)$CFG->{"grade_{$property}_flag"} & 1)) {
1372 if ($CFG->{"grade_$property"} == -1) {
1373 continue; //temporary bc before version bump
1374 }
89a5f827 1375 $this->$property = $CFG->{"grade_$property"};
1376 $updated = true;
1377 }
1378 }
1379
1380 return $updated;
1381 }
1382
1383 /**
1384 * Notification of change in forced category settings.
1385 * @static
1386 */
da3801e8 1387 public static function updated_forced_settings() {
5b0af8c5 1388 global $CFG, $DB;
1389 $params = array(1, 'course', 'category');
1390 $sql = "UPDATE {grade_items} SET needsupdate=? WHERE itemtype=? or itemtype=?";
1391 $DB->execute($sql, $params);
89a5f827 1392 }
4a490db0 1393}
8a31e65c 1394?>