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