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