fixed typo
[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
a9e38ac8 561 $this->apply_limit_rules($grade_values, $items);
9580a21f 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
a9e38ac8 737 $this->apply_limit_rules($maxes, $items);
59080eee 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
a9e38ac8 783 $this->apply_limit_rules($grade_values, $items);
0758a08e 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.
a9e38ac8 799 * @param array $grade_values itemid=>$grade_value float
800 * @param array $items grade titem objects
adc2f286 801 * @return array Limited grades.
802 */
a9e38ac8 803 public function apply_limit_rules(&$grade_values, $items) {
804 $extraused = $this->is_extracredit_used();
805
adc2f286 806 if (!empty($this->droplow)) {
a9e38ac8 807 asort($grade_values, SORT_NUMERIC);
808 $dropped = 0;
809 foreach ($grade_values as $itemid=>$value) {
810 if ($dropped < $this->droplow) {
811 if ($extraused and $items[$itemid]->aggregationcoef > 0) {
812 // no drop low for extra credits
813 } else {
814 unset($grade_values[$itemid]);
815 $dropped++;
816 }
817 } else {
818 // we have dropped enough
819 break;
59080eee 820 }
adc2f286 821 }
a9e38ac8 822
823 } else if (!empty($this->keephigh)) {
824 arsort($grade_values, SORT_NUMERIC);
825 $kept = 0;
826 foreach ($grade_values as $itemid=>$value) {
827 if ($extraused and $items[$itemid]->aggregationcoef > 0) {
828 // we keep all extra credits
829 } else if ($kept < $this->keephigh) {
830 $kept++;
831 } else {
832 unset($grade_values[$itemid]);
833 }
adc2f286 834 }
835 }
0aa32279 836 }
837
793253ae 838 /**
839 * Returns true if category uses extra credit of any kind
840 * @return boolean true if extra credit used
841 */
842 function is_extracredit_used() {
843 return ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
844 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
845 or $this->aggregation == GRADE_AGGREGATE_SUM);
846 }
847
9580a21f 848 /**
849 * Returns true if category uses special aggregation coeficient
850 * @return boolean true if coeficient used
851 */
4e9ca991 852 public function is_aggregationcoef_used() {
c2efb501 853 return ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN
d9ae2ab5 854 or $this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
2e0d37fe 855 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
856 or $this->aggregation == GRADE_AGGREGATE_SUM);
ba74762b 857
9580a21f 858 }
859
653a8648 860 /**
861 * Recursive function to find which weight/extra credit field to use in the grade item form. Inherits from a parent category
862 * if that category has aggregatesubcats set to true.
863 * @param string $coefstring
864 * @return string $coefstring
865 */
866 public function get_coefstring($first=true) {
867 if (!is_null($this->coefstring)) {
868 return $this->coefstring;
869 }
870
871 $overriding_coefstring = null;
872
873 // Stop recursing upwards if this category aggregates subcats or has no parent
874 if (!$first && !$this->aggregatesubcats) {
121d8006 875 if ($parent_category = $this->load_parent_category()) {
653a8648 876 return $parent_category->get_coefstring(false);
877 } else {
878 return null;
879 }
880 } elseif ($first) {
881 if (!$this->aggregatesubcats) {
121d8006 882 if ($parent_category = $this->load_parent_category()) {
653a8648 883 $overriding_coefstring = $parent_category->get_coefstring(false);
884 }
885 }
886 }
887
888 // If an overriding coefstring has trickled down from one of the parent categories, return it. Otherwise, return self.
889 if (!is_null($overriding_coefstring)) {
890 return $overriding_coefstring;
891 }
892
893 // No parent category is overriding this category's aggregation, return its string
894 if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
895 $this->coefstring = 'aggregationcoefweight';
d9ae2ab5 896 } else if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2) {
897 $this->coefstring = 'aggregationcoefextrasum';
653a8648 898 } else if ($this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
899 $this->coefstring = 'aggregationcoefextra';
900 } else if ($this->aggregation == GRADE_AGGREGATE_SUM) {
901 $this->coefstring = 'aggregationcoefextrasum';
902 } else {
903 $this->coefstring = 'aggregationcoef';
904 }
905 return $this->coefstring;
906 }
907
1c307f21 908 /**
b3ac6c3e 909 * Returns tree with all grade_items and categories as elements
910 * @static
911 * @param int $courseid
b3ac6c3e 912 * @param boolean $include_category_items as category children
913 * @return array
1c307f21 914 */
da3801e8 915 public static function fetch_course_tree($courseid, $include_category_items=false) {
f3ac8eb4 916 $course_category = grade_category::fetch_course_category($courseid);
514a3467 917 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
918 'children'=>$course_category->get_children($include_category_items));
919 $sortorder = 1;
920 $course_category->set_sortorder($sortorder);
921 $course_category->sortorder = $sortorder;
f3ac8eb4 922 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 923 }
924
da3801e8 925 private function _fetch_course_tree_recursion($category_array, &$sortorder) {
b3ac6c3e 926 // update the sortorder in db if needed
927 if ($category_array['object']->sortorder != $sortorder) {
928 $category_array['object']->set_sortorder($sortorder);
ce385eb4 929 }
ce385eb4 930
314c4336 931 // store the grade_item or grade_category instance with extra info
932 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 933
934 // reuse final grades if there
935 if (array_key_exists('finalgrades', $category_array)) {
936 $result['finalgrades'] = $category_array['finalgrades'];
937 }
938
939 // recursively resort children
940 if (!empty($category_array['children'])) {
941 $result['children'] = array();
29d509f5 942 //process the category item first
943 $cat_item_id = null;
b3ac6c3e 944 foreach($category_array['children'] as $oldorder=>$child_array) {
314c4336 945 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
f3ac8eb4 946 $result['children'][$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
29d509f5 947 }
2b0f65e2 948 }
29d509f5 949 foreach($category_array['children'] as $oldorder=>$child_array) {
950 if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
f3ac8eb4 951 $result['children'][++$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
b3ac6c3e 952 }
953 }
954 }
955
956 return $result;
ce385eb4 957 }
7c8a963f 958
959 /**
4a490db0 960 * Fetches and returns all the children categories and/or grade_items belonging to this category.
961 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 962 * as well as all levels (0). The elements are indexed by sort order.
7c8a963f 963 * @return array Array of child objects (grade_category and grade_item).
964 */
da3801e8 965 public function get_children($include_category_items=false) {
966 global $DB;
b3ac6c3e 967
968 // This function must be as fast as possible ;-)
969 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
970 // we have to limit the number of queries though, because it will be used often in grade reports
971
da3801e8 972 $cats = $DB->get_records('grade_categories', array('courseid' => $this->courseid));
973 $items = $DB->get_records('grade_items', array('courseid' => $this->courseid));
4a490db0 974
b3ac6c3e 975 // init children array first
976 foreach ($cats as $catid=>$cat) {
977 $cats[$catid]->children = array();
27f95e9b 978 }
4a490db0 979
b3ac6c3e 980 //first attach items to cats and add category sortorder
981 foreach ($items as $item) {
982 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
983 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 984
b3ac6c3e 985 if (!$include_category_items) {
986 continue;
987 }
988 $categoryid = $item->iteminstance;
989 } else {
990 $categoryid = $item->categoryid;
991 }
992
993 // prevent problems with duplicate sortorders in db
994 $sortorder = $item->sortorder;
995 while(array_key_exists($sortorder, $cats[$categoryid]->children)) {
f13002d5 996 //debugging("$sortorder exists in item loop");
b3ac6c3e 997 $sortorder++;
998 }
999
1000 $cats[$categoryid]->children[$sortorder] = $item;
1001
1002 }
1003
1004 // now find the requested category and connect categories as children
1005 $category = false;
1006 foreach ($cats as $catid=>$cat) {
ec3717e1 1007 if (empty($cat->parent)) {
1008 if ($cat->path !== '/'.$cat->id.'/') {
1009 $grade_category = new grade_category($cat, false);
1010 $grade_category->path = '/'.$cat->id.'/';
1011 $grade_category->depth = 1;
1012 $grade_category->update('system');
1013 return $this->get_children($include_category_items);
1014 }
1015 } else {
1016 if (empty($cat->path) or !preg_match('|/'.$cat->parent.'/'.$cat->id.'/$|', $cat->path)) {
1017 //fix paths and depts
1018 static $recursioncounter = 0; // prevents infinite recursion
1019 $recursioncounter++;
da3801e8 1020 if ($recursioncounter < 5) {
ec3717e1 1021 // fix paths and depths!
1022 $grade_category = new grade_category($cat, false);
1023 $grade_category->depth = 0;
1024 $grade_category->path = null;
1025 $grade_category->update('system');
1026 return $this->get_children($include_category_items);
1027 }
da3801e8 1028 }
b3ac6c3e 1029 // prevent problems with duplicate sortorders in db
1030 $sortorder = $cat->sortorder;
1031 while(array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 1032 //debugging("$sortorder exists in cat loop");
b3ac6c3e 1033 $sortorder++;
1034 }
1035
65370356 1036 $cats[$cat->parent]->children[$sortorder] = &$cats[$catid];
b3ac6c3e 1037 }
f3ac8eb4 1038
b3ac6c3e 1039 if ($catid == $this->id) {
1040 $category = &$cats[$catid];
1041 }
1042 }
1043
1044 unset($items); // not needed
1045 unset($cats); // not needed
1046
f3ac8eb4 1047 $children_array = grade_category::_get_children_recursion($category);
b3ac6c3e 1048
1049 ksort($children_array);
1050
1051 return $children_array;
1052
1053 }
1054
da3801e8 1055 private function _get_children_recursion($category) {
b3ac6c3e 1056
1057 $children_array = array();
1058 foreach($category->children as $sortorder=>$child) {
1059 if (array_key_exists('itemtype', $child)) {
f3ac8eb4 1060 $grade_item = new grade_item($child, false);
4faf5f99 1061 if (in_array($grade_item->itemtype, array('course', 'category'))) {
1062 $type = $grade_item->itemtype.'item';
1063 $depth = $category->depth;
314c4336 1064 } else {
1065 $type = 'item';
1066 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 1067 }
4faf5f99 1068 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 1069
7c8a963f 1070 } else {
f3ac8eb4 1071 $children = grade_category::_get_children_recursion($child);
1072 $grade_category = new grade_category($child, false);
b3ac6c3e 1073 if (empty($children)) {
314c4336 1074 $children = array();
7c8a963f 1075 }
4faf5f99 1076 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
314c4336 1077 }
27f95e9b 1078 }
1079
b3ac6c3e 1080 // sort the array
1081 ksort($children_array);
1082
27f95e9b 1083 return $children_array;
1084 }
4a490db0 1085
f151b073 1086 /**
ab53054f 1087 * Uses get_grade_item to load or create a grade_item, then saves it as $this->grade_item.
f151b073 1088 * @return object Grade_item
1089 */
da3801e8 1090 public function load_grade_item() {
ac9b0805 1091 if (empty($this->grade_item)) {
1092 $this->grade_item = $this->get_grade_item();
1093 }
ab53054f 1094 return $this->grade_item;
1095 }
4a490db0 1096
ab53054f 1097 /**
1098 * Retrieves from DB and instantiates the associated grade_item object.
1099 * If no grade_item exists yet, create one.
1100 * @return object Grade_item
1101 */
da3801e8 1102 public function get_grade_item() {
c91ed4be 1103 if (empty($this->id)) {
1104 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
1105 return false;
1106 }
1107
b3ac6c3e 1108 if (empty($this->parent)) {
1109 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
1110
1111 } else {
1112 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
1113 }
4ac209d5 1114
f3ac8eb4 1115 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 1116 // create a new one
f3ac8eb4 1117 $grade_item = new grade_item($params, false);
b8ff92b6 1118 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 1119 $grade_item->insert('system');
4a490db0 1120
b8ff92b6 1121 } else if (count($grade_items) == 1){
1122 // found existing one
1123 $grade_item = reset($grade_items);
4a490db0 1124
b8ff92b6 1125 } else {
1126 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 1127 // return first one
1128 $grade_item = reset($grade_items);
2c72af1f 1129 }
1130
ab53054f 1131 return $grade_item;
f151b073 1132 }
8c846243 1133
1134 /**
1135 * Uses $this->parent to instantiate $this->parent_category based on the
1136 * referenced record in the DB.
1137 * @return object Parent_category
1138 */
da3801e8 1139 public function load_parent_category() {
8c846243 1140 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 1141 $this->parent_category = $this->get_parent_category();
8c846243 1142 }
1143 return $this->parent_category;
4a490db0 1144 }
1145
ab53054f 1146 /**
1147 * Uses $this->parent to instantiate and return a grade_category object.
1148 * @return object Parent_category
1149 */
da3801e8 1150 public function get_parent_category() {
ab53054f 1151 if (!empty($this->parent)) {
f3ac8eb4 1152 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 1153 return $parent_category;
ab53054f 1154 } else {
1155 return null;
1156 }
1157 }
1158
2186f72c 1159 /**
4a490db0 1160 * Returns the most descriptive field for this object. This is a standard method used
2186f72c 1161 * when we do not know the exact type of an object.
1162 * @return string name
1163 */
da3801e8 1164 public function get_name() {
1165 global $DB;
8f6fdf43 1166 // For a course category, we return the course name if the fullname is set to '?' in the DB (empty in the category edit form)
1167 if (empty($this->parent) && $this->fullname == '?') {
da3801e8 1168 $course = $DB->get_record('course', array('id'=> $this->courseid));
410753fb 1169 return format_string($course->fullname);
314c4336 1170 } else {
1171 return $this->fullname;
1172 }
2186f72c 1173 }
c91ed4be 1174
0fc7f624 1175 /**
1176 * Sets this category's parent id. A generic method shared by objects that have a parent id of some kind.
f13002d5 1177 * @param int parentid
1178 * @return boolean success
0fc7f624 1179 */
da3801e8 1180 public function set_parent($parentid, $source=null) {
f13002d5 1181 if ($this->parent == $parentid) {
1182 return true;
1183 }
1184
1185 if ($parentid == $this->id) {
2f137aa1 1186 print_error('cannotassignselfasparent');
f13002d5 1187 }
1188
1189 if (empty($this->parent) and $this->is_course_category()) {
2f137aa1 1190 print_error('cannothaveparentcate');
b3ac6c3e 1191 }
f13002d5 1192
1193 // find parent and check course id
f3ac8eb4 1194 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 1195 return false;
1196 }
1197
f8e6e4db 1198 $this->force_regrading();
b3ac6c3e 1199
1200 // set new parent category
f8e6e4db 1201 $this->parent = $parent_category->id;
1202 $this->parent_category =& $parent_category;
b3ac6c3e 1203 $this->path = null; // remove old path and depth - will be recalculated in update()
ec3717e1 1204 $this->depth = 0; // remove old path and depth - will be recalculated in update()
f8e6e4db 1205 $this->update($source);
b3ac6c3e 1206
15b462da 1207 return $this->update($source);
b3ac6c3e 1208 }
1209
1210 /**
1211 * Returns the final values for this grade category.
1212 * @param int $userid Optional: to retrieve a single final grade
1213 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
1214 */
da3801e8 1215 public function get_final($userid=NULL) {
b3ac6c3e 1216 $this->load_grade_item();
1217 return $this->grade_item->get_final($userid);
0fc7f624 1218 }
4a490db0 1219
0fc7f624 1220 /**
4a490db0 1221 * Returns the sortorder of the associated grade_item. This method is also available in
5fad5061 1222 * grade_item, for cases where the object type is not known.
0fc7f624 1223 * @return int Sort order
1224 */
da3801e8 1225 public function get_sortorder() {
b3ac6c3e 1226 $this->load_grade_item();
1227 return $this->grade_item->get_sortorder();
0fc7f624 1228 }
1229
be7c0693 1230 /**
1231 * Returns the idnumber of the associated grade_item. This method is also available in
1232 * grade_item, for cases where the object type is not known.
1233 * @return string idnumber
1234 */
da3801e8 1235 public function get_idnumber() {
be7c0693 1236 $this->load_grade_item();
1237 return $this->grade_item->get_idnumber();
1238 }
1239
0fc7f624 1240 /**
b3ac6c3e 1241 * Sets sortorder variable for this category.
4a490db0 1242 * This method is also available in grade_item, for cases where the object type is not know.
0fc7f624 1243 * @param int $sortorder
1244 * @return void
1245 */
da3801e8 1246 public function set_sortorder($sortorder) {
b3ac6c3e 1247 $this->load_grade_item();
1248 $this->grade_item->set_sortorder($sortorder);
1249 }
1250
6639ead3 1251 /**
1252 * Move this category after the given sortorder - does not change the parent
1253 * @param int $sortorder to place after
1254 */
da3801e8 1255 public function move_after_sortorder($sortorder) {
f13002d5 1256 $this->load_grade_item();
1257 $this->grade_item->move_after_sortorder($sortorder);
1258 }
1259
b3ac6c3e 1260 /**
f13002d5 1261 * Return true if this is the top most category that represents the total course grade.
b3ac6c3e 1262 * @return boolean
1263 */
da3801e8 1264 public function is_course_category() {
b3ac6c3e 1265 $this->load_grade_item();
1266 return $this->grade_item->is_course_item();
1267 }
1268
1269 /**
1270 * Return the top most course category.
1271 * @static
1272 * @return object grade_category instance for course grade
1273 */
da3801e8 1274 public function fetch_course_category($courseid) {
a4503119 1275 if (empty($courseid)) {
1276 debugging('Missing course id!');
1277 return false;
1278 }
b3ac6c3e 1279
1280 // course category has no parent
f3ac8eb4 1281 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
b3ac6c3e 1282 return $course_category;
1283 }
1284
1285 // create a new one
f3ac8eb4 1286 $course_category = new grade_category();
b3ac6c3e 1287 $course_category->insert_course_category($courseid);
1288
1289 return $course_category;
0fc7f624 1290 }
4ac209d5 1291
79eabc2a 1292 /**
1293 * Is grading object editable?
1294 * @return boolean
1295 */
da3801e8 1296 public function is_editable() {
79eabc2a 1297 return true;
1298 }
1299
5fad5061 1300 /**
4a490db0 1301 * Returns the locked state/date of the associated grade_item. This method is also available in
1302 * grade_item, for cases where the object type is not known.
22e23c78 1303 * @return boolean
5fad5061 1304 */
da3801e8 1305 public function is_locked() {
5fad5061 1306 $this->load_grade_item();
22e23c78 1307 return $this->grade_item->is_locked();
5fad5061 1308 }
1309
1310 /**
1311 * Sets the grade_item's locked variable and updates the grade_item.
1312 * Method named after grade_item::set_locked().
1313 * @param int $locked 0, 1 or a timestamp int(10) after which date the item will be locked.
fb0e3570 1314 * @param boolean $cascade lock/unlock child objects too
2b0f65e2 1315 * @param boolean $refresh refresh grades when unlocking
9580a21f 1316 * @return boolean success if category locked (not all children mayb be locked though)
5fad5061 1317 */
da3801e8 1318 public function set_locked($lockedstate, $cascade=false, $refresh=true) {
5fad5061 1319 $this->load_grade_item();
2b0f65e2 1320
fb0e3570 1321 $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
1322
1323 if ($cascade) {
1324 //process all children - items and categories
f3ac8eb4 1325 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
fb0e3570 1326 foreach($children as $child) {
1327 $child->set_locked($lockedstate, true, false);
1328 if (empty($lockedstate) and $refresh) {
1329 //refresh when unlocking
1330 $child->refresh_grades();
1331 }
2b0f65e2 1332 }
7a7a53d3 1333 }
f3ac8eb4 1334 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
fb0e3570 1335 foreach($children as $child) {
1336 $child->set_locked($lockedstate, true, true);
1337 }
7a7a53d3 1338 }
1339 }
2b0f65e2 1340
b121b544 1341 return $result;
5fad5061 1342 }
4a490db0 1343
5fad5061 1344 /**
4a490db0 1345 * Returns the hidden state/date of the associated grade_item. This method is also available in
22e23c78 1346 * grade_item.
1347 * @return boolean
5fad5061 1348 */
da3801e8 1349 public function is_hidden() {
5fad5061 1350 $this->load_grade_item();
22e23c78 1351 return $this->grade_item->is_hidden();
5fad5061 1352 }
1353
597f50e6 1354 /**
1355 * Check grade hidden status. Uses data from both grade item and grade.
1356 * @return boolean true if hiddenuntil, false if not
1357 */
da3801e8 1358 public function is_hiddenuntil() {
597f50e6 1359 $this->load_grade_item();
1360 return $this->grade_item->is_hiddenuntil();
1361 }
1362
5fad5061 1363 /**
4a490db0 1364 * Sets the grade_item's hidden variable and updates the grade_item.
5fad5061 1365 * Method named after grade_item::set_hidden().
1366 * @param int $hidden 0, 1 or a timestamp int(10) after which date the item will be hidden.
f60c61b1 1367 * @param boolean $cascade apply to child objects too
5fad5061 1368 * @return void
1369 */
da3801e8 1370 public function set_hidden($hidden, $cascade=false) {
5fad5061 1371 $this->load_grade_item();
22e23c78 1372 $this->grade_item->set_hidden($hidden);
f60c61b1 1373 if ($cascade) {
f3ac8eb4 1374 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
f60c61b1 1375 foreach($children as $child) {
1376 $child->set_hidden($hidden, $cascade);
1377 }
f13002d5 1378 }
f3ac8eb4 1379 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
f60c61b1 1380 foreach($children as $child) {
1381 $child->set_hidden($hidden, $cascade);
1382 }
f13002d5 1383 }
1384 }
5fad5061 1385 }
89a5f827 1386
190af29f 1387 /**
1388 * Applies default settings on this category
1389 * @return bool true if anything changed
1390 */
da3801e8 1391 public function apply_default_settings() {
190af29f 1392 global $CFG;
1393
1394 foreach ($this->forceable as $property) {
1395 if (isset($CFG->{"grade_$property"})) {
1396 if ($CFG->{"grade_$property"} == -1) {
1397 continue; //temporary bc before version bump
1398 }
1399 $this->$property = $CFG->{"grade_$property"};
1400 }
1401 }
1402 }
1403
89a5f827 1404 /**
1405 * Applies forced settings on this category
1406 * @return bool true if anything changed
1407 */
da3801e8 1408 public function apply_forced_settings() {
89a5f827 1409 global $CFG;
1410
1411 $updated = false;
1412 foreach ($this->forceable as $property) {
190af29f 1413 if (isset($CFG->{"grade_$property"}) and isset($CFG->{"grade_{$property}_flag"}) and ((int)$CFG->{"grade_{$property}_flag"} & 1)) {
1414 if ($CFG->{"grade_$property"} == -1) {
1415 continue; //temporary bc before version bump
1416 }
89a5f827 1417 $this->$property = $CFG->{"grade_$property"};
1418 $updated = true;
1419 }
1420 }
1421
1422 return $updated;
1423 }
1424
1425 /**
1426 * Notification of change in forced category settings.
1427 * @static
1428 */
da3801e8 1429 public static function updated_forced_settings() {
5b0af8c5 1430 global $CFG, $DB;
1431 $params = array(1, 'course', 'category');
1432 $sql = "UPDATE {grade_items} SET needsupdate=? WHERE itemtype=? or itemtype=?";
1433 $DB->execute($sql, $params);
89a5f827 1434 }
4a490db0 1435}
8a31e65c 1436?>