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