MDL-11082 Improved groups upgrade performance 1.8x -> 1.9; thanks Eloy for telling...
[moodle-pu.git] / lib / grade / grade_category.php
blob70cc6fc9f602af68e803376a8073ad1123ec6145
1 <?php // $Id$
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 ///////////////////////////////////////////////////////////////////////////
26 require_once('grade_object.php');
28 class grade_category extends grade_object {
29 /**
30 * The DB table.
31 * @var string $table
33 var $table = 'grade_categories';
35 /**
36 * Array of class variables that are not part of the DB table fields
37 * @var array $nonfields
39 var $nonfields = array('table', 'required_fields', 'nonfields', 'children', 'all_children', 'grade_item', 'parent_category', 'sortorder');
41 /**
42 * The course this category belongs to.
43 * @var int $courseid
45 var $courseid;
47 /**
48 * The category this category belongs to (optional).
49 * @var int $parent
51 var $parent;
53 /**
54 * The grade_category object referenced by $this->parent (PK).
55 * @var object $parent_category
57 var $parent_category;
59 /**
60 * The number of parents this category has.
61 * @var int $depth
63 var $depth = 0;
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
70 var $path;
72 /**
73 * The name of this category.
74 * @var string $fullname
76 var $fullname;
78 /**
79 * A constant pointing to one of the predefined aggregation strategies (none, mean, median, sum etc) .
80 * @var int $aggregation
82 var $aggregation = GRADE_AGGREGATE_MEAN_ALL;
84 /**
85 * Keep only the X highest items.
86 * @var int $keephigh
88 var $keephigh = 0;
90 /**
91 * Drop the X lowest items.
92 * @var int $droplow
94 var $droplow = 0;
96 /**
97 * Aggregate outcomes together with normal items
98 * @$aggregateoutcomes
100 var $aggregateoutcomes = 0;
103 * Array of grade_items or grade_categories nested exactly 1 level below this category
104 * @var array $children
106 var $children;
109 * A hierarchical array of all children below this category. This is stored separately from
110 * $children because it is more memory-intensive and may not be used as often.
111 * @var array $all_children
113 var $all_children;
116 * An associated grade_item object, with itemtype=category, used to calculate and cache a set of grade values
117 * for this category.
118 * @var object $grade_item
120 var $grade_item;
123 * Temporary sortorder for speedup of children resorting
125 var $sortorder;
128 * Builds this category's path string based on its parents (if any) and its own id number.
129 * This is typically done just before inserting this object in the DB for the first time,
130 * or when a new parent is added or changed. It is a recursive function: once the calling
131 * object no longer has a parent, the path is complete.
133 * @static
134 * @param object $grade_category
135 * @return int The depth of this category (2 means there is one parent)
137 function build_path($grade_category) {
138 if (empty($grade_category->parent)) {
139 return '/'.$grade_category->id;
140 } else {
141 $parent = get_record('grade_categories', 'id', $grade_category->parent);
142 return grade_category::build_path($parent).'/'.$grade_category->id;
147 * Finds and returns a grade_category instance based on params.
148 * @static
150 * @param array $params associative arrays varname=>value
151 * @return object grade_category instance or false if none found.
153 function fetch($params) {
154 return grade_object::fetch_helper('grade_categories', 'grade_category', $params);
158 * Finds and returns all grade_category instances based on params.
159 * @static
161 * @param array $params associative arrays varname=>value
162 * @return array array of grade_category insatnces or false if none found.
164 function fetch_all($params) {
165 return grade_object::fetch_all_helper('grade_categories', 'grade_category', $params);
169 * In addition to update() as defined in grade_object, call force_regrading of parent categories, if applicable.
170 * @param string $source from where was the object updated (mod/forum, manual, etc.)
171 * @return boolean success
173 function update($source=null) {
174 // load the grade item or create a new one
175 $this->load_grade_item();
177 // force recalculation of path;
178 if (empty($this->path)) {
179 $this->path = grade_category::build_path($this);
180 $this->depth = substr_count($this->path, '/');
184 // Recalculate grades if needed
185 if ($this->qualifies_for_regrading()) {
186 $this->force_regrading();
189 return parent::update($source);
193 * If parent::delete() is successful, send force_regrading message to parent category.
194 * @param string $source from where was the object deleted (mod/forum, manual, etc.)
195 * @return boolean success
197 function delete($source=null) {
198 $grade_item = $this->load_grade_item();
200 if ($this->is_course_category()) {
201 if ($categories = grade_category::fetch_all(array('courseid'=>$this->courseid))) {
202 foreach ($categories as $category) {
203 if ($category->id == $this->id) {
204 continue; // do not delete course category yet
206 $category->delete($source);
210 if ($items = grade_item::fetch_all(array('courseid'=>$this->courseid))) {
211 foreach ($items as $item) {
212 if ($item->id == $grade_item->id) {
213 continue; // do not delete course item yet
215 $item->delete($source);
219 } else {
220 $this->force_regrading();
222 $parent = $this->load_parent_category();
224 // Update children's categoryid/parent field first
225 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
226 foreach ($children as $child) {
227 $child->set_parent($parent->id);
230 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
231 foreach ($children as $child) {
232 $child->set_parent($parent->id);
237 // first delete the attached grade item and grades
238 $grade_item->delete($source);
240 // delete category itself
241 return parent::delete($source);
245 * In addition to the normal insert() defined in grade_object, this method sets the depth
246 * and path for this object, and update the record accordingly. The reason why this must
247 * be done here instead of in the constructor, is that they both need to know the record's
248 * id number, which only gets created at insertion time.
249 * This method also creates an associated grade_item if this wasn't done during construction.
250 * @param string $source from where was the object inserted (mod/forum, manual, etc.)
251 * @return int PK ID if successful, false otherwise
253 function insert($source=null) {
255 if (empty($this->courseid)) {
256 error('Can not insert grade category without course id!');
259 if (empty($this->parent)) {
260 $course_category = grade_category::fetch_course_category($this->courseid);
261 $this->parent = $course_category->id;
264 $this->path = null;
266 if (!parent::insert($source)) {
267 debugging("Could not insert this category: " . print_r($this, true));
268 return false;
271 $this->force_regrading();
273 // build path and depth
274 $this->update($source);
276 return $this->id;
280 * Internal function - used only from fetch_course_category()
281 * Normal insert() can not be used for course category
282 * @param int $courseid
283 * @return bool success
285 function insert_course_category($courseid) {
286 $this->courseid = $courseid;
287 $this->fullname = 'course grade category';
288 $this->path = null;
289 $this->parent = null;
290 $this->aggregate = GRADE_AGGREGATE_MEAN_ALL;
292 if (!parent::insert('system')) {
293 debugging("Could not insert this category: " . print_r($this, true));
294 return false;
297 // build path and depth
298 $this->update('system');
300 return $this->id;
304 * Compares the values held by this object with those of the matching record in DB, and returns
305 * whether or not these differences are sufficient to justify an update of all parent objects.
306 * This assumes that this object has an id number and a matching record in DB. If not, it will return false.
307 * @return boolean
309 function qualifies_for_regrading() {
310 if (empty($this->id)) {
311 debugging("Can not regrade non existing category");
312 return false;
315 $db_item = grade_category::fetch(array('id'=>$this->id));
317 $aggregationdiff = $db_item->aggregation != $this->aggregation;
318 $keephighdiff = $db_item->keephigh != $this->keephigh;
319 $droplowdiff = $db_item->droplow != $this->droplow;
320 $aggoutcomesdiff = $db_item->aggregateoutcomes != $this->aggregateoutcomes;
322 return ($aggregationdiff || $keephighdiff || $droplowdiff || $aggoutcomesdiff);
326 * Marks the category and course item as needing update - categories are always regraded.
327 * @return void
329 function force_regrading() {
330 $grade_item = $this->load_grade_item();
331 $grade_item->force_regrading();
335 * Generates and saves raw_grades in associated category grade item.
336 * These immediate children must alrady have their own final grades.
337 * The category's aggregation method is used to generate raw grades.
339 * Please note that category grade is either calculated or aggregated - not both at the same time.
341 * This method must be used ONLY from grade_item::regrade_final_grades(),
342 * because the calculation must be done in correct order!
344 * Steps to follow:
345 * 1. Get final grades from immediate children
346 * 3. Aggregate these grades
347 * 4. Save them in raw grades of associated category grade item
349 function generate_grades($userid=null) {
350 global $CFG;
352 $this->load_grade_item();
354 if ($this->grade_item->is_locked()) {
355 return true; // no need to recalculate locked items
358 $this->grade_item->load_scale();
360 // find grade items of immediate children (category or grade items)
361 $depends_on = $this->grade_item->depends_on();
363 if (empty($depends_on)) {
364 $items = false;
365 } else {
366 $gis = implode(',', $depends_on);
367 $sql = "SELECT *
368 FROM {$CFG->prefix}grade_items
369 WHERE id IN ($gis)";
370 $items = get_records_sql($sql);
373 if ($userid) {
374 $usersql = "AND g.userid=$userid";
375 } else {
376 $usersql = "";
379 // where to look for final grades - include grade of this item too, we will store the results there
380 $gis = implode(',', array_merge($depends_on, array($this->grade_item->id)));
381 $sql = "SELECT g.*
382 FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items gi
383 WHERE gi.id = g.itemid AND gi.id IN ($gis) $usersql
384 ORDER BY g.userid";
386 // group the results by userid and aggregate the grades for this user
387 if ($rs = get_recordset_sql($sql)) {
388 if ($rs->RecordCount() > 0) {
389 $prevuser = 0;
390 $grade_values = array();
391 $excluded = array();
392 $oldgrade = null;
393 while ($used = rs_fetch_next_record($rs)) {
394 if ($used->userid != $prevuser) {
395 $this->aggregate_grades($prevuser, $items, $grade_values, $oldgrade, $excluded);
396 $prevuser = $used->userid;
397 $grade_values = array();
398 $excluded = array();
399 $oldgrade = null;
401 $grade_values[$used->itemid] = $used->finalgrade;
402 if ($used->excluded) {
403 $excluded[] = $used->itemid;
405 if ($this->grade_item->id == $used->itemid) {
406 $oldgrade = $used;
409 $this->aggregate_grades($prevuser, $items, $grade_values, $oldgrade, $excluded);//the last one
411 rs_close($rs);
414 return true;
418 * internal function for category grades aggregation
420 function aggregate_grades($userid, $items, $grade_values, $oldgrade, $excluded) {
421 if (empty($userid)) {
422 //ignore first call
423 return;
426 if ($oldgrade) {
427 $grade = new grade_grade($oldgrade, false);
428 $grade->grade_item =& $this->grade_item;
430 } else {
431 // insert final grade - it will be needed later anyway
432 $grade = new grade_grade(array('itemid'=>$this->grade_item->id, 'userid'=>$userid), false);
433 $grade->insert('system');
434 $grade->grade_item =& $this->grade_item;
436 $oldgrade = new object();
437 $oldgrade->finalgrade = $grade->finalgrade;
438 $oldgrade->rawgrade = $grade->rawgrade;
439 $oldgrade->rawgrademin = $grade->rawgrademin;
440 $oldgrade->rawgrademax = $grade->rawgrademax;
441 $oldgrade->rawscaleid = $grade->rawscaleid;
444 // no need to recalculate locked or overridden grades
445 if ($grade->is_locked() or $grade->is_overridden()) {
446 return;
449 // can not use own final category grade in calculation
450 unset($grade_values[$this->grade_item->id]);
452 // if no grades calculation possible or grading not allowed clear both final and raw
453 if (empty($grade_values) or empty($items) or ($this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE)) {
454 $grade->finalgrade = null;
455 $grade->rawgrade = null;
456 if ($grade->finalgrade !== $oldgrade->finalgrade or $grade->rawgrade !== $oldgrade->rawgrade) {
457 $grade->update('system');
459 return;
462 /// normalize the grades first - all will have value 0...1
463 // ungraded items are not used in aggregation
464 foreach ($grade_values as $itemid=>$v) {
465 if (is_null($v)) {
466 // null means no grade
467 unset($grade_values[$itemid]);
468 continue;
469 } else if (in_array($itemid, $excluded)) {
470 unset($grade_values[$itemid]);
471 continue;
474 $grade_values[$itemid] = grade_grade::standardise_score($v, $items[$itemid]->grademin, $items[$itemid]->grademax, 0, 1);
477 // use min grade if grade missing for these types
478 switch ($this->aggregation) {
479 case GRADE_AGGREGATE_MEAN_ALL:
480 case GRADE_AGGREGATE_MEDIAN_ALL:
481 case GRADE_AGGREGATE_MIN_ALL:
482 case GRADE_AGGREGATE_MAX_ALL:
483 case GRADE_AGGREGATE_MODE_ALL:
484 case GRADE_AGGREGATE_WEIGHTED_MEAN_ALL:
485 case GRADE_AGGREGATE_EXTRACREDIT_MEAN_ALL:
486 foreach($items as $itemid=>$value) {
487 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
488 $grade_values[$itemid] = 0;
491 break;
494 // limit and sort
495 $this->apply_limit_rules($grade_values);
496 asort($grade_values, SORT_NUMERIC);
498 // let's see we have still enough grades to do any statistics
499 if (count($grade_values) == 0) {
500 // not enough attempts yet
501 $grade->finalgrade = null;
502 $grade->rawgrade = null;
503 if ($grade->finalgrade !== $oldgrade->finalgrade or $grade->rawgrade !== $oldgrade->rawgrade) {
504 $grade->update('system');
506 return;
509 /// start the aggregation
510 switch ($this->aggregation) {
511 case GRADE_AGGREGATE_MEDIAN_ALL: // Middle point value in the set: ignores frequencies
512 case GRADE_AGGREGATE_MEDIAN_GRADED:
513 $num = count($grade_values);
514 $grades = array_values($grade_values);
515 if ($num % 2 == 0) {
516 $rawgrade = ($grades[intval($num/2)-1] + $grades[intval($num/2)]) / 2;
517 } else {
518 $rawgrade = $grades[intval(($num/2)-0.5)];
520 break;
522 case GRADE_AGGREGATE_MIN_ALL:
523 case GRADE_AGGREGATE_MIN_GRADED:
524 $rawgrade = reset($grade_values);
525 break;
527 case GRADE_AGGREGATE_MAX_ALL:
528 case GRADE_AGGREGATE_MAX_GRADED:
529 $rawgrade = array_pop($grade_values);
530 break;
532 case GRADE_AGGREGATE_MODE_ALL: // the most common value, average used if multimode
533 case GRADE_AGGREGATE_MODE_GRADED:
534 $freq = array_count_values($grade_values);
535 arsort($freq); // sort by frequency keeping keys
536 $top = reset($freq); // highest frequency count
537 $modes = array_keys($freq, $top); // search for all modes (have the same highest count)
538 rsort($modes, SORT_NUMERIC); // get highes mode
539 $rawgrade = reset($modes);
540 break;
542 case GRADE_AGGREGATE_WEIGHTED_MEAN_GRADED: // Weighted average of all existing final grades
543 case GRADE_AGGREGATE_WEIGHTED_MEAN_ALL:
544 $weightsum = 0;
545 $sum = 0;
546 foreach($grade_values as $itemid=>$grade_value) {
547 if ($items[$itemid]->aggregationcoef <= 0) {
548 continue;
550 $weightsum += $items[$itemid]->aggregationcoef;
551 $sum += $items[$itemid]->aggregationcoef * $grade_value;
553 if ($weightsum == 0) {
554 $rawgrade = null;
555 } else {
556 $rawgrade = $sum / $weightsum;
558 break;
560 case GRADE_AGGREGATE_EXTRACREDIT_MEAN_ALL: // special average
561 case GRADE_AGGREGATE_EXTRACREDIT_MEAN_GRADED:
562 $num = 0;
563 $sum = 0;
564 foreach($grade_values as $itemid=>$grade_value) {
565 if ($items[$itemid]->aggregationcoef == 0) {
566 $num += 1;
567 $sum += $grade_value;
568 } else if ($items[$itemid]->aggregationcoef > 0) {
569 $sum += $items[$itemid]->aggregationcoef * $grade_value;
572 if ($num == 0) {
573 $rawgrade = $sum; // only extra credits or wrong coefs
574 } else {
575 $rawgrade = $sum / $num;
577 break;
579 case GRADE_AGGREGATE_MEAN_ALL: // Arithmetic average of all grade items including even NULLs; NULL grade counted as minimum
580 case GRADE_AGGREGATE_MEAN_GRADED: // Arithmetic average of all final grades, unfinished are not calculated
581 default:
582 $num = count($grade_values);
583 $sum = array_sum($grade_values);
584 $rawgrade = $sum / $num;
585 break;
588 /// prepare update of new raw grade
589 $grade->rawgrademin = $this->grade_item->grademin;
590 $grade->rawgrademax = $this->grade_item->grademax;
591 $grade->rawscaleid = $this->grade_item->scaleid;
593 // recalculate the rawgrade back to requested range
594 $grade->rawgrade = grade_grade::standardise_score($rawgrade, 0, 1, $grade->rawgrademin, $grade->rawgrademax);
596 // calculate final grade
597 $grade->finalgrade = $this->grade_item->adjust_grade($grade->rawgrade, $grade->rawgrademin, $grade->rawgrademax);
599 // update in db if changed
600 if ( $grade->finalgrade !== $oldgrade->finalgrade
601 or $grade->rawgrade !== $oldgrade->rawgrade
602 or $grade->rawgrademin !== $oldgrade->rawgrademin
603 or $grade->rawgrademax !== $oldgrade->rawgrademax
604 or $grade->rawscaleid !== $oldgrade->rawscaleid) {
606 $grade->update('system');
609 return;
613 * Given an array of grade values (numerical indices), applies droplow or keephigh
614 * rules to limit the final array.
615 * @param array $grade_values
616 * @return array Limited grades.
618 function apply_limit_rules(&$grade_values) {
619 arsort($grade_values, SORT_NUMERIC);
620 if (!empty($this->droplow)) {
621 for ($i = 0; $i < $this->droplow; $i++) {
622 array_pop($grade_values);
624 } elseif (!empty($this->keephigh)) {
625 while (count($grade_values) > $this->keephigh) {
626 array_pop($grade_values);
633 * Returns true if category uses special aggregation coeficient
634 * @return boolean true if coeficient used
636 function is_aggregationcoef_used() {
637 return ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN_ALL
638 or $this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN_GRADED
639 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN_ALL
640 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN_GRADED);
645 * Returns tree with all grade_items and categories as elements
646 * @static
647 * @param int $courseid
648 * @param boolean $include_category_items as category children
649 * @return array
651 function fetch_course_tree($courseid, $include_category_items=false) {
652 $course_category = grade_category::fetch_course_category($courseid);
653 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
654 'children'=>$course_category->get_children($include_category_items));
655 $sortorder = 1;
656 $course_category->set_sortorder($sortorder);
657 $course_category->sortorder = $sortorder;
658 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
661 function _fetch_course_tree_recursion($category_array, &$sortorder) {
662 // update the sortorder in db if needed
663 if ($category_array['object']->sortorder != $sortorder) {
664 $category_array['object']->set_sortorder($sortorder);
667 // store the grade_item or grade_category instance with extra info
668 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
670 // reuse final grades if there
671 if (array_key_exists('finalgrades', $category_array)) {
672 $result['finalgrades'] = $category_array['finalgrades'];
675 // recursively resort children
676 if (!empty($category_array['children'])) {
677 $result['children'] = array();
678 //process the category item first
679 $cat_item_id = null;
680 foreach($category_array['children'] as $oldorder=>$child_array) {
681 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
682 $result['children'][$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
685 foreach($category_array['children'] as $oldorder=>$child_array) {
686 if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
687 $result['children'][++$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
692 return $result;
696 * Fetches and returns all the children categories and/or grade_items belonging to this category.
697 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
698 * as well as all levels (0). The elements are indexed by sort order.
699 * @return array Array of child objects (grade_category and grade_item).
701 function get_children($include_category_items=false) {
703 // This function must be as fast as possible ;-)
704 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
705 // we have to limit the number of queries though, because it will be used often in grade reports
707 $cats = get_records('grade_categories', 'courseid', $this->courseid);
708 $items = get_records('grade_items', 'courseid', $this->courseid);
710 // init children array first
711 foreach ($cats as $catid=>$cat) {
712 $cats[$catid]->children = array();
715 //first attach items to cats and add category sortorder
716 foreach ($items as $item) {
717 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
718 $cats[$item->iteminstance]->sortorder = $item->sortorder;
720 if (!$include_category_items) {
721 continue;
723 $categoryid = $item->iteminstance;
724 } else {
725 $categoryid = $item->categoryid;
728 // prevent problems with duplicate sortorders in db
729 $sortorder = $item->sortorder;
730 while(array_key_exists($sortorder, $cats[$categoryid]->children)) {
731 //debugging("$sortorder exists in item loop");
732 $sortorder++;
735 $cats[$categoryid]->children[$sortorder] = $item;
739 // now find the requested category and connect categories as children
740 $category = false;
741 foreach ($cats as $catid=>$cat) {
742 if (!empty($cat->parent)) {
743 // prevent problems with duplicate sortorders in db
744 $sortorder = $cat->sortorder;
745 while(array_key_exists($sortorder, $cats[$cat->parent]->children)) {
746 //debugging("$sortorder exists in cat loop");
747 $sortorder++;
750 $cats[$cat->parent]->children[$sortorder] = $cat;
753 if ($catid == $this->id) {
754 $category = &$cats[$catid];
758 unset($items); // not needed
759 unset($cats); // not needed
761 $children_array = grade_category::_get_children_recursion($category);
763 ksort($children_array);
765 return $children_array;
769 function _get_children_recursion($category) {
771 $children_array = array();
772 foreach($category->children as $sortorder=>$child) {
773 if (array_key_exists('itemtype', $child)) {
774 $grade_item = new grade_item($child, false);
775 if (in_array($grade_item->itemtype, array('course', 'category'))) {
776 $type = $grade_item->itemtype.'item';
777 $depth = $category->depth;
778 } else {
779 $type = 'item';
780 $depth = $category->depth; // we use this to set the same colour
782 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
784 } else {
785 $children = grade_category::_get_children_recursion($child);
786 $grade_category = new grade_category($child, false);
787 if (empty($children)) {
788 $children = array();
790 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
794 // sort the array
795 ksort($children_array);
797 return $children_array;
801 * Uses get_grade_item to load or create a grade_item, then saves it as $this->grade_item.
802 * @return object Grade_item
804 function load_grade_item() {
805 if (empty($this->grade_item)) {
806 $this->grade_item = $this->get_grade_item();
808 return $this->grade_item;
812 * Retrieves from DB and instantiates the associated grade_item object.
813 * If no grade_item exists yet, create one.
814 * @return object Grade_item
816 function get_grade_item() {
817 if (empty($this->id)) {
818 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
819 return false;
822 if (empty($this->parent)) {
823 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
825 } else {
826 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
829 if (!$grade_items = grade_item::fetch_all($params)) {
830 // create a new one
831 $grade_item = new grade_item($params, false);
832 $grade_item->gradetype = GRADE_TYPE_VALUE;
833 $grade_item->insert('system');
835 } else if (count($grade_items) == 1){
836 // found existing one
837 $grade_item = reset($grade_items);
839 } else {
840 debugging("Found more than one grade_item attached to category id:".$this->id);
841 // return first one
842 $grade_item = reset($grade_items);
845 return $grade_item;
849 * Uses $this->parent to instantiate $this->parent_category based on the
850 * referenced record in the DB.
851 * @return object Parent_category
853 function load_parent_category() {
854 if (empty($this->parent_category) && !empty($this->parent)) {
855 $this->parent_category = $this->get_parent_category();
857 return $this->parent_category;
861 * Uses $this->parent to instantiate and return a grade_category object.
862 * @return object Parent_category
864 function get_parent_category() {
865 if (!empty($this->parent)) {
866 $parent_category = new grade_category(array('id' => $this->parent));
867 return $parent_category;
868 } else {
869 return null;
874 * Returns the most descriptive field for this object. This is a standard method used
875 * when we do not know the exact type of an object.
876 * @return string name
878 function get_name() {
879 if (empty($this->parent)) {
880 $course = get_record('course', 'id', $this->courseid);
881 return format_string($course->fullname);
882 } else {
883 return $this->fullname;
888 * Sets this category's parent id. A generic method shared by objects that have a parent id of some kind.
889 * @param int parentid
890 * @return boolean success
892 function set_parent($parentid, $source=null) {
893 if ($this->parent == $parentid) {
894 return true;
897 if ($parentid == $this->id) {
898 error('Can not assign self as parent!');
901 if (empty($this->parent) and $this->is_course_category()) {
902 error('Course category can not have parent!');
905 // find parent and check course id
906 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
907 return false;
910 $this->force_regrading();
912 // set new parent category
913 $this->parent = $parent_category->id;
914 $this->parent_category =& $parent_category;
915 $this->path = null; // remove old path and depth - will be recalculated in update()
916 $this->depth = null; // remove old path and depth - will be recalculated in update()
917 $this->update($source);
919 return $this->update($source);
923 * Returns the final values for this grade category.
924 * @param int $userid Optional: to retrieve a single final grade
925 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
927 function get_final($userid=NULL) {
928 $this->load_grade_item();
929 return $this->grade_item->get_final($userid);
933 * Returns the sortorder of the associated grade_item. This method is also available in
934 * grade_item, for cases where the object type is not known.
935 * @return int Sort order
937 function get_sortorder() {
938 $this->load_grade_item();
939 return $this->grade_item->get_sortorder();
943 * Returns the idnumber of the associated grade_item. This method is also available in
944 * grade_item, for cases where the object type is not known.
945 * @return string idnumber
947 function get_idnumber() {
948 $this->load_grade_item();
949 return $this->grade_item->get_idnumber();
953 * Sets sortorder variable for this category.
954 * This method is also available in grade_item, for cases where the object type is not know.
955 * @param int $sortorder
956 * @return void
958 function set_sortorder($sortorder) {
959 $this->load_grade_item();
960 $this->grade_item->set_sortorder($sortorder);
964 * Move this category after the given sortorder - does not change the parent
965 * @param int $sortorder to place after
967 function move_after_sortorder($sortorder) {
968 $this->load_grade_item();
969 $this->grade_item->move_after_sortorder($sortorder);
973 * Return true if this is the top most category that represents the total course grade.
974 * @return boolean
976 function is_course_category() {
977 $this->load_grade_item();
978 return $this->grade_item->is_course_item();
982 * Return the top most course category.
983 * @static
984 * @return object grade_category instance for course grade
986 function fetch_course_category($courseid) {
988 // course category has no parent
989 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
990 return $course_category;
993 // create a new one
994 $course_category = new grade_category();
995 $course_category->insert_course_category($courseid);
997 return $course_category;
1001 * Is grading object editable?
1002 * @return boolean
1004 function is_editable() {
1005 return true;
1009 * Returns the locked state/date of the associated grade_item. This method is also available in
1010 * grade_item, for cases where the object type is not known.
1011 * @return boolean
1013 function is_locked() {
1014 $this->load_grade_item();
1015 return $this->grade_item->is_locked();
1019 * Sets the grade_item's locked variable and updates the grade_item.
1020 * Method named after grade_item::set_locked().
1021 * @param int $locked 0, 1 or a timestamp int(10) after which date the item will be locked.
1022 * @param boolean $cascade lock/unlock child objects too
1023 * @param boolean $refresh refresh grades when unlocking
1024 * @return boolean success if category locked (not all children mayb be locked though)
1026 function set_locked($lockedstate, $cascade=false, $refresh=true) {
1027 $this->load_grade_item();
1029 $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
1031 if ($cascade) {
1032 //process all children - items and categories
1033 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
1034 foreach($children as $child) {
1035 $child->set_locked($lockedstate, true, false);
1036 if (empty($lockedstate) and $refresh) {
1037 //refresh when unlocking
1038 $child->refresh_grades();
1042 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
1043 foreach($children as $child) {
1044 $child->set_locked($lockedstate, true, true);
1049 return $result;
1053 * Returns the hidden state/date of the associated grade_item. This method is also available in
1054 * grade_item.
1055 * @return boolean
1057 function is_hidden() {
1058 $this->load_grade_item();
1059 return $this->grade_item->is_hidden();
1063 * Sets the grade_item's hidden variable and updates the grade_item.
1064 * Method named after grade_item::set_hidden().
1065 * @param int $hidden 0, 1 or a timestamp int(10) after which date the item will be hidden.
1066 * @param boolean $cascade apply to child objects too
1067 * @return void
1069 function set_hidden($hidden, $cascade=false) {
1070 $this->load_grade_item();
1071 $this->grade_item->set_hidden($hidden);
1072 if ($cascade) {
1073 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
1074 foreach($children as $child) {
1075 $child->set_hidden($hidden, $cascade);
1078 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
1079 foreach($children as $child) {
1080 $child->set_hidden($hidden, $cascade);