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