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