Gradebook unit tests review
[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
f2c88356 256 /**
257 * TODO document
258 */
b3ac6c3e 259 function insert_course_category($courseid) {
42ff9ce6 260 $this->courseid = $courseid;
261 $this->fullname = 'course grade category';
262 $this->path = null;
263 $this->parent = null;
264 $this->aggregate = GRADE_AGGREGATE_MEAN_ALL;
4a490db0 265
aaff71da 266 if (!parent::insert('system')) {
b3ac6c3e 267 debugging("Could not insert this category: " . print_r($this, true));
268 return false;
f151b073 269 }
4a490db0 270
b3ac6c3e 271 // build path and depth
aaff71da 272 $this->update('system');
b3ac6c3e 273
aaff71da 274 return $this->id;
ce385eb4 275 }
4a490db0 276
8f4a626d 277 /**
278 * Compares the values held by this object with those of the matching record in DB, and returns
279 * whether or not these differences are sufficient to justify an update of all parent objects.
280 * This assumes that this object has an id number and a matching record in DB. If not, it will return false.
281 * @return boolean
282 */
2cc4b0f9 283 function qualifies_for_regrading() {
8f4a626d 284 if (empty($this->id)) {
6639ead3 285 debugging("Can not regrade non existing category");
8f4a626d 286 return false;
287 }
288
6639ead3 289 $db_item = grade_category::fetch(array('id'=>$this->id));
4a490db0 290
8f4a626d 291 $aggregationdiff = $db_item->aggregation != $this->aggregation;
b3ac6c3e 292 $keephighdiff = $db_item->keephigh != $this->keephigh;
293 $droplowdiff = $db_item->droplow != $this->droplow;
8f4a626d 294
b3ac6c3e 295 return ($aggregationdiff || $keephighdiff || $droplowdiff);
8f4a626d 296 }
8c846243 297
298 /**
f8e6e4db 299 * Marks the category and course item as needing update - categories are always regraded.
300 * @return void
8c846243 301 */
f8e6e4db 302 function force_regrading() {
303 $grade_item = $this->load_grade_item();
304 $grade_item->force_regrading();
8c846243 305 }
306
0aa32279 307 /**
ac9b0805 308 * Generates and saves raw_grades in associated category grade item.
309 * These immediate children must alrady have their own final grades.
310 * The category's aggregation method is used to generate raw grades.
311 *
312 * Please note that category grade is either calculated or aggregated - not both at the same time.
313 *
c86caae7 314 * This method must be used ONLY from grade_item::regrade_final_grades(),
ac9b0805 315 * because the calculation must be done in correct order!
b8ff92b6 316 *
4a490db0 317 * Steps to follow:
ac9b0805 318 * 1. Get final grades from immediate children
2df71235 319 * 3. Aggregate these grades
ac9b0805 320 * 4. Save them in raw grades of associated category grade item
0aa32279 321 */
f8e6e4db 322 function generate_grades($userid=null) {
b8ff92b6 323 global $CFG;
4a490db0 324
ac9b0805 325 $this->load_grade_item();
2cc4b0f9 326
327 if ($this->grade_item->is_locked()) {
328 return true; // no need to recalculate locked items
329 }
330
ac9b0805 331 $this->grade_item->load_scale();
2df71235 332
b3ac6c3e 333 // find grade items of immediate children (category or grade items)
61c33818 334 $depends_on = $this->grade_item->depends_on();
b3ac6c3e 335
f8e6e4db 336 if (empty($depends_on)) {
337 $items = false;
338 } else {
339 $gis = implode(',', $depends_on);
340 $sql = "SELECT *
341 FROM {$CFG->prefix}grade_items
342 WHERE id IN ($gis)";
343 $items = get_records_sql($sql);
344 }
4a490db0 345
f8e6e4db 346 if ($userid) {
347 $usersql = "AND g.userid=$userid";
348 } else {
349 $usersql = "";
b8ff92b6 350 }
4a490db0 351
f8e6e4db 352 // where to look for final grades - include grade of this item too, we will store the results there
61c33818 353 $gis = implode(',', array_merge($depends_on, array($this->grade_item->id)));
ac9b0805 354 $sql = "SELECT g.*
355 FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items gi
f8e6e4db 356 WHERE gi.id = g.itemid AND gi.id IN ($gis) $usersql
ac9b0805 357 ORDER BY g.userid";
b8ff92b6 358
9580a21f 359 // group the results by userid and aggregate the grades for this user
b8ff92b6 360 if ($rs = get_recordset_sql($sql)) {
361 if ($rs->RecordCount() > 0) {
362 $prevuser = 0;
9580a21f 363 $grade_values = array();
23207a1a 364 $excluded = array();
9580a21f 365 $oldgrade = null;
ac9b0805 366 while ($used = rs_fetch_next_record($rs)) {
367 if ($used->userid != $prevuser) {
23207a1a 368 $this->aggregate_grades($prevuser, $items, $grade_values, $oldgrade, $excluded);
ac9b0805 369 $prevuser = $used->userid;
9580a21f 370 $grade_values = array();
23207a1a 371 $excluded = array();
9580a21f 372 $oldgrade = null;
ac9b0805 373 }
9580a21f 374 $grade_values[$used->itemid] = $used->finalgrade;
23207a1a 375 if ($used->excluded) {
376 $excluded[] = $used->itemid;
377 }
f8e6e4db 378 if ($this->grade_item->id == $used->itemid) {
379 $oldgrade = $used;
b8ff92b6 380 }
2df71235 381 }
23207a1a 382 $this->aggregate_grades($prevuser, $items, $grade_values, $oldgrade, $excluded);//the last one
b8ff92b6 383 }
31a17093 384 rs_close($rs);
b8ff92b6 385 }
386
b8ff92b6 387 return true;
388 }
389
390 /**
ac9b0805 391 * internal function for category grades aggregation
b8ff92b6 392 */
23207a1a 393 function aggregate_grades($userid, $items, $grade_values, $oldgrade, $excluded) {
b8ff92b6 394 if (empty($userid)) {
f8e6e4db 395 //ignore first call
b8ff92b6 396 return;
397 }
4a490db0 398
f8e6e4db 399 if ($oldgrade) {
3ee5c201 400 $grade = new grade_grade($oldgrade, false);
f8e6e4db 401 $grade->grade_item =& $this->grade_item;
b8ff92b6 402
f8e6e4db 403 } else {
404 // insert final grade - it will be needed later anyway
3ee5c201 405 $grade = new grade_grade(array('itemid'=>$this->grade_item->id, 'userid'=>$userid), false);
f8e6e4db 406 $grade->insert('system');
407 $grade->grade_item =& $this->grade_item;
2cc4b0f9 408
f8e6e4db 409 $oldgrade = new object();
410 $oldgrade->finalgrade = $grade->finalgrade;
411 $oldgrade->rawgrade = $grade->rawgrade;
412 $oldgrade->rawgrademin = $grade->rawgrademin;
413 $oldgrade->rawgrademax = $grade->rawgrademax;
414 $oldgrade->rawscaleid = $grade->rawscaleid;
415 }
416
c86caae7 417 // no need to recalculate locked or overridden grades
418 if ($grade->is_locked() or $grade->is_overridden()) {
2cc4b0f9 419 return;
ac9b0805 420 }
421
f8e6e4db 422 // can not use own final category grade in calculation
9580a21f 423 unset($grade_values[$this->grade_item->id]);
f8e6e4db 424
ac9b0805 425 // if no grades calculation possible or grading not allowed clear both final and raw
9580a21f 426 if (empty($grade_values) or empty($items) or ($this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE)) {
f8e6e4db 427 $grade->finalgrade = null;
428 $grade->rawgrade = null;
429 if ($grade->finalgrade !== $oldgrade->finalgrade or $grade->rawgrade !== $oldgrade->rawgrade) {
430 $grade->update('system');
431 }
b8ff92b6 432 return;
433 }
4a490db0 434
f8e6e4db 435 /// normalize the grades first - all will have value 0...1
d5f0aa01 436 // ungraded items are not used in aggregation
23207a1a 437 foreach ($grade_values as $itemid=>$v) {
b8ff92b6 438 if (is_null($v)) {
439 // null means no grade
23207a1a 440 unset($grade_values[$itemid]);
441 continue;
442 } else if (in_array($itemid, $excluded)) {
443 unset($grade_values[$itemid]);
b8ff92b6 444 continue;
0aa32279 445 }
23207a1a 446
447 $grade_values[$itemid] = grade_grade::standardise_score($v, $items[$itemid]->grademin, $items[$itemid]->grademax, 0, 1);
0aa32279 448 }
dda0c7e6 449
eacd3700 450 // use min grade if grade missing for these types
451 switch ($this->aggregation) {
452 case GRADE_AGGREGATE_MEAN_ALL:
453 case GRADE_AGGREGATE_MEDIAN_ALL:
454 case GRADE_AGGREGATE_MIN_ALL:
455 case GRADE_AGGREGATE_MAX_ALL:
456 case GRADE_AGGREGATE_MODE_ALL:
457 case GRADE_AGGREGATE_WEIGHTED_MEAN_ALL:
458 case GRADE_AGGREGATE_EXTRACREDIT_MEAN_ALL:
459 foreach($items as $itemid=>$value) {
23207a1a 460 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
eacd3700 461 $grade_values[$itemid] = 0;
462 }
463 }
464 break;
465 }
466
467 // limit and sort
9580a21f 468 $this->apply_limit_rules($grade_values);
469 asort($grade_values, SORT_NUMERIC);
4a490db0 470
d5f0aa01 471 // let's see we have still enough grades to do any statistics
9580a21f 472 if (count($grade_values) == 0) {
ac9b0805 473 // not enough attempts yet
f8e6e4db 474 $grade->finalgrade = null;
475 $grade->rawgrade = null;
476 if ($grade->finalgrade !== $oldgrade->finalgrade or $grade->rawgrade !== $oldgrade->rawgrade) {
477 $grade->update('system');
b8ff92b6 478 }
479 return;
480 }
2df71235 481
f8e6e4db 482 /// start the aggregation
b8ff92b6 483 switch ($this->aggregation) {
eacd3700 484 case GRADE_AGGREGATE_MEDIAN_ALL: // Middle point value in the set: ignores frequencies
485 case GRADE_AGGREGATE_MEDIAN_GRADED:
9580a21f 486 $num = count($grade_values);
c186c7b2 487 $grades = array_values($grade_values);
488 if ($num % 2 == 0) {
489 $rawgrade = ($grades[intval($num/2)-1] + $grades[intval($num/2)]) / 2;
b8ff92b6 490 } else {
c186c7b2 491 $rawgrade = $grades[intval(($num/2)-0.5)];
b8ff92b6 492 }
493 break;
ac9b0805 494
eacd3700 495 case GRADE_AGGREGATE_MIN_ALL:
496 case GRADE_AGGREGATE_MIN_GRADED:
9580a21f 497 $rawgrade = reset($grade_values);
b8ff92b6 498 break;
499
eacd3700 500 case GRADE_AGGREGATE_MAX_ALL:
501 case GRADE_AGGREGATE_MAX_GRADED:
9580a21f 502 $rawgrade = array_pop($grade_values);
b8ff92b6 503 break;
504
eacd3700 505 case GRADE_AGGREGATE_MODE_ALL: // the most common value, average used if multimode
506 case GRADE_AGGREGATE_MODE_GRADED:
9580a21f 507 $freq = array_count_values($grade_values);
95affb8a 508 arsort($freq); // sort by frequency keeping keys
509 $top = reset($freq); // highest frequency count
510 $modes = array_keys($freq, $top); // search for all modes (have the same highest count)
511 rsort($modes, SORT_NUMERIC); // get highes mode
ac9b0805 512 $rawgrade = reset($modes);
d5fab31f 513 break;
95affb8a 514
9580a21f 515 case GRADE_AGGREGATE_WEIGHTED_MEAN_GRADED: // Weighted average of all existing final grades
eacd3700 516 case GRADE_AGGREGATE_WEIGHTED_MEAN_ALL:
9580a21f 517 $weightsum = 0;
518 $sum = 0;
eacd3700 519 foreach($grade_values as $itemid=>$grade_value) {
520 if ($items[$itemid]->aggregationcoef <= 0) {
9580a21f 521 continue;
522 }
eacd3700 523 $weightsum += $items[$itemid]->aggregationcoef;
524 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 525 }
526 if ($weightsum == 0) {
527 $rawgrade = null;
528 } else {
529 $rawgrade = $sum / $weightsum;
530 }
531 break;
532
ba74762b 533 case GRADE_AGGREGATE_EXTRACREDIT_MEAN_ALL: // special average
eacd3700 534 case GRADE_AGGREGATE_EXTRACREDIT_MEAN_GRADED:
9580a21f 535 $num = 0;
536 $sum = 0;
eacd3700 537 foreach($grade_values as $itemid=>$grade_value) {
538 if ($items[$itemid]->aggregationcoef == 0) {
9580a21f 539 $num += 1;
540 $sum += $grade_value;
eacd3700 541 } else if ($items[$itemid]->aggregationcoef > 0) {
542 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 543 }
544 }
545 if ($num == 0) {
546 $rawgrade = $sum; // only extra credits or wrong coefs
547 } else {
548 $rawgrade = $sum / $num;
549 }
550 break;
551
d5f0aa01 552 case GRADE_AGGREGATE_MEAN_ALL: // Arithmetic average of all grade items including even NULLs; NULL grade counted as minimum
95affb8a 553 case GRADE_AGGREGATE_MEAN_GRADED: // Arithmetic average of all final grades, unfinished are not calculated
ac9b0805 554 default:
9580a21f 555 $num = count($grade_values);
556 $sum = array_sum($grade_values);
ac9b0805 557 $rawgrade = $sum / $num;
b8ff92b6 558 break;
559 }
560
f8e6e4db 561 /// prepare update of new raw grade
562 $grade->rawgrademin = $this->grade_item->grademin;
563 $grade->rawgrademax = $this->grade_item->grademax;
564 $grade->rawscaleid = $this->grade_item->scaleid;
565
ac9b0805 566 // recalculate the rawgrade back to requested range
3ee5c201 567 $grade->rawgrade = grade_grade::standardise_score($rawgrade, 0, 1, $grade->rawgrademin, $grade->rawgrademax);
b8ff92b6 568
f8e6e4db 569 // calculate final grade
570 $grade->finalgrade = $this->grade_item->adjust_grade($grade->rawgrade, $grade->rawgrademin, $grade->rawgrademax);
2df71235 571
f8e6e4db 572 // update in db if changed
573 if ( $grade->finalgrade !== $oldgrade->finalgrade
574 or $grade->rawgrade !== $oldgrade->rawgrade
575 or $grade->rawgrademin !== $oldgrade->rawgrademin
576 or $grade->rawgrademax !== $oldgrade->rawgrademax
577 or $grade->rawscaleid !== $oldgrade->rawscaleid) {
578
579 $grade->update('system');
580 }
581
582 return;
0aa32279 583 }
584
adc2f286 585 /**
586 * Given an array of grade values (numerical indices), applies droplow or keephigh
587 * rules to limit the final array.
9580a21f 588 * @param array $grade_values
adc2f286 589 * @return array Limited grades.
590 */
9580a21f 591 function apply_limit_rules(&$grade_values) {
592 arsort($grade_values, SORT_NUMERIC);
adc2f286 593 if (!empty($this->droplow)) {
594 for ($i = 0; $i < $this->droplow; $i++) {
9580a21f 595 array_pop($grade_values);
adc2f286 596 }
4a490db0 597 } elseif (!empty($this->keephigh)) {
9580a21f 598 while (count($grade_values) > $this->keephigh) {
599 array_pop($grade_values);
adc2f286 600 }
601 }
0aa32279 602 }
603
9580a21f 604
605 /**
606 * Returns true if category uses special aggregation coeficient
607 * @return boolean true if coeficient used
608 */
609 function is_aggregationcoef_used() {
610 return ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN_ALL
611 or $this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN_GRADED
612 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN_ALL
613 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN_GRADED);
ba74762b 614
9580a21f 615 }
616
1c307f21 617 /**
b3ac6c3e 618 * Returns tree with all grade_items and categories as elements
619 * @static
620 * @param int $courseid
b3ac6c3e 621 * @param boolean $include_category_items as category children
622 * @return array
1c307f21 623 */
938e00b6 624 function fetch_course_tree($courseid, $include_category_items=false) {
b3ac6c3e 625 $course_category = grade_category::fetch_course_category($courseid);
514a3467 626 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
627 'children'=>$course_category->get_children($include_category_items));
628 $sortorder = 1;
629 $course_category->set_sortorder($sortorder);
630 $course_category->sortorder = $sortorder;
631 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 632 }
633
b3ac6c3e 634 function _fetch_course_tree_recursion($category_array, &$sortorder) {
635 // update the sortorder in db if needed
636 if ($category_array['object']->sortorder != $sortorder) {
637 $category_array['object']->set_sortorder($sortorder);
ce385eb4 638 }
ce385eb4 639
314c4336 640 // store the grade_item or grade_category instance with extra info
641 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 642
643 // reuse final grades if there
644 if (array_key_exists('finalgrades', $category_array)) {
645 $result['finalgrades'] = $category_array['finalgrades'];
646 }
647
648 // recursively resort children
649 if (!empty($category_array['children'])) {
650 $result['children'] = array();
651 foreach($category_array['children'] as $oldorder=>$child_array) {
314c4336 652 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
b3ac6c3e 653 $result['children'][$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
654 } else {
655 $result['children'][++$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
656 }
657 }
658 }
659
660 return $result;
ce385eb4 661 }
7c8a963f 662
663 /**
4a490db0 664 * Fetches and returns all the children categories and/or grade_items belonging to this category.
665 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 666 * as well as all levels (0). The elements are indexed by sort order.
7c8a963f 667 * @return array Array of child objects (grade_category and grade_item).
668 */
938e00b6 669 function get_children($include_category_items=false) {
b3ac6c3e 670
671 // This function must be as fast as possible ;-)
672 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
673 // we have to limit the number of queries though, because it will be used often in grade reports
674
675 $cats = get_records('grade_categories', 'courseid', $this->courseid);
676 $items = get_records('grade_items', 'courseid', $this->courseid);
4a490db0 677
b3ac6c3e 678 // init children array first
679 foreach ($cats as $catid=>$cat) {
680 $cats[$catid]->children = array();
27f95e9b 681 }
4a490db0 682
b3ac6c3e 683 //first attach items to cats and add category sortorder
684 foreach ($items as $item) {
685 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
686 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 687
b3ac6c3e 688 if (!$include_category_items) {
689 continue;
690 }
691 $categoryid = $item->iteminstance;
692 } else {
693 $categoryid = $item->categoryid;
694 }
695
696 // prevent problems with duplicate sortorders in db
697 $sortorder = $item->sortorder;
698 while(array_key_exists($sortorder, $cats[$categoryid]->children)) {
f13002d5 699 //debugging("$sortorder exists in item loop");
b3ac6c3e 700 $sortorder++;
701 }
702
703 $cats[$categoryid]->children[$sortorder] = $item;
704
705 }
706
707 // now find the requested category and connect categories as children
708 $category = false;
709 foreach ($cats as $catid=>$cat) {
710 if (!empty($cat->parent)) {
711 // prevent problems with duplicate sortorders in db
712 $sortorder = $cat->sortorder;
713 while(array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 714 //debugging("$sortorder exists in cat loop");
b3ac6c3e 715 $sortorder++;
716 }
717
718 $cats[$cat->parent]->children[$sortorder] = $cat;
719 }
720
721 if ($catid == $this->id) {
722 $category = &$cats[$catid];
723 }
724 }
725
726 unset($items); // not needed
727 unset($cats); // not needed
728
938e00b6 729 $children_array = grade_category::_get_children_recursion($category);
b3ac6c3e 730
731 ksort($children_array);
732
733 return $children_array;
734
735 }
736
938e00b6 737 function _get_children_recursion($category) {
b3ac6c3e 738
739 $children_array = array();
740 foreach($category->children as $sortorder=>$child) {
741 if (array_key_exists('itemtype', $child)) {
742 $grade_item = new grade_item($child, false);
4faf5f99 743 if (in_array($grade_item->itemtype, array('course', 'category'))) {
744 $type = $grade_item->itemtype.'item';
745 $depth = $category->depth;
314c4336 746 } else {
747 $type = 'item';
748 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 749 }
4faf5f99 750 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 751
7c8a963f 752 } else {
938e00b6 753 $children = grade_category::_get_children_recursion($child);
b3ac6c3e 754 $grade_category = new grade_category($child, false);
755 if (empty($children)) {
314c4336 756 $children = array();
7c8a963f 757 }
4faf5f99 758 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
314c4336 759 }
27f95e9b 760 }
761
b3ac6c3e 762 // sort the array
763 ksort($children_array);
764
27f95e9b 765 return $children_array;
766 }
4a490db0 767
f151b073 768 /**
ab53054f 769 * Uses get_grade_item to load or create a grade_item, then saves it as $this->grade_item.
f151b073 770 * @return object Grade_item
771 */
772 function load_grade_item() {
ac9b0805 773 if (empty($this->grade_item)) {
774 $this->grade_item = $this->get_grade_item();
775 }
ab53054f 776 return $this->grade_item;
777 }
4a490db0 778
ab53054f 779 /**
780 * Retrieves from DB and instantiates the associated grade_item object.
781 * If no grade_item exists yet, create one.
782 * @return object Grade_item
783 */
784 function get_grade_item() {
c91ed4be 785 if (empty($this->id)) {
786 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
787 return false;
788 }
789
b3ac6c3e 790 if (empty($this->parent)) {
791 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
792
793 } else {
794 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
795 }
f92dcad8 796
797 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 798 // create a new one
f92dcad8 799 $grade_item = new grade_item($params, false);
b8ff92b6 800 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 801 $grade_item->insert('system');
4a490db0 802
b8ff92b6 803 } else if (count($grade_items) == 1){
804 // found existing one
805 $grade_item = reset($grade_items);
4a490db0 806
b8ff92b6 807 } else {
808 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 809 // return first one
810 $grade_item = reset($grade_items);
2c72af1f 811 }
812
ab53054f 813 return $grade_item;
f151b073 814 }
8c846243 815
816 /**
817 * Uses $this->parent to instantiate $this->parent_category based on the
818 * referenced record in the DB.
819 * @return object Parent_category
820 */
821 function load_parent_category() {
822 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 823 $this->parent_category = $this->get_parent_category();
8c846243 824 }
825 return $this->parent_category;
4a490db0 826 }
827
ab53054f 828 /**
829 * Uses $this->parent to instantiate and return a grade_category object.
830 * @return object Parent_category
831 */
832 function get_parent_category() {
833 if (!empty($this->parent)) {
834 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 835 return $parent_category;
ab53054f 836 } else {
837 return null;
838 }
839 }
840
2186f72c 841 /**
4a490db0 842 * Returns the most descriptive field for this object. This is a standard method used
2186f72c 843 * when we do not know the exact type of an object.
844 * @return string name
845 */
846 function get_name() {
314c4336 847 if (empty($this->parent)) {
848 return "Top course category"; //TODO: localize
849 } else {
850 return $this->fullname;
851 }
2186f72c 852 }
c91ed4be 853
0fc7f624 854 /**
855 * Sets this category's parent id. A generic method shared by objects that have a parent id of some kind.
f13002d5 856 * @param int parentid
857 * @return boolean success
0fc7f624 858 */
f8e6e4db 859 function set_parent($parentid, $source=null) {
f13002d5 860 if ($this->parent == $parentid) {
861 return true;
862 }
863
864 if ($parentid == $this->id) {
865 error('Can not assign self as parent!');
866 }
867
868 if (empty($this->parent) and $this->is_course_category()) {
869 error('Course category can not have parent!');
b3ac6c3e 870 }
f13002d5 871
872 // find parent and check course id
873 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 874 return false;
875 }
876
f8e6e4db 877 $this->force_regrading();
b3ac6c3e 878
879 // set new parent category
f8e6e4db 880 $this->parent = $parent_category->id;
881 $this->parent_category =& $parent_category;
b3ac6c3e 882 $this->path = null; // remove old path and depth - will be recalculated in update()
f8e6e4db 883 $this->depth = null; // remove old path and depth - will be recalculated in update()
884 $this->update($source);
b3ac6c3e 885
15b462da 886 return $this->update($source);
b3ac6c3e 887 }
888
889 /**
890 * Returns the final values for this grade category.
891 * @param int $userid Optional: to retrieve a single final grade
892 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
893 */
894 function get_final($userid=NULL) {
895 $this->load_grade_item();
896 return $this->grade_item->get_final($userid);
0fc7f624 897 }
4a490db0 898
0fc7f624 899 /**
4a490db0 900 * Returns the sortorder of the associated grade_item. This method is also available in
5fad5061 901 * grade_item, for cases where the object type is not known.
0fc7f624 902 * @return int Sort order
903 */
904 function get_sortorder() {
b3ac6c3e 905 $this->load_grade_item();
906 return $this->grade_item->get_sortorder();
0fc7f624 907 }
908
909 /**
b3ac6c3e 910 * Sets sortorder variable for this category.
4a490db0 911 * This method is also available in grade_item, for cases where the object type is not know.
0fc7f624 912 * @param int $sortorder
913 * @return void
914 */
915 function set_sortorder($sortorder) {
b3ac6c3e 916 $this->load_grade_item();
917 $this->grade_item->set_sortorder($sortorder);
918 }
919
6639ead3 920 /**
921 * Move this category after the given sortorder - does not change the parent
922 * @param int $sortorder to place after
923 */
f13002d5 924 function move_after_sortorder($sortorder) {
925 $this->load_grade_item();
926 $this->grade_item->move_after_sortorder($sortorder);
927 }
928
b3ac6c3e 929 /**
f13002d5 930 * Return true if this is the top most category that represents the total course grade.
b3ac6c3e 931 * @return boolean
932 */
933 function is_course_category() {
934 $this->load_grade_item();
935 return $this->grade_item->is_course_item();
936 }
937
938 /**
939 * Return the top most course category.
940 * @static
941 * @return object grade_category instance for course grade
942 */
943 function fetch_course_category($courseid) {
944
945 // course category has no parent
946 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
947 return $course_category;
948 }
949
950 // create a new one
951 $course_category = new grade_category();
952 $course_category->insert_course_category($courseid);
953
954 return $course_category;
0fc7f624 955 }
4a490db0 956
79eabc2a 957 /**
958 * Is grading object editable?
959 * @return boolean
960 */
961 function is_editable() {
962 return true;
963 }
964
5fad5061 965 /**
4a490db0 966 * Returns the locked state/date of the associated grade_item. This method is also available in
967 * grade_item, for cases where the object type is not known.
22e23c78 968 * @return boolean
5fad5061 969 */
2cc4b0f9 970 function is_locked() {
5fad5061 971 $this->load_grade_item();
22e23c78 972 return $this->grade_item->is_locked();
5fad5061 973 }
974
975 /**
976 * Sets the grade_item's locked variable and updates the grade_item.
977 * Method named after grade_item::set_locked().
978 * @param int $locked 0, 1 or a timestamp int(10) after which date the item will be locked.
9580a21f 979 * @return boolean success if category locked (not all children mayb be locked though)
5fad5061 980 */
2cc4b0f9 981 function set_locked($lockedstate) {
5fad5061 982 $this->load_grade_item();
b121b544 983 $result = $this->grade_item->set_locked($lockedstate);
7a7a53d3 984 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
985 foreach($children as $child) {
2a8c101f 986 $child->set_locked($lockedstate);
7a7a53d3 987 }
988 }
989 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
990 foreach($children as $child) {
2a8c101f 991 $child->set_locked($lockedstate);
7a7a53d3 992 }
993 }
b121b544 994 return $result;
5fad5061 995 }
4a490db0 996
5fad5061 997 /**
4a490db0 998 * Returns the hidden state/date of the associated grade_item. This method is also available in
22e23c78 999 * grade_item.
1000 * @return boolean
5fad5061 1001 */
22e23c78 1002 function is_hidden() {
5fad5061 1003 $this->load_grade_item();
22e23c78 1004 return $this->grade_item->is_hidden();
5fad5061 1005 }
1006
1007 /**
4a490db0 1008 * Sets the grade_item's hidden variable and updates the grade_item.
5fad5061 1009 * Method named after grade_item::set_hidden().
1010 * @param int $hidden 0, 1 or a timestamp int(10) after which date the item will be hidden.
1011 * @return void
1012 */
1013 function set_hidden($hidden) {
1014 $this->load_grade_item();
22e23c78 1015 $this->grade_item->set_hidden($hidden);
f13002d5 1016 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
1017 foreach($children as $child) {
1018 $child->set_hidden($hidden);
1019 }
1020 }
1021 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
1022 foreach($children as $child) {
1023 $child->set_hidden($hidden);
1024 }
1025 }
5fad5061 1026 }
1027
4a490db0 1028}
8a31e65c 1029?>