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