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