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