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