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