Fixed tabindex feature
[moodle.git] / lib / grade / grade_category.php
CommitLineData
8a31e65c 1<?php // $Id$
2
3///////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Modular Object-Oriented Dynamic Learning Environment //
8// http://moodle.com //
9// //
b7064779 10// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
8a31e65c 11// //
12// This program is free software; you can redistribute it and/or modify //
13// it under the terms of the GNU General Public License as published by //
14// the Free Software Foundation; either version 2 of the License, or //
15// (at your option) any later version. //
16// //
17// This program is distributed in the hope that it will be useful, //
18// but WITHOUT ANY WARRANTY; without even the implied warranty of //
19// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20// GNU General Public License for more details: //
21// //
22// http://www.gnu.org/copyleft/gpl.html //
23// //
24///////////////////////////////////////////////////////////////////////////
25
26require_once('grade_object.php');
27
3058964f 28class grade_category extends grade_object {
8a31e65c 29 /**
7c8a963f 30 * The DB table.
8a31e65c 31 * @var string $table
32 */
33 var $table = 'grade_categories';
4a490db0 34
8a31e65c 35 /**
3f2b0c8a 36 * Array of required table fields, must start with 'id'.
37 * @var array $required_fields
8a31e65c 38 */
3f2b0c8a 39 var $required_fields = array('id', 'courseid', 'parent', 'depth', 'path', 'fullname', 'aggregation',
40 'keephigh', 'droplow', 'aggregateonlygraded', 'aggregateoutcomes',
41 'aggregatesubcats', 'timecreated', 'timemodified');
4a490db0 42
8a31e65c 43 /**
44 * The course this category belongs to.
45 * @var int $courseid
46 */
47 var $courseid;
4a490db0 48
8a31e65c 49 /**
50 * The category this category belongs to (optional).
4a490db0 51 * @var int $parent
8a31e65c 52 */
e5c674f1 53 var $parent;
4a490db0 54
8c846243 55 /**
56 * The grade_category object referenced by $this->parent (PK).
57 * @var object $parent_category
58 */
59 var $parent_category;
27f95e9b 60
e5c674f1 61 /**
62 * The number of parents this category has.
63 * @var int $depth
64 */
65 var $depth = 0;
66
67 /**
c2efb501 68 * Shows the hierarchical path for this category as /1/2/3/ (like course_categories), the last number being
e5c674f1 69 * this category's autoincrement ID number.
70 * @var string $path
71 */
72 var $path;
73
8a31e65c 74 /**
75 * The name of this category.
76 * @var string $fullname
77 */
78 var $fullname;
4a490db0 79
8a31e65c 80 /**
81 * A constant pointing to one of the predefined aggregation strategies (none, mean, median, sum etc) .
4a490db0 82 * @var int $aggregation
8a31e65c 83 */
c2efb501 84 var $aggregation = GRADE_AGGREGATE_MEAN;
4a490db0 85
8a31e65c 86 /**
87 * Keep only the X highest items.
88 * @var int $keephigh
89 */
f92dcad8 90 var $keephigh = 0;
4a490db0 91
8a31e65c 92 /**
93 * Drop the X lowest items.
94 * @var int $droplow
95 */
f92dcad8 96 var $droplow = 0;
4a490db0 97
c2efb501 98 /**
99 * Aggregate only graded items
100 * @var int $aggregateonlygraded
101 */
102 var $aggregateonlygraded = 0;
103
29d509f5 104 /**
105 * Aggregate outcomes together with normal items
c2efb501 106 * @var int $aggregateoutcomes
29d509f5 107 */
108 var $aggregateoutcomes = 0;
109
c2efb501 110 /**
111 * Ignore subcategories when aggregating
112 * @var int $aggregatesubcats
113 */
114 var $aggregatesubcats = 0;
115
8a31e65c 116 /**
117 * Array of grade_items or grade_categories nested exactly 1 level below this category
118 * @var array $children
119 */
120 var $children;
8a31e65c 121
7c8a963f 122 /**
4a490db0 123 * A hierarchical array of all children below this category. This is stored separately from
7c8a963f 124 * $children because it is more memory-intensive and may not be used as often.
125 * @var array $all_children
126 */
127 var $all_children;
128
f151b073 129 /**
130 * An associated grade_item object, with itemtype=category, used to calculate and cache a set of grade values
131 * for this category.
132 * @var object $grade_item
133 */
134 var $grade_item;
135
b3ac6c3e 136 /**
137 * Temporary sortorder for speedup of children resorting
138 */
139 var $sortorder;
140
e5c674f1 141 /**
142 * Builds this category's path string based on its parents (if any) and its own id number.
143 * This is typically done just before inserting this object in the DB for the first time,
ce385eb4 144 * or when a new parent is added or changed. It is a recursive function: once the calling
145 * object no longer has a parent, the path is complete.
146 *
147 * @static
148 * @param object $grade_category
149 * @return int The depth of this category (2 means there is one parent)
e5c674f1 150 */
ce385eb4 151 function build_path($grade_category) {
152 if (empty($grade_category->parent)) {
c2efb501 153 return '/'.$grade_category->id.'/';
ce385eb4 154 } else {
155 $parent = get_record('grade_categories', 'id', $grade_category->parent);
c2efb501 156 return grade_category::build_path($parent).$grade_category->id.'/';
ce385eb4 157 }
e5c674f1 158 }
159
8a31e65c 160 /**
f92dcad8 161 * Finds and returns a grade_category instance based on params.
61c33818 162 * @static
8a31e65c 163 *
f92dcad8 164 * @param array $params associative arrays varname=>value
165 * @return object grade_category instance or false if none found.
166 */
167 function fetch($params) {
b3ac6c3e 168 return grade_object::fetch_helper('grade_categories', 'grade_category', $params);
f92dcad8 169 }
170
171 /**
172 * Finds and returns all grade_category instances based on params.
173 * @static
174 *
175 * @param array $params associative arrays varname=>value
176 * @return array array of grade_category insatnces or false if none found.
177 */
178 function fetch_all($params) {
b3ac6c3e 179 return grade_object::fetch_all_helper('grade_categories', 'grade_category', $params);
ce385eb4 180 }
181
8f4a626d 182 /**
2cc4b0f9 183 * In addition to update() as defined in grade_object, call force_regrading of parent categories, if applicable.
aaff71da 184 * @param string $source from where was the object updated (mod/forum, manual, etc.)
185 * @return boolean success
8f4a626d 186 */
aaff71da 187 function update($source=null) {
b3ac6c3e 188 // load the grade item or create a new one
189 $this->load_grade_item();
190
191 // force recalculation of path;
192 if (empty($this->path)) {
193 $this->path = grade_category::build_path($this);
c2efb501 194 $this->depth = substr_count($this->path, '/') - 1;
4a490db0 195 }
0fc7f624 196
4a490db0 197
b3ac6c3e 198 // Recalculate grades if needed
199 if ($this->qualifies_for_regrading()) {
f8e6e4db 200 $this->force_regrading();
4a490db0 201 }
f8e6e4db 202
203 return parent::update($source);
8f4a626d 204 }
4a490db0 205
8f4a626d 206 /**
2cc4b0f9 207 * If parent::delete() is successful, send force_regrading message to parent category.
aaff71da 208 * @param string $source from where was the object deleted (mod/forum, manual, etc.)
209 * @return boolean success
8f4a626d 210 */
aaff71da 211 function delete($source=null) {
f13002d5 212 $grade_item = $this->load_grade_item();
4a490db0 213
f615fbab 214 if ($this->is_course_category()) {
215 if ($categories = grade_category::fetch_all(array('courseid'=>$this->courseid))) {
216 foreach ($categories as $category) {
217 if ($category->id == $this->id) {
218 continue; // do not delete course category yet
219 }
220 $category->delete($source);
221 }
aaff71da 222 }
2b0f65e2 223
f615fbab 224 if ($items = grade_item::fetch_all(array('courseid'=>$this->courseid))) {
225 foreach ($items as $item) {
226 if ($item->id == $grade_item->id) {
227 continue; // do not delete course item yet
228 }
229 $item->delete($source);
230 }
231 }
232
233 } else {
234 $this->force_regrading();
2b0f65e2 235
f615fbab 236 $parent = $this->load_parent_category();
2b0f65e2 237
f615fbab 238 // Update children's categoryid/parent field first
239 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
240 foreach ($children as $child) {
241 $child->set_parent($parent->id);
242 }
243 }
244 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
245 foreach ($children as $child) {
246 $child->set_parent($parent->id);
247 }
aaff71da 248 }
249 }
f13002d5 250
aaff71da 251 // first delete the attached grade item and grades
252 $grade_item->delete($source);
f13002d5 253
254 // delete category itself
aaff71da 255 return parent::delete($source);
8f4a626d 256 }
4a490db0 257
ce385eb4 258 /**
259 * In addition to the normal insert() defined in grade_object, this method sets the depth
260 * and path for this object, and update the record accordingly. The reason why this must
261 * be done here instead of in the constructor, is that they both need to know the record's
4a490db0 262 * id number, which only gets created at insertion time.
f151b073 263 * This method also creates an associated grade_item if this wasn't done during construction.
aaff71da 264 * @param string $source from where was the object inserted (mod/forum, manual, etc.)
265 * @return int PK ID if successful, false otherwise
ce385eb4 266 */
aaff71da 267 function insert($source=null) {
b3ac6c3e 268
269 if (empty($this->courseid)) {
270 error('Can not insert grade category without course id!');
b8ff92b6 271 }
4a490db0 272
b3ac6c3e 273 if (empty($this->parent)) {
274 $course_category = grade_category::fetch_course_category($this->courseid);
275 $this->parent = $course_category->id;
ce385eb4 276 }
4a490db0 277
b3ac6c3e 278 $this->path = null;
279
aaff71da 280 if (!parent::insert($source)) {
b3ac6c3e 281 debugging("Could not insert this category: " . print_r($this, true));
282 return false;
283 }
284
f8e6e4db 285 $this->force_regrading();
286
b3ac6c3e 287 // build path and depth
aaff71da 288 $this->update($source);
4a490db0 289
aaff71da 290 return $this->id;
b3ac6c3e 291 }
292
f2c88356 293 /**
f615fbab 294 * Internal function - used only from fetch_course_category()
295 * Normal insert() can not be used for course category
296 * @param int $courseid
297 * @return bool success
f2c88356 298 */
b3ac6c3e 299 function insert_course_category($courseid) {
42ff9ce6 300 $this->courseid = $courseid;
d61d8c09 301 $this->fullname = get_string('coursegradecategory', 'grades');
42ff9ce6 302 $this->path = null;
303 $this->parent = null;
c2efb501 304 $this->aggregate = GRADE_AGGREGATE_MEAN;
4a490db0 305
aaff71da 306 if (!parent::insert('system')) {
b3ac6c3e 307 debugging("Could not insert this category: " . print_r($this, true));
308 return false;
f151b073 309 }
4a490db0 310
b3ac6c3e 311 // build path and depth
aaff71da 312 $this->update('system');
b3ac6c3e 313
aaff71da 314 return $this->id;
ce385eb4 315 }
4a490db0 316
8f4a626d 317 /**
318 * Compares the values held by this object with those of the matching record in DB, and returns
319 * whether or not these differences are sufficient to justify an update of all parent objects.
320 * This assumes that this object has an id number and a matching record in DB. If not, it will return false.
321 * @return boolean
322 */
2cc4b0f9 323 function qualifies_for_regrading() {
8f4a626d 324 if (empty($this->id)) {
6639ead3 325 debugging("Can not regrade non existing category");
8f4a626d 326 return false;
327 }
328
6639ead3 329 $db_item = grade_category::fetch(array('id'=>$this->id));
4a490db0 330
c2efb501 331 $aggregationdiff = $db_item->aggregation != $this->aggregation;
332 $keephighdiff = $db_item->keephigh != $this->keephigh;
333 $droplowdiff = $db_item->droplow != $this->droplow;
334 $aggonlygrddiff = $db_item->aggregateonlygraded != $this->aggregateonlygraded;
335 $aggoutcomesdiff = $db_item->aggregateoutcomes != $this->aggregateoutcomes;
336 $aggsubcatsdiff = $db_item->aggregatesubcats != $this->aggregatesubcats;
8f4a626d 337
c2efb501 338 return ($aggregationdiff || $keephighdiff || $droplowdiff || $aggonlygrddiff || $aggoutcomesdiff || $aggsubcatsdiff);
8f4a626d 339 }
8c846243 340
341 /**
f8e6e4db 342 * Marks the category and course item as needing update - categories are always regraded.
343 * @return void
8c846243 344 */
f8e6e4db 345 function force_regrading() {
346 $grade_item = $this->load_grade_item();
347 $grade_item->force_regrading();
8c846243 348 }
349
0aa32279 350 /**
ac9b0805 351 * Generates and saves raw_grades in associated category grade item.
352 * These immediate children must alrady have their own final grades.
353 * The category's aggregation method is used to generate raw grades.
354 *
355 * Please note that category grade is either calculated or aggregated - not both at the same time.
356 *
c86caae7 357 * This method must be used ONLY from grade_item::regrade_final_grades(),
ac9b0805 358 * because the calculation must be done in correct order!
b8ff92b6 359 *
4a490db0 360 * Steps to follow:
ac9b0805 361 * 1. Get final grades from immediate children
2df71235 362 * 3. Aggregate these grades
ac9b0805 363 * 4. Save them in raw grades of associated category grade item
0aa32279 364 */
f8e6e4db 365 function generate_grades($userid=null) {
b8ff92b6 366 global $CFG;
4a490db0 367
ac9b0805 368 $this->load_grade_item();
2cc4b0f9 369
370 if ($this->grade_item->is_locked()) {
371 return true; // no need to recalculate locked items
372 }
373
ac9b0805 374 $this->grade_item->load_scale();
2df71235 375
b3ac6c3e 376 // find grade items of immediate children (category or grade items)
61c33818 377 $depends_on = $this->grade_item->depends_on();
b3ac6c3e 378
f8e6e4db 379 if (empty($depends_on)) {
380 $items = false;
381 } else {
382 $gis = implode(',', $depends_on);
383 $sql = "SELECT *
384 FROM {$CFG->prefix}grade_items
385 WHERE id IN ($gis)";
386 $items = get_records_sql($sql);
387 }
4a490db0 388
f8e6e4db 389 if ($userid) {
390 $usersql = "AND g.userid=$userid";
391 } else {
392 $usersql = "";
b8ff92b6 393 }
4a490db0 394
3f2b0c8a 395 $grade_inst = new grade_grade();
396 $fields = 'g.'.implode(',g.', $grade_inst->required_fields);
397
f8e6e4db 398 // where to look for final grades - include grade of this item too, we will store the results there
61c33818 399 $gis = implode(',', array_merge($depends_on, array($this->grade_item->id)));
3f2b0c8a 400 $sql = "SELECT $fields
ac9b0805 401 FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items gi
f8e6e4db 402 WHERE gi.id = g.itemid AND gi.id IN ($gis) $usersql
ac9b0805 403 ORDER BY g.userid";
b8ff92b6 404
9580a21f 405 // group the results by userid and aggregate the grades for this user
b8ff92b6 406 if ($rs = get_recordset_sql($sql)) {
03cedd62 407 $prevuser = 0;
408 $grade_values = array();
409 $excluded = array();
410 $oldgrade = null;
411 while ($used = rs_fetch_next_record($rs)) {
412 if ($used->userid != $prevuser) {
413 $this->aggregate_grades($prevuser, $items, $grade_values, $oldgrade, $excluded);
414 $prevuser = $used->userid;
415 $grade_values = array();
416 $excluded = array();
417 $oldgrade = null;
418 }
419 $grade_values[$used->itemid] = $used->finalgrade;
420 if ($used->excluded) {
421 $excluded[] = $used->itemid;
422 }
423 if ($this->grade_item->id == $used->itemid) {
424 $oldgrade = $used;
2df71235 425 }
b8ff92b6 426 }
03cedd62 427 $this->aggregate_grades($prevuser, $items, $grade_values, $oldgrade, $excluded);//the last one
31a17093 428 rs_close($rs);
b8ff92b6 429 }
430
b8ff92b6 431 return true;
432 }
433
434 /**
ac9b0805 435 * internal function for category grades aggregation
b8ff92b6 436 */
23207a1a 437 function aggregate_grades($userid, $items, $grade_values, $oldgrade, $excluded) {
e171963b 438 global $CFG;
b8ff92b6 439 if (empty($userid)) {
f8e6e4db 440 //ignore first call
b8ff92b6 441 return;
442 }
4a490db0 443
f8e6e4db 444 if ($oldgrade) {
3ee5c201 445 $grade = new grade_grade($oldgrade, false);
f8e6e4db 446 $grade->grade_item =& $this->grade_item;
b8ff92b6 447
f8e6e4db 448 } else {
449 // insert final grade - it will be needed later anyway
3ee5c201 450 $grade = new grade_grade(array('itemid'=>$this->grade_item->id, 'userid'=>$userid), false);
f8e6e4db 451 $grade->insert('system');
452 $grade->grade_item =& $this->grade_item;
2cc4b0f9 453
f8e6e4db 454 $oldgrade = new object();
455 $oldgrade->finalgrade = $grade->finalgrade;
456 $oldgrade->rawgrade = $grade->rawgrade;
457 $oldgrade->rawgrademin = $grade->rawgrademin;
458 $oldgrade->rawgrademax = $grade->rawgrademax;
459 $oldgrade->rawscaleid = $grade->rawscaleid;
460 }
461
c86caae7 462 // no need to recalculate locked or overridden grades
463 if ($grade->is_locked() or $grade->is_overridden()) {
2cc4b0f9 464 return;
ac9b0805 465 }
466
f8e6e4db 467 // can not use own final category grade in calculation
9580a21f 468 unset($grade_values[$this->grade_item->id]);
f8e6e4db 469
ac9b0805 470 // if no grades calculation possible or grading not allowed clear both final and raw
9580a21f 471 if (empty($grade_values) or empty($items) or ($this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE)) {
f8e6e4db 472 $grade->finalgrade = null;
473 $grade->rawgrade = null;
474 if ($grade->finalgrade !== $oldgrade->finalgrade or $grade->rawgrade !== $oldgrade->rawgrade) {
475 $grade->update('system');
476 }
b8ff92b6 477 return;
478 }
4a490db0 479
f8e6e4db 480 /// normalize the grades first - all will have value 0...1
d5f0aa01 481 // ungraded items are not used in aggregation
23207a1a 482 foreach ($grade_values as $itemid=>$v) {
b8ff92b6 483 if (is_null($v)) {
484 // null means no grade
23207a1a 485 unset($grade_values[$itemid]);
486 continue;
487 } else if (in_array($itemid, $excluded)) {
488 unset($grade_values[$itemid]);
b8ff92b6 489 continue;
0aa32279 490 }
23207a1a 491
492 $grade_values[$itemid] = grade_grade::standardise_score($v, $items[$itemid]->grademin, $items[$itemid]->grademax, 0, 1);
0aa32279 493 }
dda0c7e6 494
e171963b 495 // If global aggregateonlygraded is set, override category value
496 if ($CFG->grade_aggregateonlygraded != -1) {
497 $this->aggregateonlygraded = $CFG->grade_aggregateonlygraded;
498 }
499
eacd3700 500 // use min grade if grade missing for these types
c2efb501 501 if (!$this->aggregateonlygraded) {
502 foreach($items as $itemid=>$value) {
503 if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
504 $grade_values[$itemid] = 0;
eacd3700 505 }
c2efb501 506 }
eacd3700 507 }
508
509 // limit and sort
9580a21f 510 $this->apply_limit_rules($grade_values);
511 asort($grade_values, SORT_NUMERIC);
4a490db0 512
d5f0aa01 513 // let's see we have still enough grades to do any statistics
9580a21f 514 if (count($grade_values) == 0) {
ac9b0805 515 // not enough attempts yet
f8e6e4db 516 $grade->finalgrade = null;
517 $grade->rawgrade = null;
518 if ($grade->finalgrade !== $oldgrade->finalgrade or $grade->rawgrade !== $oldgrade->rawgrade) {
519 $grade->update('system');
b8ff92b6 520 }
521 return;
522 }
2df71235 523
d297269d 524 // do the maths
525 $agg_grade = $this->aggregate_values($grade_values, $items);
526
527 /// prepare update of new raw grade
528 $grade->rawgrademin = $this->grade_item->grademin;
529 $grade->rawgrademax = $this->grade_item->grademax;
530 $grade->rawscaleid = $this->grade_item->scaleid;
531 $grade->rawgrade = null; // categories do not use raw grades
532
533 // recalculate the rawgrade back to requested range
534 $finalgrade = grade_grade::standardise_score($agg_grade, 0, 1, $this->grade_item->grademin, $this->grade_item->grademax);
535
536 if (!is_null($finalgrade)) {
537 $grade->finalgrade = bounded_number($this->grade_item->grademin, $finalgrade, $this->grade_item->grademax);
538 } else {
539 $grade->finalgrade = $finalgrade;
540 }
541
542 // update in db if changed
543 if ( $grade->finalgrade !== $oldgrade->finalgrade
544 or $grade->rawgrade !== $oldgrade->rawgrade
545 or $grade->rawgrademin !== $oldgrade->rawgrademin
546 or $grade->rawgrademax !== $oldgrade->rawgrademax
547 or $grade->rawscaleid !== $oldgrade->rawscaleid) {
548
549 $grade->update('system');
550 }
551
552 return;
553 }
554
555 function aggregate_values($grade_values, $items) {
b8ff92b6 556 switch ($this->aggregation) {
c2efb501 557 case GRADE_AGGREGATE_MEDIAN: // Middle point value in the set: ignores frequencies
9580a21f 558 $num = count($grade_values);
c186c7b2 559 $grades = array_values($grade_values);
560 if ($num % 2 == 0) {
9c8d38fa 561 $agg_grade = ($grades[intval($num/2)-1] + $grades[intval($num/2)]) / 2;
b8ff92b6 562 } else {
9c8d38fa 563 $agg_grade = $grades[intval(($num/2)-0.5)];
b8ff92b6 564 }
565 break;
ac9b0805 566
c2efb501 567 case GRADE_AGGREGATE_MIN:
9c8d38fa 568 $agg_grade = reset($grade_values);
b8ff92b6 569 break;
570
c2efb501 571 case GRADE_AGGREGATE_MAX:
9c8d38fa 572 $agg_grade = array_pop($grade_values);
b8ff92b6 573 break;
574
c2efb501 575 case GRADE_AGGREGATE_MODE: // the most common value, average used if multimode
9580a21f 576 $freq = array_count_values($grade_values);
95affb8a 577 arsort($freq); // sort by frequency keeping keys
578 $top = reset($freq); // highest frequency count
579 $modes = array_keys($freq, $top); // search for all modes (have the same highest count)
580 rsort($modes, SORT_NUMERIC); // get highes mode
9c8d38fa 581 $agg_grade = reset($modes);
d5fab31f 582 break;
95affb8a 583
c2efb501 584 case GRADE_AGGREGATE_WEIGHTED_MEAN: // Weighted average of all existing final grades
9580a21f 585 $weightsum = 0;
586 $sum = 0;
eacd3700 587 foreach($grade_values as $itemid=>$grade_value) {
588 if ($items[$itemid]->aggregationcoef <= 0) {
9580a21f 589 continue;
590 }
eacd3700 591 $weightsum += $items[$itemid]->aggregationcoef;
592 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 593 }
594 if ($weightsum == 0) {
9c8d38fa 595 $agg_grade = null;
9580a21f 596 } else {
9c8d38fa 597 $agg_grade = $sum / $weightsum;
9580a21f 598 }
599 break;
600
c2efb501 601 case GRADE_AGGREGATE_EXTRACREDIT_MEAN: // special average
9580a21f 602 $num = 0;
603 $sum = 0;
eacd3700 604 foreach($grade_values as $itemid=>$grade_value) {
605 if ($items[$itemid]->aggregationcoef == 0) {
9580a21f 606 $num += 1;
607 $sum += $grade_value;
eacd3700 608 } else if ($items[$itemid]->aggregationcoef > 0) {
609 $sum += $items[$itemid]->aggregationcoef * $grade_value;
9580a21f 610 }
611 }
612 if ($num == 0) {
9c8d38fa 613 $agg_grade = $sum; // only extra credits or wrong coefs
9580a21f 614 } else {
9c8d38fa 615 $agg_grade = $sum / $num;
9580a21f 616 }
617 break;
618
c2efb501 619 case GRADE_AGGREGATE_MEAN: // Arithmetic average of all grade items (if ungraded aggregated, NULL counted as minimum)
ac9b0805 620 default:
9580a21f 621 $num = count($grade_values);
622 $sum = array_sum($grade_values);
9c8d38fa 623 $agg_grade = $sum / $num;
b8ff92b6 624 break;
625 }
626
d297269d 627 return $agg_grade;
0aa32279 628 }
adc2f286 629 /**
630 * Given an array of grade values (numerical indices), applies droplow or keephigh
631 * rules to limit the final array.
9580a21f 632 * @param array $grade_values
adc2f286 633 * @return array Limited grades.
634 */
9580a21f 635 function apply_limit_rules(&$grade_values) {
e171963b 636 global $CFG;
637
638 // If global keephigh and/or droplow are set, override category variable
639 if ($CFG->grade_keephigh != -1) {
640 $this->keephigh = $CFG->grade_keephigh;
641 }
642
643 if ($CFG->grade_droplow != -1) {
644 $this->droplow = $CFG->grade_droplow;
645 }
646
9580a21f 647 arsort($grade_values, SORT_NUMERIC);
adc2f286 648 if (!empty($this->droplow)) {
649 for ($i = 0; $i < $this->droplow; $i++) {
9580a21f 650 array_pop($grade_values);
adc2f286 651 }
4a490db0 652 } elseif (!empty($this->keephigh)) {
9580a21f 653 while (count($grade_values) > $this->keephigh) {
654 array_pop($grade_values);
adc2f286 655 }
656 }
0aa32279 657 }
658
9580a21f 659
660 /**
661 * Returns true if category uses special aggregation coeficient
662 * @return boolean true if coeficient used
663 */
664 function is_aggregationcoef_used() {
c2efb501 665 return ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN
666 or $this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN);
ba74762b 667
9580a21f 668 }
669
1c307f21 670 /**
b3ac6c3e 671 * Returns tree with all grade_items and categories as elements
672 * @static
673 * @param int $courseid
b3ac6c3e 674 * @param boolean $include_category_items as category children
675 * @return array
1c307f21 676 */
938e00b6 677 function fetch_course_tree($courseid, $include_category_items=false) {
b3ac6c3e 678 $course_category = grade_category::fetch_course_category($courseid);
514a3467 679 $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
680 'children'=>$course_category->get_children($include_category_items));
681 $sortorder = 1;
682 $course_category->set_sortorder($sortorder);
683 $course_category->sortorder = $sortorder;
684 return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
1c307f21 685 }
686
b3ac6c3e 687 function _fetch_course_tree_recursion($category_array, &$sortorder) {
688 // update the sortorder in db if needed
689 if ($category_array['object']->sortorder != $sortorder) {
690 $category_array['object']->set_sortorder($sortorder);
ce385eb4 691 }
ce385eb4 692
314c4336 693 // store the grade_item or grade_category instance with extra info
694 $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
b3ac6c3e 695
696 // reuse final grades if there
697 if (array_key_exists('finalgrades', $category_array)) {
698 $result['finalgrades'] = $category_array['finalgrades'];
699 }
700
701 // recursively resort children
702 if (!empty($category_array['children'])) {
703 $result['children'] = array();
29d509f5 704 //process the category item first
705 $cat_item_id = null;
b3ac6c3e 706 foreach($category_array['children'] as $oldorder=>$child_array) {
314c4336 707 if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
b3ac6c3e 708 $result['children'][$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
29d509f5 709 }
2b0f65e2 710 }
29d509f5 711 foreach($category_array['children'] as $oldorder=>$child_array) {
712 if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
b3ac6c3e 713 $result['children'][++$sortorder] = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
714 }
715 }
716 }
717
718 return $result;
ce385eb4 719 }
7c8a963f 720
721 /**
4a490db0 722 * Fetches and returns all the children categories and/or grade_items belonging to this category.
723 * By default only returns the immediate children (depth=1), but deeper levels can be requested,
a39cac25 724 * as well as all levels (0). The elements are indexed by sort order.
7c8a963f 725 * @return array Array of child objects (grade_category and grade_item).
726 */
938e00b6 727 function get_children($include_category_items=false) {
b3ac6c3e 728
729 // This function must be as fast as possible ;-)
730 // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
731 // we have to limit the number of queries though, because it will be used often in grade reports
732
733 $cats = get_records('grade_categories', 'courseid', $this->courseid);
734 $items = get_records('grade_items', 'courseid', $this->courseid);
4a490db0 735
b3ac6c3e 736 // init children array first
737 foreach ($cats as $catid=>$cat) {
738 $cats[$catid]->children = array();
27f95e9b 739 }
4a490db0 740
b3ac6c3e 741 //first attach items to cats and add category sortorder
742 foreach ($items as $item) {
743 if ($item->itemtype == 'course' or $item->itemtype == 'category') {
744 $cats[$item->iteminstance]->sortorder = $item->sortorder;
4a490db0 745
b3ac6c3e 746 if (!$include_category_items) {
747 continue;
748 }
749 $categoryid = $item->iteminstance;
750 } else {
751 $categoryid = $item->categoryid;
752 }
753
754 // prevent problems with duplicate sortorders in db
755 $sortorder = $item->sortorder;
756 while(array_key_exists($sortorder, $cats[$categoryid]->children)) {
f13002d5 757 //debugging("$sortorder exists in item loop");
b3ac6c3e 758 $sortorder++;
759 }
760
761 $cats[$categoryid]->children[$sortorder] = $item;
762
763 }
764
765 // now find the requested category and connect categories as children
766 $category = false;
767 foreach ($cats as $catid=>$cat) {
768 if (!empty($cat->parent)) {
769 // prevent problems with duplicate sortorders in db
770 $sortorder = $cat->sortorder;
771 while(array_key_exists($sortorder, $cats[$cat->parent]->children)) {
f13002d5 772 //debugging("$sortorder exists in cat loop");
b3ac6c3e 773 $sortorder++;
774 }
775
776 $cats[$cat->parent]->children[$sortorder] = $cat;
777 }
778
779 if ($catid == $this->id) {
780 $category = &$cats[$catid];
781 }
782 }
783
784 unset($items); // not needed
785 unset($cats); // not needed
786
938e00b6 787 $children_array = grade_category::_get_children_recursion($category);
b3ac6c3e 788
789 ksort($children_array);
790
791 return $children_array;
792
793 }
794
938e00b6 795 function _get_children_recursion($category) {
b3ac6c3e 796
797 $children_array = array();
798 foreach($category->children as $sortorder=>$child) {
799 if (array_key_exists('itemtype', $child)) {
800 $grade_item = new grade_item($child, false);
4faf5f99 801 if (in_array($grade_item->itemtype, array('course', 'category'))) {
802 $type = $grade_item->itemtype.'item';
803 $depth = $category->depth;
314c4336 804 } else {
805 $type = 'item';
806 $depth = $category->depth; // we use this to set the same colour
b3ac6c3e 807 }
4faf5f99 808 $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
4a490db0 809
7c8a963f 810 } else {
938e00b6 811 $children = grade_category::_get_children_recursion($child);
b3ac6c3e 812 $grade_category = new grade_category($child, false);
813 if (empty($children)) {
314c4336 814 $children = array();
7c8a963f 815 }
4faf5f99 816 $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
314c4336 817 }
27f95e9b 818 }
819
b3ac6c3e 820 // sort the array
821 ksort($children_array);
822
27f95e9b 823 return $children_array;
824 }
4a490db0 825
f151b073 826 /**
ab53054f 827 * Uses get_grade_item to load or create a grade_item, then saves it as $this->grade_item.
f151b073 828 * @return object Grade_item
829 */
830 function load_grade_item() {
ac9b0805 831 if (empty($this->grade_item)) {
832 $this->grade_item = $this->get_grade_item();
833 }
ab53054f 834 return $this->grade_item;
835 }
4a490db0 836
ab53054f 837 /**
838 * Retrieves from DB and instantiates the associated grade_item object.
839 * If no grade_item exists yet, create one.
840 * @return object Grade_item
841 */
842 function get_grade_item() {
c91ed4be 843 if (empty($this->id)) {
844 debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
845 return false;
846 }
847
b3ac6c3e 848 if (empty($this->parent)) {
849 $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
850
851 } else {
852 $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
853 }
f92dcad8 854
855 if (!$grade_items = grade_item::fetch_all($params)) {
b8ff92b6 856 // create a new one
f92dcad8 857 $grade_item = new grade_item($params, false);
b8ff92b6 858 $grade_item->gradetype = GRADE_TYPE_VALUE;
f8e6e4db 859 $grade_item->insert('system');
4a490db0 860
b8ff92b6 861 } else if (count($grade_items) == 1){
862 // found existing one
863 $grade_item = reset($grade_items);
4a490db0 864
b8ff92b6 865 } else {
866 debugging("Found more than one grade_item attached to category id:".$this->id);
ac9b0805 867 // return first one
868 $grade_item = reset($grade_items);
2c72af1f 869 }
870
ab53054f 871 return $grade_item;
f151b073 872 }
8c846243 873
874 /**
875 * Uses $this->parent to instantiate $this->parent_category based on the
876 * referenced record in the DB.
877 * @return object Parent_category
878 */
879 function load_parent_category() {
880 if (empty($this->parent_category) && !empty($this->parent)) {
ab53054f 881 $this->parent_category = $this->get_parent_category();
8c846243 882 }
883 return $this->parent_category;
4a490db0 884 }
885
ab53054f 886 /**
887 * Uses $this->parent to instantiate and return a grade_category object.
888 * @return object Parent_category
889 */
890 function get_parent_category() {
891 if (!empty($this->parent)) {
892 $parent_category = new grade_category(array('id' => $this->parent));
4a490db0 893 return $parent_category;
ab53054f 894 } else {
895 return null;
896 }
897 }
898
2186f72c 899 /**
4a490db0 900 * Returns the most descriptive field for this object. This is a standard method used
2186f72c 901 * when we do not know the exact type of an object.
902 * @return string name
903 */
904 function get_name() {
314c4336 905 if (empty($this->parent)) {
410753fb 906 $course = get_record('course', 'id', $this->courseid);
907 return format_string($course->fullname);
314c4336 908 } else {
909 return $this->fullname;
910 }
2186f72c 911 }
c91ed4be 912
0fc7f624 913 /**
914 * Sets this category's parent id. A generic method shared by objects that have a parent id of some kind.
f13002d5 915 * @param int parentid
916 * @return boolean success
0fc7f624 917 */
f8e6e4db 918 function set_parent($parentid, $source=null) {
f13002d5 919 if ($this->parent == $parentid) {
920 return true;
921 }
922
923 if ($parentid == $this->id) {
924 error('Can not assign self as parent!');
925 }
926
927 if (empty($this->parent) and $this->is_course_category()) {
928 error('Course category can not have parent!');
b3ac6c3e 929 }
f13002d5 930
931 // find parent and check course id
932 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
b3ac6c3e 933 return false;
934 }
935
f8e6e4db 936 $this->force_regrading();
b3ac6c3e 937
938 // set new parent category
f8e6e4db 939 $this->parent = $parent_category->id;
940 $this->parent_category =& $parent_category;
b3ac6c3e 941 $this->path = null; // remove old path and depth - will be recalculated in update()
f8e6e4db 942 $this->depth = null; // remove old path and depth - will be recalculated in update()
943 $this->update($source);
b3ac6c3e 944
15b462da 945 return $this->update($source);
b3ac6c3e 946 }
947
948 /**
949 * Returns the final values for this grade category.
950 * @param int $userid Optional: to retrieve a single final grade
951 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
952 */
953 function get_final($userid=NULL) {
954 $this->load_grade_item();
955 return $this->grade_item->get_final($userid);
0fc7f624 956 }
4a490db0 957
0fc7f624 958 /**
4a490db0 959 * Returns the sortorder of the associated grade_item. This method is also available in
5fad5061 960 * grade_item, for cases where the object type is not known.
0fc7f624 961 * @return int Sort order
962 */
963 function get_sortorder() {
b3ac6c3e 964 $this->load_grade_item();
965 return $this->grade_item->get_sortorder();
0fc7f624 966 }
967
be7c0693 968 /**
969 * Returns the idnumber of the associated grade_item. This method is also available in
970 * grade_item, for cases where the object type is not known.
971 * @return string idnumber
972 */
973 function get_idnumber() {
974 $this->load_grade_item();
975 return $this->grade_item->get_idnumber();
976 }
977
0fc7f624 978 /**
b3ac6c3e 979 * Sets sortorder variable for this category.
4a490db0 980 * This method is also available in grade_item, for cases where the object type is not know.
0fc7f624 981 * @param int $sortorder
982 * @return void
983 */
984 function set_sortorder($sortorder) {
b3ac6c3e 985 $this->load_grade_item();
986 $this->grade_item->set_sortorder($sortorder);
987 }
988
6639ead3 989 /**
990 * Move this category after the given sortorder - does not change the parent
991 * @param int $sortorder to place after
992 */
f13002d5 993 function move_after_sortorder($sortorder) {
994 $this->load_grade_item();
995 $this->grade_item->move_after_sortorder($sortorder);
996 }
997
b3ac6c3e 998 /**
f13002d5 999 * Return true if this is the top most category that represents the total course grade.
b3ac6c3e 1000 * @return boolean
1001 */
1002 function is_course_category() {
1003 $this->load_grade_item();
1004 return $this->grade_item->is_course_item();
1005 }
1006
1007 /**
1008 * Return the top most course category.
1009 * @static
1010 * @return object grade_category instance for course grade
1011 */
1012 function fetch_course_category($courseid) {
1013
1014 // course category has no parent
1015 if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
1016 return $course_category;
1017 }
1018
1019 // create a new one
1020 $course_category = new grade_category();
1021 $course_category->insert_course_category($courseid);
1022
1023 return $course_category;
0fc7f624 1024 }
4a490db0 1025
79eabc2a 1026 /**
1027 * Is grading object editable?
1028 * @return boolean
1029 */
1030 function is_editable() {
1031 return true;
1032 }
1033
5fad5061 1034 /**
4a490db0 1035 * Returns the locked state/date of the associated grade_item. This method is also available in
1036 * grade_item, for cases where the object type is not known.
22e23c78 1037 * @return boolean
5fad5061 1038 */
2cc4b0f9 1039 function is_locked() {
5fad5061 1040 $this->load_grade_item();
22e23c78 1041 return $this->grade_item->is_locked();
5fad5061 1042 }
1043
1044 /**
1045 * Sets the grade_item's locked variable and updates the grade_item.
1046 * Method named after grade_item::set_locked().
1047 * @param int $locked 0, 1 or a timestamp int(10) after which date the item will be locked.
fb0e3570 1048 * @param boolean $cascade lock/unlock child objects too
2b0f65e2 1049 * @param boolean $refresh refresh grades when unlocking
9580a21f 1050 * @return boolean success if category locked (not all children mayb be locked though)
5fad5061 1051 */
fb0e3570 1052 function set_locked($lockedstate, $cascade=false, $refresh=true) {
5fad5061 1053 $this->load_grade_item();
2b0f65e2 1054
fb0e3570 1055 $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
1056
1057 if ($cascade) {
1058 //process all children - items and categories
1059 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
1060 foreach($children as $child) {
1061 $child->set_locked($lockedstate, true, false);
1062 if (empty($lockedstate) and $refresh) {
1063 //refresh when unlocking
1064 $child->refresh_grades();
1065 }
2b0f65e2 1066 }
7a7a53d3 1067 }
fb0e3570 1068 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
1069 foreach($children as $child) {
1070 $child->set_locked($lockedstate, true, true);
1071 }
7a7a53d3 1072 }
1073 }
2b0f65e2 1074
b121b544 1075 return $result;
5fad5061 1076 }
4a490db0 1077
5fad5061 1078 /**
4a490db0 1079 * Returns the hidden state/date of the associated grade_item. This method is also available in
22e23c78 1080 * grade_item.
1081 * @return boolean
5fad5061 1082 */
22e23c78 1083 function is_hidden() {
5fad5061 1084 $this->load_grade_item();
22e23c78 1085 return $this->grade_item->is_hidden();
5fad5061 1086 }
1087
1088 /**
4a490db0 1089 * Sets the grade_item's hidden variable and updates the grade_item.
5fad5061 1090 * Method named after grade_item::set_hidden().
1091 * @param int $hidden 0, 1 or a timestamp int(10) after which date the item will be hidden.
f60c61b1 1092 * @param boolean $cascade apply to child objects too
5fad5061 1093 * @return void
1094 */
f60c61b1 1095 function set_hidden($hidden, $cascade=false) {
5fad5061 1096 $this->load_grade_item();
22e23c78 1097 $this->grade_item->set_hidden($hidden);
f60c61b1 1098 if ($cascade) {
1099 if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
1100 foreach($children as $child) {
1101 $child->set_hidden($hidden, $cascade);
1102 }
f13002d5 1103 }
f60c61b1 1104 if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
1105 foreach($children as $child) {
1106 $child->set_hidden($hidden, $cascade);
1107 }
f13002d5 1108 }
1109 }
5fad5061 1110 }
4a490db0 1111}
8a31e65c 1112?>