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