MDL-10396:
[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
ac9b0805 436 //limit and sort
9580a21f 437 $this->apply_limit_rules($grade_values);
438 asort($grade_values, SORT_NUMERIC);
4a490db0 439
d5f0aa01 440 // let's see we have still enough grades to do any statistics
9580a21f 441 if (count($grade_values) == 0) {
ac9b0805 442 // not enough attempts yet
f8e6e4db 443 $grade->finalgrade = null;
444 $grade->rawgrade = null;
445 if ($grade->finalgrade !== $oldgrade->finalgrade or $grade->rawgrade !== $oldgrade->rawgrade) {
446 $grade->update('system');
b8ff92b6 447 }
448 return;
449 }
2df71235 450
f8e6e4db 451 /// start the aggregation
b8ff92b6 452 switch ($this->aggregation) {
453 case GRADE_AGGREGATE_MEDIAN: // Middle point value in the set: ignores frequencies
9580a21f 454 $num = count($grade_values);
d5f0aa01 455 // re-index grade_values array
456 $sorted_values = $grade_values;
457 sort($sorted_values);
b8ff92b6 458 $halfpoint = intval($num / 2);
d5f0aa01 459 if ($num == 0) {
460 $rawgrade = null;
461 } elseif ($num == 1) {
462 $rawgrade = reset($sorted_values);
463 } else if($num % 2 == 0) {
464 $rawgrade = ($sorted_values[ceil($halfpoint)] + $sorted_values[floor($halfpoint)]) / 2;
b8ff92b6 465 } else {
d5f0aa01 466 $rawgrade = $sorted_values[$halfpoint];
b8ff92b6 467 }
468 break;
ac9b0805 469
b8ff92b6 470 case GRADE_AGGREGATE_MIN:
9580a21f 471 $rawgrade = reset($grade_values);
b8ff92b6 472 break;
473
474 case GRADE_AGGREGATE_MAX:
9580a21f 475 $rawgrade = array_pop($grade_values);
b8ff92b6 476 break;
477
95affb8a 478 case GRADE_AGGREGATE_MODE: // the most common value, the highest one if multimode
9580a21f 479 $freq = array_count_values($grade_values);
95affb8a 480 arsort($freq); // sort by frequency keeping keys
481 $top = reset($freq); // highest frequency count
482 $modes = array_keys($freq, $top); // search for all modes (have the same highest count)
483 rsort($modes, SORT_NUMERIC); // get highes mode
ac9b0805 484 $rawgrade = reset($modes);
d5fab31f 485 break;
95affb8a 486
9580a21f 487 case GRADE_AGGREGATE_WEIGHTED_MEAN_ALL: // Weighted average of all possible final grades
488 $weightsum = 0;
489 $sum = 0;
490 foreach($items as $key=>$value) {
ba74762b 491 $grade_value = isset($grade_values[$key]) ? $grade_values[$key] : 0;
9580a21f 492 if ($items[$key]->aggregationcoef <= 0) {
493 continue;
494 }
495 $weightsum += $items[$key]->aggregationcoef;
496 $sum += $items[$key]->aggregationcoef * $grade_value;
497 }
498 if ($weightsum == 0) {
499 $rawgrade = null;
500 } else {
501 $rawgrade = $sum / $weightsum;
502 }
503 break;
504
505 case GRADE_AGGREGATE_WEIGHTED_MEAN_GRADED: // Weighted average of all existing final grades
506 $weightsum = 0;
507 $sum = 0;
508 foreach($grade_values as $key=>$grade_value) {
509 if ($items[$key]->aggregationcoef <= 0) {
510 continue;
511 }
512 $weightsum += $items[$key]->aggregationcoef;
513 $sum += $items[$key]->aggregationcoef * $grade_value;
514 }
515 if ($weightsum == 0) {
516 $rawgrade = null;
517 } else {
518 $rawgrade = $sum / $weightsum;
519 }
520 break;
521
ba74762b 522 case GRADE_AGGREGATE_EXTRACREDIT_MEAN_ALL: // special average
9580a21f 523 $num = 0;
524 $sum = 0;
525 foreach($items as $key=>$value) {
ba74762b 526 $grade_value = isset($grade_values[$key]) ? $grade_values[$key] : 0;
9580a21f 527 if ($items[$key]->aggregationcoef == 0) {
528 $num += 1;
529 $sum += $grade_value;
530 } else if ($items[$key]->aggregationcoef > 0) {
531 $sum += $items[$key]->aggregationcoef * $grade_value;
532 }
533 }
534 if ($num == 0) {
535 $rawgrade = $sum; // only extra credits or wrong coefs
536 } else {
537 $rawgrade = $sum / $num;
538 }
539 break;
540
ba74762b 541 case GRADE_AGGREGATE_EXTRACREDIT_MEAN_GRADED: // special average
9580a21f 542 $num = 0;
543 $sum = 0;
544 foreach($grade_values as $key=>$grade_value) {
545 if ($items[$key]->aggregationcoef == 0) {
546 $num += 1;
547 $sum += $grade_value;
548 } else if ($items[$key]->aggregationcoef > 0) {
549 $sum += $items[$key]->aggregationcoef * $grade_value;
550 }
551 }
552 if ($num == 0) {
553 $rawgrade = $sum; // only extra credits or wrong coefs
554 } else {
555 $rawgrade = $sum / $num;
556 }
557 break;
558
d5f0aa01 559 case GRADE_AGGREGATE_MEAN_ALL: // Arithmetic average of all grade items including even NULLs; NULL grade counted as minimum
9580a21f 560 $num = count($items); // you can calculate sum from this one if you multiply it with count($this->depends_on() ;-)
561 $sum = array_sum($grade_values);
562 $rawgrade = $sum / $num;
563 break;
564
95affb8a 565 case GRADE_AGGREGATE_MEAN_GRADED: // Arithmetic average of all final grades, unfinished are not calculated
ac9b0805 566 default:
9580a21f 567 $num = count($grade_values);
568 $sum = array_sum($grade_values);
ac9b0805 569 $rawgrade = $sum / $num;
b8ff92b6 570 break;
571 }
572
f8e6e4db 573 /// prepare update of new raw grade
574 $grade->rawgrademin = $this->grade_item->grademin;
575 $grade->rawgrademax = $this->grade_item->grademax;
576 $grade->rawscaleid = $this->grade_item->scaleid;
577
ac9b0805 578 // recalculate the rawgrade back to requested range
3ee5c201 579 $grade->rawgrade = grade_grade::standardise_score($rawgrade, 0, 1, $grade->rawgrademin, $grade->rawgrademax);
b8ff92b6 580
f8e6e4db 581 // calculate final grade
582 $grade->finalgrade = $this->grade_item->adjust_grade($grade->rawgrade, $grade->rawgrademin, $grade->rawgrademax);
2df71235 583
f8e6e4db 584 // update in db if changed
585 if ( $grade->finalgrade !== $oldgrade->finalgrade
586 or $grade->rawgrade !== $oldgrade->rawgrade
587 or $grade->rawgrademin !== $oldgrade->rawgrademin
588 or $grade->rawgrademax !== $oldgrade->rawgrademax
589 or $grade->rawscaleid !== $oldgrade->rawscaleid) {
590
591 $grade->update('system');
592 }
593
594 return;
0aa32279 595 }
596
adc2f286 597 /**
598 * Given an array of grade values (numerical indices), applies droplow or keephigh
599 * rules to limit the final array.
9580a21f 600 * @param array $grade_values
adc2f286 601 * @return array Limited grades.
602 */
9580a21f 603 function apply_limit_rules(&$grade_values) {
604 arsort($grade_values, SORT_NUMERIC);
adc2f286 605 if (!empty($this->droplow)) {
606 for ($i = 0; $i < $this->droplow; $i++) {
9580a21f 607 array_pop($grade_values);
adc2f286 608 }
4a490db0 609 } elseif (!empty($this->keephigh)) {
9580a21f 610 while (count($grade_values) > $this->keephigh) {
611 array_pop($grade_values);
adc2f286 612 }
613 }
0aa32279 614 }
615
9580a21f 616
617 /**
618 * Returns true if category uses special aggregation coeficient
619 * @return boolean true if coeficient used
620 */
621 function is_aggregationcoef_used() {
622 return ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN_ALL
623 or $this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN_GRADED
624 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN_ALL
625 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN_GRADED);
ba74762b 626
9580a21f 627 }
628
0fc7f624 629 /**
630 * Returns true if this category has any child grade_category or grade_item.
631 * @return int number of direct children, or false if none found.
632 */
633 function has_children() {
634 return count_records('grade_categories', 'parent', $this->id) + count_records('grade_items', 'categoryid', $this->id);
635 }
636
1c307f21 637 /**
b3ac6c3e 638 * Returns tree with all grade_items and categories as elements
639 * @static
640 * @param int $courseid
b3ac6c3e 641 * @param boolean $include_category_items as category children
642 * @return array
1c307f21 643 */
938e00b6 644 function fetch_course_tree($courseid, $include_category_items=false) {
b3ac6c3e 645 $course_category = grade_category::fetch_course_category($courseid);
314c4336 646 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
938e00b6 647 'children'=>$course_category->get_children($include_category_items));
314c4336 648 $sortorder = 1;
649 $course_category->set_sortorder($sortorder);
650 $course_category->sortorder = $sortorder;
b3ac6c3e 651 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 652 }
653
b3ac6c3e 654 function _fetch_course_tree_recursion($category_array, &$sortorder) {
655 // update the sortorder in db if needed
656 if ($category_array['object']->sortorder != $sortorder) {
657 $category_array['object']->set_sortorder($sortorder);
ce385eb4 658 }
ce385eb4 659
314c4336 660 // store the grade_item or grade_category instance with extra info
661 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 662
663 // reuse final grades if there
664 if (array_key_exists('finalgrades', $category_array)) {
665 $result['finalgrades'] = $category_array['finalgrades'];
666 }
667
668 // recursively resort children
669 if (!empty($category_array['children'])) {
670 $result['children'] = array();
671 foreach($category_array['children'] as $oldorder=>$child_array) {
314c4336 672 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
b3ac6c3e 673 $result['children'][$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
674 } else {
675 $result['children'][++$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
676 }
677 }
678 }
679
680 return $result;
ce385eb4 681 }
7c8a963f 682
683 /**
4a490db0 684 * Fetches and returns all the children categories and/or grade_items belonging to this category.
685 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 686 * as well as all levels (0). The elements are indexed by sort order.
7c8a963f 687 * @return array Array of child objects (grade_category and grade_item).
688 */
938e00b6 689 function get_children($include_category_items=false) {
b3ac6c3e 690
691 // This function must be as fast as possible ;-)
692 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
693 // we have to limit the number of queries though, because it will be used often in grade reports
694
695 $cats = get_records('grade_categories', 'courseid', $this->courseid);
696 $items = get_records('grade_items', 'courseid', $this->courseid);
4a490db0 697
b3ac6c3e 698 // init children array first
699 foreach ($cats as $catid=>$cat) {
700 $cats[$catid]->children = array();
27f95e9b 701 }
4a490db0 702
b3ac6c3e 703 //first attach items to cats and add category sortorder
704 foreach ($items as $item) {
705 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
706 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 707
b3ac6c3e 708 if (!$include_category_items) {
709 continue;
710 }
711 $categoryid = $item->iteminstance;
712 } else {
713 $categoryid = $item->categoryid;
714 }
715
716 // prevent problems with duplicate sortorders in db
717 $sortorder = $item->sortorder;
718 while(array_key_exists($sortorder, $cats[$categoryid]->children)) {
f13002d5 719 //debugging("$sortorder exists in item loop");
b3ac6c3e 720 $sortorder++;
721 }
722
723 $cats[$categoryid]->children[$sortorder] = $item;
724
725 }
726
727 // now find the requested category and connect categories as children
728 $category = false;
729 foreach ($cats as $catid=>$cat) {
730 if (!empty($cat->parent)) {
731 // prevent problems with duplicate sortorders in db
732 $sortorder = $cat->sortorder;
733 while(array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 734 //debugging("$sortorder exists in cat loop");
b3ac6c3e 735 $sortorder++;
736 }
737
738 $cats[$cat->parent]->children[$sortorder] = $cat;
739 }
740
741 if ($catid == $this->id) {
742 $category = &$cats[$catid];
743 }
744 }
745
746 unset($items); // not needed
747 unset($cats); // not needed
748
938e00b6 749 $children_array = grade_category::_get_children_recursion($category);
b3ac6c3e 750
751 ksort($children_array);
752
753 return $children_array;
754
755 }
756
938e00b6 757 function _get_children_recursion($category) {
b3ac6c3e 758
759 $children_array = array();
760 foreach($category->children as $sortorder=>$child) {
761 if (array_key_exists('itemtype', $child)) {
762 $grade_item = new grade_item($child, false);
314c4336 763 if (in_array($grade_item->itemtype, array('course', 'category'))) {
764 $type = $grade_item->itemtype.'item';
765 $depth = $category->depth;
766 } else {
767 $type = 'item';
768 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 769 }
314c4336 770 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 771
7c8a963f 772 } else {
938e00b6 773 $children = grade_category::_get_children_recursion($child);
b3ac6c3e 774 $grade_category = new grade_category($child, false);
775 if (empty($children)) {
314c4336 776 $children = array();
7c8a963f 777 }
314c4336 778 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
779 }
27f95e9b 780 }
781
b3ac6c3e 782 // sort the array
783 ksort($children_array);
784
27f95e9b 785 return $children_array;
786 }
4a490db0 787
f151b073 788 /**
ab53054f 789 * Uses get_grade_item to load or create a grade_item, then saves it as $this->grade_item.
f151b073 790 * @return object Grade_item
791 */
792 function load_grade_item() {
ac9b0805 793 if (empty($this->grade_item)) {
794 $this->grade_item = $this->get_grade_item();
795 }
ab53054f 796 return $this->grade_item;
797 }
4a490db0 798
ab53054f 799 /**
800 * Retrieves from DB and instantiates the associated grade_item object.
801 * If no grade_item exists yet, create one.
802 * @return object Grade_item
803 */
804 function get_grade_item() {
c91ed4be 805 if (empty($this->id)) {
806 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
807 return false;
808 }
809
b3ac6c3e 810 if (empty($this->parent)) {
811 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
812
813 } else {
814 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
815 }
f92dcad8 816
817 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 818 // create a new one
f92dcad8 819 $grade_item = new grade_item($params, false);
b8ff92b6 820 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 821 $grade_item->insert('system');
4a490db0 822
b8ff92b6 823 } else if (count($grade_items) == 1){
824 // found existing one
825 $grade_item = reset($grade_items);
4a490db0 826
b8ff92b6 827 } else {
828 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 829 // return first one
830 $grade_item = reset($grade_items);
2c72af1f 831 }
832
ab53054f 833 return $grade_item;
f151b073 834 }
8c846243 835
836 /**
837 * Uses $this->parent to instantiate $this->parent_category based on the
838 * referenced record in the DB.
839 * @return object Parent_category
840 */
841 function load_parent_category() {
842 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 843 $this->parent_category = $this->get_parent_category();
8c846243 844 }
845 return $this->parent_category;
4a490db0 846 }
847
ab53054f 848 /**
849 * Uses $this->parent to instantiate and return a grade_category object.
850 * @return object Parent_category
851 */
852 function get_parent_category() {
853 if (!empty($this->parent)) {
854 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 855 return $parent_category;
ab53054f 856 } else {
857 return null;
858 }
859 }
860
2186f72c 861 /**
4a490db0 862 * Returns the most descriptive field for this object. This is a standard method used
2186f72c 863 * when we do not know the exact type of an object.
864 * @return string name
865 */
866 function get_name() {
314c4336 867 if (empty($this->parent)) {
868 return "Top course category"; //TODO: localize
869 } else {
870 return $this->fullname;
871 }
2186f72c 872 }
c91ed4be 873
0fc7f624 874 /**
875 * Sets this category's parent id. A generic method shared by objects that have a parent id of some kind.
f13002d5 876 * @param int parentid
877 * @return boolean success
0fc7f624 878 */
f8e6e4db 879 function set_parent($parentid, $source=null) {
f13002d5 880 if ($this->parent == $parentid) {
881 return true;
882 }
883
884 if ($parentid == $this->id) {
885 error('Can not assign self as parent!');
886 }
887
888 if (empty($this->parent) and $this->is_course_category()) {
889 error('Course category can not have parent!');
b3ac6c3e 890 }
f13002d5 891
892 // find parent and check course id
893 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 894 return false;
895 }
896
f8e6e4db 897 $this->force_regrading();
b3ac6c3e 898
899 // set new parent category
f8e6e4db 900 $this->parent = $parent_category->id;
901 $this->parent_category =& $parent_category;
b3ac6c3e 902 $this->path = null; // remove old path and depth - will be recalculated in update()
f8e6e4db 903 $this->depth = null; // remove old path and depth - will be recalculated in update()
904 $this->update($source);
b3ac6c3e 905
15b462da 906 return $this->update($source);
b3ac6c3e 907 }
908
909 /**
910 * Returns the final values for this grade category.
911 * @param int $userid Optional: to retrieve a single final grade
912 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
913 */
914 function get_final($userid=NULL) {
915 $this->load_grade_item();
916 return $this->grade_item->get_final($userid);
0fc7f624 917 }
4a490db0 918
0fc7f624 919 /**
4a490db0 920 * Returns the sortorder of the associated grade_item. This method is also available in
5fad5061 921 * grade_item, for cases where the object type is not known.
0fc7f624 922 * @return int Sort order
923 */
924 function get_sortorder() {
b3ac6c3e 925 $this->load_grade_item();
926 return $this->grade_item->get_sortorder();
0fc7f624 927 }
928
929 /**
b3ac6c3e 930 * Sets sortorder variable for this category.
4a490db0 931 * This method is also available in grade_item, for cases where the object type is not know.
0fc7f624 932 * @param int $sortorder
933 * @return void
934 */
935 function set_sortorder($sortorder) {
b3ac6c3e 936 $this->load_grade_item();
937 $this->grade_item->set_sortorder($sortorder);
938 }
939
6639ead3 940 /**
941 * Move this category after the given sortorder - does not change the parent
942 * @param int $sortorder to place after
943 */
f13002d5 944 function move_after_sortorder($sortorder) {
945 $this->load_grade_item();
946 $this->grade_item->move_after_sortorder($sortorder);
947 }
948
b3ac6c3e 949 /**
f13002d5 950 * Return true if this is the top most category that represents the total course grade.
b3ac6c3e 951 * @return boolean
952 */
953 function is_course_category() {
954 $this->load_grade_item();
955 return $this->grade_item->is_course_item();
956 }
957
958 /**
959 * Return the top most course category.
960 * @static
961 * @return object grade_category instance for course grade
962 */
963 function fetch_course_category($courseid) {
964
965 // course category has no parent
966 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
967 return $course_category;
968 }
969
970 // create a new one
971 $course_category = new grade_category();
972 $course_category->insert_course_category($courseid);
973
974 return $course_category;
0fc7f624 975 }
4a490db0 976
79eabc2a 977 /**
978 * Is grading object editable?
979 * @return boolean
980 */
981 function is_editable() {
982 return true;
983 }
984
5fad5061 985 /**
4a490db0 986 * Returns the locked state/date of the associated grade_item. This method is also available in
987 * grade_item, for cases where the object type is not known.
22e23c78 988 * @return boolean
5fad5061 989 */
2cc4b0f9 990 function is_locked() {
5fad5061 991 $this->load_grade_item();
22e23c78 992 return $this->grade_item->is_locked();
5fad5061 993 }
994
995 /**
996 * Sets the grade_item's locked variable and updates the grade_item.
997 * Method named after grade_item::set_locked().
998 * @param int $locked 0, 1 or a timestamp int(10) after which date the item will be locked.
9580a21f 999 * @return boolean success if category locked (not all children mayb be locked though)
5fad5061 1000 */
2cc4b0f9 1001 function set_locked($lockedstate) {
5fad5061 1002 $this->load_grade_item();
b121b544 1003 $result = $this->grade_item->set_locked($lockedstate);
7a7a53d3 1004 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
1005 foreach($children as $child) {
2a8c101f 1006 $child->set_locked($lockedstate);
7a7a53d3 1007 }
1008 }
1009 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
1010 foreach($children as $child) {
2a8c101f 1011 $child->set_locked($lockedstate);
7a7a53d3 1012 }
1013 }
b121b544 1014 return $result;
5fad5061 1015 }
4a490db0 1016
5fad5061 1017 /**
4a490db0 1018 * Returns the hidden state/date of the associated grade_item. This method is also available in
22e23c78 1019 * grade_item.
1020 * @return boolean
5fad5061 1021 */
22e23c78 1022 function is_hidden() {
5fad5061 1023 $this->load_grade_item();
22e23c78 1024 return $this->grade_item->is_hidden();
5fad5061 1025 }
1026
1027 /**
4a490db0 1028 * Sets the grade_item's hidden variable and updates the grade_item.
5fad5061 1029 * Method named after grade_item::set_hidden().
1030 * @param int $hidden 0, 1 or a timestamp int(10) after which date the item will be hidden.
1031 * @return void
1032 */
1033 function set_hidden($hidden) {
1034 $this->load_grade_item();
22e23c78 1035 $this->grade_item->set_hidden($hidden);
f13002d5 1036 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
1037 foreach($children as $child) {
1038 $child->set_hidden($hidden);
1039 }
1040 }
1041 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
1042 foreach($children as $child) {
1043 $child->set_hidden($hidden);
1044 }
1045 }
5fad5061 1046 }
1047
4a490db0 1048}
8a31e65c 1049?>