MDL-10237 - Improve wording on true/false edit form. Merged from MOODLE_18_STABLE.
[moodle.git] / lib / grade / grade_category.php
CommitLineData
8a31e65c 1<?php // $Id$
2
3///////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Modular Object-Oriented Dynamic Learning Environment //
8// http://moodle.com //
9// //
10// Copyright (C) 2001-2003 Martin Dougiamas http://dougiamas.com //
11// //
12// This program is free software; you can redistribute it and/or modify //
13// it under the terms of the GNU General Public License as published by //
14// the Free Software Foundation; either version 2 of the License, or //
15// (at your option) any later version. //
16// //
17// This program is distributed in the hope that it will be useful, //
18// but WITHOUT ANY WARRANTY; without even the implied warranty of //
19// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20// GNU General Public License for more details: //
21// //
22// http://www.gnu.org/copyleft/gpl.html //
23// //
24///////////////////////////////////////////////////////////////////////////
25
26require_once('grade_object.php');
27
3058964f 28class grade_category extends grade_object {
8a31e65c 29 /**
7c8a963f 30 * The DB table.
8a31e65c 31 * @var string $table
32 */
33 var $table = 'grade_categories';
4a490db0 34
8a31e65c 35 /**
36 * Array of class variables that are not part of the DB table fields
37 * @var array $nonfields
38 */
ac9b0805 39 var $nonfields = array('table', 'nonfields', 'children', 'all_children', 'grade_item', 'parent_category');
4a490db0 40
8a31e65c 41 /**
42 * The course this category belongs to.
43 * @var int $courseid
44 */
45 var $courseid;
4a490db0 46
8a31e65c 47 /**
48 * The category this category belongs to (optional).
4a490db0 49 * @var int $parent
8a31e65c 50 */
e5c674f1 51 var $parent;
4a490db0 52
8c846243 53 /**
54 * The grade_category object referenced by $this->parent (PK).
55 * @var object $parent_category
56 */
57 var $parent_category;
27f95e9b 58
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;
4a490db0 83
8a31e65c 84 /**
85 * A constant pointing to one of the predefined aggregation strategies (none, mean, median, sum etc) .
4a490db0 86 * @var int $aggregation
8a31e65c 87 */
88 var $aggregation;
4a490db0 89
8a31e65c 90 /**
91 * Keep only the X highest items.
92 * @var int $keephigh
93 */
94 var $keephigh;
4a490db0 95
8a31e65c 96 /**
97 * Drop the X lowest items.
98 * @var int $droplow
99 */
100 var $droplow;
4a490db0 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 /**
4a490db0 109 * A hierarchical array of all children below this category. This is stored separately from
7c8a963f 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 */
b8ff92b6 128 function grade_category($params=NULL, $fetch=true) {
e5c674f1 129 $this->grade_object($params, $fetch);
2df71235 130 $this->path = grade_category::build_path($this);
e5c674f1 131 }
132
4a490db0 133
e5c674f1 134 /**
135 * Builds this category's path string based on its parents (if any) and its own id number.
136 * This is typically done just before inserting this object in the DB for the first time,
ce385eb4 137 * or when a new parent is added or changed. It is a recursive function: once the calling
138 * object no longer has a parent, the path is complete.
139 *
140 * @static
141 * @param object $grade_category
142 * @return int The depth of this category (2 means there is one parent)
e5c674f1 143 */
ce385eb4 144 function build_path($grade_category) {
145 if (empty($grade_category->parent)) {
146 return "/$grade_category->id";
147 } else {
148 $parent = get_record('grade_categories', 'id', $grade_category->parent);
149 return grade_category::build_path($parent) . "/$grade_category->id";
150 }
e5c674f1 151 }
152
8a31e65c 153
8a31e65c 154 /**
155 * Finds and returns a grade_category object based on 1-3 field values.
61c33818 156 * @static
8a31e65c 157 *
8a31e65c 158 * @param string $field1
159 * @param string $value1
160 * @param string $field2
161 * @param string $value2
162 * @param string $field3
163 * @param string $value3
164 * @param string $fields
165 * @return object grade_category object or false if none found.
166 */
4a490db0 167 function fetch($field1, $value1, $field2='', $value2='', $field3='', $value3='', $fields="*") {
8a31e65c 168 if ($grade_category = get_record('grade_categories', $field1, $value1, $field2, $value2, $field3, $value3, $fields)) {
61c33818 169 $grade_category = new grade_category($grade_category);
170 return $grade_category;
171
8a31e65c 172 } else {
173 return false;
174 }
ce385eb4 175 }
176
8f4a626d 177 /**
2cc4b0f9 178 * In addition to update() as defined in grade_object, call force_regrading of parent categories, if applicable.
8f4a626d 179 */
4a490db0 180 function update() {
2cc4b0f9 181 $qualifies = $this->qualifies_for_regrading();
8f4a626d 182
0fc7f624 183 // Update the grade_item's sortorder if needed
184 if (!empty($this->sortorder)) {
185 $this->load_grade_item();
186 if (!empty($this->grade_item)) {
187 $this->grade_item->sortorder = $this->sortorder;
188 $this->grade_item->update();
189 }
190 unset($this->sortorder);
4a490db0 191 }
0fc7f624 192
8f4a626d 193 $result = parent::update();
4a490db0 194
cb64c6b2 195 // Use $this->path to update all parent categories
8f4a626d 196 if ($result && $qualifies) {
2cc4b0f9 197 $this->force_regrading();
4a490db0 198 }
8f4a626d 199 return $result;
200 }
4a490db0 201
8f4a626d 202 /**
2cc4b0f9 203 * If parent::delete() is successful, send force_regrading message to parent category.
8f4a626d 204 * @return boolean Success or failure.
205 */
206 function delete() {
207 $result = parent::delete();
4a490db0 208
8f4a626d 209 if ($result) {
210 $this->load_parent_category();
211 if (!empty($this->parent_category)) {
2cc4b0f9 212 $result = $result && $this->parent_category->force_regrading();
8f4a626d 213 }
4a490db0 214
215 // Update children's categoryid/parent field
216 global $db;
217 $set_field_result = set_field('grade_items', 'categoryid', null, 'categoryid', $this->id);
218 $set_field_result = set_field('grade_categories', 'parent', null, 'parent', $this->id);
8f4a626d 219 }
220
221 return $result;
222 }
4a490db0 223
ce385eb4 224 /**
225 * In addition to the normal insert() defined in grade_object, this method sets the depth
226 * and path for this object, and update the record accordingly. The reason why this must
227 * be done here instead of in the constructor, is that they both need to know the record's
4a490db0 228 * id number, which only gets created at insertion time.
f151b073 229 * This method also creates an associated grade_item if this wasn't done during construction.
ce385eb4 230 */
231 function insert() {
b8ff92b6 232 if (!parent::insert()) {
233 debugging("Could not insert this category: " . print_r($this, true));
234 return false;
235 }
4a490db0 236
77d2540e 237 $this->path = grade_category::build_path($this);
ce385eb4 238
239 // Build path and depth variables
240 if (!empty($this->parent)) {
ce385eb4 241 $this->depth = $this->get_depth_from_path();
242 } else {
243 $this->depth = 1;
ce385eb4 244 }
4a490db0 245
ce385eb4 246 $this->update();
4a490db0 247
b8ff92b6 248 // initialize grade_item for this category
249 $this->grade_item = $this->get_grade_item();
4a490db0 250
b8ff92b6 251 // Notify parent category of need to update.
252 $this->load_parent_category();
253 if (!empty($this->parent_category)) {
2cc4b0f9 254 if (!$this->parent_category->force_regrading()) {
b8ff92b6 255 debugging("Could not notify parent category of the need to update its final grades.");
6527197b 256 return false;
257 }
f151b073 258 }
4a490db0 259
b8ff92b6 260 return true;
ce385eb4 261 }
4a490db0 262
8f4a626d 263 /**
264 * Compares the values held by this object with those of the matching record in DB, and returns
265 * whether or not these differences are sufficient to justify an update of all parent objects.
266 * This assumes that this object has an id number and a matching record in DB. If not, it will return false.
267 * @return boolean
268 */
2cc4b0f9 269 function qualifies_for_regrading() {
8f4a626d 270 if (empty($this->id)) {
271 return false;
272 }
273
274 $db_item = new grade_category(array('id' => $this->id));
4a490db0 275
8f4a626d 276 $aggregationdiff = $db_item->aggregation != $this->aggregation;
277 $keephighdiff = $db_item->keephigh != $this->keephigh;
278 $droplowdiff = $db_item->droplow != $this->droplow;
279
280 if ($aggregationdiff || $keephighdiff || $droplowdiff) {
281 return true;
282 } else {
283 return false;
284 }
285 }
8c846243 286
287 /**
288 * Sets this category's and its parent's grade_item.needsupdate to true.
289 * This is triggered whenever any change in any lower level may cause grade_finals
290 * for this category to require an update. The flag needs to be propagated up all
291 * levels until it reaches the top category. This is then used to determine whether or not
cb64c6b2 292 * to regenerate the raw and final grades for each category grade_item. This is accomplished
293 * thanks to the path variable, so we don't need to use recursion.
8c846243 294 * @return boolean Success or failure
295 */
2cc4b0f9 296 function force_regrading() {
b8ff92b6 297 if (empty($this->id)) {
298 debugging("Needsupdate requested before insering grade category.");
299 return true;
300 }
301
8c846243 302 $this->load_grade_item();
8f4a626d 303
2e53372c 304 if ($this->grade_item->needsupdate) {
305 // this grade_item (and category) already needs update, no need to set it again here or in parent categories
306 return true;
307 }
308
cb64c6b2 309 $paths = explode('/', $this->path);
4a490db0 310
77d2540e 311 // Remove the first index, which is always empty
312 unset($paths[0]);
4a490db0 313
2e53372c 314 $result = true;
315
77d2540e 316 if (!empty($paths)) {
317 $wheresql = '';
4a490db0 318
77d2540e 319 foreach ($paths as $categoryid) {
320 $wheresql .= "iteminstance = $categoryid OR ";
321 }
322 $wheresql = substr($wheresql, 0, strrpos($wheresql, 'OR'));
a3d55942 323 $grade_items = set_field_select('grade_items', 'needsupdate', '1', $wheresql . ' AND courseid = ' . $this->courseid);
77d2540e 324 $this->grade_item->update_from_db();
2cc4b0f9 325
326 }
327
8c846243 328 return $result;
329 }
330
0aa32279 331 /**
ac9b0805 332 * Generates and saves raw_grades in associated category grade item.
333 * These immediate children must alrady have their own final grades.
334 * The category's aggregation method is used to generate raw grades.
335 *
336 * Please note that category grade is either calculated or aggregated - not both at the same time.
337 *
338 * This method must be used ONLY from grade_item::update_final_grades(),
339 * because the calculation must be done in correct order!
b8ff92b6 340 *
4a490db0 341 * Steps to follow:
ac9b0805 342 * 1. Get final grades from immediate children
2df71235 343 * 3. Aggregate these grades
ac9b0805 344 * 4. Save them in raw grades of associated category grade item
0aa32279 345 */
346 function generate_grades() {
b8ff92b6 347 global $CFG;
4a490db0 348
ac9b0805 349 $this->load_grade_item();
2cc4b0f9 350
351 if ($this->grade_item->is_locked()) {
352 return true; // no need to recalculate locked items
353 }
354
ac9b0805 355 $this->grade_item->load_scale();
2df71235 356
2cc4b0f9 357
ac9b0805 358 // find grde items of immediate children (category or grade items)
61c33818 359 $depends_on = $this->grade_item->depends_on();
b8ff92b6 360 $items = array();
4a490db0 361
61c33818 362 foreach($depends_on as $dep) {
b8ff92b6 363 $items[$dep] = grade_item::fetch('id', $dep);
364 }
4a490db0 365
ac9b0805 366 // where to look for final grades - include or grade item too
61c33818 367 $gis = implode(',', array_merge($depends_on, array($this->grade_item->id)));
b8ff92b6 368
ac9b0805 369 $sql = "SELECT g.*
370 FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items gi
371 WHERE gi.id = g.itemid AND gi.courseid={$this->grade_item->courseid} AND gi.id IN ($gis)
372 ORDER BY g.userid";
b8ff92b6 373
ac9b0805 374 // group the results by userid and aggregate the grades in this group
b8ff92b6 375 if ($rs = get_recordset_sql($sql)) {
376 if ($rs->RecordCount() > 0) {
377 $prevuser = 0;
378 $grades = array();
ac9b0805 379 $final = null;
380 while ($used = rs_fetch_next_record($rs)) {
381 if ($used->userid != $prevuser) {
61c33818 382 $this->aggregate_grades($prevuser, $items, $grades, $depends_on, $final);
ac9b0805 383 $prevuser = $used->userid;
b8ff92b6 384 $grades = array();
ac9b0805 385 $final = null;
386 }
387 if ($used->itemid == $this->grade_item->id) {
388 $final = new grade_grades($used, false);
2cc4b0f9 389 $final->grade_item =& $this->grade_item;
b8ff92b6 390 }
ac9b0805 391 $grades[$used->itemid] = $used->finalgrade;
2df71235 392 }
61c33818 393 $this->aggregate_grades($prevuser, $items, $grades, $depends_on, $final);
b8ff92b6 394 }
395 }
396
b8ff92b6 397 return true;
398 }
399
400 /**
ac9b0805 401 * internal function for category grades aggregation
b8ff92b6 402 */
61c33818 403 function aggregate_grades($userid, $items, $grades, $depends_on, $final) {
b8ff92b6 404 if (empty($userid)) {
ac9b0805 405 //ignore first run
b8ff92b6 406 return;
407 }
4a490db0 408
ac9b0805 409 // no circular references allowed
410 unset($grades[$this->grade_item->id]);
b8ff92b6 411
2cc4b0f9 412 // insert final grade - it will be needed later anyway
ac9b0805 413 if (empty($final)) {
414 $final = new grade_grades(array('itemid'=>$this->grade_item->id, 'userid'=>$userid), false);
415 $final->insert();
2cc4b0f9 416 $final->grade_item =& $this->grade_item;
417
418 } else if ($final->is_locked()) {
419 // no need to recalculate locked grades
420 return;
ac9b0805 421 }
422
423 // if no grades calculation possible or grading not allowed clear both final and raw
424 if (empty($grades) or empty($items) or ($this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE)) {
425 $final->finalgrade = null;
426 $final->rawgrade = null;
427 $final->update();
b8ff92b6 428 return;
429 }
4a490db0 430
b8ff92b6 431 // normalize the grades first - all will have value 0...1
ac9b0805 432 // ungraded items are not used in aggreagation
b8ff92b6 433 foreach ($grades as $k=>$v) {
434 if (is_null($v)) {
435 // null means no grade
436 unset($grades[$k]);
437 continue;
0aa32279 438 }
ac9b0805 439 $grades[$k] = grade_grades::standardise_score($v, $items[$k]->grademin, $items[$k]->grademax, 0, 1);
0aa32279 440 }
dda0c7e6 441
ac9b0805 442 //limit and sort
b8ff92b6 443 $this->apply_limit_rules($grades);
444 sort($grades, SORT_NUMERIC);
4a490db0 445
ac9b0805 446 // let's see we have still enough grades to do any statisctics
b8ff92b6 447 if (count($grades) == 0) {
ac9b0805 448 // not enough attempts yet
449 if (!is_null($final->finalgrade) or !is_null($final->rawgrade)) {
450 $final->finalgrade = null;
451 $final->rawgrade = null;
452 $final->update();
b8ff92b6 453 }
454 return;
455 }
2df71235 456
b8ff92b6 457 switch ($this->aggregation) {
458 case GRADE_AGGREGATE_MEDIAN: // Middle point value in the set: ignores frequencies
459 $num = count($grades);
460 $halfpoint = intval($num / 2);
461
462 if($num % 2 == 0) {
ac9b0805 463 $rawgrade = ($grades[ceil($halfpoint)] + $grades[floor($halfpoint)]) / 2;
b8ff92b6 464 } else {
ac9b0805 465 $rawgrade = $grades[$halfpoint];
b8ff92b6 466 }
467 break;
ac9b0805 468
b8ff92b6 469 case GRADE_AGGREGATE_MIN:
ac9b0805 470 $rawgrade = reset($grades);
b8ff92b6 471 break;
472
473 case GRADE_AGGREGATE_MAX:
ac9b0805 474 $rawgrade = array_pop($grades);
b8ff92b6 475 break;
476
95affb8a 477 case GRADE_AGGREGATE_MEAN_ALL: // Arithmetic average of all grade items including even NULLs; NULL grade caunted as minimum
61c33818 478 $num = count($depends_on); // you can calculate sum from this one if you multiply it with count($this->depends_on() ;-)
b8ff92b6 479 $sum = array_sum($grades);
ac9b0805 480 $rawgrade = $sum / $num;
b8ff92b6 481 break;
482
95affb8a 483 case GRADE_AGGREGATE_MODE: // the most common value, the highest one if multimode
484 $freq = array_count_values($grades);
485 arsort($freq); // sort by frequency keeping keys
486 $top = reset($freq); // highest frequency count
487 $modes = array_keys($freq, $top); // search for all modes (have the same highest count)
488 rsort($modes, SORT_NUMERIC); // get highes mode
ac9b0805 489 $rawgrade = reset($modes);
95affb8a 490
491 case GRADE_AGGREGATE_MEAN_GRADED: // Arithmetic average of all final grades, unfinished are not calculated
ac9b0805 492 default:
b8ff92b6 493 $num = count($grades);
494 $sum = array_sum($grades);
ac9b0805 495 $rawgrade = $sum / $num;
b8ff92b6 496 break;
497 }
498
ac9b0805 499 // recalculate the rawgrade back to requested range
500 $rawgrade = $this->grade_item->adjust_grade($rawgrade, 0, 1);
b8ff92b6 501
ac9b0805 502 // prepare update of new raw grade
503 $final->rawgrade = $rawgrade;
504 $final->finalgrade = null;
505 $final->rawgrademin = $this->grade_item->grademin;
506 $final->rawgrademax = $this->grade_item->grademax;
507 $final->rawscaleid = $this->grade_item->scaleid;
2df71235 508
ac9b0805 509 // TODO - add some checks to prevent updates when not needed
510 $final->update();
0aa32279 511 }
512
adc2f286 513 /**
514 * Given an array of grade values (numerical indices), applies droplow or keephigh
515 * rules to limit the final array.
516 * @param array $grades
517 * @return array Limited grades.
518 */
b8ff92b6 519 function apply_limit_rules(&$grades) {
adc2f286 520 rsort($grades, SORT_NUMERIC);
521 if (!empty($this->droplow)) {
522 for ($i = 0; $i < $this->droplow; $i++) {
523 array_pop($grades);
524 }
4a490db0 525 } elseif (!empty($this->keephigh)) {
adc2f286 526 while (count($grades) > $this->keephigh) {
4a490db0 527 array_pop($grades);
adc2f286 528 }
529 }
0aa32279 530 }
531
0fc7f624 532 /**
533 * Given an array of stdClass children of a certain $object_type, returns a flat or nested
534 * array of these children, ready for appending to a tree built by get_children.
535 * @static
536 * @param array $children
537 * @param string $arraytype
538 * @param string $object_type
539 * @return array
540 */
541 function children_to_array($children, $arraytype='nested', $object_type='grade_item') {
542 $children_array = array();
543
544 foreach ($children as $id => $child) {
545 $child = new $object_type($child, false);
546 if ($arraytype == 'nested') {
547 $children_array[$child->get_sortorder()] = array('object' => $child);
548 } else {
549 $children_array[$child->get_sortorder()] = $child;
550 }
4a490db0 551 }
0fc7f624 552
553 return $children_array;
554 }
555
556 /**
557 * Returns true if this category has any child grade_category or grade_item.
558 * @return int number of direct children, or false if none found.
559 */
560 function has_children() {
561 return count_records('grade_categories', 'parent', $this->id) + count_records('grade_items', 'categoryid', $this->id);
562 }
563
564 /**
4a490db0 565 * Checks whether an existing child exists for this category. If the new child is of a
210611f6 566 * different type, the method will return false (not allowed). Otherwise it will return true.
0fc7f624 567 * @param object $child This must be a complete object, not a stdClass
568 * @return boolean Success or failure
569 */
570 function can_add_child($child) {
571 if ($this->has_children()) {
572 if (get_class($child) != $this->get_childrentype()) {
573 return false;
574 } else {
575 return true;
576 }
577 } else {
578 return true;
579 }
580 }
581
1c307f21 582 /**
583 * Disassociates this category from its category parent(s). The object is then updated in DB.
584 * @return boolean Success or Failure
585 */
586 function divorce_parent() {
4a490db0 587 $this->old_parent = $this->get_parent_category();
1c307f21 588 $this->parent = null;
589 $this->parent_category = null;
590 $this->depth = 1;
591 $this->path = '/' . $this->id;
4a490db0 592 return $this->update();
1c307f21 593 }
594
ce385eb4 595 /**
596 * Looks at a path string (e.g. /2/45/56) and returns the depth level represented by this path (in this example, 3).
597 * If no string is given, it looks at the obect's path and assigns the resulting depth to its $depth variable.
598 * @param string $path
599 * @return int Depth level
600 */
601 function get_depth_from_path($path=NULL) {
602 if (empty($path)) {
603 $path = $this->path;
604 }
605 preg_match_all('/\/([0-9]+)+?/', $path, $matches);
606 $depth = count($matches[0]);
607
608 return $depth;
609 }
7c8a963f 610
611 /**
4a490db0 612 * Fetches and returns all the children categories and/or grade_items belonging to this category.
613 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 614 * as well as all levels (0). The elements are indexed by sort order.
7c8a963f 615 * @param int $depth 1 for immediate children, 0 for all children, and 2+ for specific levels deeper than 1.
616 * @param string $arraytype Either 'nested' or 'flat'. A nested array represents the true hierarchy, but is more difficult to work with.
617 * @return array Array of child objects (grade_category and grade_item).
618 */
619 function get_children($depth=1, $arraytype='nested') {
27f95e9b 620 $children_array = array();
4a490db0 621
27f95e9b 622 // Set up $depth for recursion
623 $newdepth = $depth;
624 if ($depth > 1) {
625 $newdepth--;
626 }
4a490db0 627
27f95e9b 628 $childrentype = $this->get_childrentype();
4a490db0 629
27f95e9b 630 if ($childrentype == 'grade_item') {
f151b073 631 $children = get_records('grade_items', 'categoryid', $this->id);
27f95e9b 632 // No need to proceed with recursion
633 $children_array = $this->children_to_array($children, $arraytype, 'grade_item');
634 $this->children = $this->children_to_array($children, 'flat', 'grade_item');
635 } elseif ($childrentype == 'grade_category') {
636 $children = get_records('grade_categories', 'parent', $this->id, 'id');
4a490db0 637
27f95e9b 638 if ($depth == 1) {
639 $children_array = $this->children_to_array($children, $arraytype, 'grade_category');
640 $this->children = $this->children_to_array($children, 'flat', 'grade_category');
7c8a963f 641 } else {
27f95e9b 642 foreach ($children as $id => $child) {
643 $cat = new grade_category($child, false);
644
645 if ($cat->has_children()) {
646 if ($arraytype == 'nested') {
a39cac25 647 $children_array[$cat->get_sortorder()] = array('object' => $cat, 'children' => $cat->get_children($newdepth, $arraytype));
27f95e9b 648 } else {
a39cac25 649 $children_array[$cat->get_sortorder()] = $cat;
27f95e9b 650 $cat_children = $cat->get_children($newdepth, $arraytype);
651 foreach ($cat_children as $id => $cat_child) {
a39cac25 652 $children_array[$cat_child->get_sortorder()] = new grade_category($cat_child, false);
27f95e9b 653 }
654 }
655 } else {
656 if ($arraytype == 'nested') {
a39cac25 657 $children_array[$cat->get_sortorder()] = array('object' => $cat);
27f95e9b 658 } else {
a39cac25 659 $children_array[$cat->get_sortorder()] = $cat;
27f95e9b 660 }
661 }
7c8a963f 662 }
27f95e9b 663 }
664 } else {
665 return null;
666 }
667
668 return $children_array;
669 }
4a490db0 670
27f95e9b 671 /**
4a490db0 672 * Check the type of the first child of this category, to see whether it is a
27f95e9b 673 * grade_category or a grade_item, and returns that type as a string (get_class).
674 * @return string
675 */
676 function get_childrentype() {
27f95e9b 677 if (empty($this->children)) {
678 $count_item_children = count_records('grade_items', 'categoryid', $this->id);
679 $count_cat_children = count_records('grade_categories', 'parent', $this->id);
4a490db0 680
27f95e9b 681 if ($count_item_children > 0) {
682 return 'grade_item';
683 } elseif ($count_cat_children > 0) {
684 return 'grade_category';
685 } else {
686 return null;
7c8a963f 687 }
7c8a963f 688 }
a15428a2 689 reset($this->children);
690 return get_class(current($this->children));
7c8a963f 691 }
f151b073 692
693 /**
ab53054f 694 * Uses get_grade_item to load or create a grade_item, then saves it as $this->grade_item.
f151b073 695 * @return object Grade_item
696 */
697 function load_grade_item() {
ac9b0805 698 if (empty($this->grade_item)) {
699 $this->grade_item = $this->get_grade_item();
700 }
ab53054f 701 return $this->grade_item;
702 }
4a490db0 703
ab53054f 704 /**
705 * Retrieves from DB and instantiates the associated grade_item object.
706 * If no grade_item exists yet, create one.
707 * @return object Grade_item
708 */
709 function get_grade_item() {
c91ed4be 710 if (empty($this->id)) {
711 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
712 return false;
713 }
714
b8ff92b6 715 $grade_item = new grade_item(array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id), false);
716 if (!$grade_items = $grade_item->fetch_all_using_this()) {
717 // create a new one
718 $grade_item->gradetype = GRADE_TYPE_VALUE;
719 $grade_item->insert();
4a490db0 720
b8ff92b6 721 } else if (count($grade_items) == 1){
722 // found existing one
723 $grade_item = reset($grade_items);
4a490db0 724
b8ff92b6 725 } else {
726 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 727 // return first one
728 $grade_item = reset($grade_items);
2c72af1f 729 }
730
ab53054f 731 return $grade_item;
f151b073 732 }
8c846243 733
734 /**
735 * Uses $this->parent to instantiate $this->parent_category based on the
736 * referenced record in the DB.
737 * @return object Parent_category
738 */
739 function load_parent_category() {
740 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 741 $this->parent_category = $this->get_parent_category();
8c846243 742 }
743 return $this->parent_category;
4a490db0 744 }
745
ab53054f 746 /**
747 * Uses $this->parent to instantiate and return a grade_category object.
748 * @return object Parent_category
749 */
750 function get_parent_category() {
751 if (!empty($this->parent)) {
752 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 753 return $parent_category;
ab53054f 754 } else {
755 return null;
756 }
757 }
758
03f01edd 759 /**
c91ed4be 760 * 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 761 * A number of constraints are necessary:
762 * - The children must all be of the same type and at the same level
03f01edd 763 * - The children cannot already be top categories
c91ed4be 764 * - The children all belong to the same course
03f01edd 765 * @param array $children An array of fully instantiated grade_category OR grade_item objects
ffa6e8d3 766 *
03f01edd 767 * @return boolean Success or Failure
ffa6e8d3 768 * @TODO big problem of performance
03f01edd 769 */
770 function set_as_parent($children) {
771 global $CFG;
772
210611f6 773 if (empty($children) || !is_array($children)) {
774 debugging("Passed an empty or non-array variable to grade_category::set_as_parent()");
775 return false;
776 }
777
03f01edd 778 // Check type and sortorder of first child
779 $first_child = current($children);
780 $first_child_type = get_class($first_child);
9f9afbdb 781
782 // If this->courseid is not set, set it to the first child's courseid
783 if (empty($this->courseid)) {
784 $this->courseid = $first_child->courseid;
785 }
786
787 $grade_tree = new grade_tree();
03f01edd 788
789 foreach ($children as $child) {
790 if (get_class($child) != $first_child_type) {
791 debugging("Violated constraint: Attempted to set a category as a parent over children of 2 different types.");
792 return false;
793 }
4a490db0 794
526e1a8a 795 if ($grade_tree->get_element_type($child) == 'topcat') {
03f01edd 796 debugging("Violated constraint: Attempted to set a category over children which are already top categories.");
797 return false;
798 }
4a490db0 799
9f9afbdb 800 if ($first_child_type == 'grade_category' or $first_child_type == 'grade_item') {
03f01edd 801 if (!empty($child->parent)) {
802 debugging("Violated constraint: Attempted to set a category over children that already have a top category.");
4a490db0 803 return false;
03f01edd 804 }
805 } else {
806 debugging("Attempted to set a category over children that are neither grade_items nor grade_categories.");
807 return false;
4a490db0 808 }
c91ed4be 809
9f9afbdb 810 if ($child->courseid != $this->courseid) {
c91ed4be 811 debugging("Attempted to set a category over children which do not belong to the same course.");
812 return false;
813 }
4a490db0 814 }
03f01edd 815
816 // We passed all the checks, time to set the category as a parent.
817 foreach ($children as $child) {
1c307f21 818 $child->divorce_parent();
819 $child->set_parent_id($this->id);
820 if (!$child->update()) {
821 debugging("Could not set this category as a parent for one of its children, DB operation failed.");
822 return false;
4a490db0 823 }
03f01edd 824 }
825
826 // TODO Assign correct sortorders to the newly assigned children and parent. Simply add 1 to all of them!
827 $this->load_grade_item();
828 $this->grade_item->sortorder = $first_child->get_sortorder();
4a490db0 829
03f01edd 830 if (!$this->update()) {
831 debugging("Could not update this category's sortorder in DB.");
832 return false;
833 }
4a490db0 834
750b0550 835 $query = "UPDATE {$CFG->prefix}grade_items SET sortorder = sortorder + 1 WHERE sortorder >= {$this->grade_item->sortorder}";
ffa6e8d3 836 $query .= " AND courseid = $this->courseid";
837
03f01edd 838 if (!execute_sql($query)) {
839 debugging("Could not update the sortorder of grade_items listed after this category.");
750b0550 840 return false;
03f01edd 841 } else {
842 return true;
843 }
844 }
2186f72c 845
846 /**
4a490db0 847 * Returns the most descriptive field for this object. This is a standard method used
2186f72c 848 * when we do not know the exact type of an object.
849 * @return string name
850 */
851 function get_name() {
852 return $this->fullname;
853 }
c91ed4be 854
855 /**
856 * Returns this category's grade_item's id. This is specified for cases where we do not
857 * know an object's type, and want to get either an item's id or a category's item's id.
858 *
859 * @return int
860 */
861 function get_item_id() {
862 $this->load_grade_item();
863 return $this->grade_item->id;
864 }
0fc7f624 865
866 /**
867 * Returns this category's parent id. A generic method shared by objects that have a parent id of some kind.
868 * @return id $parentid
869 */
870 function get_parent_id() {
871 return $this->parent;
872 }
873
874 /**
875 * Sets this category's parent id. A generic method shared by objects that have a parent id of some kind.
876 * @param id $parentid
877 */
878 function set_parent_id($parentid) {
879 $this->parent = $parentid;
88e794d6 880 $this->path = grade_category::build_path($this);
881 $this->depth = $this->get_depth_from_path();
0fc7f624 882 }
4a490db0 883
0fc7f624 884 /**
4a490db0 885 * Returns the sortorder of the associated grade_item. This method is also available in
5fad5061 886 * grade_item, for cases where the object type is not known.
0fc7f624 887 * @return int Sort order
888 */
889 function get_sortorder() {
890 if (empty($this->sortorder)) {
891 $this->load_grade_item();
892 if (!empty($this->grade_item)) {
893 return $this->grade_item->sortorder;
894 }
895 } else {
896 return $this->sortorder;
897 }
898 }
899
900 /**
4a490db0 901 * Sets a temporary sortorder variable for this category. It is used in the update() method to update the grade_item.
902 * This method is also available in grade_item, for cases where the object type is not know.
0fc7f624 903 * @param int $sortorder
904 * @return void
905 */
906 function set_sortorder($sortorder) {
907 $this->sortorder = $sortorder;
908 }
4a490db0 909
5fad5061 910 /**
4a490db0 911 * Returns the locked state/date of the associated grade_item. This method is also available in
912 * grade_item, for cases where the object type is not known.
5fad5061 913 * @return int 0, 1 or timestamp int(10)
914 */
2cc4b0f9 915 function is_locked() {
5fad5061 916 $this->load_grade_item();
917 if (!empty($this->grade_item)) {
2cc4b0f9 918 return $this->grade_item->is_locked();
5fad5061 919 } else {
920 return false;
921 }
922 }
923
924 /**
925 * Sets the grade_item's locked variable and updates the grade_item.
926 * Method named after grade_item::set_locked().
927 * @param int $locked 0, 1 or a timestamp int(10) after which date the item will be locked.
2cc4b0f9 928 * @return boolean success
5fad5061 929 */
2cc4b0f9 930 function set_locked($lockedstate) {
5fad5061 931 $this->load_grade_item();
2cc4b0f9 932
5fad5061 933 if (!empty($this->grade_item)) {
2cc4b0f9 934 return $this->grade_item->set_locked($lockedstate);
935
5fad5061 936 } else {
937 return false;
938 }
939 }
4a490db0 940
5fad5061 941 /**
4a490db0 942 * Returns the hidden state/date of the associated grade_item. This method is also available in
943 * grade_item, for cases where the object type is not known.
5fad5061 944 * @return int 0, 1 or timestamp int(10)
945 */
946 function get_hidden() {
947 $this->load_grade_item();
948 if (!empty($this->grade_item)) {
949 return $this->grade_item->hidden;
950 } else {
951 return false;
952 }
953 }
954
955 /**
4a490db0 956 * Sets the grade_item's hidden variable and updates the grade_item.
5fad5061 957 * Method named after grade_item::set_hidden().
958 * @param int $hidden 0, 1 or a timestamp int(10) after which date the item will be hidden.
959 * @return void
960 */
961 function set_hidden($hidden) {
962 $this->load_grade_item();
963 if (!empty($this->grade_item)) {
964 $this->grade_item->hidden = $hidden;
965 return $this->grade_item->update();
966 } else {
967 return false;
968 }
969 }
970
4a490db0 971 /**
88e794d6 972 * If the old parent is set (after an update), this checks and returns whether it has any children. Important for
973 * deleting childless categories.
974 * @return boolean
975 */
976 function is_old_parent_childless() {
977 if (!empty($this->old_parent)) {
978 return !$this->old_parent->has_children();
979 } else {
980 return false;
981 }
4a490db0 982 }
983}
8a31e65c 984?>