Fixed typo stopping image importing working
[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
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;
77
78 /**
79 * A constant pointing to one of the predefined aggregation strategies (none, mean, median, sum etc) .
80 * @var int $aggregation
81 */
82 var $aggregation;
83
84 /**
85 * Keep only the X highest items.
86 * @var int $keephigh
87 */
88 var $keephigh;
89
90 /**
91 * Drop the X lowest items.
92 * @var int $droplow
93 */
94 var $droplow;
95
96 /**
97 * Date until which to hide this category. If null, 0 or false, category is not hidden.
98 * @var int $hidden
99 */
100 var $hidden;
101
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 /**
537 * This method checks whether an existing child exists for this
538 * category. If the new child is of a different type, the method will return false (not allowed).
539 * Otherwise it will return true.
540 * @param object $child This must be a complete object, not a stdClass
541 * @return boolean Success or failure
542 */
543 function can_add_child($child) {
544 if ($this->has_children()) {
545 if (get_class($child) != $this->get_childrentype()) {
546 return false;
547 } else {
548 return true;
549 }
550 } else {
551 return true;
552 }
553 }
554
ce385eb4 555 /**
556 * Looks at a path string (e.g. /2/45/56) and returns the depth level represented by this path (in this example, 3).
557 * If no string is given, it looks at the obect's path and assigns the resulting depth to its $depth variable.
558 * @param string $path
559 * @return int Depth level
560 */
561 function get_depth_from_path($path=NULL) {
562 if (empty($path)) {
563 $path = $this->path;
564 }
565 preg_match_all('/\/([0-9]+)+?/', $path, $matches);
566 $depth = count($matches[0]);
567
568 return $depth;
569 }
7c8a963f 570
571 /**
572 * Fetches and returns all the children categories and/or grade_items belonging to this category.
573 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 574 * as well as all levels (0). The elements are indexed by sort order.
7c8a963f 575 * @param int $depth 1 for immediate children, 0 for all children, and 2+ for specific levels deeper than 1.
576 * @param string $arraytype Either 'nested' or 'flat'. A nested array represents the true hierarchy, but is more difficult to work with.
577 * @return array Array of child objects (grade_category and grade_item).
578 */
579 function get_children($depth=1, $arraytype='nested') {
27f95e9b 580 $children_array = array();
581
582 // Set up $depth for recursion
583 $newdepth = $depth;
584 if ($depth > 1) {
585 $newdepth--;
586 }
587
588 $childrentype = $this->get_childrentype();
f151b073 589
27f95e9b 590 if ($childrentype == 'grade_item') {
f151b073 591 $children = get_records('grade_items', 'categoryid', $this->id);
27f95e9b 592 // No need to proceed with recursion
593 $children_array = $this->children_to_array($children, $arraytype, 'grade_item');
594 $this->children = $this->children_to_array($children, 'flat', 'grade_item');
595 } elseif ($childrentype == 'grade_category') {
596 $children = get_records('grade_categories', 'parent', $this->id, 'id');
f151b073 597
27f95e9b 598 if ($depth == 1) {
599 $children_array = $this->children_to_array($children, $arraytype, 'grade_category');
600 $this->children = $this->children_to_array($children, 'flat', 'grade_category');
7c8a963f 601 } else {
27f95e9b 602 foreach ($children as $id => $child) {
603 $cat = new grade_category($child, false);
604
605 if ($cat->has_children()) {
606 if ($arraytype == 'nested') {
a39cac25 607 $children_array[$cat->get_sortorder()] = array('object' => $cat, 'children' => $cat->get_children($newdepth, $arraytype));
27f95e9b 608 } else {
a39cac25 609 $children_array[$cat->get_sortorder()] = $cat;
27f95e9b 610 $cat_children = $cat->get_children($newdepth, $arraytype);
611 foreach ($cat_children as $id => $cat_child) {
a39cac25 612 $children_array[$cat_child->get_sortorder()] = new grade_category($cat_child, false);
27f95e9b 613 }
614 }
615 } else {
616 if ($arraytype == 'nested') {
a39cac25 617 $children_array[$cat->get_sortorder()] = array('object' => $cat);
27f95e9b 618 } else {
a39cac25 619 $children_array[$cat->get_sortorder()] = $cat;
27f95e9b 620 }
621 }
7c8a963f 622 }
27f95e9b 623 }
624 } else {
625 return null;
626 }
627
628 return $children_array;
629 }
a39cac25 630
27f95e9b 631 /**
632 * Check the type of the first child of this category, to see whether it is a
633 * grade_category or a grade_item, and returns that type as a string (get_class).
634 * @return string
635 */
636 function get_childrentype() {
27f95e9b 637 if (empty($this->children)) {
638 $count_item_children = count_records('grade_items', 'categoryid', $this->id);
639 $count_cat_children = count_records('grade_categories', 'parent', $this->id);
f151b073 640
27f95e9b 641 if ($count_item_children > 0) {
642 return 'grade_item';
643 } elseif ($count_cat_children > 0) {
644 return 'grade_category';
645 } else {
646 return null;
7c8a963f 647 }
7c8a963f 648 }
a15428a2 649 reset($this->children);
650 return get_class(current($this->children));
7c8a963f 651 }
f151b073 652
653 /**
ab53054f 654 * Uses get_grade_item to load or create a grade_item, then saves it as $this->grade_item.
f151b073 655 * @return object Grade_item
656 */
657 function load_grade_item() {
ab53054f 658 $this->grade_item = $this->get_grade_item();
659 return $this->grade_item;
660 }
661
662 /**
663 * Retrieves from DB and instantiates the associated grade_item object.
664 * If no grade_item exists yet, create one.
665 * @return object Grade_item
666 */
667 function get_grade_item() {
c91ed4be 668 if (empty($this->id)) {
669 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
670 return false;
671 }
672
8f4a626d 673 $grade_items = get_records_select('grade_items', "iteminstance = $this->id AND itemtype = 'category'", null, '*', 0, 1);
1d4b6668 674
675 if ($grade_items){
676 $params = current($grade_items);
ab53054f 677 $grade_item = new grade_item($params);
1d4b6668 678 } else {
ab53054f 679 $grade_item = new grade_item();
1d4b6668 680 }
2c72af1f 681
8f4a626d 682 // If the associated grade_item isn't yet created, do it now. But first try loading it, in case it exists in DB.
ab53054f 683 if (empty($grade_item->id)) {
684 $grade_item->iteminstance = $this->id;
a3d55942 685 $grade_item->courseid = $this->courseid;
ab53054f 686 $grade_item->itemtype = 'category';
687 $grade_item->insert();
688 $grade_item->update_from_db();
2c72af1f 689 }
690
ab53054f 691 return $grade_item;
f151b073 692 }
8c846243 693
694 /**
695 * Uses $this->parent to instantiate $this->parent_category based on the
696 * referenced record in the DB.
697 * @return object Parent_category
698 */
699 function load_parent_category() {
700 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 701 $this->parent_category = $this->get_parent_category();
8c846243 702 }
703 return $this->parent_category;
a39cac25 704 }
ab53054f 705
706 /**
707 * Uses $this->parent to instantiate and return a grade_category object.
708 * @return object Parent_category
709 */
710 function get_parent_category() {
711 if (!empty($this->parent)) {
712 $parent_category = new grade_category(array('id' => $this->parent));
713 return $parent_category;
714 } else {
715 return null;
716 }
717 }
718
03f01edd 719 /**
c91ed4be 720 * 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 721 * A number of constraints are necessary:
722 * - The children must all be of the same type and at the same level
03f01edd 723 * - The children cannot already be top categories
c91ed4be 724 * - The children cannot already have a top categorya
725 * - The children all belong to the same course
03f01edd 726 * @param array $children An array of fully instantiated grade_category OR grade_item objects
727 * @return boolean Success or Failure
728 */
729 function set_as_parent($children) {
730 global $CFG;
731
732 // Check type and sortorder of first child
733 $first_child = current($children);
734 $first_child_type = get_class($first_child);
c91ed4be 735 $first_child_courseid = $first_child->courseid;
03f01edd 736
737 foreach ($children as $child) {
738 if (get_class($child) != $first_child_type) {
739 debugging("Violated constraint: Attempted to set a category as a parent over children of 2 different types.");
740 return false;
741 }
526e1a8a 742
743 $grade_tree = new grade_tree();
744
745 if ($grade_tree->get_element_type($child) == 'topcat') {
03f01edd 746 debugging("Violated constraint: Attempted to set a category over children which are already top categories.");
747 return false;
748 }
749 if ($first_child_type == 'grade_item') {
750 $child->load_category();
751 if (!empty($child->category->parent)) {
752 debugging("Violated constraint: Attempted to set a category over children that already have a top category.");
753 return false;
754 }
755 } elseif ($first_child_type == 'grade_category') {
756 if (!empty($child->parent)) {
757 debugging("Violated constraint: Attempted to set a category over children that already have a top category.");
758 return false;
759 }
760 } else {
761 debugging("Attempted to set a category over children that are neither grade_items nor grade_categories.");
762 return false;
763 }
c91ed4be 764
765 if ($child->courseid != $first_child_courseid) {
766 debugging("Attempted to set a category over children which do not belong to the same course.");
767 return false;
768 }
03f01edd 769 }
770
771 // We passed all the checks, time to set the category as a parent.
772 foreach ($children as $child) {
773 if ($first_child_type == 'grade_item') {
774 $child->categoryid = $this->id;
775 if (!$child->update()) {
776 debugging("Could not set this category as a parent for one of its child grade_items, DB operation failed.");
777 return false;
778 }
779 } elseif ($first_child_type == 'grade_category') {
780 $child->parent = $this->id;
781 if (!$child->update()) {
782 debugging("Could not set this category as a parent for one of its child categories, DB operation failed.");
783 return false;
784 }
785 }
786 }
787
788 // TODO Assign correct sortorders to the newly assigned children and parent. Simply add 1 to all of them!
789 $this->load_grade_item();
790 $this->grade_item->sortorder = $first_child->get_sortorder();
791
c91ed4be 792 // If this->courseid is not set, set it to the first child's courseid
793 if (empty($this->courseid)) {
794 $this->courseid = $first_child_courseid;
795 }
796
03f01edd 797 if (!$this->update()) {
798 debugging("Could not update this category's sortorder in DB.");
799 return false;
800 }
750b0550 801
802 $query = "UPDATE {$CFG->prefix}grade_items SET sortorder = sortorder + 1 WHERE sortorder >= {$this->grade_item->sortorder}";
03f01edd 803 if (!execute_sql($query)) {
804 debugging("Could not update the sortorder of grade_items listed after this category.");
750b0550 805 return false;
03f01edd 806 } else {
807 return true;
808 }
809 }
2186f72c 810
811 /**
812 * Returns the most descriptive field for this object. This is a standard method used
813 * when we do not know the exact type of an object.
814 * @return string name
815 */
816 function get_name() {
817 return $this->fullname;
818 }
c91ed4be 819
820 /**
821 * Returns this category's grade_item's id. This is specified for cases where we do not
822 * know an object's type, and want to get either an item's id or a category's item's id.
823 *
824 * @return int
825 */
826 function get_item_id() {
827 $this->load_grade_item();
828 return $this->grade_item->id;
829 }
0fc7f624 830
831 /**
832 * Returns this category's parent id. A generic method shared by objects that have a parent id of some kind.
833 * @return id $parentid
834 */
835 function get_parent_id() {
836 return $this->parent;
837 }
838
839 /**
840 * Sets this category's parent id. A generic method shared by objects that have a parent id of some kind.
841 * @param id $parentid
842 */
843 function set_parent_id($parentid) {
844 $this->parent = $parentid;
845 }
846
847 /**
848 * Returns the sortorder of the associated grade_item. This method is also available in
849 * grade_item, for cases where the object type is not know. It will act as a virtual
850 * variable for a grade_category.
851 * @return int Sort order
852 */
853 function get_sortorder() {
854 if (empty($this->sortorder)) {
855 $this->load_grade_item();
856 if (!empty($this->grade_item)) {
857 return $this->grade_item->sortorder;
858 }
859 } else {
860 return $this->sortorder;
861 }
862 }
863
864 /**
865 * Sets a temporary sortorder variable for this category. It is used in the update() method to update the grade_item.
866 * This method is also available in grade_item, for cases where the object type is not know.
867 * @param int $sortorder
868 * @return void
869 */
870 function set_sortorder($sortorder) {
871 $this->sortorder = $sortorder;
872 }
873
8ff4550a 874}
8a31e65c 875?>