MDL-9268
[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// //
10// Copyright (C) 2001-2003 Martin Dougiamas http://dougiamas.com //
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 */
33 var $table = 'grade_categories';
4a490db0 34
8a31e65c 35 /**
36 * Array of class variables that are not part of the DB table fields
37 * @var array $nonfields
38 */
aaff71da 39 var $nonfields = array('table', 'required_fields', 'nonfields', 'children', 'all_children', 'grade_item', 'parent_category', 'sortorder');
4a490db0 40
8a31e65c 41 /**
42 * The course this category belongs to.
43 * @var int $courseid
44 */
45 var $courseid;
4a490db0 46
8a31e65c 47 /**
48 * The category this category belongs to (optional).
4a490db0 49 * @var int $parent
8a31e65c 50 */
e5c674f1 51 var $parent;
4a490db0 52
8c846243 53 /**
54 * The grade_category object referenced by $this->parent (PK).
55 * @var object $parent_category
56 */
57 var $parent_category;
27f95e9b 58
e5c674f1 59 /**
60 * The number of parents this category has.
61 * @var int $depth
62 */
63 var $depth = 0;
64
65 /**
66 * Shows the hierarchical path for this category as /1/2/3 (like course_categories), the last number being
67 * this category's autoincrement ID number.
68 * @var string $path
69 */
70 var $path;
71
8a31e65c 72 /**
73 * The name of this category.
74 * @var string $fullname
75 */
76 var $fullname;
4a490db0 77
8a31e65c 78 /**
79 * A constant pointing to one of the predefined aggregation strategies (none, mean, median, sum etc) .
4a490db0 80 * @var int $aggregation
8a31e65c 81 */
f92dcad8 82 var $aggregation = GRADE_AGGREGATE_MEAN_ALL;
4a490db0 83
8a31e65c 84 /**
85 * Keep only the X highest items.
86 * @var int $keephigh
87 */
f92dcad8 88 var $keephigh = 0;
4a490db0 89
8a31e65c 90 /**
91 * Drop the X lowest items.
92 * @var int $droplow
93 */
f92dcad8 94 var $droplow = 0;
4a490db0 95
8a31e65c 96 /**
97 * Array of grade_items or grade_categories nested exactly 1 level below this category
98 * @var array $children
99 */
100 var $children;
8a31e65c 101
7c8a963f 102 /**
4a490db0 103 * A hierarchical array of all children below this category. This is stored separately from
7c8a963f 104 * $children because it is more memory-intensive and may not be used as often.
105 * @var array $all_children
106 */
107 var $all_children;
108
f151b073 109 /**
110 * An associated grade_item object, with itemtype=category, used to calculate and cache a set of grade values
111 * for this category.
112 * @var object $grade_item
113 */
114 var $grade_item;
115
b3ac6c3e 116 /**
117 * Temporary sortorder for speedup of children resorting
118 */
119 var $sortorder;
120
e5c674f1 121 /**
122 * Builds this category's path string based on its parents (if any) and its own id number.
123 * This is typically done just before inserting this object in the DB for the first time,
ce385eb4 124 * or when a new parent is added or changed. It is a recursive function: once the calling
125 * object no longer has a parent, the path is complete.
126 *
127 * @static
128 * @param object $grade_category
129 * @return int The depth of this category (2 means there is one parent)
e5c674f1 130 */
ce385eb4 131 function build_path($grade_category) {
132 if (empty($grade_category->parent)) {
b3ac6c3e 133 return '/'.$grade_category->id;
ce385eb4 134 } else {
135 $parent = get_record('grade_categories', 'id', $grade_category->parent);
b3ac6c3e 136 return grade_category::build_path($parent).'/'.$grade_category->id;
ce385eb4 137 }
e5c674f1 138 }
139
8a31e65c 140 /**
f92dcad8 141 * Finds and returns a grade_category instance based on params.
61c33818 142 * @static
8a31e65c 143 *
f92dcad8 144 * @param array $params associative arrays varname=>value
145 * @return object grade_category instance or false if none found.
146 */
147 function fetch($params) {
b3ac6c3e 148 return grade_object::fetch_helper('grade_categories', 'grade_category', $params);
f92dcad8 149 }
150
151 /**
152 * Finds and returns all grade_category instances based on params.
153 * @static
154 *
155 * @param array $params associative arrays varname=>value
156 * @return array array of grade_category insatnces or false if none found.
157 */
158 function fetch_all($params) {
b3ac6c3e 159 return grade_object::fetch_all_helper('grade_categories', 'grade_category', $params);
ce385eb4 160 }
161
8f4a626d 162 /**
2cc4b0f9 163 * In addition to update() as defined in grade_object, call force_regrading of parent categories, if applicable.
aaff71da 164 * @param string $source from where was the object updated (mod/forum, manual, etc.)
165 * @return boolean success
8f4a626d 166 */
aaff71da 167 function update($source=null) {
b3ac6c3e 168 // load the grade item or create a new one
169 $this->load_grade_item();
170
171 // force recalculation of path;
172 if (empty($this->path)) {
173 $this->path = grade_category::build_path($this);
174 $this->depth = substr_count($this->path, '/');
4a490db0 175 }
0fc7f624 176
4a490db0 177
b3ac6c3e 178 // Recalculate grades if needed
179 if ($this->qualifies_for_regrading()) {
aaff71da 180 if (!parent::update($source)) {
6639ead3 181 return false;
182 }
aaff71da 183 $this->grade_item->force_regrading($source);
6639ead3 184 return true;
185
186 } else {
aaff71da 187 return parent::update($source);
4a490db0 188 }
8f4a626d 189 }
4a490db0 190
8f4a626d 191 /**
2cc4b0f9 192 * If parent::delete() is successful, send force_regrading message to parent category.
aaff71da 193 * @param string $source from where was the object deleted (mod/forum, manual, etc.)
194 * @return boolean success
8f4a626d 195 */
aaff71da 196 function delete($source=null) {
f13002d5 197 if ($this->is_course_category()) {
198 debuggin('Can not delete top course category!');
199 return false;
200 }
4a490db0 201
f13002d5 202 $grade_item = $this->load_grade_item();
203 $parent = $this->load_parent_category();
4a490db0 204
f13002d5 205 // Update children's categoryid/parent field first
aaff71da 206 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
207 foreach ($children as $child) {
208 $child->set_parent($parent->id);
209 }
210 }
211 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
212 foreach ($children as $child) {
213 $child->set_parent($parent->id);
214 }
215 }
f13002d5 216
aaff71da 217 // first delete the attached grade item and grades
218 $grade_item->delete($source);
f13002d5 219
220 // delete category itself
aaff71da 221 return parent::delete($source);
8f4a626d 222 }
4a490db0 223
ce385eb4 224 /**
225 * In addition to the normal insert() defined in grade_object, this method sets the depth
226 * and path for this object, and update the record accordingly. The reason why this must
227 * be done here instead of in the constructor, is that they both need to know the record's
4a490db0 228 * id number, which only gets created at insertion time.
f151b073 229 * This method also creates an associated grade_item if this wasn't done during construction.
aaff71da 230 * @param string $source from where was the object inserted (mod/forum, manual, etc.)
231 * @return int PK ID if successful, false otherwise
ce385eb4 232 */
aaff71da 233 function insert($source=null) {
b3ac6c3e 234
235 if (empty($this->courseid)) {
236 error('Can not insert grade category without course id!');
b8ff92b6 237 }
4a490db0 238
b3ac6c3e 239 if (empty($this->parent)) {
240 $course_category = grade_category::fetch_course_category($this->courseid);
241 $this->parent = $course_category->id;
ce385eb4 242 }
4a490db0 243
b3ac6c3e 244 $this->path = null;
245
aaff71da 246 if (!parent::insert($source)) {
b3ac6c3e 247 debugging("Could not insert this category: " . print_r($this, true));
248 return false;
249 }
250
251 // build path and depth
aaff71da 252 $this->update($source);
4a490db0 253
aaff71da 254 return $this->id;
b3ac6c3e 255 }
256
257 function insert_course_category($courseid) {
258 $this->courseid = $courseid;
259 $this->fullname = 'course grade category';
260 $this->path = null;
261 $this->parent = null;
4a490db0 262
aaff71da 263 if (!parent::insert('system')) {
b3ac6c3e 264 debugging("Could not insert this category: " . print_r($this, true));
265 return false;
f151b073 266 }
4a490db0 267
b3ac6c3e 268 // build path and depth
aaff71da 269 $this->update('system');
b3ac6c3e 270
aaff71da 271 return $this->id;
ce385eb4 272 }
4a490db0 273
8f4a626d 274 /**
275 * Compares the values held by this object with those of the matching record in DB, and returns
276 * whether or not these differences are sufficient to justify an update of all parent objects.
277 * This assumes that this object has an id number and a matching record in DB. If not, it will return false.
278 * @return boolean
279 */
2cc4b0f9 280 function qualifies_for_regrading() {
8f4a626d 281 if (empty($this->id)) {
6639ead3 282 debugging("Can not regrade non existing category");
8f4a626d 283 return false;
284 }
285
6639ead3 286 $db_item = grade_category::fetch(array('id'=>$this->id));
4a490db0 287
8f4a626d 288 $aggregationdiff = $db_item->aggregation != $this->aggregation;
b3ac6c3e 289 $keephighdiff = $db_item->keephigh != $this->keephigh;
290 $droplowdiff = $db_item->droplow != $this->droplow;
8f4a626d 291
b3ac6c3e 292 return ($aggregationdiff || $keephighdiff || $droplowdiff);
8f4a626d 293 }
8c846243 294
295 /**
296 * Sets this category's and its parent's grade_item.needsupdate to true.
297 * This is triggered whenever any change in any lower level may cause grade_finals
298 * for this category to require an update. The flag needs to be propagated up all
299 * levels until it reaches the top category. This is then used to determine whether or not
cb64c6b2 300 * to regenerate the raw and final grades for each category grade_item. This is accomplished
301 * thanks to the path variable, so we don't need to use recursion.
aaff71da 302 * @param string $source from where was the object updated (mod/forum, manual, etc.)
8c846243 303 * @return boolean Success or failure
304 */
aaff71da 305 function force_regrading($source=null) {
b8ff92b6 306 if (empty($this->id)) {
6639ead3 307 debugging("Needsupdate requested before inserting grade category.");
b8ff92b6 308 return true;
309 }
310
8c846243 311 $this->load_grade_item();
8f4a626d 312
2e53372c 313 if ($this->grade_item->needsupdate) {
314 // this grade_item (and category) already needs update, no need to set it again here or in parent categories
315 return true;
316 }
317
cb64c6b2 318 $paths = explode('/', $this->path);
4a490db0 319
77d2540e 320 // Remove the first index, which is always empty
321 unset($paths[0]);
4a490db0 322
2e53372c 323 $result = true;
324
77d2540e 325 if (!empty($paths)) {
326 $wheresql = '';
4a490db0 327
77d2540e 328 foreach ($paths as $categoryid) {
329 $wheresql .= "iteminstance = $categoryid OR ";
330 }
331 $wheresql = substr($wheresql, 0, strrpos($wheresql, 'OR'));
a3d55942 332 $grade_items = set_field_select('grade_items', 'needsupdate', '1', $wheresql . ' AND courseid = ' . $this->courseid);
77d2540e 333 $this->grade_item->update_from_db();
2cc4b0f9 334
335 }
336
8c846243 337 return $result;
338 }
339
0aa32279 340 /**
ac9b0805 341 * Generates and saves raw_grades in associated category grade item.
342 * These immediate children must alrady have their own final grades.
343 * The category's aggregation method is used to generate raw grades.
344 *
345 * Please note that category grade is either calculated or aggregated - not both at the same time.
346 *
347 * This method must be used ONLY from grade_item::update_final_grades(),
348 * because the calculation must be done in correct order!
b8ff92b6 349 *
4a490db0 350 * Steps to follow:
ac9b0805 351 * 1. Get final grades from immediate children
2df71235 352 * 3. Aggregate these grades
ac9b0805 353 * 4. Save them in raw grades of associated category grade item
0aa32279 354 */
355 function generate_grades() {
b8ff92b6 356 global $CFG;
4a490db0 357
ac9b0805 358 $this->load_grade_item();
2cc4b0f9 359
360 if ($this->grade_item->is_locked()) {
361 return true; // no need to recalculate locked items
362 }
363
ac9b0805 364 $this->grade_item->load_scale();
2df71235 365
2cc4b0f9 366
b3ac6c3e 367 // find grade items of immediate children (category or grade items)
61c33818 368 $depends_on = $this->grade_item->depends_on();
b3ac6c3e 369
b8ff92b6 370 $items = array();
4a490db0 371
61c33818 372 foreach($depends_on as $dep) {
f92dcad8 373 $items[$dep] = grade_item::fetch(array('id'=>$dep));
b8ff92b6 374 }
4a490db0 375
ac9b0805 376 // where to look for final grades - include or grade item too
61c33818 377 $gis = implode(',', array_merge($depends_on, array($this->grade_item->id)));
b8ff92b6 378
ac9b0805 379 $sql = "SELECT g.*
380 FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items gi
381 WHERE gi.id = g.itemid AND gi.courseid={$this->grade_item->courseid} AND gi.id IN ($gis)
382 ORDER BY g.userid";
b8ff92b6 383
ac9b0805 384 // group the results by userid and aggregate the grades in this group
b8ff92b6 385 if ($rs = get_recordset_sql($sql)) {
386 if ($rs->RecordCount() > 0) {
387 $prevuser = 0;
388 $grades = array();
ac9b0805 389 $final = null;
390 while ($used = rs_fetch_next_record($rs)) {
391 if ($used->userid != $prevuser) {
61c33818 392 $this->aggregate_grades($prevuser, $items, $grades, $depends_on, $final);
ac9b0805 393 $prevuser = $used->userid;
b8ff92b6 394 $grades = array();
ac9b0805 395 $final = null;
396 }
397 if ($used->itemid == $this->grade_item->id) {
398 $final = new grade_grades($used, false);
2cc4b0f9 399 $final->grade_item =& $this->grade_item;
b8ff92b6 400 }
ac9b0805 401 $grades[$used->itemid] = $used->finalgrade;
2df71235 402 }
61c33818 403 $this->aggregate_grades($prevuser, $items, $grades, $depends_on, $final);
b8ff92b6 404 }
405 }
406
b8ff92b6 407 return true;
408 }
409
410 /**
ac9b0805 411 * internal function for category grades aggregation
b8ff92b6 412 */
61c33818 413 function aggregate_grades($userid, $items, $grades, $depends_on, $final) {
b8ff92b6 414 if (empty($userid)) {
ac9b0805 415 //ignore first run
b8ff92b6 416 return;
417 }
4a490db0 418
ac9b0805 419 // no circular references allowed
420 unset($grades[$this->grade_item->id]);
b8ff92b6 421
2cc4b0f9 422 // insert final grade - it will be needed later anyway
ac9b0805 423 if (empty($final)) {
424 $final = new grade_grades(array('itemid'=>$this->grade_item->id, 'userid'=>$userid), false);
425 $final->insert();
2cc4b0f9 426 $final->grade_item =& $this->grade_item;
427
428 } else if ($final->is_locked()) {
429 // no need to recalculate locked grades
430 return;
ac9b0805 431 }
432
433 // if no grades calculation possible or grading not allowed clear both final and raw
434 if (empty($grades) or empty($items) or ($this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE)) {
435 $final->finalgrade = null;
436 $final->rawgrade = null;
437 $final->update();
b8ff92b6 438 return;
439 }
4a490db0 440
b8ff92b6 441 // normalize the grades first - all will have value 0...1
ac9b0805 442 // ungraded items are not used in aggreagation
b8ff92b6 443 foreach ($grades as $k=>$v) {
444 if (is_null($v)) {
445 // null means no grade
446 unset($grades[$k]);
447 continue;
0aa32279 448 }
ac9b0805 449 $grades[$k] = grade_grades::standardise_score($v, $items[$k]->grademin, $items[$k]->grademax, 0, 1);
0aa32279 450 }
dda0c7e6 451
ac9b0805 452 //limit and sort
b8ff92b6 453 $this->apply_limit_rules($grades);
454 sort($grades, SORT_NUMERIC);
4a490db0 455
ac9b0805 456 // let's see we have still enough grades to do any statisctics
b8ff92b6 457 if (count($grades) == 0) {
ac9b0805 458 // not enough attempts yet
459 if (!is_null($final->finalgrade) or !is_null($final->rawgrade)) {
460 $final->finalgrade = null;
461 $final->rawgrade = null;
462 $final->update();
b8ff92b6 463 }
464 return;
465 }
2df71235 466
b8ff92b6 467 switch ($this->aggregation) {
468 case GRADE_AGGREGATE_MEDIAN: // Middle point value in the set: ignores frequencies
469 $num = count($grades);
470 $halfpoint = intval($num / 2);
471
472 if($num % 2 == 0) {
ac9b0805 473 $rawgrade = ($grades[ceil($halfpoint)] + $grades[floor($halfpoint)]) / 2;
b8ff92b6 474 } else {
ac9b0805 475 $rawgrade = $grades[$halfpoint];
b8ff92b6 476 }
477 break;
ac9b0805 478
b8ff92b6 479 case GRADE_AGGREGATE_MIN:
ac9b0805 480 $rawgrade = reset($grades);
b8ff92b6 481 break;
482
483 case GRADE_AGGREGATE_MAX:
ac9b0805 484 $rawgrade = array_pop($grades);
b8ff92b6 485 break;
486
95affb8a 487 case GRADE_AGGREGATE_MEAN_ALL: // Arithmetic average of all grade items including even NULLs; NULL grade caunted as minimum
61c33818 488 $num = count($depends_on); // you can calculate sum from this one if you multiply it with count($this->depends_on() ;-)
b8ff92b6 489 $sum = array_sum($grades);
ac9b0805 490 $rawgrade = $sum / $num;
b8ff92b6 491 break;
492
95affb8a 493 case GRADE_AGGREGATE_MODE: // the most common value, the highest one if multimode
494 $freq = array_count_values($grades);
495 arsort($freq); // sort by frequency keeping keys
496 $top = reset($freq); // highest frequency count
497 $modes = array_keys($freq, $top); // search for all modes (have the same highest count)
498 rsort($modes, SORT_NUMERIC); // get highes mode
ac9b0805 499 $rawgrade = reset($modes);
95affb8a 500
501 case GRADE_AGGREGATE_MEAN_GRADED: // Arithmetic average of all final grades, unfinished are not calculated
ac9b0805 502 default:
b8ff92b6 503 $num = count($grades);
504 $sum = array_sum($grades);
ac9b0805 505 $rawgrade = $sum / $num;
b8ff92b6 506 break;
507 }
508
ac9b0805 509 // recalculate the rawgrade back to requested range
510 $rawgrade = $this->grade_item->adjust_grade($rawgrade, 0, 1);
b8ff92b6 511
ac9b0805 512 // prepare update of new raw grade
513 $final->rawgrade = $rawgrade;
514 $final->finalgrade = null;
515 $final->rawgrademin = $this->grade_item->grademin;
516 $final->rawgrademax = $this->grade_item->grademax;
517 $final->rawscaleid = $this->grade_item->scaleid;
2df71235 518
ac9b0805 519 // TODO - add some checks to prevent updates when not needed
520 $final->update();
0aa32279 521 }
522
adc2f286 523 /**
524 * Given an array of grade values (numerical indices), applies droplow or keephigh
525 * rules to limit the final array.
526 * @param array $grades
527 * @return array Limited grades.
528 */
b8ff92b6 529 function apply_limit_rules(&$grades) {
adc2f286 530 rsort($grades, SORT_NUMERIC);
531 if (!empty($this->droplow)) {
532 for ($i = 0; $i < $this->droplow; $i++) {
533 array_pop($grades);
534 }
4a490db0 535 } elseif (!empty($this->keephigh)) {
adc2f286 536 while (count($grades) > $this->keephigh) {
4a490db0 537 array_pop($grades);
adc2f286 538 }
539 }
0aa32279 540 }
541
0fc7f624 542 /**
543 * Returns true if this category has any child grade_category or grade_item.
544 * @return int number of direct children, or false if none found.
545 */
546 function has_children() {
547 return count_records('grade_categories', 'parent', $this->id) + count_records('grade_items', 'categoryid', $this->id);
548 }
549
1c307f21 550 /**
b3ac6c3e 551 * Returns tree with all grade_items and categories as elements
552 * @static
553 * @param int $courseid
554 * @param boolean $include_grades include final grades
555 * @param boolean $include_category_items as category children
556 * @return array
1c307f21 557 */
b3ac6c3e 558 function fetch_course_tree($courseid, $include_grades=false, $include_category_items=false) {
559 $course_category = grade_category::fetch_course_category($courseid);
314c4336 560 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
b3ac6c3e 561 'children'=>$course_category->get_children($include_grades, $include_category_items));
562 if ($include_grades) {
563 $category_array['finalgrades'] = $course_category->get_final();
564 }
314c4336 565 $sortorder = 1;
566 $course_category->set_sortorder($sortorder);
567 $course_category->sortorder = $sortorder;
b3ac6c3e 568 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 569 }
570
b3ac6c3e 571 function _fetch_course_tree_recursion($category_array, &$sortorder) {
572 // update the sortorder in db if needed
573 if ($category_array['object']->sortorder != $sortorder) {
574 $category_array['object']->set_sortorder($sortorder);
ce385eb4 575 }
ce385eb4 576
314c4336 577 // store the grade_item or grade_category instance with extra info
578 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 579
580 // reuse final grades if there
581 if (array_key_exists('finalgrades', $category_array)) {
582 $result['finalgrades'] = $category_array['finalgrades'];
583 }
584
585 // recursively resort children
586 if (!empty($category_array['children'])) {
587 $result['children'] = array();
588 foreach($category_array['children'] as $oldorder=>$child_array) {
314c4336 589 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
b3ac6c3e 590 $result['children'][$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
591 } else {
592 $result['children'][++$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
593 }
594 }
595 }
596
597 return $result;
ce385eb4 598 }
7c8a963f 599
600 /**
4a490db0 601 * Fetches and returns all the children categories and/or grade_items belonging to this category.
602 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 603 * as well as all levels (0). The elements are indexed by sort order.
7c8a963f 604 * @return array Array of child objects (grade_category and grade_item).
605 */
b3ac6c3e 606 function get_children($include_grades=false, $include_category_items=false) {
607
608 // This function must be as fast as possible ;-)
609 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
610 // we have to limit the number of queries though, because it will be used often in grade reports
611
612 $cats = get_records('grade_categories', 'courseid', $this->courseid);
613 $items = get_records('grade_items', 'courseid', $this->courseid);
4a490db0 614
b3ac6c3e 615 // init children array first
616 foreach ($cats as $catid=>$cat) {
617 $cats[$catid]->children = array();
27f95e9b 618 }
4a490db0 619
b3ac6c3e 620 //first attach items to cats and add category sortorder
621 foreach ($items as $item) {
622 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
623 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 624
b3ac6c3e 625 if (!$include_category_items) {
626 continue;
627 }
628 $categoryid = $item->iteminstance;
629 } else {
630 $categoryid = $item->categoryid;
631 }
632
633 // prevent problems with duplicate sortorders in db
634 $sortorder = $item->sortorder;
635 while(array_key_exists($sortorder, $cats[$categoryid]->children)) {
f13002d5 636 //debugging("$sortorder exists in item loop");
b3ac6c3e 637 $sortorder++;
638 }
639
640 $cats[$categoryid]->children[$sortorder] = $item;
641
642 }
643
644 // now find the requested category and connect categories as children
645 $category = false;
646 foreach ($cats as $catid=>$cat) {
647 if (!empty($cat->parent)) {
648 // prevent problems with duplicate sortorders in db
649 $sortorder = $cat->sortorder;
650 while(array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 651 //debugging("$sortorder exists in cat loop");
b3ac6c3e 652 $sortorder++;
653 }
654
655 $cats[$cat->parent]->children[$sortorder] = $cat;
656 }
657
658 if ($catid == $this->id) {
659 $category = &$cats[$catid];
660 }
661 }
662
663 unset($items); // not needed
664 unset($cats); // not needed
665
666 $children_array = grade_category::_get_children_recursion($category, $include_grades);
667
668 ksort($children_array);
669
670 return $children_array;
671
672 }
673
674 function _get_children_recursion($category, $include_grades) {
675
676 $children_array = array();
677 foreach($category->children as $sortorder=>$child) {
678 if (array_key_exists('itemtype', $child)) {
679 $grade_item = new grade_item($child, false);
314c4336 680 if (in_array($grade_item->itemtype, array('course', 'category'))) {
681 $type = $grade_item->itemtype.'item';
682 $depth = $category->depth;
683 } else {
684 $type = 'item';
685 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 686 }
314c4336 687 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 688
7c8a963f 689 } else {
b3ac6c3e 690 $children = grade_category::_get_children_recursion($child, $include_grades);
691 $grade_category = new grade_category($child, false);
692 if (empty($children)) {
314c4336 693 $children = array();
7c8a963f 694 }
314c4336 695 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
696 }
697
698 if ($include_grades) {
699 $children_array[$sortorder]['finalgrades'] = $grade_item->get_final();
27f95e9b 700 }
27f95e9b 701 }
702
b3ac6c3e 703 // sort the array
704 ksort($children_array);
705
27f95e9b 706 return $children_array;
707 }
4a490db0 708
f151b073 709 /**
ab53054f 710 * Uses get_grade_item to load or create a grade_item, then saves it as $this->grade_item.
f151b073 711 * @return object Grade_item
712 */
713 function load_grade_item() {
ac9b0805 714 if (empty($this->grade_item)) {
715 $this->grade_item = $this->get_grade_item();
716 }
ab53054f 717 return $this->grade_item;
718 }
4a490db0 719
ab53054f 720 /**
721 * Retrieves from DB and instantiates the associated grade_item object.
722 * If no grade_item exists yet, create one.
723 * @return object Grade_item
724 */
725 function get_grade_item() {
c91ed4be 726 if (empty($this->id)) {
727 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
728 return false;
729 }
730
b3ac6c3e 731 if (empty($this->parent)) {
732 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
733
734 } else {
735 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
736 }
f92dcad8 737
738 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 739 // create a new one
f92dcad8 740 $grade_item = new grade_item($params, false);
b8ff92b6 741 $grade_item->gradetype = GRADE_TYPE_VALUE;
742 $grade_item->insert();
4a490db0 743
b8ff92b6 744 } else if (count($grade_items) == 1){
745 // found existing one
746 $grade_item = reset($grade_items);
4a490db0 747
b8ff92b6 748 } else {
749 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 750 // return first one
751 $grade_item = reset($grade_items);
2c72af1f 752 }
753
ab53054f 754 return $grade_item;
f151b073 755 }
8c846243 756
757 /**
758 * Uses $this->parent to instantiate $this->parent_category based on the
759 * referenced record in the DB.
760 * @return object Parent_category
761 */
762 function load_parent_category() {
763 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 764 $this->parent_category = $this->get_parent_category();
8c846243 765 }
766 return $this->parent_category;
4a490db0 767 }
768
ab53054f 769 /**
770 * Uses $this->parent to instantiate and return a grade_category object.
771 * @return object Parent_category
772 */
773 function get_parent_category() {
774 if (!empty($this->parent)) {
775 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 776 return $parent_category;
ab53054f 777 } else {
778 return null;
779 }
780 }
781
2186f72c 782 /**
4a490db0 783 * Returns the most descriptive field for this object. This is a standard method used
2186f72c 784 * when we do not know the exact type of an object.
785 * @return string name
786 */
787 function get_name() {
314c4336 788 if (empty($this->parent)) {
789 return "Top course category"; //TODO: localize
790 } else {
791 return $this->fullname;
792 }
2186f72c 793 }
c91ed4be 794
0fc7f624 795 /**
796 * Sets this category's parent id. A generic method shared by objects that have a parent id of some kind.
f13002d5 797 * @param int parentid
798 * @return boolean success
0fc7f624 799 */
f13002d5 800 function set_parent($parentid) {
801 if ($this->parent == $parentid) {
802 return true;
803 }
804
805 if ($parentid == $this->id) {
806 error('Can not assign self as parent!');
807 }
808
809 if (empty($this->parent) and $this->is_course_category()) {
810 error('Course category can not have parent!');
b3ac6c3e 811 }
f13002d5 812
813 // find parent and check course id
814 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 815 return false;
816 }
817
818 $this->force_regrading(); // mark old parent as needing regrading
819
820 // set new parent category
821 $this->parent = $parentid;
822 $this->path = null; // remove old path and depth - will be recalculated in update()
823 $this->parent_category = null;
824 $this->update();
825
826 $grade_item = $this->load_grade_item();
827 $grade_item->parent_category = null;
828 return $grade_item->update(); // marks new parent as needing regrading too
829 }
830
831 /**
832 * Returns the final values for this grade category.
833 * @param int $userid Optional: to retrieve a single final grade
834 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
835 */
836 function get_final($userid=NULL) {
837 $this->load_grade_item();
838 return $this->grade_item->get_final($userid);
0fc7f624 839 }
4a490db0 840
0fc7f624 841 /**
4a490db0 842 * Returns the sortorder of the associated grade_item. This method is also available in
5fad5061 843 * grade_item, for cases where the object type is not known.
0fc7f624 844 * @return int Sort order
845 */
846 function get_sortorder() {
b3ac6c3e 847 $this->load_grade_item();
848 return $this->grade_item->get_sortorder();
0fc7f624 849 }
850
851 /**
b3ac6c3e 852 * Sets sortorder variable for this category.
4a490db0 853 * This method is also available in grade_item, for cases where the object type is not know.
0fc7f624 854 * @param int $sortorder
855 * @return void
856 */
857 function set_sortorder($sortorder) {
b3ac6c3e 858 $this->load_grade_item();
859 $this->grade_item->set_sortorder($sortorder);
860 }
861
6639ead3 862 /**
863 * Move this category after the given sortorder - does not change the parent
864 * @param int $sortorder to place after
865 */
f13002d5 866 function move_after_sortorder($sortorder) {
867 $this->load_grade_item();
868 $this->grade_item->move_after_sortorder($sortorder);
869 }
870
b3ac6c3e 871 /**
f13002d5 872 * Return true if this is the top most category that represents the total course grade.
b3ac6c3e 873 * @return boolean
874 */
875 function is_course_category() {
876 $this->load_grade_item();
877 return $this->grade_item->is_course_item();
878 }
879
880 /**
881 * Return the top most course category.
882 * @static
883 * @return object grade_category instance for course grade
884 */
885 function fetch_course_category($courseid) {
886
887 // course category has no parent
888 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
889 return $course_category;
890 }
891
892 // create a new one
893 $course_category = new grade_category();
894 $course_category->insert_course_category($courseid);
895
896 return $course_category;
0fc7f624 897 }
4a490db0 898
5fad5061 899 /**
4a490db0 900 * Returns the locked state/date of the associated grade_item. This method is also available in
901 * grade_item, for cases where the object type is not known.
22e23c78 902 * @return boolean
5fad5061 903 */
2cc4b0f9 904 function is_locked() {
5fad5061 905 $this->load_grade_item();
22e23c78 906 return $this->grade_item->is_locked();
5fad5061 907 }
908
909 /**
910 * Sets the grade_item's locked variable and updates the grade_item.
911 * Method named after grade_item::set_locked().
912 * @param int $locked 0, 1 or a timestamp int(10) after which date the item will be locked.
2cc4b0f9 913 * @return boolean success
5fad5061 914 */
2cc4b0f9 915 function set_locked($lockedstate) {
5fad5061 916 $this->load_grade_item();
22e23c78 917 return $this->grade_item->set_locked($lockedstate);
5fad5061 918 }
4a490db0 919
5fad5061 920 /**
4a490db0 921 * Returns the hidden state/date of the associated grade_item. This method is also available in
22e23c78 922 * grade_item.
923 * @return boolean
5fad5061 924 */
22e23c78 925 function is_hidden() {
5fad5061 926 $this->load_grade_item();
22e23c78 927 return $this->grade_item->is_hidden();
5fad5061 928 }
929
930 /**
4a490db0 931 * Sets the grade_item's hidden variable and updates the grade_item.
5fad5061 932 * Method named after grade_item::set_hidden().
933 * @param int $hidden 0, 1 or a timestamp int(10) after which date the item will be hidden.
934 * @return void
935 */
936 function set_hidden($hidden) {
937 $this->load_grade_item();
22e23c78 938 $this->grade_item->set_hidden($hidden);
f13002d5 939 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
940 foreach($children as $child) {
941 $child->set_hidden($hidden);
942 }
943 }
944 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
945 foreach($children as $child) {
946 $child->set_hidden($hidden);
947 }
948 }
5fad5061 949 }
950
4a490db0 951}
8a31e65c 952?>