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