Minor change from 0 to null in formats. More correct and compatible
[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);
f04873a9 631 if (is_array($course_category)) {
632 debugging("grade_category::fetch_course_category($courseid) returned an array instead of an object. Returning only the first item.");
633 $course_category = reset($course_category);
634 }
635
636 if (is_object($course_category)) {
637 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
638 'children'=>$course_category->get_children($include_category_items));
639 $sortorder = 1;
640 $course_category->set_sortorder($sortorder);
641 $course_category->sortorder = $sortorder;
642 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
643 } else {
644 debugging("grade_category::fetch_course_category($courseid) returned '$course_category'");
645 return false;
646 }
1c307f21 647 }
648
b3ac6c3e 649 function _fetch_course_tree_recursion($category_array, &$sortorder) {
650 // update the sortorder in db if needed
651 if ($category_array['object']->sortorder != $sortorder) {
652 $category_array['object']->set_sortorder($sortorder);
ce385eb4 653 }
ce385eb4 654
314c4336 655 // store the grade_item or grade_category instance with extra info
656 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 657
658 // reuse final grades if there
659 if (array_key_exists('finalgrades', $category_array)) {
660 $result['finalgrades'] = $category_array['finalgrades'];
661 }
662
663 // recursively resort children
664 if (!empty($category_array['children'])) {
665 $result['children'] = array();
666 foreach($category_array['children'] as $oldorder=>$child_array) {
314c4336 667 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
b3ac6c3e 668 $result['children'][$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
669 } else {
670 $result['children'][++$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
671 }
672 }
673 }
674
675 return $result;
ce385eb4 676 }
7c8a963f 677
678 /**
4a490db0 679 * Fetches and returns all the children categories and/or grade_items belonging to this category.
680 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 681 * as well as all levels (0). The elements are indexed by sort order.
7c8a963f 682 * @return array Array of child objects (grade_category and grade_item).
683 */
938e00b6 684 function get_children($include_category_items=false) {
b3ac6c3e 685
686 // This function must be as fast as possible ;-)
687 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
688 // we have to limit the number of queries though, because it will be used often in grade reports
689
690 $cats = get_records('grade_categories', 'courseid', $this->courseid);
691 $items = get_records('grade_items', 'courseid', $this->courseid);
4a490db0 692
f04873a9 693 if (count($cats) == 0) {
694 debugging("get_records('grade_categories', 'courseid', $this->courseid) returned nothing.");
695 }
696
b3ac6c3e 697 // init children array first
698 foreach ($cats as $catid=>$cat) {
699 $cats[$catid]->children = array();
27f95e9b 700 }
4a490db0 701
b3ac6c3e 702 //first attach items to cats and add category sortorder
703 foreach ($items as $item) {
704 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
705 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 706
b3ac6c3e 707 if (!$include_category_items) {
708 continue;
709 }
710 $categoryid = $item->iteminstance;
f04873a9 711 if (is_null($categoryid)) {
712 debugging("Itemtype was '$item->itemtype' (item->id=$item->id), but its iteminstance was null...");
713 }
b3ac6c3e 714 } else {
715 $categoryid = $item->categoryid;
716 }
717
718 // prevent problems with duplicate sortorders in db
719 $sortorder = $item->sortorder;
720 while(array_key_exists($sortorder, $cats[$categoryid]->children)) {
f13002d5 721 //debugging("$sortorder exists in item loop");
b3ac6c3e 722 $sortorder++;
723 }
724
f04873a9 725 if (is_null($categoryid)) {
726 debugging('$categoryid was null!');
727 }
728
b3ac6c3e 729 $cats[$categoryid]->children[$sortorder] = $item;
730
731 }
732
733 // now find the requested category and connect categories as children
734 $category = false;
735 foreach ($cats as $catid=>$cat) {
736 if (!empty($cat->parent)) {
737 // prevent problems with duplicate sortorders in db
738 $sortorder = $cat->sortorder;
739 while(array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 740 //debugging("$sortorder exists in cat loop");
b3ac6c3e 741 $sortorder++;
742 }
743
744 $cats[$cat->parent]->children[$sortorder] = $cat;
745 }
746
747 if ($catid == $this->id) {
748 $category = &$cats[$catid];
749 }
750 }
751
752 unset($items); // not needed
753 unset($cats); // not needed
754
938e00b6 755 $children_array = grade_category::_get_children_recursion($category);
b3ac6c3e 756
757 ksort($children_array);
758
759 return $children_array;
760
761 }
762
938e00b6 763 function _get_children_recursion($category) {
b3ac6c3e 764
765 $children_array = array();
766 foreach($category->children as $sortorder=>$child) {
767 if (array_key_exists('itemtype', $child)) {
768 $grade_item = new grade_item($child, false);
4faf5f99 769 if (in_array($grade_item->itemtype, array('course', 'category'))) {
770 $type = $grade_item->itemtype.'item';
771 $depth = $category->depth;
314c4336 772 } else {
773 $type = 'item';
774 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 775 }
4faf5f99 776 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 777
7c8a963f 778 } else {
938e00b6 779 $children = grade_category::_get_children_recursion($child);
b3ac6c3e 780 $grade_category = new grade_category($child, false);
781 if (empty($children)) {
314c4336 782 $children = array();
7c8a963f 783 }
4faf5f99 784 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
314c4336 785 }
27f95e9b 786 }
787
b3ac6c3e 788 // sort the array
789 ksort($children_array);
790
27f95e9b 791 return $children_array;
792 }
4a490db0 793
f151b073 794 /**
ab53054f 795 * Uses get_grade_item to load or create a grade_item, then saves it as $this->grade_item.
f151b073 796 * @return object Grade_item
797 */
798 function load_grade_item() {
ac9b0805 799 if (empty($this->grade_item)) {
800 $this->grade_item = $this->get_grade_item();
801 }
ab53054f 802 return $this->grade_item;
803 }
4a490db0 804
ab53054f 805 /**
806 * Retrieves from DB and instantiates the associated grade_item object.
807 * If no grade_item exists yet, create one.
808 * @return object Grade_item
809 */
810 function get_grade_item() {
c91ed4be 811 if (empty($this->id)) {
812 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
813 return false;
814 }
815
b3ac6c3e 816 if (empty($this->parent)) {
817 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
818
819 } else {
820 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
821 }
f92dcad8 822
823 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 824 // create a new one
f92dcad8 825 $grade_item = new grade_item($params, false);
b8ff92b6 826 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 827 $grade_item->insert('system');
4a490db0 828
b8ff92b6 829 } else if (count($grade_items) == 1){
830 // found existing one
831 $grade_item = reset($grade_items);
4a490db0 832
b8ff92b6 833 } else {
834 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 835 // return first one
836 $grade_item = reset($grade_items);
2c72af1f 837 }
838
ab53054f 839 return $grade_item;
f151b073 840 }
8c846243 841
842 /**
843 * Uses $this->parent to instantiate $this->parent_category based on the
844 * referenced record in the DB.
845 * @return object Parent_category
846 */
847 function load_parent_category() {
848 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 849 $this->parent_category = $this->get_parent_category();
8c846243 850 }
851 return $this->parent_category;
4a490db0 852 }
853
ab53054f 854 /**
855 * Uses $this->parent to instantiate and return a grade_category object.
856 * @return object Parent_category
857 */
858 function get_parent_category() {
859 if (!empty($this->parent)) {
860 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 861 return $parent_category;
ab53054f 862 } else {
863 return null;
864 }
865 }
866
2186f72c 867 /**
4a490db0 868 * Returns the most descriptive field for this object. This is a standard method used
2186f72c 869 * when we do not know the exact type of an object.
870 * @return string name
871 */
872 function get_name() {
314c4336 873 if (empty($this->parent)) {
874 return "Top course category"; //TODO: localize
875 } else {
876 return $this->fullname;
877 }
2186f72c 878 }
c91ed4be 879
0fc7f624 880 /**
881 * Sets this category's parent id. A generic method shared by objects that have a parent id of some kind.
f13002d5 882 * @param int parentid
883 * @return boolean success
0fc7f624 884 */
f8e6e4db 885 function set_parent($parentid, $source=null) {
f13002d5 886 if ($this->parent == $parentid) {
887 return true;
888 }
889
890 if ($parentid == $this->id) {
891 error('Can not assign self as parent!');
892 }
893
894 if (empty($this->parent) and $this->is_course_category()) {
895 error('Course category can not have parent!');
b3ac6c3e 896 }
f13002d5 897
898 // find parent and check course id
899 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 900 return false;
901 }
902
f8e6e4db 903 $this->force_regrading();
b3ac6c3e 904
905 // set new parent category
f8e6e4db 906 $this->parent = $parent_category->id;
907 $this->parent_category =& $parent_category;
b3ac6c3e 908 $this->path = null; // remove old path and depth - will be recalculated in update()
f8e6e4db 909 $this->depth = null; // remove old path and depth - will be recalculated in update()
910 $this->update($source);
b3ac6c3e 911
15b462da 912 return $this->update($source);
b3ac6c3e 913 }
914
915 /**
916 * Returns the final values for this grade category.
917 * @param int $userid Optional: to retrieve a single final grade
918 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
919 */
920 function get_final($userid=NULL) {
921 $this->load_grade_item();
922 return $this->grade_item->get_final($userid);
0fc7f624 923 }
4a490db0 924
0fc7f624 925 /**
4a490db0 926 * Returns the sortorder of the associated grade_item. This method is also available in
5fad5061 927 * grade_item, for cases where the object type is not known.
0fc7f624 928 * @return int Sort order
929 */
930 function get_sortorder() {
b3ac6c3e 931 $this->load_grade_item();
932 return $this->grade_item->get_sortorder();
0fc7f624 933 }
934
935 /**
b3ac6c3e 936 * Sets sortorder variable for this category.
4a490db0 937 * This method is also available in grade_item, for cases where the object type is not know.
0fc7f624 938 * @param int $sortorder
939 * @return void
940 */
941 function set_sortorder($sortorder) {
b3ac6c3e 942 $this->load_grade_item();
943 $this->grade_item->set_sortorder($sortorder);
944 }
945
6639ead3 946 /**
947 * Move this category after the given sortorder - does not change the parent
948 * @param int $sortorder to place after
949 */
f13002d5 950 function move_after_sortorder($sortorder) {
951 $this->load_grade_item();
952 $this->grade_item->move_after_sortorder($sortorder);
953 }
954
b3ac6c3e 955 /**
f13002d5 956 * Return true if this is the top most category that represents the total course grade.
b3ac6c3e 957 * @return boolean
958 */
959 function is_course_category() {
960 $this->load_grade_item();
961 return $this->grade_item->is_course_item();
962 }
963
964 /**
965 * Return the top most course category.
966 * @static
967 * @return object grade_category instance for course grade
968 */
969 function fetch_course_category($courseid) {
970
971 // course category has no parent
972 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
973 return $course_category;
974 }
975
976 // create a new one
977 $course_category = new grade_category();
978 $course_category->insert_course_category($courseid);
979
980 return $course_category;
0fc7f624 981 }
4a490db0 982
79eabc2a 983 /**
984 * Is grading object editable?
985 * @return boolean
986 */
987 function is_editable() {
988 return true;
989 }
990
5fad5061 991 /**
4a490db0 992 * Returns the locked state/date of the associated grade_item. This method is also available in
993 * grade_item, for cases where the object type is not known.
22e23c78 994 * @return boolean
5fad5061 995 */
2cc4b0f9 996 function is_locked() {
5fad5061 997 $this->load_grade_item();
22e23c78 998 return $this->grade_item->is_locked();
5fad5061 999 }
1000
1001 /**
1002 * Sets the grade_item's locked variable and updates the grade_item.
1003 * Method named after grade_item::set_locked().
1004 * @param int $locked 0, 1 or a timestamp int(10) after which date the item will be locked.
9580a21f 1005 * @return boolean success if category locked (not all children mayb be locked though)
5fad5061 1006 */
2cc4b0f9 1007 function set_locked($lockedstate) {
5fad5061 1008 $this->load_grade_item();
b121b544 1009 $result = $this->grade_item->set_locked($lockedstate);
7a7a53d3 1010 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
1011 foreach($children as $child) {
2a8c101f 1012 $child->set_locked($lockedstate);
7a7a53d3 1013 }
1014 }
1015 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
1016 foreach($children as $child) {
2a8c101f 1017 $child->set_locked($lockedstate);
7a7a53d3 1018 }
1019 }
b121b544 1020 return $result;
5fad5061 1021 }
4a490db0 1022
5fad5061 1023 /**
4a490db0 1024 * Returns the hidden state/date of the associated grade_item. This method is also available in
22e23c78 1025 * grade_item.
1026 * @return boolean
5fad5061 1027 */
22e23c78 1028 function is_hidden() {
5fad5061 1029 $this->load_grade_item();
22e23c78 1030 return $this->grade_item->is_hidden();
5fad5061 1031 }
1032
1033 /**
4a490db0 1034 * Sets the grade_item's hidden variable and updates the grade_item.
5fad5061 1035 * Method named after grade_item::set_hidden().
1036 * @param int $hidden 0, 1 or a timestamp int(10) after which date the item will be hidden.
1037 * @return void
1038 */
1039 function set_hidden($hidden) {
1040 $this->load_grade_item();
22e23c78 1041 $this->grade_item->set_hidden($hidden);
f13002d5 1042 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
1043 foreach($children as $child) {
1044 $child->set_hidden($hidden);
1045 }
1046 }
1047 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
1048 foreach($children as $child) {
1049 $child->set_hidden($hidden);
1050 }
1051 }
5fad5061 1052 }
1053
4a490db0 1054}
8a31e65c 1055?>