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