MDL-9836
[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';
34
35 /**
36 * Array of class variables that are not part of the DB table fields
37 * @var array $nonfields
38 */
7c8a963f 39 var $nonfields = array('table', 'nonfields', 'children', 'all_children');
8a31e65c 40
41 /**
42 * The course this category belongs to.
43 * @var int $courseid
44 */
45 var $courseid;
46
47 /**
48 * The category this category belongs to (optional).
e5c674f1 49 * @var int $parent
8a31e65c 50 */
e5c674f1 51 var $parent;
8c846243 52
53 /**
54 * The grade_category object referenced by $this->parent (PK).
55 * @var object $parent_category
56 */
57 var $parent_category;
27f95e9b 58
88e794d6 59 /**
60 * A grade_category object this category used to belong to before getting updated. Will be deleted shortly.
61 * @var object $old_parent
62 */
63 var $old_parent;
64
e5c674f1 65 /**
66 * The number of parents this category has.
67 * @var int $depth
68 */
69 var $depth = 0;
70
71 /**
72 * Shows the hierarchical path for this category as /1/2/3 (like course_categories), the last number being
73 * this category's autoincrement ID number.
74 * @var string $path
75 */
76 var $path;
77
8a31e65c 78 /**
79 * The name of this category.
80 * @var string $fullname
81 */
82 var $fullname;
83
84 /**
85 * A constant pointing to one of the predefined aggregation strategies (none, mean, median, sum etc) .
86 * @var int $aggregation
87 */
88 var $aggregation;
89
90 /**
91 * Keep only the X highest items.
92 * @var int $keephigh
93 */
94 var $keephigh;
95
96 /**
97 * Drop the X lowest items.
98 * @var int $droplow
99 */
100 var $droplow;
101
8a31e65c 102 /**
103 * Array of grade_items or grade_categories nested exactly 1 level below this category
104 * @var array $children
105 */
106 var $children;
8a31e65c 107
7c8a963f 108 /**
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
112 */
113 var $all_children;
114
f151b073 115 /**
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
119 */
120 var $grade_item;
121
e5c674f1 122 /**
123 * Constructor. Extends the basic functionality defined in grade_object.
124 * @param array $params Can also be a standard object.
f151b073 125 * @param boolean $fetch Whether or not to fetch the corresponding row from the DB.
126 * @param object $grade_item The associated grade_item object can be passed during construction.
e5c674f1 127 */
f151b073 128 function grade_category($params=NULL, $fetch=true, $grade_item=NULL) {
e5c674f1 129 $this->grade_object($params, $fetch);
f151b073 130 if (!empty($grade_item) && $grade_item->itemtype == 'category') {
131 $this->grade_item = $grade_item;
132 if (empty($this->grade_item->iteminstance)) {
133 $this->grade_item->iteminstance = $this->id;
134 $this->grade_item->update();
135 }
136 }
2df71235 137
138 $this->path = grade_category::build_path($this);
e5c674f1 139 }
140
141
142 /**
143 * Builds this category's path string based on its parents (if any) and its own id number.
144 * This is typically done just before inserting this object in the DB for the first time,
ce385eb4 145 * or when a new parent is added or changed. It is a recursive function: once the calling
146 * object no longer has a parent, the path is complete.
147 *
148 * @static
149 * @param object $grade_category
150 * @return int The depth of this category (2 means there is one parent)
e5c674f1 151 */
ce385eb4 152 function build_path($grade_category) {
153 if (empty($grade_category->parent)) {
154 return "/$grade_category->id";
155 } else {
156 $parent = get_record('grade_categories', 'id', $grade_category->parent);
157 return grade_category::build_path($parent) . "/$grade_category->id";
158 }
e5c674f1 159 }
160
8a31e65c 161
8a31e65c 162 /**
163 * Finds and returns a grade_category object based on 1-3 field values.
164 *
8a31e65c 165 * @param string $field1
166 * @param string $value1
167 * @param string $field2
168 * @param string $value2
169 * @param string $field3
170 * @param string $value3
171 * @param string $fields
172 * @return object grade_category object or false if none found.
173 */
27f95e9b 174 function fetch($field1, $value1, $field2='', $value2='', $field3='', $value3='', $fields="*") {
8a31e65c 175 if ($grade_category = get_record('grade_categories', $field1, $value1, $field2, $value2, $field3, $value3, $fields)) {
7c8a963f 176 if (isset($this) && get_class($this) == 'grade_category') {
8a31e65c 177 foreach ($grade_category as $param => $value) {
178 $this->$param = $value;
179 }
180 return $this;
7c8a963f 181 } else {
182 $grade_category = new grade_category($grade_category);
183 return $grade_category;
8a31e65c 184 }
185 } else {
186 return false;
187 }
ce385eb4 188 }
189
8f4a626d 190 /**
191 * In addition to update() as defined in grade_object, call flag_for_update of parent categories, if applicable.
192 */
193 function update() {
194 $qualifies = $this->qualifies_for_update();
195
0fc7f624 196 // Update the grade_item's sortorder if needed
197 if (!empty($this->sortorder)) {
198 $this->load_grade_item();
199 if (!empty($this->grade_item)) {
200 $this->grade_item->sortorder = $this->sortorder;
201 $this->grade_item->update();
202 }
203 unset($this->sortorder);
204 }
205
8f4a626d 206 $result = parent::update();
207
cb64c6b2 208 // Use $this->path to update all parent categories
8f4a626d 209 if ($result && $qualifies) {
cb64c6b2 210 $this->flag_for_update();
8f4a626d 211 }
8f4a626d 212 return $result;
213 }
214
215 /**
216 * If parent::delete() is successful, send flag_for_update message to parent category.
217 * @return boolean Success or failure.
218 */
219 function delete() {
220 $result = parent::delete();
221
222 if ($result) {
223 $this->load_parent_category();
224 if (!empty($this->parent_category)) {
225 $result = $result && $this->parent_category->flag_for_update();
226 }
227 }
228
229 return $result;
230 }
231
ce385eb4 232 /**
233 * In addition to the normal insert() defined in grade_object, this method sets the depth
234 * and path for this object, and update the record accordingly. The reason why this must
235 * be done here instead of in the constructor, is that they both need to know the record's
27f95e9b 236 * id number, which only gets created at insertion time.
f151b073 237 * This method also creates an associated grade_item if this wasn't done during construction.
ce385eb4 238 */
239 function insert() {
240 $result = parent::insert();
77d2540e 241
242 $this->path = grade_category::build_path($this);
ce385eb4 243
244 // Build path and depth variables
245 if (!empty($this->parent)) {
ce385eb4 246 $this->depth = $this->get_depth_from_path();
247 } else {
248 $this->depth = 1;
ce385eb4 249 }
250
251 $this->update();
f151b073 252
253 if (empty($this->grade_item)) {
254 $grade_item = new grade_item();
255 $grade_item->iteminstance = $this->id;
256 $grade_item->itemtype = 'category';
6527197b 257
258 if (!$grade_item->insert()) {
a39cac25 259 debugging("Could not insert this grade_item in the database: " . print_r($grade_item, true));
6527197b 260 return false;
261 }
262
f151b073 263 $this->grade_item = $grade_item;
264 }
cb64c6b2 265
8f4a626d 266 // Notify parent category of need to update.
267 if ($result) {
268 $this->load_parent_category();
269 if (!empty($this->parent_category)) {
270 if (!$this->parent_category->flag_for_update()) {
a39cac25 271 debugging("Could not notify parent category of the need to update its final grades.");
8f4a626d 272 return false;
273 }
274 }
275 }
ce385eb4 276 return $result;
277 }
8f4a626d 278
279 /**
280 * Compares the values held by this object with those of the matching record in DB, and returns
281 * whether or not these differences are sufficient to justify an update of all parent objects.
282 * This assumes that this object has an id number and a matching record in DB. If not, it will return false.
283 * @return boolean
284 */
285 function qualifies_for_update() {
286 if (empty($this->id)) {
287 return false;
288 }
289
290 $db_item = new grade_category(array('id' => $this->id));
291
292 $aggregationdiff = $db_item->aggregation != $this->aggregation;
293 $keephighdiff = $db_item->keephigh != $this->keephigh;
294 $droplowdiff = $db_item->droplow != $this->droplow;
295
296 if ($aggregationdiff || $keephighdiff || $droplowdiff) {
297 return true;
298 } else {
299 return false;
300 }
301 }
8c846243 302
303 /**
304 * Sets this category's and its parent's grade_item.needsupdate to true.
305 * This is triggered whenever any change in any lower level may cause grade_finals
306 * for this category to require an update. The flag needs to be propagated up all
307 * levels until it reaches the top category. This is then used to determine whether or not
cb64c6b2 308 * to regenerate the raw and final grades for each category grade_item. This is accomplished
309 * thanks to the path variable, so we don't need to use recursion.
8c846243 310 * @return boolean Success or failure
311 */
312 function flag_for_update() {
313 $result = true;
8f4a626d 314
8c846243 315 $this->load_grade_item();
8f4a626d 316
317 if (empty($this->grade_item)) {
318 die("Associated grade_item object does not exist for this grade_category!" . print_object($this));
77d2540e 319 // TODO Send error message, this is a critical error: each category MUST have a matching grade_item object and load_grade_item() is supposed to create one!
8f4a626d 320 }
8f4a626d 321
cb64c6b2 322 $paths = explode('/', $this->path);
1d4b6668 323
77d2540e 324 // Remove the first index, which is always empty
325 unset($paths[0]);
1d4b6668 326
77d2540e 327 if (!empty($paths)) {
328 $wheresql = '';
329
330 foreach ($paths as $categoryid) {
331 $wheresql .= "iteminstance = $categoryid OR ";
332 }
333 $wheresql = substr($wheresql, 0, strrpos($wheresql, 'OR'));
a3d55942 334 $grade_items = set_field_select('grade_items', 'needsupdate', '1', $wheresql . ' AND courseid = ' . $this->courseid);
77d2540e 335 $this->grade_item->update_from_db();
8c846243 336 }
8c846243 337 return $result;
338 }
339
0aa32279 340 /**
341 * Generates and saves raw_grades, based on this category's immediate children, then uses the
342 * associated grade_item to generate matching final grades. These immediate children must first have their own
343 * raw and final grades, which means that ultimately we must get grade_items as children. The category's aggregation
344 * method is used to generate these raw grades, which can then be used by the category's associated grade_item
345 * to apply calculations to and generate final grades.
2df71235 346 * Steps to follow:
347 * 1. If the children are categories, AND their grade_item's needsupdate is true call generate_grades() on each of them (recursion)
348 * 2. Get final grades from immediate children (if the children are categories, get the final grades from their grade_item)
349 * 3. Aggregate these grades
350 * 4. Save them under $this->grade_item->grade_grades_raw
351 * 5. Use the grade_item's methods for generating the final grades.
0aa32279 352 */
353 function generate_grades() {
2df71235 354 // 1. Get immediate children
355 $children = $this->get_children(1, 'flat');
0aa32279 356
2df71235 357 if (empty($children)) {
a39cac25 358 debugging("Could not generate grades for this category, it has no children.");
2df71235 359 return false;
0aa32279 360 }
2df71235 361
362 // This assumes that all immediate children are of the same type (category OR item)
363 $childrentype = get_class(current($children));
2c72af1f 364
2df71235 365 $final_grades_for_aggregation = array();
366
367 // 2. Get final grades from immediate children, after generating them if needed.
368 // NOTE: Make sure that the arrays of final grades are indexed by userid. The resulting arrays are unlikely to match in sizes.
369 if ($childrentype == 'grade_category') {
370 foreach ($children as $id => $category) {
371 $category->load_grade_item();
372
373 if ($category->grade_item->needsupdate) {
374 $category->generate_grades();
375 }
376
377 $final_grades_for_aggregation[] = $category->grade_item->get_standardised_final();
2c72af1f 378 }
2df71235 379 } elseif ($childrentype == 'grade_item') {
380 foreach ($children as $id => $item) {
381 if ($item->needsupdate) {
382 $item->generate_final();
383 }
384
385 $final_grades_for_aggregation[] = $item->get_standardised_final();
0aa32279 386 }
0aa32279 387 }
dda0c7e6 388
2df71235 389 // 3. Aggregate the grades
390 $aggregated_grades = $this->aggregate_grades($final_grades_for_aggregation);
096858ff 391
2df71235 392 // 4. Save the resulting array of grades as raw grades
393 $this->load_grade_item();
394 $this->grade_item->save_raw($aggregated_grades);
395
396 // 5. Use the grade_item's generate_final method
397 $this->grade_item->generate_final();
398
399 return true;
0aa32279 400 }
401
adc2f286 402 /**
403 * Given an array of grade values (numerical indices), applies droplow or keephigh
404 * rules to limit the final array.
405 * @param array $grades
406 * @return array Limited grades.
407 */
408 function apply_limit_rules($grades) {
409 rsort($grades, SORT_NUMERIC);
410 if (!empty($this->droplow)) {
411 for ($i = 0; $i < $this->droplow; $i++) {
412 array_pop($grades);
413 }
414 } elseif (!empty($this->keephigh)) {
415 while (count($grades) > $this->keephigh) {
416 array_pop($grades);
417 }
418 }
419 sort($grades, SORT_NUMERIC);
420 return $grades;
421 }
422
0aa32279 423 /**
2df71235 424 * Given an array of arrays of values, standardised from 0 to 1 and indexed by userid,
425 * uses this category's aggregation method to
426 * compute and return a single array of grade_raw objects with the aggregated gradevalue.
0aa32279 427 * @param array $raw_grade_sets
428 * @return array Raw grade objects
429 */
2df71235 430 function aggregate_grades($final_grade_sets) {
431 if (empty($final_grade_sets)) {
a39cac25 432 debugging("Could not aggregate grades: no array of grades given to aggregate.");
2c72af1f 433 return null;
434 }
096858ff 435
2c72af1f 436 $aggregated_grades = array();
437 $pooled_grades = array();
438
2df71235 439 foreach ($final_grade_sets as $setkey => $set) {
440 foreach ($set as $userid => $final_grade) {
2c72af1f 441 $this->load_grade_item();
2df71235 442 $value = standardise_score((float) $final_grade, 0, 1, $this->grade_item->grademin, $this->grade_item->grademax);
ab53054f 443 $pooled_grades[$userid][] = (string) $value;
2c72af1f 444 }
445 }
096858ff 446
2c72af1f 447 foreach ($pooled_grades as $userid => $grades) {
448 $aggregated_value = null;
ab53054f 449
adc2f286 450 $grades = $this->apply_limit_rules($grades);
096858ff 451
ab53054f 452 if (count($grades) > 1) {
453
454 switch ($this->aggregation) {
455 case GRADE_AGGREGATE_MEAN : // Arithmetic average
456 $num = count($grades);
457 $sum = array_sum($grades);
458 $aggregated_value = $sum / $num;
459 break;
460 case GRADE_AGGREGATE_MEDIAN : // Middle point value in the set: ignores frequencies
461 sort($grades);
462 $num = count($grades);
463 $halfpoint = intval($num / 2);
464
465 if($num % 2 == 0) {
466 $aggregated_value = ($grades[ceil($halfpoint)] + $grades[floor($halfpoint)]) / 2;
467 } else {
468 $aggregated_value = $grades[$halfpoint];
469 }
470
471 break;
472 case GRADE_AGGREGATE_MODE : // Value that occurs most frequently. Not always useful (all values are likely to be different)
473 // TODO implement or reject
474 break;
475 case GRADE_AGGREGATE_SUM : // I don't see much point to this one either
476 $aggregated_value = array_sum($grades);
477 break;
478 default:
479 $num = count($grades);
480 $sum = array_sum($grades);
481 $aggregated_value = $sum / $num;
482 break;
483 }
484 } elseif (count($grades) == 1) {
485 $aggregated_value = $grades[0];
486 } else {
487 // TODO what happens if the droplow and keephigh rules have deleted all grades?
488 $aggregated_value = 0;
489 }
dda0c7e6 490
2c72af1f 491 $grade_raw = new grade_grades_raw();
dda0c7e6 492
2c72af1f 493 $grade_raw->userid = $userid;
494 $grade_raw->gradevalue = $aggregated_value;
495 $grade_raw->grademin = $this->grade_item->grademin;
496 $grade_raw->grademax = $this->grade_item->grademax;
497 $grade_raw->itemid = $this->grade_item->id;
498 $aggregated_grades[$userid] = $grade_raw;
499 }
096858ff 500
2c72af1f 501 return $aggregated_grades;
0aa32279 502 }
503
0fc7f624 504 /**
505 * Given an array of stdClass children of a certain $object_type, returns a flat or nested
506 * array of these children, ready for appending to a tree built by get_children.
507 * @static
508 * @param array $children
509 * @param string $arraytype
510 * @param string $object_type
511 * @return array
512 */
513 function children_to_array($children, $arraytype='nested', $object_type='grade_item') {
514 $children_array = array();
515
516 foreach ($children as $id => $child) {
517 $child = new $object_type($child, false);
518 if ($arraytype == 'nested') {
519 $children_array[$child->get_sortorder()] = array('object' => $child);
520 } else {
521 $children_array[$child->get_sortorder()] = $child;
522 }
523 }
524
525 return $children_array;
526 }
527
528 /**
529 * Returns true if this category has any child grade_category or grade_item.
530 * @return int number of direct children, or false if none found.
531 */
532 function has_children() {
533 return count_records('grade_categories', 'parent', $this->id) + count_records('grade_items', 'categoryid', $this->id);
534 }
535
536 /**
210611f6 537 * Checks whether an existing child exists for this category. If the new child is of a
538 * different type, the method will return false (not allowed). Otherwise it will return true.
0fc7f624 539 * @param object $child This must be a complete object, not a stdClass
540 * @return boolean Success or failure
541 */
542 function can_add_child($child) {
543 if ($this->has_children()) {
544 if (get_class($child) != $this->get_childrentype()) {
545 return false;
546 } else {
547 return true;
548 }
549 } else {
550 return true;
551 }
552 }
553
1c307f21 554 /**
555 * Disassociates this category from its category parent(s). The object is then updated in DB.
556 * @return boolean Success or Failure
557 */
558 function divorce_parent() {
559 $this->old_parent = $this->get_parent_category();
560 $this->parent = null;
561 $this->parent_category = null;
562 $this->depth = 1;
563 $this->path = '/' . $this->id;
564 return $this->update();
565 }
566
ce385eb4 567 /**
568 * Looks at a path string (e.g. /2/45/56) and returns the depth level represented by this path (in this example, 3).
569 * If no string is given, it looks at the obect's path and assigns the resulting depth to its $depth variable.
570 * @param string $path
571 * @return int Depth level
572 */
573 function get_depth_from_path($path=NULL) {
574 if (empty($path)) {
575 $path = $this->path;
576 }
577 preg_match_all('/\/([0-9]+)+?/', $path, $matches);
578 $depth = count($matches[0]);
579
580 return $depth;
581 }
7c8a963f 582
583 /**
584 * Fetches and returns all the children categories and/or grade_items belonging to this category.
585 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 586 * as well as all levels (0). The elements are indexed by sort order.
7c8a963f 587 * @param int $depth 1 for immediate children, 0 for all children, and 2+ for specific levels deeper than 1.
588 * @param string $arraytype Either 'nested' or 'flat'. A nested array represents the true hierarchy, but is more difficult to work with.
589 * @return array Array of child objects (grade_category and grade_item).
590 */
591 function get_children($depth=1, $arraytype='nested') {
27f95e9b 592 $children_array = array();
593
594 // Set up $depth for recursion
595 $newdepth = $depth;
596 if ($depth > 1) {
597 $newdepth--;
598 }
599
600 $childrentype = $this->get_childrentype();
f151b073 601
27f95e9b 602 if ($childrentype == 'grade_item') {
f151b073 603 $children = get_records('grade_items', 'categoryid', $this->id);
27f95e9b 604 // No need to proceed with recursion
605 $children_array = $this->children_to_array($children, $arraytype, 'grade_item');
606 $this->children = $this->children_to_array($children, 'flat', 'grade_item');
607 } elseif ($childrentype == 'grade_category') {
608 $children = get_records('grade_categories', 'parent', $this->id, 'id');
f151b073 609
27f95e9b 610 if ($depth == 1) {
611 $children_array = $this->children_to_array($children, $arraytype, 'grade_category');
612 $this->children = $this->children_to_array($children, 'flat', 'grade_category');
7c8a963f 613 } else {
27f95e9b 614 foreach ($children as $id => $child) {
615 $cat = new grade_category($child, false);
616
617 if ($cat->has_children()) {
618 if ($arraytype == 'nested') {
a39cac25 619 $children_array[$cat->get_sortorder()] = array('object' => $cat, 'children' => $cat->get_children($newdepth, $arraytype));
27f95e9b 620 } else {
a39cac25 621 $children_array[$cat->get_sortorder()] = $cat;
27f95e9b 622 $cat_children = $cat->get_children($newdepth, $arraytype);
623 foreach ($cat_children as $id => $cat_child) {
a39cac25 624 $children_array[$cat_child->get_sortorder()] = new grade_category($cat_child, false);
27f95e9b 625 }
626 }
627 } else {
628 if ($arraytype == 'nested') {
a39cac25 629 $children_array[$cat->get_sortorder()] = array('object' => $cat);
27f95e9b 630 } else {
a39cac25 631 $children_array[$cat->get_sortorder()] = $cat;
27f95e9b 632 }
633 }
7c8a963f 634 }
27f95e9b 635 }
636 } else {
637 return null;
638 }
639
640 return $children_array;
641 }
a39cac25 642
27f95e9b 643 /**
644 * Check the type of the first child of this category, to see whether it is a
645 * grade_category or a grade_item, and returns that type as a string (get_class).
646 * @return string
647 */
648 function get_childrentype() {
27f95e9b 649 if (empty($this->children)) {
650 $count_item_children = count_records('grade_items', 'categoryid', $this->id);
651 $count_cat_children = count_records('grade_categories', 'parent', $this->id);
f151b073 652
27f95e9b 653 if ($count_item_children > 0) {
654 return 'grade_item';
655 } elseif ($count_cat_children > 0) {
656 return 'grade_category';
657 } else {
658 return null;
7c8a963f 659 }
7c8a963f 660 }
a15428a2 661 reset($this->children);
662 return get_class(current($this->children));
7c8a963f 663 }
f151b073 664
665 /**
ab53054f 666 * Uses get_grade_item to load or create a grade_item, then saves it as $this->grade_item.
f151b073 667 * @return object Grade_item
668 */
669 function load_grade_item() {
ab53054f 670 $this->grade_item = $this->get_grade_item();
671 return $this->grade_item;
672 }
673
674 /**
675 * Retrieves from DB and instantiates the associated grade_item object.
676 * If no grade_item exists yet, create one.
677 * @return object Grade_item
678 */
679 function get_grade_item() {
c91ed4be 680 if (empty($this->id)) {
681 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
682 return false;
683 }
684
8f4a626d 685 $grade_items = get_records_select('grade_items', "iteminstance = $this->id AND itemtype = 'category'", null, '*', 0, 1);
1d4b6668 686
687 if ($grade_items){
688 $params = current($grade_items);
ab53054f 689 $grade_item = new grade_item($params);
1d4b6668 690 } else {
ab53054f 691 $grade_item = new grade_item();
1d4b6668 692 }
2c72af1f 693
8f4a626d 694 // If the associated grade_item isn't yet created, do it now. But first try loading it, in case it exists in DB.
ab53054f 695 if (empty($grade_item->id)) {
696 $grade_item->iteminstance = $this->id;
a3d55942 697 $grade_item->courseid = $this->courseid;
ab53054f 698 $grade_item->itemtype = 'category';
699 $grade_item->insert();
2c72af1f 700 }
701
ab53054f 702 return $grade_item;
f151b073 703 }
8c846243 704
705 /**
706 * Uses $this->parent to instantiate $this->parent_category based on the
707 * referenced record in the DB.
708 * @return object Parent_category
709 */
710 function load_parent_category() {
711 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 712 $this->parent_category = $this->get_parent_category();
8c846243 713 }
714 return $this->parent_category;
a39cac25 715 }
ab53054f 716
717 /**
718 * Uses $this->parent to instantiate and return a grade_category object.
719 * @return object Parent_category
720 */
721 function get_parent_category() {
722 if (!empty($this->parent)) {
723 $parent_category = new grade_category(array('id' => $this->parent));
724 return $parent_category;
725 } else {
726 return null;
727 }
728 }
729
03f01edd 730 /**
c91ed4be 731 * Sets this category as the parent for the given children. If the category's courseid isn't set, it uses that of the children items.
03f01edd 732 * A number of constraints are necessary:
733 * - The children must all be of the same type and at the same level
03f01edd 734 * - The children cannot already be top categories
c91ed4be 735 * - The children all belong to the same course
03f01edd 736 * @param array $children An array of fully instantiated grade_category OR grade_item objects
ffa6e8d3 737 *
03f01edd 738 * @return boolean Success or Failure
ffa6e8d3 739 * @TODO big problem of performance
03f01edd 740 */
741 function set_as_parent($children) {
742 global $CFG;
743
210611f6 744 if (empty($children) || !is_array($children)) {
745 debugging("Passed an empty or non-array variable to grade_category::set_as_parent()");
746 return false;
747 }
748
03f01edd 749 // Check type and sortorder of first child
750 $first_child = current($children);
751 $first_child_type = get_class($first_child);
9f9afbdb 752
753 // If this->courseid is not set, set it to the first child's courseid
754 if (empty($this->courseid)) {
755 $this->courseid = $first_child->courseid;
756 }
757
758 $grade_tree = new grade_tree();
03f01edd 759
760 foreach ($children as $child) {
761 if (get_class($child) != $first_child_type) {
762 debugging("Violated constraint: Attempted to set a category as a parent over children of 2 different types.");
763 return false;
764 }
526e1a8a 765
526e1a8a 766 if ($grade_tree->get_element_type($child) == 'topcat') {
03f01edd 767 debugging("Violated constraint: Attempted to set a category over children which are already top categories.");
768 return false;
769 }
210611f6 770
9f9afbdb 771 if ($first_child_type == 'grade_category' or $first_child_type == 'grade_item') {
03f01edd 772 if (!empty($child->parent)) {
773 debugging("Violated constraint: Attempted to set a category over children that already have a top category.");
774 return false;
775 }
776 } else {
777 debugging("Attempted to set a category over children that are neither grade_items nor grade_categories.");
778 return false;
779 }
c91ed4be 780
9f9afbdb 781 if ($child->courseid != $this->courseid) {
c91ed4be 782 debugging("Attempted to set a category over children which do not belong to the same course.");
783 return false;
784 }
03f01edd 785 }
786
787 // We passed all the checks, time to set the category as a parent.
788 foreach ($children as $child) {
1c307f21 789 $child->divorce_parent();
790 $child->set_parent_id($this->id);
791 if (!$child->update()) {
792 debugging("Could not set this category as a parent for one of its children, DB operation failed.");
793 return false;
794 }
03f01edd 795 }
796
797 // TODO Assign correct sortorders to the newly assigned children and parent. Simply add 1 to all of them!
798 $this->load_grade_item();
799 $this->grade_item->sortorder = $first_child->get_sortorder();
800
801 if (!$this->update()) {
802 debugging("Could not update this category's sortorder in DB.");
803 return false;
804 }
750b0550 805
806 $query = "UPDATE {$CFG->prefix}grade_items SET sortorder = sortorder + 1 WHERE sortorder >= {$this->grade_item->sortorder}";
ffa6e8d3 807 $query .= " AND courseid = $this->courseid";
808
03f01edd 809 if (!execute_sql($query)) {
810 debugging("Could not update the sortorder of grade_items listed after this category.");
750b0550 811 return false;
03f01edd 812 } else {
813 return true;
814 }
815 }
2186f72c 816
817 /**
818 * Returns the most descriptive field for this object. This is a standard method used
819 * when we do not know the exact type of an object.
820 * @return string name
821 */
822 function get_name() {
823 return $this->fullname;
824 }
c91ed4be 825
826 /**
827 * Returns this category's grade_item's id. This is specified for cases where we do not
828 * know an object's type, and want to get either an item's id or a category's item's id.
829 *
830 * @return int
831 */
832 function get_item_id() {
833 $this->load_grade_item();
834 return $this->grade_item->id;
835 }
0fc7f624 836
837 /**
838 * Returns this category's parent id. A generic method shared by objects that have a parent id of some kind.
839 * @return id $parentid
840 */
841 function get_parent_id() {
842 return $this->parent;
843 }
844
845 /**
846 * Sets this category's parent id. A generic method shared by objects that have a parent id of some kind.
847 * @param id $parentid
848 */
849 function set_parent_id($parentid) {
850 $this->parent = $parentid;
88e794d6 851 $this->path = grade_category::build_path($this);
852 $this->depth = $this->get_depth_from_path();
0fc7f624 853 }
854
855 /**
856 * Returns the sortorder of the associated grade_item. This method is also available in
5fad5061 857 * grade_item, for cases where the object type is not known.
0fc7f624 858 * @return int Sort order
859 */
860 function get_sortorder() {
861 if (empty($this->sortorder)) {
862 $this->load_grade_item();
863 if (!empty($this->grade_item)) {
864 return $this->grade_item->sortorder;
865 }
866 } else {
867 return $this->sortorder;
868 }
869 }
870
871 /**
872 * Sets a temporary sortorder variable for this category. It is used in the update() method to update the grade_item.
873 * This method is also available in grade_item, for cases where the object type is not know.
874 * @param int $sortorder
875 * @return void
876 */
877 function set_sortorder($sortorder) {
878 $this->sortorder = $sortorder;
879 }
88e794d6 880
5fad5061 881 /**
882 * Returns the locked state/date of the associated grade_item. This method is also available in
883 * grade_item, for cases where the object type is not known.
884 * @return int 0, 1 or timestamp int(10)
885 */
886 function get_locked() {
887 $this->load_grade_item();
888 if (!empty($this->grade_item)) {
889 return $this->grade_item->locked;
890 } else {
891 return false;
892 }
893 }
894
895 /**
896 * Sets the grade_item's locked variable and updates the grade_item.
897 * Method named after grade_item::set_locked().
898 * @param int $locked 0, 1 or a timestamp int(10) after which date the item will be locked.
899 * @return void
900 */
901 function set_locked($locked) {
902 $this->load_grade_item();
903 if (!empty($this->grade_item)) {
904 $this->grade_item->locked = $locked;
905 return $this->grade_item->update();
906 } else {
907 return false;
908 }
909 }
910
911 /**
912 * Returns the hidden state/date of the associated grade_item. This method is also available in
913 * grade_item, for cases where the object type is not known.
914 * @return int 0, 1 or timestamp int(10)
915 */
916 function get_hidden() {
917 $this->load_grade_item();
918 if (!empty($this->grade_item)) {
919 return $this->grade_item->hidden;
920 } else {
921 return false;
922 }
923 }
924
925 /**
926 * Sets the grade_item's hidden variable and updates the grade_item.
927 * Method named after grade_item::set_hidden().
928 * @param int $hidden 0, 1 or a timestamp int(10) after which date the item will be hidden.
929 * @return void
930 */
931 function set_hidden($hidden) {
932 $this->load_grade_item();
933 if (!empty($this->grade_item)) {
934 $this->grade_item->hidden = $hidden;
935 return $this->grade_item->update();
936 } else {
937 return false;
938 }
939 }
940
88e794d6 941 /**
942 * If the old parent is set (after an update), this checks and returns whether it has any children. Important for
943 * deleting childless categories.
944 * @return boolean
945 */
946 function is_old_parent_childless() {
947 if (!empty($this->old_parent)) {
948 return !$this->old_parent->has_children();
949 } else {
950 return false;
951 }
952 }
8ff4550a 953}
8a31e65c 954?>