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