aggregation improvements; fixed aggregation of course category when changing type...
[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 */
aaff71da 39 var $nonfields = array('table', 'required_fields', 'nonfields', 'children', 'all_children', 'grade_item', 'parent_category', 'sortorder');
4a490db0 40
8a31e65c 41 /**
42 * The course this category belongs to.
43 * @var int $courseid
44 */
45 var $courseid;
4a490db0 46
8a31e65c 47 /**
48 * The category this category belongs to (optional).
4a490db0 49 * @var int $parent
8a31e65c 50 */
e5c674f1 51 var $parent;
4a490db0 52
8c846243 53 /**
54 * The grade_category object referenced by $this->parent (PK).
55 * @var object $parent_category
56 */
57 var $parent_category;
27f95e9b 58
e5c674f1 59 /**
60 * The number of parents this category has.
61 * @var int $depth
62 */
63 var $depth = 0;
64
65 /**
66 * Shows the hierarchical path for this category as /1/2/3 (like course_categories), the last number being
67 * this category's autoincrement ID number.
68 * @var string $path
69 */
70 var $path;
71
8a31e65c 72 /**
73 * The name of this category.
74 * @var string $fullname
75 */
76 var $fullname;
4a490db0 77
8a31e65c 78 /**
79 * A constant pointing to one of the predefined aggregation strategies (none, mean, median, sum etc) .
4a490db0 80 * @var int $aggregation
8a31e65c 81 */
f92dcad8 82 var $aggregation = GRADE_AGGREGATE_MEAN_ALL;
4a490db0 83
8a31e65c 84 /**
85 * Keep only the X highest items.
86 * @var int $keephigh
87 */
f92dcad8 88 var $keephigh = 0;
4a490db0 89
8a31e65c 90 /**
91 * Drop the X lowest items.
92 * @var int $droplow
93 */
f92dcad8 94 var $droplow = 0;
4a490db0 95
8a31e65c 96 /**
97 * Array of grade_items or grade_categories nested exactly 1 level below this category
98 * @var array $children
99 */
100 var $children;
8a31e65c 101
7c8a963f 102 /**
4a490db0 103 * A hierarchical array of all children below this category. This is stored separately from
7c8a963f 104 * $children because it is more memory-intensive and may not be used as often.
105 * @var array $all_children
106 */
107 var $all_children;
108
f151b073 109 /**
110 * An associated grade_item object, with itemtype=category, used to calculate and cache a set of grade values
111 * for this category.
112 * @var object $grade_item
113 */
114 var $grade_item;
115
b3ac6c3e 116 /**
117 * Temporary sortorder for speedup of children resorting
118 */
119 var $sortorder;
120
e5c674f1 121 /**
122 * Builds this category's path string based on its parents (if any) and its own id number.
123 * This is typically done just before inserting this object in the DB for the first time,
ce385eb4 124 * or when a new parent is added or changed. It is a recursive function: once the calling
125 * object no longer has a parent, the path is complete.
126 *
127 * @static
128 * @param object $grade_category
129 * @return int The depth of this category (2 means there is one parent)
e5c674f1 130 */
ce385eb4 131 function build_path($grade_category) {
132 if (empty($grade_category->parent)) {
b3ac6c3e 133 return '/'.$grade_category->id;
ce385eb4 134 } else {
135 $parent = get_record('grade_categories', 'id', $grade_category->parent);
b3ac6c3e 136 return grade_category::build_path($parent).'/'.$grade_category->id;
ce385eb4 137 }
e5c674f1 138 }
139
8a31e65c 140 /**
f92dcad8 141 * Finds and returns a grade_category instance based on params.
61c33818 142 * @static
8a31e65c 143 *
f92dcad8 144 * @param array $params associative arrays varname=>value
145 * @return object grade_category instance or false if none found.
146 */
147 function fetch($params) {
b3ac6c3e 148 return grade_object::fetch_helper('grade_categories', 'grade_category', $params);
f92dcad8 149 }
150
151 /**
152 * Finds and returns all grade_category instances based on params.
153 * @static
154 *
155 * @param array $params associative arrays varname=>value
156 * @return array array of grade_category insatnces or false if none found.
157 */
158 function fetch_all($params) {
b3ac6c3e 159 return grade_object::fetch_all_helper('grade_categories', 'grade_category', $params);
ce385eb4 160 }
161
8f4a626d 162 /**
2cc4b0f9 163 * In addition to update() as defined in grade_object, call force_regrading of parent categories, if applicable.
aaff71da 164 * @param string $source from where was the object updated (mod/forum, manual, etc.)
165 * @return boolean success
8f4a626d 166 */
aaff71da 167 function update($source=null) {
b3ac6c3e 168 // load the grade item or create a new one
169 $this->load_grade_item();
170
171 // force recalculation of path;
172 if (empty($this->path)) {
173 $this->path = grade_category::build_path($this);
174 $this->depth = substr_count($this->path, '/');
4a490db0 175 }
0fc7f624 176
4a490db0 177
b3ac6c3e 178 // Recalculate grades if needed
179 if ($this->qualifies_for_regrading()) {
f8e6e4db 180 $this->force_regrading();
4a490db0 181 }
f8e6e4db 182
183 return parent::update($source);
8f4a626d 184 }
4a490db0 185
8f4a626d 186 /**
2cc4b0f9 187 * If parent::delete() is successful, send force_regrading message to parent category.
aaff71da 188 * @param string $source from where was the object deleted (mod/forum, manual, etc.)
189 * @return boolean success
8f4a626d 190 */
aaff71da 191 function delete($source=null) {
f13002d5 192 if ($this->is_course_category()) {
193 debuggin('Can not delete top course category!');
194 return false;
195 }
4a490db0 196
f8e6e4db 197 $this->force_regrading();
198
f13002d5 199 $grade_item = $this->load_grade_item();
200 $parent = $this->load_parent_category();
4a490db0 201
f13002d5 202 // Update children's categoryid/parent field first
aaff71da 203 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
204 foreach ($children as $child) {
205 $child->set_parent($parent->id);
206 }
207 }
208 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
209 foreach ($children as $child) {
210 $child->set_parent($parent->id);
211 }
212 }
f13002d5 213
aaff71da 214 // first delete the attached grade item and grades
215 $grade_item->delete($source);
f13002d5 216
217 // delete category itself
aaff71da 218 return parent::delete($source);
8f4a626d 219 }
4a490db0 220
ce385eb4 221 /**
222 * In addition to the normal insert() defined in grade_object, this method sets the depth
223 * and path for this object, and update the record accordingly. The reason why this must
224 * be done here instead of in the constructor, is that they both need to know the record's
4a490db0 225 * id number, which only gets created at insertion time.
f151b073 226 * This method also creates an associated grade_item if this wasn't done during construction.
aaff71da 227 * @param string $source from where was the object inserted (mod/forum, manual, etc.)
228 * @return int PK ID if successful, false otherwise
ce385eb4 229 */
aaff71da 230 function insert($source=null) {
b3ac6c3e 231
232 if (empty($this->courseid)) {
233 error('Can not insert grade category without course id!');
b8ff92b6 234 }
4a490db0 235
b3ac6c3e 236 if (empty($this->parent)) {
237 $course_category = grade_category::fetch_course_category($this->courseid);
238 $this->parent = $course_category->id;
ce385eb4 239 }
4a490db0 240
b3ac6c3e 241 $this->path = null;
242
aaff71da 243 if (!parent::insert($source)) {
b3ac6c3e 244 debugging("Could not insert this category: " . print_r($this, true));
245 return false;
246 }
247
f8e6e4db 248 $this->force_regrading();
249
b3ac6c3e 250 // build path and depth
aaff71da 251 $this->update($source);
4a490db0 252
aaff71da 253 return $this->id;
b3ac6c3e 254 }
255
256 function insert_course_category($courseid) {
257 $this->courseid = $courseid;
258 $this->fullname = 'course grade category';
259 $this->path = null;
260 $this->parent = null;
4a490db0 261
aaff71da 262 if (!parent::insert('system')) {
b3ac6c3e 263 debugging("Could not insert this category: " . print_r($this, true));
264 return false;
f151b073 265 }
4a490db0 266
b3ac6c3e 267 // build path and depth
aaff71da 268 $this->update('system');
b3ac6c3e 269
aaff71da 270 return $this->id;
ce385eb4 271 }
4a490db0 272
8f4a626d 273 /**
274 * Compares the values held by this object with those of the matching record in DB, and returns
275 * whether or not these differences are sufficient to justify an update of all parent objects.
276 * This assumes that this object has an id number and a matching record in DB. If not, it will return false.
277 * @return boolean
278 */
2cc4b0f9 279 function qualifies_for_regrading() {
8f4a626d 280 if (empty($this->id)) {
6639ead3 281 debugging("Can not regrade non existing category");
8f4a626d 282 return false;
283 }
284
6639ead3 285 $db_item = grade_category::fetch(array('id'=>$this->id));
4a490db0 286
8f4a626d 287 $aggregationdiff = $db_item->aggregation != $this->aggregation;
b3ac6c3e 288 $keephighdiff = $db_item->keephigh != $this->keephigh;
289 $droplowdiff = $db_item->droplow != $this->droplow;
8f4a626d 290
b3ac6c3e 291 return ($aggregationdiff || $keephighdiff || $droplowdiff);
8f4a626d 292 }
8c846243 293
294 /**
f8e6e4db 295 * Marks the category and course item as needing update - categories are always regraded.
296 * @return void
8c846243 297 */
f8e6e4db 298 function force_regrading() {
299 $grade_item = $this->load_grade_item();
300 $grade_item->force_regrading();
8c846243 301 }
302
0aa32279 303 /**
ac9b0805 304 * Generates and saves raw_grades in associated category grade item.
305 * These immediate children must alrady have their own final grades.
306 * The category's aggregation method is used to generate raw grades.
307 *
308 * Please note that category grade is either calculated or aggregated - not both at the same time.
309 *
c86caae7 310 * This method must be used ONLY from grade_item::regrade_final_grades(),
ac9b0805 311 * because the calculation must be done in correct order!
b8ff92b6 312 *
4a490db0 313 * Steps to follow:
ac9b0805 314 * 1. Get final grades from immediate children
2df71235 315 * 3. Aggregate these grades
ac9b0805 316 * 4. Save them in raw grades of associated category grade item
0aa32279 317 */
f8e6e4db 318 function generate_grades($userid=null) {
b8ff92b6 319 global $CFG;
4a490db0 320
ac9b0805 321 $this->load_grade_item();
2cc4b0f9 322
323 if ($this->grade_item->is_locked()) {
324 return true; // no need to recalculate locked items
325 }
326
ac9b0805 327 $this->grade_item->load_scale();
2df71235 328
b3ac6c3e 329 // find grade items of immediate children (category or grade items)
61c33818 330 $depends_on = $this->grade_item->depends_on();
b3ac6c3e 331
f8e6e4db 332 if (empty($depends_on)) {
333 $items = false;
334 } else {
335 $gis = implode(',', $depends_on);
336 $sql = "SELECT *
337 FROM {$CFG->prefix}grade_items
338 WHERE id IN ($gis)";
339 $items = get_records_sql($sql);
340 }
4a490db0 341
f8e6e4db 342 if ($userid) {
343 $usersql = "AND g.userid=$userid";
344 } else {
345 $usersql = "";
b8ff92b6 346 }
4a490db0 347
f8e6e4db 348 // where to look for final grades - include grade of this item too, we will store the results there
61c33818 349 $gis = implode(',', array_merge($depends_on, array($this->grade_item->id)));
ac9b0805 350 $sql = "SELECT g.*
351 FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items gi
f8e6e4db 352 WHERE gi.id = g.itemid AND gi.id IN ($gis) $usersql
ac9b0805 353 ORDER BY g.userid";
b8ff92b6 354
9580a21f 355 // group the results by userid and aggregate the grades for this user
b8ff92b6 356 if ($rs = get_recordset_sql($sql)) {
357 if ($rs->RecordCount() > 0) {
358 $prevuser = 0;
9580a21f 359 $grade_values = array();
360 $oldgrade = null;
ac9b0805 361 while ($used = rs_fetch_next_record($rs)) {
362 if ($used->userid != $prevuser) {
9580a21f 363 $this->aggregate_grades($prevuser, $items, $grade_values, $oldgrade);
ac9b0805 364 $prevuser = $used->userid;
9580a21f 365 $grade_values = array();
366 $oldgrade = null;
ac9b0805 367 }
9580a21f 368 $grade_values[$used->itemid] = $used->finalgrade;
f8e6e4db 369 if ($this->grade_item->id == $used->itemid) {
370 $oldgrade = $used;
b8ff92b6 371 }
2df71235 372 }
9580a21f 373 $this->aggregate_grades($prevuser, $items, $grade_values, $oldgrade);//the last one
b8ff92b6 374 }
375 }
376
b8ff92b6 377 return true;
378 }
379
380 /**
ac9b0805 381 * internal function for category grades aggregation
b8ff92b6 382 */
9580a21f 383 function aggregate_grades($userid, $items, $grade_values, $oldgrade) {
b8ff92b6 384 if (empty($userid)) {
f8e6e4db 385 //ignore first call
b8ff92b6 386 return;
387 }
4a490db0 388
f8e6e4db 389 if ($oldgrade) {
3ee5c201 390 $grade = new grade_grade($oldgrade, false);
f8e6e4db 391 $grade->grade_item =& $this->grade_item;
b8ff92b6 392
f8e6e4db 393 } else {
394 // insert final grade - it will be needed later anyway
3ee5c201 395 $grade = new grade_grade(array('itemid'=>$this->grade_item->id, 'userid'=>$userid), false);
f8e6e4db 396 $grade->insert('system');
397 $grade->grade_item =& $this->grade_item;
2cc4b0f9 398
f8e6e4db 399 $oldgrade = new object();
400 $oldgrade->finalgrade = $grade->finalgrade;
401 $oldgrade->rawgrade = $grade->rawgrade;
402 $oldgrade->rawgrademin = $grade->rawgrademin;
403 $oldgrade->rawgrademax = $grade->rawgrademax;
404 $oldgrade->rawscaleid = $grade->rawscaleid;
405 }
406
c86caae7 407 // no need to recalculate locked or overridden grades
408 if ($grade->is_locked() or $grade->is_overridden()) {
2cc4b0f9 409 return;
ac9b0805 410 }
411
f8e6e4db 412 // can not use own final category grade in calculation
9580a21f 413 unset($grade_values[$this->grade_item->id]);
f8e6e4db 414
ac9b0805 415 // if no grades calculation possible or grading not allowed clear both final and raw
9580a21f 416 if (empty($grade_values) or empty($items) or ($this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE)) {
f8e6e4db 417 $grade->finalgrade = null;
418 $grade->rawgrade = null;
419 if ($grade->finalgrade !== $oldgrade->finalgrade or $grade->rawgrade !== $oldgrade->rawgrade) {
420 $grade->update('system');
421 }
b8ff92b6 422 return;
423 }
4a490db0 424
f8e6e4db 425 /// normalize the grades first - all will have value 0...1
d5f0aa01 426 // ungraded items are not used in aggregation
9580a21f 427 foreach ($grade_values as $k=>$v) {
b8ff92b6 428 if (is_null($v)) {
429 // null means no grade
9580a21f 430 unset($grade_values[$k]);
b8ff92b6 431 continue;
0aa32279 432 }
3ee5c201 433 $grade_values[$k] = grade_grade::standardise_score($v, $items[$k]->grademin, $items[$k]->grademax, 0, 1);
0aa32279 434 }
dda0c7e6 435
eacd3700 436 // use min grade if grade missing for these types
437 switch ($this->aggregation) {
438 case GRADE_AGGREGATE_MEAN_ALL:
439 case GRADE_AGGREGATE_MEDIAN_ALL:
440 case GRADE_AGGREGATE_MIN_ALL:
441 case GRADE_AGGREGATE_MAX_ALL:
442 case GRADE_AGGREGATE_MODE_ALL:
443 case GRADE_AGGREGATE_WEIGHTED_MEAN_ALL:
444 case GRADE_AGGREGATE_EXTRACREDIT_MEAN_ALL:
445 foreach($items as $itemid=>$value) {
446 if (!isset($grade_values[$itemid])) {
447 $grade_values[$itemid] = 0;
448 }
449 }
450 break;
451 }
452
453 // limit and sort
9580a21f 454 $this->apply_limit_rules($grade_values);
455 asort($grade_values, SORT_NUMERIC);
4a490db0 456
d5f0aa01 457 // let's see we have still enough grades to do any statistics
9580a21f 458 if (count($grade_values) == 0) {
ac9b0805 459 // not enough attempts yet
f8e6e4db 460 $grade->finalgrade = null;
461 $grade->rawgrade = null;
462 if ($grade->finalgrade !== $oldgrade->finalgrade or $grade->rawgrade !== $oldgrade->rawgrade) {
463 $grade->update('system');
b8ff92b6 464 }
465 return;
466 }
2df71235 467
f8e6e4db 468 /// start the aggregation
b8ff92b6 469 switch ($this->aggregation) {
eacd3700 470 case GRADE_AGGREGATE_MEDIAN_ALL: // Middle point value in the set: ignores frequencies
471 case GRADE_AGGREGATE_MEDIAN_GRADED:
9580a21f 472 $num = count($grade_values);
c186c7b2 473 $grades = array_values($grade_values);
474 if ($num % 2 == 0) {
475 $rawgrade = ($grades[intval($num/2)-1] + $grades[intval($num/2)]) / 2;
b8ff92b6 476 } else {
c186c7b2 477 $rawgrade = $grades[intval(($num/2)-0.5)];
b8ff92b6 478 }
479 break;
ac9b0805 480
eacd3700 481 case GRADE_AGGREGATE_MIN_ALL:
482 case GRADE_AGGREGATE_MIN_GRADED:
9580a21f 483 $rawgrade = reset($grade_values);
b8ff92b6 484 break;
485
eacd3700 486 case GRADE_AGGREGATE_MAX_ALL:
487 case GRADE_AGGREGATE_MAX_GRADED:
9580a21f 488 $rawgrade = array_pop($grade_values);
b8ff92b6 489 break;
490
eacd3700 491 case GRADE_AGGREGATE_MODE_ALL: // the most common value, average used if multimode
492 case GRADE_AGGREGATE_MODE_GRADED:
9580a21f 493 $freq = array_count_values($grade_values);
95affb8a 494 arsort($freq); // sort by frequency keeping keys
495 $top = reset($freq); // highest frequency count
496 $modes = array_keys($freq, $top); // search for all modes (have the same highest count)
497 rsort($modes, SORT_NUMERIC); // get highes mode
ac9b0805 498 $rawgrade = reset($modes);
d5fab31f 499 break;
95affb8a 500
9580a21f 501 case GRADE_AGGREGATE_WEIGHTED_MEAN_GRADED: // Weighted average of all existing final grades
eacd3700 502 case GRADE_AGGREGATE_WEIGHTED_MEAN_ALL:
9580a21f 503 $weightsum = 0;
504 $sum = 0;
eacd3700 505 foreach($grade_values as $itemid=>$grade_value) {
506 if ($items[$itemid]->aggregationcoef <= 0) {
9580a21f 507 continue;
508 }
eacd3700 509 $weightsum += $items[$itemid]->aggregationcoef;
510 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 511 }
512 if ($weightsum == 0) {
513 $rawgrade = null;
514 } else {
515 $rawgrade = $sum / $weightsum;
516 }
517 break;
518
ba74762b 519 case GRADE_AGGREGATE_EXTRACREDIT_MEAN_ALL: // special average
eacd3700 520 case GRADE_AGGREGATE_EXTRACREDIT_MEAN_GRADED:
9580a21f 521 $num = 0;
522 $sum = 0;
eacd3700 523 foreach($grade_values as $itemid=>$grade_value) {
524 if ($items[$itemid]->aggregationcoef == 0) {
9580a21f 525 $num += 1;
526 $sum += $grade_value;
eacd3700 527 } else if ($items[$itemid]->aggregationcoef > 0) {
528 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 529 }
530 }
531 if ($num == 0) {
532 $rawgrade = $sum; // only extra credits or wrong coefs
533 } else {
534 $rawgrade = $sum / $num;
535 }
536 break;
537
d5f0aa01 538 case GRADE_AGGREGATE_MEAN_ALL: // Arithmetic average of all grade items including even NULLs; NULL grade counted as minimum
95affb8a 539 case GRADE_AGGREGATE_MEAN_GRADED: // Arithmetic average of all final grades, unfinished are not calculated
ac9b0805 540 default:
9580a21f 541 $num = count($grade_values);
542 $sum = array_sum($grade_values);
ac9b0805 543 $rawgrade = $sum / $num;
b8ff92b6 544 break;
545 }
546
f8e6e4db 547 /// prepare update of new raw grade
548 $grade->rawgrademin = $this->grade_item->grademin;
549 $grade->rawgrademax = $this->grade_item->grademax;
550 $grade->rawscaleid = $this->grade_item->scaleid;
551
ac9b0805 552 // recalculate the rawgrade back to requested range
3ee5c201 553 $grade->rawgrade = grade_grade::standardise_score($rawgrade, 0, 1, $grade->rawgrademin, $grade->rawgrademax);
b8ff92b6 554
f8e6e4db 555 // calculate final grade
556 $grade->finalgrade = $this->grade_item->adjust_grade($grade->rawgrade, $grade->rawgrademin, $grade->rawgrademax);
2df71235 557
f8e6e4db 558 // update in db if changed
559 if ( $grade->finalgrade !== $oldgrade->finalgrade
560 or $grade->rawgrade !== $oldgrade->rawgrade
561 or $grade->rawgrademin !== $oldgrade->rawgrademin
562 or $grade->rawgrademax !== $oldgrade->rawgrademax
563 or $grade->rawscaleid !== $oldgrade->rawscaleid) {
564
565 $grade->update('system');
566 }
567
568 return;
0aa32279 569 }
570
adc2f286 571 /**
572 * Given an array of grade values (numerical indices), applies droplow or keephigh
573 * rules to limit the final array.
9580a21f 574 * @param array $grade_values
adc2f286 575 * @return array Limited grades.
576 */
9580a21f 577 function apply_limit_rules(&$grade_values) {
578 arsort($grade_values, SORT_NUMERIC);
adc2f286 579 if (!empty($this->droplow)) {
580 for ($i = 0; $i < $this->droplow; $i++) {
9580a21f 581 array_pop($grade_values);
adc2f286 582 }
4a490db0 583 } elseif (!empty($this->keephigh)) {
9580a21f 584 while (count($grade_values) > $this->keephigh) {
585 array_pop($grade_values);
adc2f286 586 }
587 }
0aa32279 588 }
589
9580a21f 590
591 /**
592 * Returns true if category uses special aggregation coeficient
593 * @return boolean true if coeficient used
594 */
595 function is_aggregationcoef_used() {
596 return ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN_ALL
597 or $this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN_GRADED
598 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN_ALL
599 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN_GRADED);
ba74762b 600
9580a21f 601 }
602
0fc7f624 603 /**
604 * Returns true if this category has any child grade_category or grade_item.
605 * @return int number of direct children, or false if none found.
606 */
607 function has_children() {
608 return count_records('grade_categories', 'parent', $this->id) + count_records('grade_items', 'categoryid', $this->id);
609 }
610
1c307f21 611 /**
b3ac6c3e 612 * Returns tree with all grade_items and categories as elements
613 * @static
614 * @param int $courseid
b3ac6c3e 615 * @param boolean $include_category_items as category children
616 * @return array
1c307f21 617 */
938e00b6 618 function fetch_course_tree($courseid, $include_category_items=false) {
b3ac6c3e 619 $course_category = grade_category::fetch_course_category($courseid);
314c4336 620 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
938e00b6 621 'children'=>$course_category->get_children($include_category_items));
314c4336 622 $sortorder = 1;
623 $course_category->set_sortorder($sortorder);
624 $course_category->sortorder = $sortorder;
b3ac6c3e 625 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 626 }
627
b3ac6c3e 628 function _fetch_course_tree_recursion($category_array, &$sortorder) {
629 // update the sortorder in db if needed
630 if ($category_array['object']->sortorder != $sortorder) {
631 $category_array['object']->set_sortorder($sortorder);
ce385eb4 632 }
ce385eb4 633
314c4336 634 // store the grade_item or grade_category instance with extra info
635 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 636
637 // reuse final grades if there
638 if (array_key_exists('finalgrades', $category_array)) {
639 $result['finalgrades'] = $category_array['finalgrades'];
640 }
641
642 // recursively resort children
643 if (!empty($category_array['children'])) {
644 $result['children'] = array();
645 foreach($category_array['children'] as $oldorder=>$child_array) {
314c4336 646 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
b3ac6c3e 647 $result['children'][$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
648 } else {
649 $result['children'][++$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
650 }
651 }
652 }
653
654 return $result;
ce385eb4 655 }
7c8a963f 656
657 /**
4a490db0 658 * Fetches and returns all the children categories and/or grade_items belonging to this category.
659 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 660 * as well as all levels (0). The elements are indexed by sort order.
7c8a963f 661 * @return array Array of child objects (grade_category and grade_item).
662 */
938e00b6 663 function get_children($include_category_items=false) {
b3ac6c3e 664
665 // This function must be as fast as possible ;-)
666 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
667 // we have to limit the number of queries though, because it will be used often in grade reports
668
669 $cats = get_records('grade_categories', 'courseid', $this->courseid);
670 $items = get_records('grade_items', 'courseid', $this->courseid);
4a490db0 671
b3ac6c3e 672 // init children array first
673 foreach ($cats as $catid=>$cat) {
674 $cats[$catid]->children = array();
27f95e9b 675 }
4a490db0 676
b3ac6c3e 677 //first attach items to cats and add category sortorder
678 foreach ($items as $item) {
679 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
680 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 681
b3ac6c3e 682 if (!$include_category_items) {
683 continue;
684 }
685 $categoryid = $item->iteminstance;
686 } else {
687 $categoryid = $item->categoryid;
688 }
689
690 // prevent problems with duplicate sortorders in db
691 $sortorder = $item->sortorder;
692 while(array_key_exists($sortorder, $cats[$categoryid]->children)) {
f13002d5 693 //debugging("$sortorder exists in item loop");
b3ac6c3e 694 $sortorder++;
695 }
696
697 $cats[$categoryid]->children[$sortorder] = $item;
698
699 }
700
701 // now find the requested category and connect categories as children
702 $category = false;
703 foreach ($cats as $catid=>$cat) {
704 if (!empty($cat->parent)) {
705 // prevent problems with duplicate sortorders in db
706 $sortorder = $cat->sortorder;
707 while(array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 708 //debugging("$sortorder exists in cat loop");
b3ac6c3e 709 $sortorder++;
710 }
711
712 $cats[$cat->parent]->children[$sortorder] = $cat;
713 }
714
715 if ($catid == $this->id) {
716 $category = &$cats[$catid];
717 }
718 }
719
720 unset($items); // not needed
721 unset($cats); // not needed
722
938e00b6 723 $children_array = grade_category::_get_children_recursion($category);
b3ac6c3e 724
725 ksort($children_array);
726
727 return $children_array;
728
729 }
730
938e00b6 731 function _get_children_recursion($category) {
b3ac6c3e 732
733 $children_array = array();
734 foreach($category->children as $sortorder=>$child) {
735 if (array_key_exists('itemtype', $child)) {
736 $grade_item = new grade_item($child, false);
314c4336 737 if (in_array($grade_item->itemtype, array('course', 'category'))) {
738 $type = $grade_item->itemtype.'item';
739 $depth = $category->depth;
740 } else {
741 $type = 'item';
742 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 743 }
314c4336 744 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 745
7c8a963f 746 } else {
938e00b6 747 $children = grade_category::_get_children_recursion($child);
b3ac6c3e 748 $grade_category = new grade_category($child, false);
749 if (empty($children)) {
314c4336 750 $children = array();
7c8a963f 751 }
314c4336 752 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
753 }
27f95e9b 754 }
755
b3ac6c3e 756 // sort the array
757 ksort($children_array);
758
27f95e9b 759 return $children_array;
760 }
4a490db0 761
f151b073 762 /**
ab53054f 763 * Uses get_grade_item to load or create a grade_item, then saves it as $this->grade_item.
f151b073 764 * @return object Grade_item
765 */
766 function load_grade_item() {
ac9b0805 767 if (empty($this->grade_item)) {
768 $this->grade_item = $this->get_grade_item();
769 }
ab53054f 770 return $this->grade_item;
771 }
4a490db0 772
ab53054f 773 /**
774 * Retrieves from DB and instantiates the associated grade_item object.
775 * If no grade_item exists yet, create one.
776 * @return object Grade_item
777 */
778 function get_grade_item() {
c91ed4be 779 if (empty($this->id)) {
780 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
781 return false;
782 }
783
b3ac6c3e 784 if (empty($this->parent)) {
785 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
786
787 } else {
788 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
789 }
f92dcad8 790
791 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 792 // create a new one
f92dcad8 793 $grade_item = new grade_item($params, false);
b8ff92b6 794 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 795 $grade_item->insert('system');
4a490db0 796
b8ff92b6 797 } else if (count($grade_items) == 1){
798 // found existing one
799 $grade_item = reset($grade_items);
4a490db0 800
b8ff92b6 801 } else {
802 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 803 // return first one
804 $grade_item = reset($grade_items);
2c72af1f 805 }
806
ab53054f 807 return $grade_item;
f151b073 808 }
8c846243 809
810 /**
811 * Uses $this->parent to instantiate $this->parent_category based on the
812 * referenced record in the DB.
813 * @return object Parent_category
814 */
815 function load_parent_category() {
816 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 817 $this->parent_category = $this->get_parent_category();
8c846243 818 }
819 return $this->parent_category;
4a490db0 820 }
821
ab53054f 822 /**
823 * Uses $this->parent to instantiate and return a grade_category object.
824 * @return object Parent_category
825 */
826 function get_parent_category() {
827 if (!empty($this->parent)) {
828 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 829 return $parent_category;
ab53054f 830 } else {
831 return null;
832 }
833 }
834
2186f72c 835 /**
4a490db0 836 * Returns the most descriptive field for this object. This is a standard method used
2186f72c 837 * when we do not know the exact type of an object.
838 * @return string name
839 */
840 function get_name() {
314c4336 841 if (empty($this->parent)) {
842 return "Top course category"; //TODO: localize
843 } else {
844 return $this->fullname;
845 }
2186f72c 846 }
c91ed4be 847
0fc7f624 848 /**
849 * Sets this category's parent id. A generic method shared by objects that have a parent id of some kind.
f13002d5 850 * @param int parentid
851 * @return boolean success
0fc7f624 852 */
f8e6e4db 853 function set_parent($parentid, $source=null) {
f13002d5 854 if ($this->parent == $parentid) {
855 return true;
856 }
857
858 if ($parentid == $this->id) {
859 error('Can not assign self as parent!');
860 }
861
862 if (empty($this->parent) and $this->is_course_category()) {
863 error('Course category can not have parent!');
b3ac6c3e 864 }
f13002d5 865
866 // find parent and check course id
867 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 868 return false;
869 }
870
f8e6e4db 871 $this->force_regrading();
b3ac6c3e 872
873 // set new parent category
f8e6e4db 874 $this->parent = $parent_category->id;
875 $this->parent_category =& $parent_category;
b3ac6c3e 876 $this->path = null; // remove old path and depth - will be recalculated in update()
f8e6e4db 877 $this->depth = null; // remove old path and depth - will be recalculated in update()
878 $this->update($source);
b3ac6c3e 879
15b462da 880 return $this->update($source);
b3ac6c3e 881 }
882
883 /**
884 * Returns the final values for this grade category.
885 * @param int $userid Optional: to retrieve a single final grade
886 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
887 */
888 function get_final($userid=NULL) {
889 $this->load_grade_item();
890 return $this->grade_item->get_final($userid);
0fc7f624 891 }
4a490db0 892
0fc7f624 893 /**
4a490db0 894 * Returns the sortorder of the associated grade_item. This method is also available in
5fad5061 895 * grade_item, for cases where the object type is not known.
0fc7f624 896 * @return int Sort order
897 */
898 function get_sortorder() {
b3ac6c3e 899 $this->load_grade_item();
900 return $this->grade_item->get_sortorder();
0fc7f624 901 }
902
903 /**
b3ac6c3e 904 * Sets sortorder variable for this category.
4a490db0 905 * This method is also available in grade_item, for cases where the object type is not know.
0fc7f624 906 * @param int $sortorder
907 * @return void
908 */
909 function set_sortorder($sortorder) {
b3ac6c3e 910 $this->load_grade_item();
911 $this->grade_item->set_sortorder($sortorder);
912 }
913
6639ead3 914 /**
915 * Move this category after the given sortorder - does not change the parent
916 * @param int $sortorder to place after
917 */
f13002d5 918 function move_after_sortorder($sortorder) {
919 $this->load_grade_item();
920 $this->grade_item->move_after_sortorder($sortorder);
921 }
922
b3ac6c3e 923 /**
f13002d5 924 * Return true if this is the top most category that represents the total course grade.
b3ac6c3e 925 * @return boolean
926 */
927 function is_course_category() {
928 $this->load_grade_item();
929 return $this->grade_item->is_course_item();
930 }
931
932 /**
933 * Return the top most course category.
934 * @static
935 * @return object grade_category instance for course grade
936 */
937 function fetch_course_category($courseid) {
938
939 // course category has no parent
940 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
941 return $course_category;
942 }
943
944 // create a new one
945 $course_category = new grade_category();
946 $course_category->insert_course_category($courseid);
947
948 return $course_category;
0fc7f624 949 }
4a490db0 950
79eabc2a 951 /**
952 * Is grading object editable?
953 * @return boolean
954 */
955 function is_editable() {
956 return true;
957 }
958
5fad5061 959 /**
4a490db0 960 * Returns the locked state/date of the associated grade_item. This method is also available in
961 * grade_item, for cases where the object type is not known.
22e23c78 962 * @return boolean
5fad5061 963 */
2cc4b0f9 964 function is_locked() {
5fad5061 965 $this->load_grade_item();
22e23c78 966 return $this->grade_item->is_locked();
5fad5061 967 }
968
969 /**
970 * Sets the grade_item's locked variable and updates the grade_item.
971 * Method named after grade_item::set_locked().
972 * @param int $locked 0, 1 or a timestamp int(10) after which date the item will be locked.
9580a21f 973 * @return boolean success if category locked (not all children mayb be locked though)
5fad5061 974 */
2cc4b0f9 975 function set_locked($lockedstate) {
5fad5061 976 $this->load_grade_item();
b121b544 977 $result = $this->grade_item->set_locked($lockedstate);
7a7a53d3 978 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
979 foreach($children as $child) {
2a8c101f 980 $child->set_locked($lockedstate);
7a7a53d3 981 }
982 }
983 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
984 foreach($children as $child) {
2a8c101f 985 $child->set_locked($lockedstate);
7a7a53d3 986 }
987 }
b121b544 988 return $result;
5fad5061 989 }
4a490db0 990
5fad5061 991 /**
4a490db0 992 * Returns the hidden state/date of the associated grade_item. This method is also available in
22e23c78 993 * grade_item.
994 * @return boolean
5fad5061 995 */
22e23c78 996 function is_hidden() {
5fad5061 997 $this->load_grade_item();
22e23c78 998 return $this->grade_item->is_hidden();
5fad5061 999 }
1000
1001 /**
4a490db0 1002 * Sets the grade_item's hidden variable and updates the grade_item.
5fad5061 1003 * Method named after grade_item::set_hidden().
1004 * @param int $hidden 0, 1 or a timestamp int(10) after which date the item will be hidden.
1005 * @return void
1006 */
1007 function set_hidden($hidden) {
1008 $this->load_grade_item();
22e23c78 1009 $this->grade_item->set_hidden($hidden);
f13002d5 1010 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
1011 foreach($children as $child) {
1012 $child->set_hidden($hidden);
1013 }
1014 }
1015 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
1016 foreach($children as $child) {
1017 $child->set_hidden($hidden);
1018 }
1019 }
5fad5061 1020 }
1021
4a490db0 1022}
8a31e65c 1023?>