MDL-12114 Fixed typo in elements array.
[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);
162 var_dump($parent);
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) {
0758a08e 477 if (!is_null($oldgrade->finalgrade)) {
478 // we need proper floats here for !== comparison later
f1ad9e04 479 $oldfinalgrade = (float)$oldgrade->finalgrade;
0758a08e 480 }
4fc9ec1e 481 $grade = $this->get_instance('grade_grade', $oldgrade, false);
f8e6e4db 482 $grade->grade_item =& $this->grade_item;
b8ff92b6 483
f8e6e4db 484 } else {
485 // insert final grade - it will be needed later anyway
4fc9ec1e 486 $grade = $this->get_instance('grade_grade', array('itemid'=>$this->grade_item->id, 'userid'=>$userid), false);
f8e6e4db 487 $grade->grade_item =& $this->grade_item;
f1ad9e04 488 $grade->insert('system');
489 $oldfinalgrade = null;
f8e6e4db 490 }
f1ad9e04 491
c86caae7 492 // no need to recalculate locked or overridden grades
493 if ($grade->is_locked() or $grade->is_overridden()) {
2cc4b0f9 494 return;
ac9b0805 495 }
496
f8e6e4db 497 // can not use own final category grade in calculation
9580a21f 498 unset($grade_values[$this->grade_item->id]);
f8e6e4db 499
f1ad9e04 500
501 /// sum is a special aggregation types - it adjusts the min max, does not use relative values
502 if ($this->aggregation == GRADE_AGGREGATE_SUM) {
503 $this->sum_grades($grade, $oldfinalgrade, $items, $grade_values, $excluded);
504 return;
505 }
506
0758a08e 507 // if no grades calculation possible or grading not allowed clear final grade
9580a21f 508 if (empty($grade_values) or empty($items) or ($this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE)) {
f8e6e4db 509 $grade->finalgrade = null;
f1ad9e04 510 if ($grade->finalgrade !== $oldfinalgrade) {
0758a08e 511 $grade->update('aggregation');
f8e6e4db 512 }
b8ff92b6 513 return;
514 }
0758a08e 515
f8e6e4db 516 /// normalize the grades first - all will have value 0...1
d5f0aa01 517 // ungraded items are not used in aggregation
23207a1a 518 foreach ($grade_values as $itemid=>$v) {
b8ff92b6 519 if (is_null($v)) {
520 // null means no grade
23207a1a 521 unset($grade_values[$itemid]);
522 continue;
523 } else if (in_array($itemid, $excluded)) {
524 unset($grade_values[$itemid]);
b8ff92b6 525 continue;
0aa32279 526 }
9a68cffc 527 $grade_values[$itemid] = grade_grade::standardise_score($v, $items[$itemid]->grademin, $items[$itemid]->grademax, 0, 1);
0aa32279 528 }
dda0c7e6 529
eacd3700 530 // use min grade if grade missing for these types
c2efb501 531 if (!$this->aggregateonlygraded) {
532 foreach($items as $itemid=>$value) {
533 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
534 $grade_values[$itemid] = 0;
eacd3700 535 }
c2efb501 536 }
eacd3700 537 }
538
539 // limit and sort
9580a21f 540 $this->apply_limit_rules($grade_values);
541 asort($grade_values, SORT_NUMERIC);
4a490db0 542
d5f0aa01 543 // let's see we have still enough grades to do any statistics
9580a21f 544 if (count($grade_values) == 0) {
ac9b0805 545 // not enough attempts yet
f8e6e4db 546 $grade->finalgrade = null;
f1ad9e04 547 if ($grade->finalgrade !== $oldfinalgrade) {
0758a08e 548 $grade->update('aggregation');
b8ff92b6 549 }
550 return;
551 }
2df71235 552
d297269d 553 // do the maths
554 $agg_grade = $this->aggregate_values($grade_values, $items);
555
0758a08e 556 // recalculate the grade back to requested range
9a68cffc 557 $finalgrade = grade_grade::standardise_score($agg_grade, 0, 1, $this->grade_item->grademin, $this->grade_item->grademax);
d297269d 558
f1ad9e04 559 if (is_null($finalgrade)) {
560 $grade->finalgrade = null;
d297269d 561 } else {
f1ad9e04 562 $grade->finalgrade = (float)bounded_number($this->grade_item->grademin, $finalgrade, $this->grade_item->grademax);
d297269d 563 }
564
565 // update in db if changed
f1ad9e04 566 if ($grade->finalgrade !== $oldfinalgrade) {
0758a08e 567 $grade->update('aggregation');
d297269d 568 }
569
570 return;
571 }
572
89a5f827 573 /**
574 * Internal function - aggregation maths.
575 */
d297269d 576 function aggregate_values($grade_values, $items) {
b8ff92b6 577 switch ($this->aggregation) {
c2efb501 578 case GRADE_AGGREGATE_MEDIAN: // Middle point value in the set: ignores frequencies
9580a21f 579 $num = count($grade_values);
c186c7b2 580 $grades = array_values($grade_values);
581 if ($num % 2 == 0) {
9c8d38fa 582 $agg_grade = ($grades[intval($num/2)-1] + $grades[intval($num/2)]) / 2;
b8ff92b6 583 } else {
9c8d38fa 584 $agg_grade = $grades[intval(($num/2)-0.5)];
b8ff92b6 585 }
586 break;
ac9b0805 587
c2efb501 588 case GRADE_AGGREGATE_MIN:
9c8d38fa 589 $agg_grade = reset($grade_values);
b8ff92b6 590 break;
591
c2efb501 592 case GRADE_AGGREGATE_MAX:
9c8d38fa 593 $agg_grade = array_pop($grade_values);
b8ff92b6 594 break;
595
c2efb501 596 case GRADE_AGGREGATE_MODE: // the most common value, average used if multimode
9580a21f 597 $freq = array_count_values($grade_values);
95affb8a 598 arsort($freq); // sort by frequency keeping keys
599 $top = reset($freq); // highest frequency count
600 $modes = array_keys($freq, $top); // search for all modes (have the same highest count)
601 rsort($modes, SORT_NUMERIC); // get highes mode
9c8d38fa 602 $agg_grade = reset($modes);
d5fab31f 603 break;
95affb8a 604
c2efb501 605 case GRADE_AGGREGATE_WEIGHTED_MEAN: // Weighted average of all existing final grades
9580a21f 606 $weightsum = 0;
607 $sum = 0;
eacd3700 608 foreach($grade_values as $itemid=>$grade_value) {
609 if ($items[$itemid]->aggregationcoef <= 0) {
9580a21f 610 continue;
611 }
eacd3700 612 $weightsum += $items[$itemid]->aggregationcoef;
613 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 614 }
615 if ($weightsum == 0) {
9c8d38fa 616 $agg_grade = null;
9580a21f 617 } else {
9c8d38fa 618 $agg_grade = $sum / $weightsum;
9580a21f 619 }
620 break;
621
c2efb501 622 case GRADE_AGGREGATE_EXTRACREDIT_MEAN: // special average
9580a21f 623 $num = 0;
624 $sum = 0;
eacd3700 625 foreach($grade_values as $itemid=>$grade_value) {
626 if ($items[$itemid]->aggregationcoef == 0) {
9580a21f 627 $num += 1;
628 $sum += $grade_value;
eacd3700 629 } else if ($items[$itemid]->aggregationcoef > 0) {
630 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 631 }
632 }
633 if ($num == 0) {
9c8d38fa 634 $agg_grade = $sum; // only extra credits or wrong coefs
9580a21f 635 } else {
9c8d38fa 636 $agg_grade = $sum / $num;
9580a21f 637 }
638 break;
639
c2efb501 640 case GRADE_AGGREGATE_MEAN: // Arithmetic average of all grade items (if ungraded aggregated, NULL counted as minimum)
ac9b0805 641 default:
9580a21f 642 $num = count($grade_values);
643 $sum = array_sum($grade_values);
9c8d38fa 644 $agg_grade = $sum / $num;
b8ff92b6 645 break;
646 }
647
d297269d 648 return $agg_grade;
0aa32279 649 }
0758a08e 650
0758a08e 651 /**
652 * internal function for category grades summing
653 *
f1ad9e04 654 * @param object $grade
0758a08e 655 * @param int $userid
f1ad9e04 656 * @param float $oldfinalgrade
0758a08e 657 * @param array $items
658 * @param array $grade_values
0758a08e 659 * @param bool $excluded
660 * @return boolean (just plain return;)
661 */
f1ad9e04 662 function sum_grades(&$grade, $oldfinalgrade, $items, $grade_values, $excluded) {
0758a08e 663 // ungraded and exluded items are not used in aggregation
664 foreach ($grade_values as $itemid=>$v) {
665 if (is_null($v)) {
666 unset($grade_values[$itemid]);
667 } else if (in_array($itemid, $excluded)) {
668 unset($grade_values[$itemid]);
669 }
670 }
671
672 $max = 0;
673
674 //find max grade
675 foreach ($items as $item) {
676 if ($item->gradetype != GRADE_TYPE_VALUE) {
677 continue; // sum only items with value grades, no scales and outcomes!
678 }
679 $max += $item->grademax;
680 }
681
682 if ($this->grade_item->grademax != $max or $this->grade_item->grademin != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE){
683 $this->grade_item->grademax = $max;
684 $this->grade_item->grademin = 0;
685 $this->grade_item->gradetype = GRADE_TYPE_VALUE;
686 $this->grade_item->update('aggregation');
687 }
688
689 $this->apply_limit_rules($grade_values);
690
691 $sum = array_sum($grade_values);
f1ad9e04 692 $grade->finalgrade = (float)bounded_number($this->grade_item->grademin, $sum, $this->grade_item->grademax);
0758a08e 693
694 // update in db if changed
f1ad9e04 695 if ($grade->finalgrade !== $oldfinalgrade) {
0758a08e 696 $grade->update('aggregation');
697 }
698
699 return;
700 }
701
adc2f286 702 /**
703 * Given an array of grade values (numerical indices), applies droplow or keephigh
704 * rules to limit the final array.
9580a21f 705 * @param array $grade_values
adc2f286 706 * @return array Limited grades.
707 */
9580a21f 708 function apply_limit_rules(&$grade_values) {
709 arsort($grade_values, SORT_NUMERIC);
adc2f286 710 if (!empty($this->droplow)) {
711 for ($i = 0; $i < $this->droplow; $i++) {
9580a21f 712 array_pop($grade_values);
adc2f286 713 }
4a490db0 714 } elseif (!empty($this->keephigh)) {
9580a21f 715 while (count($grade_values) > $this->keephigh) {
716 array_pop($grade_values);
adc2f286 717 }
718 }
0aa32279 719 }
720
9580a21f 721
722 /**
723 * Returns true if category uses special aggregation coeficient
724 * @return boolean true if coeficient used
725 */
726 function is_aggregationcoef_used() {
c2efb501 727 return ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN
728 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN);
ba74762b 729
9580a21f 730 }
731
1c307f21 732 /**
b3ac6c3e 733 * Returns tree with all grade_items and categories as elements
734 * @static
735 * @param int $courseid
b3ac6c3e 736 * @param boolean $include_category_items as category children
737 * @return array
1c307f21 738 */
938e00b6 739 function fetch_course_tree($courseid, $include_category_items=false) {
aaefeda4 740 $obj = grade_object::get_instance('grade_category');
4fc9ec1e 741 $course_category = $obj->fetch_course_category($courseid);
514a3467 742 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
743 'children'=>$course_category->get_children($include_category_items));
744 $sortorder = 1;
745 $course_category->set_sortorder($sortorder);
746 $course_category->sortorder = $sortorder;
4fc9ec1e 747 return $obj->_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 748 }
749
b3ac6c3e 750 function _fetch_course_tree_recursion($category_array, &$sortorder) {
751 // update the sortorder in db if needed
752 if ($category_array['object']->sortorder != $sortorder) {
753 $category_array['object']->set_sortorder($sortorder);
ce385eb4 754 }
ce385eb4 755
314c4336 756 // store the grade_item or grade_category instance with extra info
757 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 758
759 // reuse final grades if there
760 if (array_key_exists('finalgrades', $category_array)) {
761 $result['finalgrades'] = $category_array['finalgrades'];
762 }
763
764 // recursively resort children
765 if (!empty($category_array['children'])) {
766 $result['children'] = array();
29d509f5 767 //process the category item first
768 $cat_item_id = null;
b3ac6c3e 769 foreach($category_array['children'] as $oldorder=>$child_array) {
314c4336 770 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
4fc9ec1e 771 $result['children'][$sortorder] = $this->_fetch_course_tree_recursion($child_array, $sortorder);
29d509f5 772 }
2b0f65e2 773 }
29d509f5 774 foreach($category_array['children'] as $oldorder=>$child_array) {
775 if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
4fc9ec1e 776 $result['children'][++$sortorder] = $this->_fetch_course_tree_recursion($child_array, $sortorder);
b3ac6c3e 777 }
778 }
779 }
780
781 return $result;
ce385eb4 782 }
7c8a963f 783
784 /**
4a490db0 785 * Fetches and returns all the children categories and/or grade_items belonging to this category.
786 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 787 * as well as all levels (0). The elements are indexed by sort order.
7c8a963f 788 * @return array Array of child objects (grade_category and grade_item).
789 */
938e00b6 790 function get_children($include_category_items=false) {
b3ac6c3e 791
792 // This function must be as fast as possible ;-)
793 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
794 // we have to limit the number of queries though, because it will be used often in grade reports
795
4fc9ec1e 796 $cats = $this->lib_wrapper->get_records('grade_categories', 'courseid', $this->courseid);
797 $items = $this->lib_wrapper->get_records('grade_items', 'courseid', $this->courseid);
4a490db0 798
b3ac6c3e 799 // init children array first
800 foreach ($cats as $catid=>$cat) {
801 $cats[$catid]->children = array();
27f95e9b 802 }
4a490db0 803
b3ac6c3e 804 //first attach items to cats and add category sortorder
805 foreach ($items as $item) {
806 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
807 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 808
b3ac6c3e 809 if (!$include_category_items) {
810 continue;
811 }
812 $categoryid = $item->iteminstance;
813 } else {
814 $categoryid = $item->categoryid;
815 }
816
817 // prevent problems with duplicate sortorders in db
818 $sortorder = $item->sortorder;
819 while(array_key_exists($sortorder, $cats[$categoryid]->children)) {
f13002d5 820 //debugging("$sortorder exists in item loop");
b3ac6c3e 821 $sortorder++;
822 }
823
824 $cats[$categoryid]->children[$sortorder] = $item;
825
826 }
827
828 // now find the requested category and connect categories as children
829 $category = false;
830 foreach ($cats as $catid=>$cat) {
831 if (!empty($cat->parent)) {
832 // prevent problems with duplicate sortorders in db
833 $sortorder = $cat->sortorder;
834 while(array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 835 //debugging("$sortorder exists in cat loop");
b3ac6c3e 836 $sortorder++;
837 }
838
839 $cats[$cat->parent]->children[$sortorder] = $cat;
840 }
b3ac6c3e 841 if ($catid == $this->id) {
842 $category = &$cats[$catid];
843 }
844 }
845
846 unset($items); // not needed
847 unset($cats); // not needed
848
4fc9ec1e 849 $children_array = $this->_get_children_recursion($category);
b3ac6c3e 850
851 ksort($children_array);
852
853 return $children_array;
854
855 }
856
938e00b6 857 function _get_children_recursion($category) {
b3ac6c3e 858
859 $children_array = array();
860 foreach($category->children as $sortorder=>$child) {
861 if (array_key_exists('itemtype', $child)) {
4fc9ec1e 862 $grade_item = $this->get_instance('grade_item', $child, false);
4faf5f99 863 if (in_array($grade_item->itemtype, array('course', 'category'))) {
864 $type = $grade_item->itemtype.'item';
865 $depth = $category->depth;
314c4336 866 } else {
867 $type = 'item';
868 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 869 }
4faf5f99 870 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 871
7c8a963f 872 } else {
4fc9ec1e 873 $children = $this->_get_children_recursion($child);
874 $grade_category = $this->get_instance('grade_category', $child, false);
b3ac6c3e 875 if (empty($children)) {
314c4336 876 $children = array();
7c8a963f 877 }
4faf5f99 878 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
314c4336 879 }
27f95e9b 880 }
881
b3ac6c3e 882 // sort the array
883 ksort($children_array);
884
27f95e9b 885 return $children_array;
886 }
4a490db0 887
f151b073 888 /**
ab53054f 889 * Uses get_grade_item to load or create a grade_item, then saves it as $this->grade_item.
f151b073 890 * @return object Grade_item
891 */
892 function load_grade_item() {
ac9b0805 893 if (empty($this->grade_item)) {
894 $this->grade_item = $this->get_grade_item();
895 }
ab53054f 896 return $this->grade_item;
897 }
4a490db0 898
ab53054f 899 /**
900 * Retrieves from DB and instantiates the associated grade_item object.
901 * If no grade_item exists yet, create one.
902 * @return object Grade_item
903 */
904 function get_grade_item() {
c91ed4be 905 if (empty($this->id)) {
906 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
907 return false;
908 }
909
b3ac6c3e 910 if (empty($this->parent)) {
911 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
912
913 } else {
914 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
915 }
4fc9ec1e 916
aaefeda4 917 $grade_item = grade_object::get_instance('grade_item');
f92dcad8 918
4fc9ec1e 919 if (!$grade_items = $grade_item->fetch_all($params)) {
b8ff92b6 920 // create a new one
4fc9ec1e 921 $grade_item = $this->get_instance('grade_item', $params, false);
b8ff92b6 922 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 923 $grade_item->insert('system');
4a490db0 924
b8ff92b6 925 } else if (count($grade_items) == 1){
926 // found existing one
927 $grade_item = reset($grade_items);
4a490db0 928
b8ff92b6 929 } else {
930 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 931 // return first one
932 $grade_item = reset($grade_items);
2c72af1f 933 }
934
ab53054f 935 return $grade_item;
f151b073 936 }
8c846243 937
938 /**
939 * Uses $this->parent to instantiate $this->parent_category based on the
940 * referenced record in the DB.
941 * @return object Parent_category
942 */
943 function load_parent_category() {
944 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 945 $this->parent_category = $this->get_parent_category();
8c846243 946 }
947 return $this->parent_category;
4a490db0 948 }
949
ab53054f 950 /**
951 * Uses $this->parent to instantiate and return a grade_category object.
952 * @return object Parent_category
953 */
954 function get_parent_category() {
955 if (!empty($this->parent)) {
4fc9ec1e 956 $parent_category = $this->get_instance('grade_category', array('id' => $this->parent));
4a490db0 957 return $parent_category;
ab53054f 958 } else {
959 return null;
960 }
961 }
962
2186f72c 963 /**
4a490db0 964 * Returns the most descriptive field for this object. This is a standard method used
2186f72c 965 * when we do not know the exact type of an object.
966 * @return string name
967 */
968 function get_name() {
314c4336 969 if (empty($this->parent)) {
4fc9ec1e 970 $course = $this->lib_wrapper->get_record('course', 'id', $this->courseid);
410753fb 971 return format_string($course->fullname);
314c4336 972 } else {
973 return $this->fullname;
974 }
2186f72c 975 }
c91ed4be 976
0fc7f624 977 /**
978 * Sets this category's parent id. A generic method shared by objects that have a parent id of some kind.
f13002d5 979 * @param int parentid
980 * @return boolean success
0fc7f624 981 */
f8e6e4db 982 function set_parent($parentid, $source=null) {
f13002d5 983 if ($this->parent == $parentid) {
984 return true;
985 }
986
987 if ($parentid == $this->id) {
988 error('Can not assign self as parent!');
989 }
990
991 if (empty($this->parent) and $this->is_course_category()) {
992 error('Course category can not have parent!');
b3ac6c3e 993 }
f13002d5 994
995 // find parent and check course id
aaefeda4 996 $obj = grade_object::get_instance('grade_category');
997 if (!$parent_category = $obj->fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 998 return false;
999 }
1000
f8e6e4db 1001 $this->force_regrading();
b3ac6c3e 1002
1003 // set new parent category
f8e6e4db 1004 $this->parent = $parent_category->id;
1005 $this->parent_category =& $parent_category;
b3ac6c3e 1006 $this->path = null; // remove old path and depth - will be recalculated in update()
f8e6e4db 1007 $this->depth = null; // remove old path and depth - will be recalculated in update()
1008 $this->update($source);
b3ac6c3e 1009
15b462da 1010 return $this->update($source);
b3ac6c3e 1011 }
1012
1013 /**
1014 * Returns the final values for this grade category.
1015 * @param int $userid Optional: to retrieve a single final grade
1016 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
1017 */
1018 function get_final($userid=NULL) {
1019 $this->load_grade_item();
1020 return $this->grade_item->get_final($userid);
0fc7f624 1021 }
4a490db0 1022
0fc7f624 1023 /**
4a490db0 1024 * Returns the sortorder of the associated grade_item. This method is also available in
5fad5061 1025 * grade_item, for cases where the object type is not known.
0fc7f624 1026 * @return int Sort order
1027 */
1028 function get_sortorder() {
b3ac6c3e 1029 $this->load_grade_item();
1030 return $this->grade_item->get_sortorder();
0fc7f624 1031 }
1032
be7c0693 1033 /**
1034 * Returns the idnumber of the associated grade_item. This method is also available in
1035 * grade_item, for cases where the object type is not known.
1036 * @return string idnumber
1037 */
1038 function get_idnumber() {
1039 $this->load_grade_item();
1040 return $this->grade_item->get_idnumber();
1041 }
1042
0fc7f624 1043 /**
b3ac6c3e 1044 * Sets sortorder variable for this category.
4a490db0 1045 * This method is also available in grade_item, for cases where the object type is not know.
0fc7f624 1046 * @param int $sortorder
1047 * @return void
1048 */
1049 function set_sortorder($sortorder) {
b3ac6c3e 1050 $this->load_grade_item();
1051 $this->grade_item->set_sortorder($sortorder);
1052 }
1053
6639ead3 1054 /**
1055 * Move this category after the given sortorder - does not change the parent
1056 * @param int $sortorder to place after
1057 */
f13002d5 1058 function move_after_sortorder($sortorder) {
1059 $this->load_grade_item();
1060 $this->grade_item->move_after_sortorder($sortorder);
1061 }
1062
b3ac6c3e 1063 /**
f13002d5 1064 * Return true if this is the top most category that represents the total course grade.
b3ac6c3e 1065 * @return boolean
1066 */
1067 function is_course_category() {
1068 $this->load_grade_item();
1069 return $this->grade_item->is_course_item();
1070 }
1071
1072 /**
1073 * Return the top most course category.
1074 * @static
1075 * @return object grade_category instance for course grade
1076 */
1077 function fetch_course_category($courseid) {
1078
1079 // course category has no parent
aaefeda4 1080 $obj = grade_object::get_instance('grade_category');
1081 if ($course_category = $obj->fetch(array('courseid'=>$courseid, 'parent'=>null))) {
b3ac6c3e 1082 return $course_category;
1083 }
1084
1085 // create a new one
aaefeda4 1086 $course_category = grade_object::get_instance('grade_category');
b3ac6c3e 1087 $course_category->insert_course_category($courseid);
1088
1089 return $course_category;
0fc7f624 1090 }
4fc9ec1e 1091
79eabc2a 1092 /**
1093 * Is grading object editable?
1094 * @return boolean
1095 */
1096 function is_editable() {
1097 return true;
1098 }
1099
5fad5061 1100 /**
4a490db0 1101 * Returns the locked state/date of the associated grade_item. This method is also available in
1102 * grade_item, for cases where the object type is not known.
22e23c78 1103 * @return boolean
5fad5061 1104 */
2cc4b0f9 1105 function is_locked() {
5fad5061 1106 $this->load_grade_item();
22e23c78 1107 return $this->grade_item->is_locked();
5fad5061 1108 }
1109
1110 /**
1111 * Sets the grade_item's locked variable and updates the grade_item.
1112 * Method named after grade_item::set_locked().
1113 * @param int $locked 0, 1 or a timestamp int(10) after which date the item will be locked.
fb0e3570 1114 * @param boolean $cascade lock/unlock child objects too
2b0f65e2 1115 * @param boolean $refresh refresh grades when unlocking
9580a21f 1116 * @return boolean success if category locked (not all children mayb be locked though)
5fad5061 1117 */
fb0e3570 1118 function set_locked($lockedstate, $cascade=false, $refresh=true) {
5fad5061 1119 $this->load_grade_item();
2b0f65e2 1120
fb0e3570 1121 $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
1122
1123 if ($cascade) {
1124 //process all children - items and categories
aaefeda4 1125 $grade_item = grade_object::get_instance('grade_item');
9a68cffc 1126 var_dump($grade_item);
4fc9ec1e 1127 if ($children = $grade_item->fetch_all(array('categoryid'=>$this->id))) {
fb0e3570 1128 foreach($children as $child) {
1129 $child->set_locked($lockedstate, true, false);
1130 if (empty($lockedstate) and $refresh) {
1131 //refresh when unlocking
1132 $child->refresh_grades();
1133 }
2b0f65e2 1134 }
7a7a53d3 1135 }
aaefeda4 1136 $obj = grade_object::get_instance('grade_category');
1137 if ($children = $obj->fetch_all(array('parent'=>$this->id))) {
fb0e3570 1138 foreach($children as $child) {
1139 $child->set_locked($lockedstate, true, true);
1140 }
7a7a53d3 1141 }
1142 }
2b0f65e2 1143
b121b544 1144 return $result;
5fad5061 1145 }
4a490db0 1146
5fad5061 1147 /**
4a490db0 1148 * Returns the hidden state/date of the associated grade_item. This method is also available in
22e23c78 1149 * grade_item.
1150 * @return boolean
5fad5061 1151 */
22e23c78 1152 function is_hidden() {
5fad5061 1153 $this->load_grade_item();
22e23c78 1154 return $this->grade_item->is_hidden();
5fad5061 1155 }
1156
597f50e6 1157 /**
1158 * Check grade hidden status. Uses data from both grade item and grade.
1159 * @return boolean true if hiddenuntil, false if not
1160 */
1161 function is_hiddenuntil() {
1162 $this->load_grade_item();
1163 return $this->grade_item->is_hiddenuntil();
1164 }
1165
5fad5061 1166 /**
4a490db0 1167 * Sets the grade_item's hidden variable and updates the grade_item.
5fad5061 1168 * Method named after grade_item::set_hidden().
1169 * @param int $hidden 0, 1 or a timestamp int(10) after which date the item will be hidden.
f60c61b1 1170 * @param boolean $cascade apply to child objects too
5fad5061 1171 * @return void
1172 */
f60c61b1 1173 function set_hidden($hidden, $cascade=false) {
5fad5061 1174 $this->load_grade_item();
22e23c78 1175 $this->grade_item->set_hidden($hidden);
f60c61b1 1176 if ($cascade) {
aaefeda4 1177 $grade_item = grade_object::get_instance('grade_item');
4fc9ec1e 1178 if ($children = $grade_item->fetch_all(array('categoryid'=>$this->id))) {
f60c61b1 1179 foreach($children as $child) {
1180 $child->set_hidden($hidden, $cascade);
1181 }
f13002d5 1182 }
aaefeda4 1183 $obj = grade_object::get_instance('grade_category');
1184 if ($children = $obj->fetch_all(array('parent'=>$this->id))) {
f60c61b1 1185 foreach($children as $child) {
1186 $child->set_hidden($hidden, $cascade);
1187 }
f13002d5 1188 }
1189 }
5fad5061 1190 }
89a5f827 1191
1192 /**
1193 * Applies forced settings on this category
1194 * @return bool true if anything changed
1195 */
1196 function apply_forced_settings() {
1197 global $CFG;
1198
1199 $updated = false;
1200 foreach ($this->forceable as $property) {
1201 if (isset($CFG->{"grade_$property"}) and $CFG->{"grade_$property"} != -1) {
1202 $this->$property = $CFG->{"grade_$property"};
1203 $updated = true;
1204 }
1205 }
1206
1207 return $updated;
1208 }
1209
1210 /**
1211 * Notification of change in forced category settings.
1212 * @static
1213 */
1214 function updated_forced_settings() {
1215 global $CFG;
1216 $sql = "UPDATE {$CFG->prefix}grade_items SET needsupdate=1 WHERE itemtype='course' or itemtype='category'";
4fc9ec1e 1217 $this->lib_wrapper->execute_sql($sql, false);
89a5f827 1218 }
4a490db0 1219}
8a31e65c 1220?>