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