Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Definition of a class to represent a grade category
19
 *
20
 * @package   core_grades
21
 * @copyright 2006 Nicolas Connault
22
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
defined('MOODLE_INTERNAL') || die();
26
 
27
require_once(__DIR__ . '/grade_object.php');
28
 
29
/**
30
 * grade_category is an object mapped to DB table {prefix}grade_categories
31
 *
32
 * @package   core_grades
33
 * @category  grade
34
 * @copyright 2007 Nicolas Connault
35
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36
 */
37
class grade_category extends grade_object {
38
    /**
39
     * The DB table.
40
     * @var string $table
41
     */
42
    public $table = 'grade_categories';
43
 
44
    /**
45
     * Array of required table fields, must start with 'id'.
46
     * @var array $required_fields
47
     */
48
    public $required_fields = array('id', 'courseid', 'parent', 'depth', 'path', 'fullname', 'aggregation',
49
                                 'keephigh', 'droplow', 'aggregateonlygraded', 'aggregateoutcomes',
50
                                 'timecreated', 'timemodified', 'hidden');
51
 
52
    /**
53
     * The course this category belongs to.
54
     * @var int $courseid
55
     */
56
    public $courseid;
57
 
58
    /**
59
     * The category this category belongs to (optional).
60
     * @var int $parent
61
     */
62
    public $parent;
63
 
64
    /**
65
     * The grade_category object referenced by $this->parent (PK).
66
     * @var grade_category $parent_category
67
     */
68
    public $parent_category;
69
 
70
    /**
71
     * The number of parents this category has.
72
     * @var int $depth
73
     */
74
    public $depth = 0;
75
 
76
    /**
77
     * Shows the hierarchical path for this category as /1/2/3/ (like course_categories), the last number being
78
     * this category's autoincrement ID number.
79
     * @var string $path
80
     */
81
    public $path;
82
 
83
    /**
84
     * The name of this category.
85
     * @var string $fullname
86
     */
87
    public $fullname;
88
 
89
    /**
90
     * A constant pointing to one of the predefined aggregation strategies (none, mean, median, sum etc) .
91
     * @var int $aggregation
92
     */
93
    public $aggregation = GRADE_AGGREGATE_SUM;
94
 
95
    /**
96
     * Keep only the X highest items.
97
     * @var int $keephigh
98
     */
99
    public $keephigh = 0;
100
 
101
    /**
102
     * Drop the X lowest items.
103
     * @var int $droplow
104
     */
105
    public $droplow = 0;
106
 
107
    /**
108
     * Aggregate only graded items
109
     * @var int $aggregateonlygraded
110
     */
111
    public $aggregateonlygraded = 0;
112
 
113
    /**
114
     * Aggregate outcomes together with normal items
115
     * @var int $aggregateoutcomes
116
     */
117
    public $aggregateoutcomes = 0;
118
 
119
    /**
120
     * Array of grade_items or grade_categories nested exactly 1 level below this category
121
     * @var array $children
122
     */
123
    public $children;
124
 
125
    /**
126
     * A hierarchical array of all children below this category. This is stored separately from
127
     * $children because it is more memory-intensive and may not be used as often.
128
     * @var array $all_children
129
     */
130
    public $all_children;
131
 
132
    /**
133
     * An associated grade_item object, with itemtype=category, used to calculate and cache a set of grade values
134
     * for this category.
135
     * @var grade_item $grade_item
136
     */
137
    public $grade_item;
138
 
139
    /**
140
     * Temporary sortorder for speedup of children resorting
141
     * @var int $sortorder
142
     */
143
    public $sortorder;
144
 
145
    /**
146
     * List of options which can be "forced" from site settings.
147
     * @var array $forceable
148
     */
149
    public $forceable = array('aggregation', 'keephigh', 'droplow', 'aggregateonlygraded', 'aggregateoutcomes');
150
 
151
    /**
152
     * String representing the aggregation coefficient. Variable is used as cache.
153
     * @var string $coefstring
154
     */
155
    public $coefstring = null;
156
 
157
    /**
158
     * Static variable storing the result from {@link self::can_apply_limit_rules}.
159
     * @var bool
160
     */
161
    protected $canapplylimitrules;
162
 
163
    /**
164
     * e.g. 'category', 'course' and 'mod', 'blocks', 'import', etc...
165
     * @var string $itemtype
166
     */
167
    public $itemtype;
168
 
169
    /**
170
     * Builds this category's path string based on its parents (if any) and its own id number.
171
     * This is typically done just before inserting this object in the DB for the first time,
172
     * or when a new parent is added or changed. It is a recursive function: once the calling
173
     * object no longer has a parent, the path is complete.
174
     *
175
     * @param grade_category $grade_category A Grade_Category object
176
     * @return string The category's path string
177
     */
178
    public static function build_path($grade_category) {
179
        global $DB;
180
 
181
        if (empty($grade_category->parent)) {
182
            return '/'.$grade_category->id.'/';
183
 
184
        } else {
185
            $parent = $DB->get_record('grade_categories', array('id' => $grade_category->parent));
186
            return grade_category::build_path($parent).$grade_category->id.'/';
187
        }
188
    }
189
 
190
    /**
191
     * Finds and returns a grade_category instance based on params.
192
     *
193
     * @param array $params associative arrays varname=>value
194
     * @return grade_category The retrieved grade_category instance or false if none found.
195
     */
196
    public static function fetch($params) {
197
        if ($records = self::retrieve_record_set($params)) {
198
            return reset($records);
199
        }
200
 
201
        $record = grade_object::fetch_helper('grade_categories', 'grade_category', $params);
202
 
203
        // We store it as an array to keep a key => result set interface in the cache, grade_object::fetch_helper is
204
        // managing exceptions. We return only the first element though.
205
        $records = false;
206
        if ($record) {
207
            $records = array($record->id => $record);
208
        }
209
 
210
        self::set_record_set($params, $records);
211
 
212
        return $record;
213
    }
214
 
215
    /**
216
     * Finds and returns all grade_category instances based on params.
217
     *
218
     * @param array $params associative arrays varname=>value
219
     * @return array array of grade_category insatnces or false if none found.
220
     */
221
    public static function fetch_all($params) {
222
        if ($records = self::retrieve_record_set($params)) {
223
            return $records;
224
        }
225
 
226
        $records = grade_object::fetch_all_helper('grade_categories', 'grade_category', $params);
227
        self::set_record_set($params, $records);
228
 
229
        return $records;
230
    }
231
 
232
    /**
233
     * In addition to update() as defined in grade_object, call force_regrading of parent categories, if applicable.
234
     *
235
     * @param string $source from where was the object updated (mod/forum, manual, etc.)
236
     * @param bool $isbulkupdate If bulk grade update is happening.
237
     * @return bool success
238
     */
239
    public function update($source = null, $isbulkupdate = false) {
240
        // load the grade item or create a new one
241
        $this->load_grade_item();
242
 
243
        // force recalculation of path;
244
        if (empty($this->path)) {
245
            $this->path  = grade_category::build_path($this);
246
            $this->depth = substr_count($this->path, '/') - 1;
247
            $updatechildren = true;
248
 
249
        } else {
250
            $updatechildren = false;
251
        }
252
 
253
        $this->apply_forced_settings();
254
 
255
        // these are exclusive
256
        if ($this->droplow > 0) {
257
            $this->keephigh = 0;
258
 
259
        } else if ($this->keephigh > 0) {
260
            $this->droplow = 0;
261
        }
262
 
263
        // Recalculate grades if needed
264
        if ($this->qualifies_for_regrading()) {
265
            $this->force_regrading();
266
        }
267
 
268
        $this->timemodified = time();
269
 
270
        $result = parent::update($source);
271
 
272
        // now update paths in all child categories
273
        if ($result and $updatechildren) {
274
 
275
            if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
276
 
277
                foreach ($children as $child) {
278
                    $child->path  = null;
279
                    $child->depth = 0;
280
                    $child->update($source);
281
                }
282
            }
283
        }
284
 
285
        return $result;
286
    }
287
 
288
    /**
289
     * If parent::delete() is successful, send force_regrading message to parent category.
290
     *
291
     * @param string $source from where was the object deleted (mod/forum, manual, etc.)
292
     * @return bool success
293
     */
294
    public function delete($source=null) {
295
        global $DB;
296
 
297
        try {
298
            $transaction = $DB->start_delegated_transaction();
299
            $grade_item = $this->load_grade_item();
300
 
301
            if ($this->is_course_category()) {
302
 
303
                if ($categories = self::fetch_all(['courseid' => $this->courseid])) {
304
 
305
                    foreach ($categories as $category) {
306
 
307
                        if ($category->id == $this->id) {
308
                            continue; // Do not delete course category yet.
309
                        }
310
                        $category->delete($source);
311
                    }
312
                }
313
 
314
                if ($items = grade_item::fetch_all(['courseid' => $this->courseid])) {
315
 
316
                    foreach ($items as $item) {
317
 
318
                        if ($item->id == $grade_item->id) {
319
                            continue; // Do not delete course item yet.
320
                        }
321
                        $item->delete($source);
322
                    }
323
                }
324
 
325
            } else {
326
                $this->force_regrading();
327
 
328
                $parent = $this->load_parent_category();
329
 
330
                // Update children's categoryid/parent field first.
331
                if ($children = grade_item::fetch_all(['categoryid' => $this->id])) {
332
                    foreach ($children as $child) {
333
                        $child->set_parent($parent->id);
334
                    }
335
                }
336
 
337
                if ($children = self::fetch_all(['parent' => $this->id])) {
338
                    foreach ($children as $child) {
339
                        $child->set_parent($parent->id);
340
                    }
341
                }
342
            }
343
 
344
            // First delete the attached grade item and grades.
345
            $grade_item->delete($source);
346
 
347
            // Delete category itself.
348
            $success = parent::delete($source);
349
 
350
            $transaction->allow_commit();
351
        } catch (Exception $e) {
352
            $transaction->rollback($e);
353
        }
354
        return $success;
355
    }
356
 
357
    /**
358
     * In addition to the normal insert() defined in grade_object, this method sets the depth
359
     * and path for this object, and update the record accordingly.
360
     *
361
     * We do this here instead of in the constructor as they both need to know the record's
362
     * ID number, which only gets created at insertion time.
363
     * This method also creates an associated grade_item if this wasn't done during construction.
364
     *
365
     * @param string $source from where was the object inserted (mod/forum, manual, etc.)
366
     * @param bool $isbulkupdate If bulk grade update is happening.
367
     * @return int PK ID if successful, false otherwise
368
     */
369
    public function insert($source = null, $isbulkupdate = false) {
370
 
371
        if (empty($this->courseid)) {
372
            throw new \moodle_exception('cannotinsertgrade');
373
        }
374
 
375
        if (empty($this->parent)) {
376
            $course_category = grade_category::fetch_course_category($this->courseid);
377
            $this->parent = $course_category->id;
378
        }
379
 
380
        $this->path = null;
381
 
382
        $this->timecreated = $this->timemodified = time();
383
 
384
        if (!parent::insert($source)) {
385
            debugging("Could not insert this category: " . print_r($this, true));
386
            return false;
387
        }
388
 
389
        $this->force_regrading();
390
 
391
        // build path and depth
392
        $this->update($source);
393
 
394
        return $this->id;
395
    }
396
 
397
    /**
398
     * Internal function - used only from fetch_course_category()
399
     * Normal insert() can not be used for course category
400
     *
401
     * @param int $courseid The course ID
402
     * @return int The ID of the new course category
403
     */
404
    public function insert_course_category($courseid) {
405
        $this->courseid    = $courseid;
406
        $this->fullname    = '?';
407
        $this->path        = null;
408
        $this->parent      = null;
409
        $this->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2;
410
 
411
        $this->apply_default_settings();
412
        $this->apply_forced_settings();
413
 
414
        $this->timecreated = $this->timemodified = time();
415
 
416
        if (!parent::insert('system')) {
417
            debugging("Could not insert this category: " . print_r($this, true));
418
            return false;
419
        }
420
 
421
        // build path and depth
422
        $this->update('system');
423
 
424
        return $this->id;
425
    }
426
 
427
    /**
428
     * Compares the values held by this object with those of the matching record in DB, and returns
429
     * whether or not these differences are sufficient to justify an update of all parent objects.
430
     * This assumes that this object has an ID number and a matching record in DB. If not, it will return false.
431
     *
432
     * @return bool
433
     */
434
    public function qualifies_for_regrading() {
435
        if (empty($this->id)) {
436
            debugging("Can not regrade non existing category");
437
            return false;
438
        }
439
 
440
        $db_item = grade_category::fetch(array('id'=>$this->id));
441
 
442
        $aggregationdiff = $db_item->aggregation         != $this->aggregation;
443
        $keephighdiff    = $db_item->keephigh            != $this->keephigh;
444
        $droplowdiff     = $db_item->droplow             != $this->droplow;
445
        $aggonlygrddiff  = $db_item->aggregateonlygraded != $this->aggregateonlygraded;
446
        $aggoutcomesdiff = $db_item->aggregateoutcomes   != $this->aggregateoutcomes;
447
 
448
        return ($aggregationdiff || $keephighdiff || $droplowdiff || $aggonlygrddiff || $aggoutcomesdiff);
449
    }
450
 
451
    /**
452
     * Marks this grade categories' associated grade item as needing regrading
453
     */
454
    public function force_regrading() {
455
        $grade_item = $this->load_grade_item();
456
        $grade_item->force_regrading();
457
    }
458
 
459
    /**
460
     * Something that should be called before we start regrading the whole course.
461
     *
462
     * @return void
463
     */
464
    public function pre_regrade_final_grades() {
465
        $this->auto_update_weights();
466
        $this->auto_update_max();
467
    }
468
 
469
    /**
470
     * Generates and saves final grades in associated category grade item.
471
     * These immediate children must already have their own final grades.
472
     * The category's aggregation method is used to generate final grades.
473
     *
474
     * Please note that category grade is either calculated or aggregated, not both at the same time.
475
     *
476
     * This method must be used ONLY from grade_item::regrade_final_grades(),
477
     * because the calculation must be done in correct order!
478
     *
479
     * Steps to follow:
480
     *  1. Get final grades from immediate children
481
     *  3. Aggregate these grades
482
     *  4. Save them in final grades of associated category grade item
483
     *
484
     * @param int $userid The user ID if final grade generation should be limited to a single user
485
     * @param \core\progress\base|null $progress Optional progress indicator
486
     * @return bool
487
     */
488
    public function generate_grades($userid=null, ?\core\progress\base $progress = null) {
489
        global $CFG, $DB;
490
 
491
        $this->load_grade_item();
492
 
493
        if ($this->grade_item->is_locked()) {
494
            return true; // no need to recalculate locked items
495
        }
496
 
497
        // find grade items of immediate children (category or grade items) and force site settings
498
        $depends_on = $this->grade_item->depends_on();
499
 
500
        if (empty($depends_on)) {
501
            $items = false;
502
 
503
        } else {
504
            list($usql, $params) = $DB->get_in_or_equal($depends_on);
505
            $sql = "SELECT *
506
                      FROM {grade_items}
507
                     WHERE id $usql";
508
            $items = $DB->get_records_sql($sql, $params);
509
            foreach ($items as $id => $item) {
510
                $items[$id] = new grade_item($item, false);
511
            }
512
        }
513
 
1441 ariadna 514
        $gradeinst = new grade_grade();
515
        $fields = implode(',', $gradeinst->required_fields);
1 efrain 516
 
517
        // where to look for final grades - include grade of this item too, we will store the results there
518
        $gis = array_merge($depends_on, array($this->grade_item->id));
519
        list($usql, $params) = $DB->get_in_or_equal($gis);
520
 
521
        if ($userid) {
1441 ariadna 522
            $usersql = "AND userid=?";
1 efrain 523
            $params[] = $userid;
524
 
525
        } else {
526
            $usersql = "";
527
        }
528
 
529
        // group the results by userid and aggregate the grades for this user
1441 ariadna 530
        $rs = $DB->get_recordset_select('grade_grades', "itemid $usql $usersql", $params, 'userid', $fields);
1 efrain 531
        if ($rs->valid()) {
532
            $prevuser = 0;
533
            $grade_values = array();
534
            $excluded     = array();
535
            $oldgrade     = null;
536
            $grademaxoverrides = array();
537
            $grademinoverrides = array();
538
 
539
            foreach ($rs as $used) {
540
                $grade = new grade_grade($used, false);
541
                if (isset($items[$grade->itemid])) {
542
                    // Prevent grade item to be fetched from DB.
543
                    $grade->grade_item =& $items[$grade->itemid];
544
                } else if ($grade->itemid == $this->grade_item->id) {
545
                    // This grade's grade item is not in $items.
546
                    $grade->grade_item =& $this->grade_item;
547
                }
548
                if ($grade->userid != $prevuser) {
549
                    $this->aggregate_grades($prevuser,
550
                                            $items,
551
                                            $grade_values,
552
                                            $oldgrade,
553
                                            $excluded,
554
                                            $grademinoverrides,
555
                                            $grademaxoverrides);
556
                    $prevuser = $grade->userid;
557
                    $grade_values = array();
558
                    $excluded     = array();
559
                    $oldgrade     = null;
560
                    $grademaxoverrides = array();
561
                    $grademinoverrides = array();
562
                }
563
                $grade_values[$grade->itemid] = $grade->finalgrade;
564
                $grademaxoverrides[$grade->itemid] = $grade->get_grade_max();
565
                $grademinoverrides[$grade->itemid] = $grade->get_grade_min();
566
 
567
                if ($grade->excluded) {
568
                    $excluded[] = $grade->itemid;
569
                }
570
 
571
                if ($this->grade_item->id == $grade->itemid) {
572
                    $oldgrade = $grade;
573
                }
574
 
575
                if ($progress) {
576
                    // Incrementing the progress by nothing causes it to send an update (once per second)
577
                    // to the web browser so as to prevent the connection timing out.
578
                    $progress->increment_progress(0);
579
                }
580
            }
581
            $this->aggregate_grades($prevuser,
582
                                    $items,
583
                                    $grade_values,
584
                                    $oldgrade,
585
                                    $excluded,
586
                                    $grademinoverrides,
587
                                    $grademaxoverrides);//the last one
588
        }
589
        $rs->close();
590
 
591
        return true;
592
    }
593
 
594
    /**
595
     * Internal function for grade category grade aggregation
596
     *
597
     * @param int    $userid The User ID
598
     * @param array  $items Grade items
599
     * @param array  $grade_values Array of grade values
600
     * @param object $oldgrade Old grade
601
     * @param array  $excluded Excluded
602
     * @param array  $grademinoverrides User specific grademin values if different to the grade_item grademin (key is itemid)
603
     * @param array  $grademaxoverrides User specific grademax values if different to the grade_item grademax (key is itemid)
604
     */
605
    private function aggregate_grades($userid,
606
                                      $items,
607
                                      $grade_values,
608
                                      $oldgrade,
609
                                      $excluded,
610
                                      $grademinoverrides,
611
                                      $grademaxoverrides) {
612
        global $CFG, $DB;
613
 
614
        // Remember these so we can set flags on them to describe how they were used in the aggregation.
615
        $novalue = array();
616
        $dropped = array();
617
        $extracredit = array();
618
        $usedweights = array();
619
 
620
        if (empty($userid)) {
621
            //ignore first call
622
            return;
623
        }
624
 
625
        if ($oldgrade) {
626
            $oldfinalgrade = $oldgrade->finalgrade;
627
            $grade = new grade_grade($oldgrade, false);
628
            $grade->grade_item =& $this->grade_item;
629
 
630
        } else {
631
            // insert final grade - it will be needed later anyway
632
            $grade = new grade_grade(array('itemid'=>$this->grade_item->id, 'userid'=>$userid), false);
633
            $grade->grade_item =& $this->grade_item;
634
            $grade->insert('system');
635
            $oldfinalgrade = null;
636
        }
637
 
638
        // no need to recalculate locked or overridden grades
639
        if ($grade->is_locked() or $grade->is_overridden()) {
640
            return;
641
        }
642
 
643
        // can not use own final category grade in calculation
644
        unset($grade_values[$this->grade_item->id]);
645
 
646
        // Make sure a grade_grade exists for every grade_item.
647
        // We need to do this so we can set the aggregationstatus
648
        // with a set_field call instead of checking if each one exists and creating/updating.
649
        if (!empty($items)) {
650
            list($ggsql, $params) = $DB->get_in_or_equal(array_keys($items), SQL_PARAMS_NAMED, 'g');
651
 
652
 
653
            $params['userid'] = $userid;
654
            $sql = "SELECT itemid
655
                      FROM {grade_grades}
656
                     WHERE itemid $ggsql AND userid = :userid";
657
            $existingitems = $DB->get_records_sql($sql, $params);
658
 
659
            $notexisting = array_diff(array_keys($items), array_keys($existingitems));
660
            foreach ($notexisting as $itemid) {
661
                $gradeitem = $items[$itemid];
662
                $gradegrade = new grade_grade(array('itemid' => $itemid,
663
                                                    'userid' => $userid,
664
                                                    'rawgrademin' => $gradeitem->grademin,
665
                                                    'rawgrademax' => $gradeitem->grademax), false);
666
                $gradegrade->grade_item = $gradeitem;
667
                $gradegrade->insert('system');
668
            }
669
        }
670
 
671
        // if no grades calculation possible or grading not allowed clear final grade
672
        if (empty($grade_values) or empty($items) or ($this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE)) {
673
            $grade->finalgrade = null;
674
 
675
            if (!is_null($oldfinalgrade)) {
676
                $grade->timemodified = time();
677
                $success = $grade->update('aggregation');
678
 
679
                // If successful trigger a user_graded event.
680
                if ($success) {
681
                    \core\event\user_graded::create_from_grade($grade, \core\event\base::USER_OTHER)->trigger();
682
                }
683
            }
684
            $dropped = $grade_values;
685
            $this->set_usedinaggregation($userid, $usedweights, $novalue, $dropped, $extracredit);
686
            return;
687
        }
688
 
689
        // Normalize the grades first - all will have value 0...1
690
        // ungraded items are not used in aggregation.
691
        foreach ($grade_values as $itemid=>$v) {
692
            if (is_null($v)) {
693
                // If null, it means no grade.
694
                if ($this->aggregateonlygraded) {
695
                    unset($grade_values[$itemid]);
696
                    // Mark this item as "excluded empty" because it has no grade.
697
                    $novalue[$itemid] = 0;
698
                    continue;
699
                }
700
            }
701
            if (in_array($itemid, $excluded)) {
702
                unset($grade_values[$itemid]);
703
                $dropped[$itemid] = 0;
704
                continue;
705
            }
706
            // Check for user specific grade min/max overrides.
707
            $usergrademin = $items[$itemid]->grademin;
708
            $usergrademax = $items[$itemid]->grademax;
709
            if (isset($grademinoverrides[$itemid])) {
710
                $usergrademin = $grademinoverrides[$itemid];
711
            }
712
            if (isset($grademaxoverrides[$itemid])) {
713
                $usergrademax = $grademaxoverrides[$itemid];
714
            }
715
            if ($this->aggregation == GRADE_AGGREGATE_SUM) {
716
                // Assume that the grademin is 0 when standardising the score, to preserve negative grades.
717
                $grade_values[$itemid] = grade_grade::standardise_score($v, 0, $usergrademax, 0, 1);
718
            } else {
719
                $grade_values[$itemid] = grade_grade::standardise_score($v, $usergrademin, $usergrademax, 0, 1);
720
            }
721
 
722
        }
723
 
724
        // First, check if all grades are null, because the final grade will be null
725
        // even when aggreateonlygraded is true.
726
        $allnull = true;
727
        foreach ($grade_values as $v) {
728
            if (!is_null($v)) {
729
                $allnull = false;
730
                break;
731
            }
732
        }
733
 
734
        // For items with no value, and not excluded - either set their grade to 0 or exclude them.
735
        foreach ($items as $itemid=>$value) {
736
            if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
737
                if (!$this->aggregateonlygraded) {
738
                    $grade_values[$itemid] = 0;
739
                } else {
740
                    // We are specifically marking these items as "excluded empty".
741
                    $novalue[$itemid] = 0;
742
                }
743
            }
744
        }
745
 
746
        // limit and sort
747
        $allvalues = $grade_values;
748
        if ($this->can_apply_limit_rules()) {
749
            $this->apply_limit_rules($grade_values, $items);
750
        }
751
 
752
        $moredropped = array_diff($allvalues, $grade_values);
753
        foreach ($moredropped as $drop => $unused) {
754
            $dropped[$drop] = 0;
755
        }
756
 
757
        foreach ($grade_values as $itemid => $val) {
758
            if (self::is_extracredit_used() && ($items[$itemid]->aggregationcoef > 0)) {
759
                $extracredit[$itemid] = 0;
760
            }
761
        }
762
 
763
        asort($grade_values, SORT_NUMERIC);
764
 
765
        // let's see we have still enough grades to do any statistics
766
        if (count($grade_values) == 0) {
767
            // not enough attempts yet
768
            $grade->finalgrade = null;
769
 
770
            if (!is_null($oldfinalgrade)) {
771
                $grade->timemodified = time();
772
                $success = $grade->update('aggregation');
773
 
774
                // If successful trigger a user_graded event.
775
                if ($success) {
776
                    \core\event\user_graded::create_from_grade($grade, \core\event\base::USER_OTHER)->trigger();
777
                }
778
            }
779
            $this->set_usedinaggregation($userid, $usedweights, $novalue, $dropped, $extracredit);
780
            return;
781
        }
782
 
783
        // do the maths
784
        $result = $this->aggregate_values_and_adjust_bounds($grade_values,
785
                                                            $items,
786
                                                            $usedweights,
787
                                                            $grademinoverrides,
788
                                                            $grademaxoverrides);
789
        $agg_grade = $result['grade'];
790
 
791
        // Set the actual grademin and max to bind the grade properly.
792
        $this->grade_item->grademin = $result['grademin'];
793
        $this->grade_item->grademax = $result['grademax'];
794
 
795
        if ($this->aggregation == GRADE_AGGREGATE_SUM) {
796
            // The natural aggregation always displays the range as coming from 0 for categories.
797
            // However, when we bind the grade we allow for negative values.
798
            $result['grademin'] = 0;
799
        }
800
 
801
        if ($allnull) {
802
            $grade->finalgrade = null;
803
        } else {
804
            // Recalculate the grade back to requested range.
805
            $finalgrade = grade_grade::standardise_score($agg_grade, 0, 1, $result['grademin'], $result['grademax']);
806
            $grade->finalgrade = $this->grade_item->bounded_grade($finalgrade);
807
        }
808
 
809
        $oldrawgrademin = $grade->rawgrademin;
810
        $oldrawgrademax = $grade->rawgrademax;
811
        $grade->rawgrademin = $result['grademin'];
812
        $grade->rawgrademax = $result['grademax'];
813
 
814
        // Update in db if changed.
815
        if (grade_floats_different($grade->finalgrade, $oldfinalgrade) ||
816
                grade_floats_different($grade->rawgrademax, $oldrawgrademax) ||
817
                grade_floats_different($grade->rawgrademin, $oldrawgrademin)) {
818
            $grade->timemodified = time();
819
            $success = $grade->update('aggregation');
820
 
821
            // If successful trigger a user_graded event.
822
            if ($success) {
823
                \core\event\user_graded::create_from_grade($grade, \core\event\base::USER_OTHER)->trigger();
824
            }
825
        }
826
 
827
        $this->set_usedinaggregation($userid, $usedweights, $novalue, $dropped, $extracredit);
828
 
829
        return;
830
    }
831
 
832
    /**
833
     * Set the flags on the grade_grade items to indicate how individual grades are used
834
     * in the aggregation.
835
     *
836
     * WARNING: This function is called a lot during gradebook recalculation, be very performance considerate.
837
     *
838
     * @param int $userid The user we have aggregated the grades for.
839
     * @param array $usedweights An array with keys for each of the grade_item columns included in the aggregation. The value are the relative weight.
840
     * @param array $novalue An array with keys for each of the grade_item columns skipped because
841
     *                       they had no value in the aggregation.
842
     * @param array $dropped An array with keys for each of the grade_item columns dropped
843
     *                       because of any drop lowest/highest settings in the aggregation.
844
     * @param array $extracredit An array with keys for each of the grade_item columns
845
     *                       considered extra credit by the aggregation.
846
     */
847
    private function set_usedinaggregation($userid, $usedweights, $novalue, $dropped, $extracredit) {
848
        global $DB;
849
 
850
        // We want to know all current user grades so we can decide whether they need to be updated or they already contain the
851
        // expected value.
852
        $sql = "SELECT gi.id, gg.aggregationstatus, gg.aggregationweight FROM {grade_grades} gg
853
                  JOIN {grade_items} gi ON (gg.itemid = gi.id)
854
                 WHERE gg.userid = :userid";
855
        $params = array('categoryid' => $this->id, 'userid' => $userid);
856
 
857
        // These are all grade_item ids which grade_grades will NOT end up being 'unknown' (because they are not unknown or
858
        // because we will update them to something different that 'unknown').
859
        $giids = array_keys($usedweights + $novalue + $dropped + $extracredit);
860
 
861
        if ($giids) {
862
            // We include grade items that might not be in categoryid.
863
            list($itemsql, $itemlist) = $DB->get_in_or_equal($giids, SQL_PARAMS_NAMED, 'gg');
864
            $sql .= ' AND (gi.categoryid = :categoryid OR gi.id ' . $itemsql . ')';
865
            $params = $params + $itemlist;
866
        } else {
867
            $sql .= ' AND gi.categoryid = :categoryid';
868
        }
869
        $currentgrades = $DB->get_recordset_sql($sql, $params);
870
 
871
        // We will store here the grade_item ids that need to be updated on db.
872
        $toupdate = array();
873
 
874
        if ($currentgrades->valid()) {
875
 
876
            // Iterate through the user grades to see if we really need to update any of them.
877
            foreach ($currentgrades as $currentgrade) {
878
 
879
                // Unset $usedweights that we do not need to update.
880
                if (!empty($usedweights) && isset($usedweights[$currentgrade->id]) && $currentgrade->aggregationstatus === 'used') {
881
                    // We discard the ones that already have the contribution specified in $usedweights and are marked as 'used'.
882
                    if (grade_floats_equal($currentgrade->aggregationweight, $usedweights[$currentgrade->id])) {
883
                        unset($usedweights[$currentgrade->id]);
884
                    }
885
                    // Used weights can be present in multiple set_usedinaggregation arguments.
886
                    if (!isset($novalue[$currentgrade->id]) && !isset($dropped[$currentgrade->id]) &&
887
                            !isset($extracredit[$currentgrade->id])) {
888
                        continue;
889
                    }
890
                }
891
 
892
                // No value grades.
893
                if (!empty($novalue) && isset($novalue[$currentgrade->id])) {
894
                    if ($currentgrade->aggregationstatus !== 'novalue' ||
895
                            grade_floats_different($currentgrade->aggregationweight, 0)) {
896
                        $toupdate['novalue'][] = $currentgrade->id;
897
                    }
898
                    continue;
899
                }
900
 
901
                // Dropped grades.
902
                if (!empty($dropped) && isset($dropped[$currentgrade->id])) {
903
                    if ($currentgrade->aggregationstatus !== 'dropped' ||
904
                            grade_floats_different($currentgrade->aggregationweight, 0)) {
905
                        $toupdate['dropped'][] = $currentgrade->id;
906
                    }
907
                    continue;
908
                }
909
 
910
                // Extra credit grades.
911
                if (!empty($extracredit) && isset($extracredit[$currentgrade->id])) {
912
 
913
                    // If this grade item is already marked as 'extra' and it already has the provided $usedweights value would be
914
                    // silly to update to 'used' to later update to 'extra'.
915
                    if (!empty($usedweights) && isset($usedweights[$currentgrade->id]) &&
916
                            grade_floats_equal($currentgrade->aggregationweight, $usedweights[$currentgrade->id])) {
917
                        unset($usedweights[$currentgrade->id]);
918
                    }
919
 
920
                    // Update the item to extra if it is not already marked as extra in the database or if the item's
921
                    // aggregationweight will be updated when going through $usedweights items.
922
                    if ($currentgrade->aggregationstatus !== 'extra' ||
923
                            (!empty($usedweights) && isset($usedweights[$currentgrade->id]))) {
924
                        $toupdate['extracredit'][] = $currentgrade->id;
925
                    }
926
                    continue;
927
                }
928
 
929
                // If is not in any of the above groups it should be set to 'unknown', checking that the item is not already
930
                // unknown, if it is we don't need to update it.
931
                if ($currentgrade->aggregationstatus !== 'unknown' || grade_floats_different($currentgrade->aggregationweight, 0)) {
932
                    $toupdate['unknown'][] = $currentgrade->id;
933
                }
934
            }
935
            $currentgrades->close();
936
        }
937
 
938
        // Update items to 'unknown' status.
939
        if (!empty($toupdate['unknown'])) {
940
            list($itemsql, $itemlist) = $DB->get_in_or_equal($toupdate['unknown'], SQL_PARAMS_NAMED, 'g');
941
 
942
            $itemlist['userid'] = $userid;
943
 
944
            $sql = "UPDATE {grade_grades}
945
                       SET aggregationstatus = 'unknown',
946
                           aggregationweight = 0
947
                     WHERE itemid $itemsql AND userid = :userid";
948
            $DB->execute($sql, $itemlist);
949
        }
950
 
951
        // Update items to 'used' status and setting the proper weight.
952
        if (!empty($usedweights)) {
953
            // The usedweights items are updated individually to record the weights.
954
            foreach ($usedweights as $gradeitemid => $contribution) {
955
                $sql = "UPDATE {grade_grades}
956
                           SET aggregationstatus = 'used',
957
                               aggregationweight = :contribution
958
                         WHERE itemid = :itemid AND userid = :userid";
959
 
960
                $params = array('contribution' => $contribution, 'itemid' => $gradeitemid, 'userid' => $userid);
961
                $DB->execute($sql, $params);
962
            }
963
        }
964
 
965
        // Update items to 'novalue' status.
966
        if (!empty($toupdate['novalue'])) {
967
            list($itemsql, $itemlist) = $DB->get_in_or_equal($toupdate['novalue'], SQL_PARAMS_NAMED, 'g');
968
 
969
            $itemlist['userid'] = $userid;
970
 
971
            $sql = "UPDATE {grade_grades}
972
                       SET aggregationstatus = 'novalue',
973
                           aggregationweight = 0
974
                     WHERE itemid $itemsql AND userid = :userid";
975
 
976
            $DB->execute($sql, $itemlist);
977
        }
978
 
979
        // Update items to 'dropped' status.
980
        if (!empty($toupdate['dropped'])) {
981
            list($itemsql, $itemlist) = $DB->get_in_or_equal($toupdate['dropped'], SQL_PARAMS_NAMED, 'g');
982
 
983
            $itemlist['userid'] = $userid;
984
 
985
            $sql = "UPDATE {grade_grades}
986
                       SET aggregationstatus = 'dropped',
987
                           aggregationweight = 0
988
                     WHERE itemid $itemsql AND userid = :userid";
989
 
990
            $DB->execute($sql, $itemlist);
991
        }
992
 
993
        // Update items to 'extracredit' status.
994
        if (!empty($toupdate['extracredit'])) {
995
            list($itemsql, $itemlist) = $DB->get_in_or_equal($toupdate['extracredit'], SQL_PARAMS_NAMED, 'g');
996
 
997
            $itemlist['userid'] = $userid;
998
 
999
            $DB->set_field_select('grade_grades',
1000
                                  'aggregationstatus',
1001
                                  'extra',
1002
                                  "itemid $itemsql AND userid = :userid",
1003
                                  $itemlist);
1004
        }
1005
    }
1006
 
1007
    /**
1008
     * Internal function that calculates the aggregated grade and new min/max for this grade category
1009
     *
1010
     * Must be public as it is used by grade_grade::get_hiding_affected()
1011
     *
1012
     * @param array $grade_values An array of values to be aggregated
1013
     * @param array $items The array of grade_items
1014
     * @since Moodle 2.6.5, 2.7.2
1015
     * @param array & $weights If provided, will be filled with the normalized weights
1016
     *                         for each grade_item as used in the aggregation.
1017
     *                         Some rules for the weights are:
1018
     *                         1. The weights must add up to 1 (unless there are extra credit)
1019
     *                         2. The contributed points column must add up to the course
1020
     *                         final grade and this column is calculated from these weights.
1021
     * @param array  $grademinoverrides User specific grademin values if different to the grade_item grademin (key is itemid)
1022
     * @param array  $grademaxoverrides User specific grademax values if different to the grade_item grademax (key is itemid)
1023
     * @return array containing values for:
1024
     *                'grade' => the new calculated grade
1025
     *                'grademin' => the new calculated min grade for the category
1026
     *                'grademax' => the new calculated max grade for the category
1027
     */
1028
    public function aggregate_values_and_adjust_bounds($grade_values,
1029
                                                       $items,
1030
                                                       & $weights = null,
1031
                                                       $grademinoverrides = array(),
1032
                                                       $grademaxoverrides = array()) {
1033
        global $CFG;
1034
 
1035
        $category_item = $this->load_grade_item();
1036
        $grademin = $category_item->grademin;
1037
        $grademax = $category_item->grademax;
1038
 
1039
        switch ($this->aggregation) {
1040
 
1041
            case GRADE_AGGREGATE_MEDIAN: // Middle point value in the set: ignores frequencies
1042
                $num = count($grade_values);
1043
                $grades = array_values($grade_values);
1044
 
1045
                // The median gets 100% - others get 0.
1046
                if ($weights !== null && $num > 0) {
1047
                    $count = 0;
1048
                    foreach ($grade_values as $itemid=>$grade_value) {
1049
                        if (($num % 2 == 0) && ($count == intval($num/2)-1 || $count == intval($num/2))) {
1050
                            $weights[$itemid] = 0.5;
1051
                        } else if (($num % 2 != 0) && ($count == intval(($num/2)-0.5))) {
1052
                            $weights[$itemid] = 1.0;
1053
                        } else {
1054
                            $weights[$itemid] = 0;
1055
                        }
1056
                        $count++;
1057
                    }
1058
                }
1059
                if ($num % 2 == 0) {
1060
                    $agg_grade = ($grades[intval($num/2)-1] + $grades[intval($num/2)]) / 2;
1061
                } else {
1062
                    $agg_grade = $grades[intval(($num/2)-0.5)];
1063
                }
1064
 
1065
                break;
1066
 
1067
            case GRADE_AGGREGATE_MIN:
1068
                $agg_grade = reset($grade_values);
1069
                // Record the weights as used.
1070
                if ($weights !== null) {
1071
                    foreach ($grade_values as $itemid=>$grade_value) {
1072
                        $weights[$itemid] = 0;
1073
                    }
1074
                }
1075
                // Set the first item to 1.
1076
                $itemids = array_keys($grade_values);
1077
                $weights[reset($itemids)] = 1;
1078
                break;
1079
 
1080
            case GRADE_AGGREGATE_MAX:
1081
                // Record the weights as used.
1082
                if ($weights !== null) {
1083
                    foreach ($grade_values as $itemid=>$grade_value) {
1084
                        $weights[$itemid] = 0;
1085
                    }
1086
                }
1087
                // Set the last item to 1.
1088
                $itemids = array_keys($grade_values);
1089
                $weights[end($itemids)] = 1;
1090
                $agg_grade = end($grade_values);
1091
                break;
1092
 
1093
            case GRADE_AGGREGATE_MODE:       // the most common value
1094
                // array_count_values only counts INT and STRING, so if grades are floats we must convert them to string
1095
                $converted_grade_values = array();
1096
 
1097
                foreach ($grade_values as $k => $gv) {
1098
 
1099
                    if (!is_int($gv) && !is_string($gv)) {
1100
                        $converted_grade_values[$k] = (string) $gv;
1101
 
1102
                    } else {
1103
                        $converted_grade_values[$k] = $gv;
1104
                    }
1105
                    if ($weights !== null) {
1106
                        $weights[$k] = 0;
1107
                    }
1108
                }
1109
 
1110
                $freq = array_count_values($converted_grade_values);
1111
                arsort($freq);                      // sort by frequency keeping keys
1112
                $top = reset($freq);               // highest frequency count
1113
                $modes = moodle_array_keys_filter($freq, $top);  // Search for all modes (have the same highest count).
1114
                rsort($modes, SORT_NUMERIC);       // get highest mode
1115
                $agg_grade = reset($modes);
1116
                // Record the weights as used.
1117
                if ($weights !== null && $top > 0) {
1118
                    foreach ($grade_values as $k => $gv) {
1119
                        if ($gv == $agg_grade) {
1120
                            $weights[$k] = 1.0 / $top;
1121
                        }
1122
                    }
1123
                }
1124
                break;
1125
 
1126
            case GRADE_AGGREGATE_WEIGHTED_MEAN: // Weighted average of all existing final grades, weight specified in coef
1127
                $weightsum = 0;
1128
                $sum       = 0;
1129
 
1130
                foreach ($grade_values as $itemid=>$grade_value) {
1131
                    if ($weights !== null) {
1132
                        $weights[$itemid] = $items[$itemid]->aggregationcoef;
1133
                    }
1134
                    if ($items[$itemid]->aggregationcoef <= 0) {
1135
                        continue;
1136
                    }
1137
                    $weightsum += $items[$itemid]->aggregationcoef;
1138
                    $sum       += $items[$itemid]->aggregationcoef * $grade_value;
1139
                }
1140
                if ($weightsum == 0) {
1141
                    $agg_grade = null;
1142
 
1143
                } else {
1144
                    $agg_grade = $sum / $weightsum;
1145
                    if ($weights !== null) {
1146
                        // Normalise the weights.
1147
                        foreach ($weights as $itemid => $weight) {
1148
                            $weights[$itemid] = $weight / $weightsum;
1149
                        }
1150
                    }
1151
 
1152
                }
1153
                break;
1154
 
1155
            case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1156
                // Weighted average of all existing final grades with optional extra credit flag,
1157
                // weight is the range of grade (usually grademax)
1158
                $this->load_grade_item();
1159
                $weightsum = 0;
1160
                $sum       = null;
1161
 
1162
                foreach ($grade_values as $itemid=>$grade_value) {
1163
                    if ($items[$itemid]->aggregationcoef > 0) {
1164
                        continue;
1165
                    }
1166
 
1167
                    $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
1168
                    if ($weight <= 0) {
1169
                        continue;
1170
                    }
1171
 
1172
                    $weightsum += $weight;
1173
                    $sum += $weight * $grade_value;
1174
                }
1175
 
1176
                // Handle the extra credit items separately to calculate their weight accurately.
1177
                foreach ($grade_values as $itemid => $grade_value) {
1178
                    if ($items[$itemid]->aggregationcoef <= 0) {
1179
                        continue;
1180
                    }
1181
 
1182
                    $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
1183
                    if ($weight <= 0) {
1184
                        $weights[$itemid] = 0;
1185
                        continue;
1186
                    }
1187
 
1188
                    $oldsum = $sum;
1189
                    $weightedgrade = $weight * $grade_value;
1190
                    $sum += $weightedgrade;
1191
 
1192
                    if ($weights !== null) {
1193
                        if ($weightsum <= 0) {
1194
                            $weights[$itemid] = 0;
1195
                            continue;
1196
                        }
1197
 
1198
                        $oldgrade = $oldsum / $weightsum;
1199
                        $grade = $sum / $weightsum;
1200
                        $normoldgrade = grade_grade::standardise_score($oldgrade, 0, 1, $grademin, $grademax);
1201
                        $normgrade = grade_grade::standardise_score($grade, 0, 1, $grademin, $grademax);
1202
                        $boundedoldgrade = $this->grade_item->bounded_grade($normoldgrade);
1203
                        $boundedgrade = $this->grade_item->bounded_grade($normgrade);
1204
 
1205
                        if ($boundedgrade - $boundedoldgrade <= 0) {
1206
                            // Nothing new was added to the grade.
1207
                            $weights[$itemid] = 0;
1208
                        } else if ($boundedgrade < $normgrade) {
1209
                            // The grade has been bounded, the extra credit item needs to have a different weight.
1210
                            $gradediff = $boundedgrade - $normoldgrade;
1211
                            $gradediffnorm = grade_grade::standardise_score($gradediff, $grademin, $grademax, 0, 1);
1212
                            $weights[$itemid] = $gradediffnorm / $grade_value;
1213
                        } else {
1214
                            // Default weighting.
1215
                            $weights[$itemid] = $weight / $weightsum;
1216
                        }
1217
                    }
1218
                }
1219
 
1220
                if ($weightsum == 0) {
1221
                    $agg_grade = $sum; // only extra credits
1222
 
1223
                } else {
1224
                    $agg_grade = $sum / $weightsum;
1225
                }
1226
 
1227
                // Record the weights as used.
1228
                if ($weights !== null) {
1229
                    foreach ($grade_values as $itemid=>$grade_value) {
1230
                        if ($items[$itemid]->aggregationcoef > 0) {
1231
                            // Ignore extra credit items, the weights have already been computed.
1232
                            continue;
1233
                        }
1234
                        if ($weightsum > 0) {
1235
                            $weight = $items[$itemid]->grademax - $items[$itemid]->grademin;
1236
                            $weights[$itemid] = $weight / $weightsum;
1237
                        } else {
1238
                            $weights[$itemid] = 0;
1239
                        }
1240
                    }
1241
                }
1242
                break;
1243
 
1244
            case GRADE_AGGREGATE_EXTRACREDIT_MEAN: // special average
1245
                $this->load_grade_item();
1246
                $num = 0;
1247
                $sum = null;
1248
 
1249
                foreach ($grade_values as $itemid=>$grade_value) {
1250
                    if ($items[$itemid]->aggregationcoef == 0) {
1251
                        $num += 1;
1252
                        $sum += $grade_value;
1253
                        if ($weights !== null) {
1254
                            $weights[$itemid] = 1;
1255
                        }
1256
                    }
1257
                }
1258
 
1259
                // Treating the extra credit items separately to get a chance to calculate their effective weights.
1260
                foreach ($grade_values as $itemid=>$grade_value) {
1261
                    if ($items[$itemid]->aggregationcoef > 0) {
1262
                        $oldsum = $sum;
1263
                        $sum += $items[$itemid]->aggregationcoef * $grade_value;
1264
 
1265
                        if ($weights !== null) {
1266
                            if ($num <= 0) {
1267
                                // The category only contains extra credit items, not setting the weight.
1268
                                continue;
1269
                            }
1270
 
1271
                            $oldgrade = $oldsum / $num;
1272
                            $grade = $sum / $num;
1273
                            $normoldgrade = grade_grade::standardise_score($oldgrade, 0, 1, $grademin, $grademax);
1274
                            $normgrade = grade_grade::standardise_score($grade, 0, 1, $grademin, $grademax);
1275
                            $boundedoldgrade = $this->grade_item->bounded_grade($normoldgrade);
1276
                            $boundedgrade = $this->grade_item->bounded_grade($normgrade);
1277
 
1278
                            if ($boundedgrade - $boundedoldgrade <= 0) {
1279
                                // Nothing new was added to the grade.
1280
                                $weights[$itemid] = 0;
1281
                            } else if ($boundedgrade < $normgrade) {
1282
                                // The grade has been bounded, the extra credit item needs to have a different weight.
1283
                                $gradediff = $boundedgrade - $normoldgrade;
1284
                                $gradediffnorm = grade_grade::standardise_score($gradediff, $grademin, $grademax, 0, 1);
1285
                                $weights[$itemid] = $gradediffnorm / $grade_value;
1286
                            } else {
1287
                                // Default weighting.
1288
                                $weights[$itemid] = 1.0 / $num;
1289
                            }
1290
                        }
1291
                    }
1292
                }
1293
 
1294
                if ($weights !== null && $num > 0) {
1295
                    foreach ($grade_values as $itemid=>$grade_value) {
1296
                        if ($items[$itemid]->aggregationcoef > 0) {
1297
                            // Extra credit weights were already calculated.
1298
                            continue;
1299
                        }
1300
                        if ($weights[$itemid]) {
1301
                            $weights[$itemid] = 1.0 / $num;
1302
                        }
1303
                    }
1304
                }
1305
 
1306
                if ($num == 0) {
1307
                    $agg_grade = $sum; // only extra credits or wrong coefs
1308
 
1309
                } else {
1310
                    $agg_grade = $sum / $num;
1311
                }
1312
 
1313
                break;
1314
 
1315
            case GRADE_AGGREGATE_SUM:    // Add up all the items.
1316
                $this->load_grade_item();
1317
                $num = count($grade_values);
1318
                $sum = 0;
1319
 
1320
                // This setting indicates if we should use algorithm prior to MDL-49257 fix for calculating extra credit weights.
1321
                // Even though old algorith has bugs in it, we need to preserve existing grades.
1322
                $gradebookcalculationfreeze = 'gradebook_calculations_freeze_' . $this->courseid;
1323
                $oldextracreditcalculation = isset($CFG->$gradebookcalculationfreeze)
1324
                        && ($CFG->$gradebookcalculationfreeze <= 20150619);
1325
 
1326
                $sumweights = 0;
1327
                $grademin = 0;
1328
                $grademax = 0;
1329
                $extracredititems = array();
1330
                foreach ($grade_values as $itemid => $gradevalue) {
1331
                    // We need to check if the grademax/min was adjusted per user because of excluded items.
1332
                    $usergrademin = $items[$itemid]->grademin;
1333
                    $usergrademax = $items[$itemid]->grademax;
1334
                    if (isset($grademinoverrides[$itemid])) {
1335
                        $usergrademin = $grademinoverrides[$itemid];
1336
                    }
1337
                    if (isset($grademaxoverrides[$itemid])) {
1338
                        $usergrademax = $grademaxoverrides[$itemid];
1339
                    }
1340
 
1341
                    // Keep track of the extra credit items, we will need them later on.
1342
                    if ($items[$itemid]->aggregationcoef > 0) {
1343
                        $extracredititems[$itemid] = $items[$itemid];
1344
                    }
1345
 
1346
                    // Ignore extra credit and items with a weight of 0.
1347
                    if (!isset($extracredititems[$itemid]) && $items[$itemid]->aggregationcoef2 > 0) {
1348
                        $grademin += $usergrademin;
1349
                        $grademax += $usergrademax;
1350
                        $sumweights += $items[$itemid]->aggregationcoef2;
1351
                    }
1352
                }
1353
                $userweights = array();
1354
                $totaloverriddenweight = 0;
1355
                $totaloverriddengrademax = 0;
1356
                // We first need to rescale all manually assigned weights down by the
1357
                // percentage of weights missing from the category.
1358
                foreach ($grade_values as $itemid => $gradevalue) {
1359
                    if ($items[$itemid]->weightoverride) {
1360
                        if ($items[$itemid]->aggregationcoef2 <= 0) {
1361
                            // Records the weight of 0 and continue.
1362
                            $userweights[$itemid] = 0;
1363
                            continue;
1364
                        }
1365
                        $userweights[$itemid] = $sumweights ? ($items[$itemid]->aggregationcoef2 / $sumweights) : 0;
1366
                        if (!$oldextracreditcalculation && isset($extracredititems[$itemid])) {
1367
                            // Extra credit items do not affect totals.
1368
                            continue;
1369
                        }
1370
                        $totaloverriddenweight += $userweights[$itemid];
1371
                        $usergrademax = $items[$itemid]->grademax;
1372
                        if (isset($grademaxoverrides[$itemid])) {
1373
                            $usergrademax = $grademaxoverrides[$itemid];
1374
                        }
1375
                        $totaloverriddengrademax += $usergrademax;
1376
                    }
1377
                }
1378
                $nonoverriddenpoints = $grademax - $totaloverriddengrademax;
1379
 
1380
                // Then we need to recalculate the automatic weights except for extra credit items.
1381
                foreach ($grade_values as $itemid => $gradevalue) {
1382
                    if (!$items[$itemid]->weightoverride && ($oldextracreditcalculation || !isset($extracredititems[$itemid]))) {
1383
                        $usergrademax = $items[$itemid]->grademax;
1384
                        if (isset($grademaxoverrides[$itemid])) {
1385
                            $usergrademax = $grademaxoverrides[$itemid];
1386
                        }
1387
                        if ($nonoverriddenpoints > 0) {
1388
                            $userweights[$itemid] = ($usergrademax/$nonoverriddenpoints) * (1 - $totaloverriddenweight);
1389
                        } else {
1390
                            $userweights[$itemid] = 0;
1391
                            if ($items[$itemid]->aggregationcoef2 > 0) {
1392
                                // Items with a weight of 0 should not count for the grade max,
1393
                                // though this only applies if the weight was changed to 0.
1394
                                $grademax -= $usergrademax;
1395
                            }
1396
                        }
1397
                    }
1398
                }
1399
 
1400
                // Now when we finally know the grademax we can adjust the automatic weights of extra credit items.
1401
                if (!$oldextracreditcalculation) {
1402
                    foreach ($grade_values as $itemid => $gradevalue) {
1403
                        if (!$items[$itemid]->weightoverride && isset($extracredititems[$itemid])) {
1404
                            $usergrademax = $items[$itemid]->grademax;
1405
                            if (isset($grademaxoverrides[$itemid])) {
1406
                                $usergrademax = $grademaxoverrides[$itemid];
1407
                            }
1408
                            $userweights[$itemid] = $grademax ? ($usergrademax / $grademax) : 0;
1409
                        }
1410
                    }
1411
                }
1412
 
1413
                // We can use our freshly corrected weights below.
1414
                foreach ($grade_values as $itemid => $gradevalue) {
1415
                    if (isset($extracredititems[$itemid])) {
1416
                        // We skip the extra credit items first.
1417
                        continue;
1418
                    }
1419
                    $sum += $gradevalue * $userweights[$itemid] * $grademax;
1420
                    if ($weights !== null) {
1421
                        $weights[$itemid] = $userweights[$itemid];
1422
                    }
1423
                }
1424
 
1425
                // No we proceed with the extra credit items. They might have a different final
1426
                // weight in case the final grade was bounded. So we need to treat them different.
1427
                // Also, as we need to use the bounded_grade() method, we have to inject the
1428
                // right values there, and restore them afterwards.
1429
                $oldgrademax = $this->grade_item->grademax;
1430
                $oldgrademin = $this->grade_item->grademin;
1431
                foreach ($grade_values as $itemid => $gradevalue) {
1432
                    if (!isset($extracredititems[$itemid])) {
1433
                        continue;
1434
                    }
1435
                    $oldsum = $sum;
1436
                    $weightedgrade = $gradevalue * $userweights[$itemid] * $grademax;
1437
                    $sum += $weightedgrade;
1438
 
1439
                    // Only go through this when we need to record the weights.
1440
                    if ($weights !== null) {
1441
                        if ($grademax <= 0) {
1442
                            // There are only extra credit items in this category,
1443
                            // all the weights should be accurate (and be 0).
1444
                            $weights[$itemid] = $userweights[$itemid];
1445
                            continue;
1446
                        }
1447
 
1448
                        $oldfinalgrade = $this->grade_item->bounded_grade($oldsum);
1449
                        $newfinalgrade = $this->grade_item->bounded_grade($sum);
1450
                        $finalgradediff = $newfinalgrade - $oldfinalgrade;
1451
                        if ($finalgradediff <= 0) {
1452
                            // This item did not contribute to the category total at all.
1453
                            $weights[$itemid] = 0;
1454
                        } else if ($finalgradediff < $weightedgrade) {
1455
                            // The weight needs to be adjusted because only a portion of the
1456
                            // extra credit item contributed to the category total.
1457
                            $weights[$itemid] = $finalgradediff / ($gradevalue * $grademax);
1458
                        } else {
1459
                            // The weight was accurate.
1460
                            $weights[$itemid] = $userweights[$itemid];
1461
                        }
1462
                    }
1463
                }
1464
                $this->grade_item->grademax = $oldgrademax;
1465
                $this->grade_item->grademin = $oldgrademin;
1466
 
1467
                if ($grademax > 0) {
1468
                    $agg_grade = $sum / $grademax; // Re-normalize score.
1469
                } else {
1470
                    // Every item in the category is extra credit.
1471
                    $agg_grade = $sum;
1472
                    $grademax = $sum;
1473
                }
1474
 
1475
                break;
1476
 
1477
            case GRADE_AGGREGATE_MEAN:    // Arithmetic average of all grade items (if ungraded aggregated, NULL counted as minimum)
1478
            default:
1479
                $num = count($grade_values);
1480
                $sum = array_sum($grade_values);
1481
                $agg_grade = $sum / $num;
1482
                // Record the weights evenly.
1483
                if ($weights !== null && $num > 0) {
1484
                    foreach ($grade_values as $itemid=>$grade_value) {
1485
                        $weights[$itemid] = 1.0 / $num;
1486
                    }
1487
                }
1488
                break;
1489
        }
1490
 
1491
        return array('grade' => $agg_grade, 'grademin' => $grademin, 'grademax' => $grademax);
1492
    }
1493
 
1494
    /**
1495
     * Internal function that calculates the aggregated grade for this grade category
1496
     *
1497
     * Must be public as it is used by grade_grade::get_hiding_affected()
1498
     *
1499
     * @deprecated since Moodle 2.8
1500
     * @param array $grade_values An array of values to be aggregated
1501
     * @param array $items The array of grade_items
1502
     * @return float The aggregate grade for this grade category
1503
     */
1504
    public function aggregate_values($grade_values, $items) {
1505
        debugging('grade_category::aggregate_values() is deprecated.
1506
                   Call grade_category::aggregate_values_and_adjust_bounds() instead.', DEBUG_DEVELOPER);
1507
        $result = $this->aggregate_values_and_adjust_bounds($grade_values, $items);
1508
        return $result['grade'];
1509
    }
1510
 
1511
    /**
1512
     * Some aggregation types may need to update their max grade.
1513
     *
1514
     * This must be executed after updating the weights as it relies on them.
1515
     *
1516
     * @return void
1517
     */
1518
    private function auto_update_max() {
1519
        global $CFG, $DB;
1520
        if ($this->aggregation != GRADE_AGGREGATE_SUM) {
1521
            // not needed at all
1522
            return;
1523
        }
1524
 
1525
        // Find grade items of immediate children (category or grade items) and force site settings.
1526
        $this->load_grade_item();
1527
        $depends_on = $this->grade_item->depends_on();
1528
 
1529
        // Check to see if the gradebook is frozen. This allows grades to not be altered at all until a user verifies that they
1530
        // wish to update the grades.
1531
        $gradebookcalculationfreeze = 'gradebook_calculations_freeze_' . $this->courseid;
1532
        $oldextracreditcalculation = isset($CFG->$gradebookcalculationfreeze) && ($CFG->$gradebookcalculationfreeze <= 20150627);
1533
        // Only run if the gradebook isn't frozen.
1534
        if (!$oldextracreditcalculation) {
1535
            // Don't automatically update the max for calculated items.
1536
            if ($this->grade_item->is_calculated()) {
1537
                return;
1538
            }
1539
        }
1540
 
1541
        $items = false;
1542
        if (!empty($depends_on)) {
1543
            list($usql, $params) = $DB->get_in_or_equal($depends_on);
1544
            $sql = "SELECT *
1545
                      FROM {grade_items}
1546
                     WHERE id $usql";
1547
            $items = $DB->get_records_sql($sql, $params);
1548
        }
1549
 
1550
        if (!$items) {
1551
 
1552
            if ($this->grade_item->grademax != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
1553
                $this->grade_item->grademax  = 0;
1554
                $this->grade_item->grademin  = 0;
1555
                $this->grade_item->gradetype = GRADE_TYPE_VALUE;
1556
                $this->grade_item->update('aggregation');
1557
            }
1558
            return;
1559
        }
1560
 
1561
        //find max grade possible
1562
        $maxes = array();
1563
 
1564
        foreach ($items as $item) {
1565
 
1566
            if ($item->aggregationcoef > 0) {
1567
                // extra credit from this activity - does not affect total
1568
                continue;
1569
            } else if ($item->aggregationcoef2 <= 0) {
1570
                // Items with a weight of 0 do not affect the total.
1571
                continue;
1572
            }
1573
 
1574
            if ($item->gradetype == GRADE_TYPE_VALUE) {
1575
                $maxes[$item->id] = $item->grademax;
1576
 
1577
            } else if ($item->gradetype == GRADE_TYPE_SCALE) {
1578
                $maxes[$item->id] = $item->grademax; // 0 = nograde, 1 = first scale item, 2 = second scale item
1579
            }
1580
        }
1581
 
1582
        if ($this->can_apply_limit_rules()) {
1583
            // Apply droplow and keephigh.
1584
            $this->apply_limit_rules($maxes, $items);
1585
        }
1586
        $max = array_sum($maxes);
1587
 
1588
        // update db if anything changed
1589
        if ($this->grade_item->grademax != $max or $this->grade_item->grademin != 0 or $this->grade_item->gradetype != GRADE_TYPE_VALUE) {
1590
            $this->grade_item->grademax  = $max;
1591
            $this->grade_item->grademin  = 0;
1592
            $this->grade_item->gradetype = GRADE_TYPE_VALUE;
1593
            $this->grade_item->update('aggregation');
1594
        }
1595
    }
1596
 
1597
    /**
1598
     * Recalculate the weights of the grade items in this category.
1599
     *
1600
     * The category total is not updated here, a further call to
1601
     * {@link self::auto_update_max()} is required.
1602
     *
1603
     * @return void
1604
     */
1605
    private function auto_update_weights() {
1606
        global $CFG;
1607
        if ($this->aggregation != GRADE_AGGREGATE_SUM) {
1608
            // This is only required if we are using natural weights.
1609
            return;
1610
        }
1611
        $children = $this->get_children();
1612
 
1613
        $gradeitem = null;
1614
 
1615
        // Calculate the sum of the grademax's of all the items within this category.
1616
        $totalnonoverriddengrademax = 0;
1617
        $totalgrademax = 0;
1618
 
1619
        // Out of 1, how much weight has been manually overriden by a user?
1620
        $totaloverriddenweight  = 0;
1621
        $totaloverriddengrademax  = 0;
1622
 
1623
        // Has every assessment in this category been overridden?
1624
        $automaticgradeitemspresent = false;
1625
        // Does the grade item require normalising?
1626
        $requiresnormalising = false;
1627
 
1628
        // This array keeps track of the id and weight of every grade item that has been overridden.
1629
        $overridearray = array();
1630
        foreach ($children as $sortorder => $child) {
1631
            $gradeitem = null;
1632
 
1633
            if ($child['type'] == 'item') {
1634
                $gradeitem = $child['object'];
1635
            } else if ($child['type'] == 'category') {
1636
                $gradeitem = $child['object']->load_grade_item();
1637
            }
1638
 
1639
            if ($gradeitem->gradetype == GRADE_TYPE_NONE || $gradeitem->gradetype == GRADE_TYPE_TEXT) {
1640
                // Text items and none items do not have a weight.
1641
                continue;
1642
            } else if (!$this->aggregateoutcomes && $gradeitem->is_outcome_item()) {
1643
                // We will not aggregate outcome items, so we can ignore them.
1644
                continue;
1645
            } else if (empty($CFG->grade_includescalesinaggregation) && $gradeitem->gradetype == GRADE_TYPE_SCALE) {
1646
                // The scales are not included in the aggregation, ignore them.
1647
                continue;
1648
            }
1649
 
1650
            // Record the ID and the weight for this grade item.
1651
            $overridearray[$gradeitem->id] = array();
1652
            $overridearray[$gradeitem->id]['extracredit'] = intval($gradeitem->aggregationcoef);
1653
            $overridearray[$gradeitem->id]['weight'] = $gradeitem->aggregationcoef2;
1654
            $overridearray[$gradeitem->id]['weightoverride'] = intval($gradeitem->weightoverride);
1655
            // If this item has had its weight overridden then set the flag to true, but
1656
            // only if all previous items were also overridden. Note that extra credit items
1657
            // are counted as overridden grade items.
1658
            if (!$gradeitem->weightoverride && $gradeitem->aggregationcoef == 0) {
1659
                $automaticgradeitemspresent = true;
1660
            }
1661
 
1662
            if ($gradeitem->aggregationcoef > 0) {
1663
                // An extra credit grade item doesn't contribute to $totaloverriddengrademax.
1664
                continue;
1665
            } else if ($gradeitem->weightoverride > 0 && $gradeitem->aggregationcoef2 <= 0) {
1666
                // An overridden item that defines a weight of 0 does not contribute to $totaloverriddengrademax.
1667
                continue;
1668
            }
1669
 
1670
            $totalgrademax += $gradeitem->grademax;
1671
            if ($gradeitem->weightoverride > 0) {
1672
                $totaloverriddenweight += $gradeitem->aggregationcoef2;
1673
                $totaloverriddengrademax += $gradeitem->grademax;
1674
            }
1675
        }
1676
 
1677
        // Initialise this variable (used to keep track of the weight override total).
1678
        $normalisetotal = 0;
1679
        // Keep a record of how much the override total is to see if it is above 100. It it is then we need to set the
1680
        // other weights to zero and normalise the others.
1681
        $overriddentotal = 0;
1682
        // Total up all of the weights.
1683
        foreach ($overridearray as $gradeitemdetail) {
1684
            // If the grade item has extra credit, then don't add it to the normalisetotal.
1685
            if (!$gradeitemdetail['extracredit']) {
1686
                $normalisetotal += $gradeitemdetail['weight'];
1687
            }
1688
            // The overridden total comprises of items that are set as overridden, that aren't extra credit and have a value
1689
            // greater than zero.
1690
            if ($gradeitemdetail['weightoverride'] && !$gradeitemdetail['extracredit'] && $gradeitemdetail['weight'] > 0) {
1691
                // Add overriden weights up to see if they are greater than 1.
1692
                $overriddentotal += $gradeitemdetail['weight'];
1693
            }
1694
        }
1695
        if ($overriddentotal > 1) {
1696
            // Make sure that this catergory of weights gets normalised.
1697
            $requiresnormalising = true;
1698
            // The normalised weights are only the overridden weights, so we just use the total of those.
1699
            $normalisetotal = $overriddentotal;
1700
        }
1701
 
1702
        $totalnonoverriddengrademax = $totalgrademax - $totaloverriddengrademax;
1703
 
1704
        // This setting indicates if we should use algorithm prior to MDL-49257 fix for calculating extra credit weights.
1705
        // Even though old algorith has bugs in it, we need to preserve existing grades.
1706
        $gradebookcalculationfreeze = (int)get_config('core', 'gradebook_calculations_freeze_' . $this->courseid);
1707
        $oldextracreditcalculation = $gradebookcalculationfreeze && ($gradebookcalculationfreeze <= 20150619);
1708
 
1709
        reset($children);
1710
        foreach ($children as $sortorder => $child) {
1711
            $gradeitem = null;
1712
 
1713
            if ($child['type'] == 'item') {
1714
                $gradeitem = $child['object'];
1715
            } else if ($child['type'] == 'category') {
1716
                $gradeitem = $child['object']->load_grade_item();
1717
            }
1718
 
1719
            if ($gradeitem->gradetype == GRADE_TYPE_NONE || $gradeitem->gradetype == GRADE_TYPE_TEXT) {
1720
                // Text items and none items do not have a weight, no need to set their weight to
1721
                // zero as they must never be used during aggregation.
1722
                continue;
1723
            } else if (!$this->aggregateoutcomes && $gradeitem->is_outcome_item()) {
1724
                // We will not aggregate outcome items, so we can ignore updating their weights.
1725
                continue;
1726
            } else if (empty($CFG->grade_includescalesinaggregation) && $gradeitem->gradetype == GRADE_TYPE_SCALE) {
1727
                // We will not aggregate the scales, so we can ignore upating their weights.
1728
                continue;
1729
            } else if (!$oldextracreditcalculation && $gradeitem->aggregationcoef > 0 && $gradeitem->weightoverride) {
1730
                // For an item with extra credit ignore other weigths and overrides but do not change anything at all
1731
                // if it's weight was already overridden.
1732
                continue;
1733
            }
1734
 
1735
            // Store the previous value here, no need to update if it is the same value.
1736
            $prevaggregationcoef2 = $gradeitem->aggregationcoef2;
1737
 
1738
            if (!$oldextracreditcalculation && $gradeitem->aggregationcoef > 0 && !$gradeitem->weightoverride) {
1739
                // For an item with extra credit ignore other weigths and overrides.
1740
                $gradeitem->aggregationcoef2 = $totalgrademax ? ($gradeitem->grademax / $totalgrademax) : 0;
1741
 
1742
            } else if (!$gradeitem->weightoverride) {
1743
                // Calculations with a grade maximum of zero will cause problems. Just set the weight to zero.
1744
                if ($totaloverriddenweight >= 1 || $totalnonoverriddengrademax == 0 || $gradeitem->grademax == 0) {
1745
                    // There is no more weight to distribute.
1746
                    $gradeitem->aggregationcoef2 = 0;
1747
                } else {
1748
                    // Calculate this item's weight as a percentage of the non-overridden total grade maxes
1749
                    // then convert it to a proportion of the available non-overriden weight.
1750
                    $gradeitem->aggregationcoef2 = ($gradeitem->grademax/$totalnonoverriddengrademax) *
1751
                            (1 - $totaloverriddenweight);
1752
                }
1753
 
1754
            } else if ((!$automaticgradeitemspresent && $normalisetotal != 1) || ($requiresnormalising)
1755
                    || $overridearray[$gradeitem->id]['weight'] < 0) {
1756
                // Just divide the overriden weight for this item against the total weight override of all
1757
                // items in this category.
1758
                if ($normalisetotal == 0 || $overridearray[$gradeitem->id]['weight'] < 0) {
1759
                    // If the normalised total equals zero, or the weight value is less than zero,
1760
                    // set the weight for the grade item to zero.
1761
                    $gradeitem->aggregationcoef2 = 0;
1762
                } else {
1763
                    $gradeitem->aggregationcoef2 = $overridearray[$gradeitem->id]['weight'] / $normalisetotal;
1764
                }
1765
            }
1766
 
1767
            if (grade_floatval($prevaggregationcoef2) !== grade_floatval($gradeitem->aggregationcoef2)) {
1768
                // Update the grade item to reflect these changes.
1769
                $gradeitem->update();
1770
            }
1771
        }
1772
    }
1773
 
1774
    /**
1775
     * Given an array of grade values (numerical indices) applies droplow or keephigh rules to limit the final array.
1776
     *
1777
     * @param array $grade_values itemid=>$grade_value float
1778
     * @param array $items grade item objects
1779
     * @return array Limited grades.
1780
     */
1781
    public function apply_limit_rules(&$grade_values, $items) {
1782
        $extraused = $this->is_extracredit_used();
1783
 
1784
        if (!empty($this->droplow)) {
1785
            asort($grade_values, SORT_NUMERIC);
1786
            $dropped = 0;
1787
 
1788
            // If we have fewer grade items available to drop than $this->droplow, use this flag to escape the loop
1789
            // May occur because of "extra credit" or if droplow is higher than the number of grade items
1790
            $droppedsomething = true;
1791
 
1792
            while ($dropped < $this->droplow && $droppedsomething) {
1793
                $droppedsomething = false;
1794
 
1795
                $grade_keys = array_keys($grade_values);
1796
                $gradekeycount = count($grade_keys);
1797
 
1798
                if ($gradekeycount === 0) {
1799
                    //We've dropped all grade items
1800
                    break;
1801
                }
1802
 
1803
                $originalindex = $founditemid = $foundmax = null;
1804
 
1805
                // Find the first remaining grade item that is available to be dropped
1806
                foreach ($grade_keys as $gradekeyindex=>$gradekey) {
1807
                    if (!$extraused || $items[$gradekey]->aggregationcoef <= 0) {
1808
                        // Found a non-extra credit grade item that is eligible to be dropped
1809
                        $originalindex = $gradekeyindex;
1810
                        $founditemid = $grade_keys[$originalindex];
1811
                        $foundmax = $items[$founditemid]->grademax;
1812
                        break;
1813
                    }
1814
                }
1815
 
1816
                if (empty($founditemid)) {
1817
                    // No grade items available to drop
1818
                    break;
1819
                }
1820
 
1821
                // Now iterate over the remaining grade items
1822
                // We're looking for other grade items with the same grade value but a higher grademax
1823
                $i = 1;
1824
                while ($originalindex + $i < $gradekeycount) {
1825
 
1826
                    $possibleitemid = $grade_keys[$originalindex+$i];
1827
                    $i++;
1828
 
1829
                    if ($grade_values[$founditemid] != $grade_values[$possibleitemid]) {
1830
                        // The next grade item has a different grade value. Stop looking.
1831
                        break;
1832
                    }
1833
 
1834
                    if ($extraused && $items[$possibleitemid]->aggregationcoef > 0) {
1835
                        // Don't drop extra credit grade items. Continue the search.
1836
                        continue;
1837
                    }
1838
 
1839
                    if ($foundmax < $items[$possibleitemid]->grademax) {
1840
                        // Found a grade item with the same grade value and a higher grademax
1841
                        $foundmax = $items[$possibleitemid]->grademax;
1842
                        $founditemid = $possibleitemid;
1843
                        // Continue searching to see if there is an even higher grademax
1844
                    }
1845
                }
1846
 
1847
                // Now drop whatever grade item we have found
1848
                unset($grade_values[$founditemid]);
1849
                $dropped++;
1850
                $droppedsomething = true;
1851
            }
1852
 
1853
        } else if (!empty($this->keephigh)) {
1854
            arsort($grade_values, SORT_NUMERIC);
1855
            $kept = 0;
1856
 
1857
            foreach ($grade_values as $itemid=>$value) {
1858
 
1859
                if ($extraused and $items[$itemid]->aggregationcoef > 0) {
1860
                    // we keep all extra credits
1861
 
1862
                } else if ($kept < $this->keephigh) {
1863
                    $kept++;
1864
 
1865
                } else {
1866
                    unset($grade_values[$itemid]);
1867
                }
1868
            }
1869
        }
1870
    }
1871
 
1872
    /**
1873
     * Returns whether or not we can apply the limit rules.
1874
     *
1875
     * There are cases where drop lowest or keep highest should not be used
1876
     * at all. This method will determine whether or not this logic can be
1877
     * applied considering the current setup of the category.
1878
     *
1879
     * @return bool
1880
     */
1881
    public function can_apply_limit_rules() {
1882
        if ($this->canapplylimitrules !== null) {
1883
            return $this->canapplylimitrules;
1884
        }
1885
 
1886
        // Set it to be supported by default.
1887
        $this->canapplylimitrules = true;
1888
 
1889
        // Natural aggregation.
1890
        if ($this->aggregation == GRADE_AGGREGATE_SUM) {
1891
            $canapply = true;
1892
 
1893
            // Check until one child breaks the rules.
1894
            $gradeitems = $this->get_children();
1895
            $validitems = 0;
1896
            $lastweight = null;
1897
            $lastmaxgrade = null;
1898
            foreach ($gradeitems as $gradeitem) {
1899
                $gi = $gradeitem['object'];
1900
 
1901
                if ($gradeitem['type'] == 'category') {
1902
                    // Sub categories are not allowed because they can have dynamic weights/maxgrades.
1903
                    $canapply = false;
1904
                    break;
1905
                }
1906
 
1907
                if ($gi->aggregationcoef > 0) {
1908
                    // Extra credit items are not allowed.
1909
                    $canapply = false;
1910
                    break;
1911
                }
1912
 
1913
                if ($lastweight !== null && $lastweight != $gi->aggregationcoef2) {
1914
                    // One of the weight differs from another item.
1915
                    $canapply = false;
1916
                    break;
1917
                }
1918
 
1919
                if ($lastmaxgrade !== null && $lastmaxgrade != $gi->grademax) {
1920
                    // One of the max grade differ from another item. This is not allowed for now
1921
                    // because we could be end up with different max grade between users for this category.
1922
                    $canapply = false;
1923
                    break;
1924
                }
1925
 
1926
                $lastweight = $gi->aggregationcoef2;
1927
                $lastmaxgrade = $gi->grademax;
1928
            }
1929
 
1930
            $this->canapplylimitrules = $canapply;
1931
        }
1932
 
1933
        return $this->canapplylimitrules;
1934
    }
1935
 
1936
    /**
1937
     * Returns true if category uses extra credit of any kind
1938
     *
1939
     * @return bool True if extra credit used
1940
     */
1941
    public function is_extracredit_used() {
1942
        return self::aggregation_uses_extracredit($this->aggregation);
1943
    }
1944
 
1945
    /**
1946
     * Returns true if aggregation passed is using extracredit.
1947
     *
1948
     * @param int $aggregation Aggregation const.
1949
     * @return bool True if extra credit used
1950
     */
1951
    public static function aggregation_uses_extracredit($aggregation) {
1952
        return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1953
             or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1954
             or $aggregation == GRADE_AGGREGATE_SUM);
1955
    }
1956
 
1957
    /**
1958
     * Returns true if category uses special aggregation coefficient
1959
     *
1960
     * @return bool True if an aggregation coefficient is being used
1961
     */
1962
    public function is_aggregationcoef_used() {
1963
        return self::aggregation_uses_aggregationcoef($this->aggregation);
1964
 
1965
    }
1966
 
1967
    /**
1968
     * Returns true if aggregation uses aggregationcoef
1969
     *
1970
     * @param int $aggregation Aggregation const.
1971
     * @return bool True if an aggregation coefficient is being used
1972
     */
1973
    public static function aggregation_uses_aggregationcoef($aggregation) {
1974
        return ($aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN
1975
             or $aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2
1976
             or $aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN
1977
             or $aggregation == GRADE_AGGREGATE_SUM);
1978
 
1979
    }
1980
 
1981
    /**
1982
     * Recursive function to find which weight/extra credit field to use in the grade item form.
1983
     *
1984
     * @param string $first Whether or not this is the first item in the recursion
1985
     * @return string
1986
     */
1987
    public function get_coefstring($first=true) {
1988
        if (!is_null($this->coefstring)) {
1989
            return $this->coefstring;
1990
        }
1991
 
1992
        $overriding_coefstring = null;
1993
 
1994
        // Stop recursing upwards if this category has no parent
1995
        if (!$first) {
1996
 
1997
            if ($parent_category = $this->load_parent_category()) {
1998
                return $parent_category->get_coefstring(false);
1999
 
2000
            } else {
2001
                return null;
2002
            }
2003
 
2004
        } else if ($first) {
2005
 
2006
            if ($parent_category = $this->load_parent_category()) {
2007
                $overriding_coefstring = $parent_category->get_coefstring(false);
2008
            }
2009
        }
2010
 
2011
        // If an overriding coefstring has trickled down from one of the parent categories, return it. Otherwise, return self.
2012
        if (!is_null($overriding_coefstring)) {
2013
            return $overriding_coefstring;
2014
        }
2015
 
2016
        // No parent category is overriding this category's aggregation, return its string
2017
        if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
2018
            $this->coefstring = 'aggregationcoefweight';
2019
 
2020
        } else if ($this->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2) {
2021
            $this->coefstring = 'aggregationcoefextrasum';
2022
 
2023
        } else if ($this->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
2024
            $this->coefstring = 'aggregationcoefextraweight';
2025
 
2026
        } else if ($this->aggregation == GRADE_AGGREGATE_SUM) {
2027
            $this->coefstring = 'aggregationcoefextraweightsum';
2028
 
2029
        } else {
2030
            $this->coefstring = 'aggregationcoef';
2031
        }
2032
        return $this->coefstring;
2033
    }
2034
 
2035
    /**
2036
     * Returns tree with all grade_items and categories as elements
2037
     *
2038
     * @param int $courseid The course ID
2039
     * @param bool $include_category_items as category children
2040
     * @return array
2041
     */
2042
    public static function fetch_course_tree($courseid, $include_category_items=false) {
2043
        $course_category = grade_category::fetch_course_category($courseid);
2044
        $category_array = array('object'=>$course_category, 'type'=>'category', 'depth'=>1,
2045
                                'children'=>$course_category->get_children($include_category_items));
2046
 
2047
        $course_category->sortorder = $course_category->get_sortorder();
2048
        $sortorder = $course_category->get_sortorder();
2049
        return grade_category::_fetch_course_tree_recursion($category_array, $sortorder);
2050
    }
2051
 
2052
    /**
2053
     * An internal function that recursively sorts grade categories within a course
2054
     *
2055
     * @param array $category_array The seed of the recursion
2056
     * @param int   $sortorder The current sortorder
2057
     * @return array An array containing 'object', 'type', 'depth' and optionally 'children'
2058
     */
2059
    private static function _fetch_course_tree_recursion($category_array, &$sortorder) {
2060
        if (isset($category_array['object']->gradetype) && $category_array['object']->gradetype==GRADE_TYPE_NONE) {
2061
            return null;
2062
        }
2063
 
2064
        // store the grade_item or grade_category instance with extra info
2065
        $result = array('object'=>$category_array['object'], 'type'=>$category_array['type'], 'depth'=>$category_array['depth']);
2066
 
2067
        // reuse final grades if there
2068
        if (array_key_exists('finalgrades', $category_array)) {
2069
            $result['finalgrades'] = $category_array['finalgrades'];
2070
        }
2071
 
2072
        // recursively resort children
2073
        if (!empty($category_array['children'])) {
2074
            $result['children'] = array();
2075
            //process the category item first
2076
            $child = null;
2077
 
2078
            foreach ($category_array['children'] as $oldorder=>$child_array) {
2079
 
2080
                if ($child_array['type'] == 'courseitem' or $child_array['type'] == 'categoryitem') {
2081
                    $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
2082
                    if (!empty($child)) {
2083
                        $result['children'][$sortorder] = $child;
2084
                    }
2085
                }
2086
            }
2087
 
2088
            foreach ($category_array['children'] as $oldorder=>$child_array) {
2089
 
2090
                if ($child_array['type'] != 'courseitem' and $child_array['type'] != 'categoryitem') {
2091
                    $child = grade_category::_fetch_course_tree_recursion($child_array, $sortorder);
2092
                    if (!empty($child)) {
2093
                        $result['children'][++$sortorder] = $child;
2094
                    }
2095
                }
2096
            }
2097
        }
2098
 
2099
        return $result;
2100
    }
2101
 
2102
    /**
2103
     * Fetches and returns all the children categories and/or grade_items belonging to this category.
2104
     * By default only returns the immediate children (depth=1), but deeper levels can be requested,
2105
     * as well as all levels (0). The elements are indexed by sort order.
2106
     *
2107
     * @param bool $include_category_items Whether or not to include category grade_items in the children array
2108
     * @return array Array of child objects (grade_category and grade_item).
2109
     */
2110
    public function get_children($include_category_items=false) {
2111
        global $DB;
2112
 
2113
        // This function must be as fast as possible ;-)
2114
        // fetch all course grade items and categories into memory - we do not expect hundreds of these in course
2115
        // we have to limit the number of queries though, because it will be used often in grade reports
2116
 
2117
        $cats  = $DB->get_records('grade_categories', array('courseid' => $this->courseid));
2118
        $items = $DB->get_records('grade_items', array('courseid' => $this->courseid));
2119
 
2120
        // init children array first
2121
        foreach ($cats as $catid=>$cat) {
2122
            $cats[$catid]->children = array();
2123
        }
2124
 
2125
        //first attach items to cats and add category sortorder
2126
        foreach ($items as $item) {
2127
 
2128
            if ($item->itemtype == 'course' or $item->itemtype == 'category') {
2129
                $cats[$item->iteminstance]->sortorder = $item->sortorder;
2130
 
2131
                if (!$include_category_items) {
2132
                    continue;
2133
                }
2134
                $categoryid = $item->iteminstance;
2135
 
2136
            } else {
2137
                $categoryid = $item->categoryid;
2138
                if (empty($categoryid)) {
2139
                    debugging('Found a grade item that isnt in a category');
2140
                }
2141
            }
2142
 
2143
            // prevent problems with duplicate sortorders in db
2144
            $sortorder = $item->sortorder;
2145
 
2146
            while (array_key_exists($categoryid, $cats)
2147
                && array_key_exists($sortorder, $cats[$categoryid]->children)) {
2148
 
2149
                $sortorder++;
2150
            }
2151
 
2152
            $cats[$categoryid]->children[$sortorder] = $item;
2153
 
2154
        }
2155
 
2156
        // now find the requested category and connect categories as children
2157
        $category = false;
2158
 
2159
        foreach ($cats as $catid=>$cat) {
2160
 
2161
            if (empty($cat->parent)) {
2162
 
2163
                if ($cat->path !== '/'.$cat->id.'/') {
2164
                    $grade_category = new grade_category($cat, false);
2165
                    $grade_category->path  = '/'.$cat->id.'/';
2166
                    $grade_category->depth = 1;
2167
                    $grade_category->update('system');
2168
                    return $this->get_children($include_category_items);
2169
                }
2170
 
2171
            } else {
2172
 
2173
                if (empty($cat->path) or !preg_match('|/'.$cat->parent.'/'.$cat->id.'/$|', $cat->path)) {
2174
                    //fix paths and depts
2175
                    static $recursioncounter = 0; // prevents infinite recursion
2176
                    $recursioncounter++;
2177
 
2178
                    if ($recursioncounter < 5) {
2179
                        // fix paths and depths!
2180
                        $grade_category = new grade_category($cat, false);
2181
                        $grade_category->depth = 0;
2182
                        $grade_category->path  = null;
2183
                        $grade_category->update('system');
2184
                        return $this->get_children($include_category_items);
2185
                    }
2186
                }
2187
                // prevent problems with duplicate sortorders in db
2188
                $sortorder = $cat->sortorder;
2189
 
2190
                while (array_key_exists($sortorder, $cats[$cat->parent]->children)) {
2191
                    //debugging("$sortorder exists in cat loop");
2192
                    $sortorder++;
2193
                }
2194
 
2195
                $cats[$cat->parent]->children[$sortorder] = &$cats[$catid];
2196
            }
2197
 
2198
            if ($catid == $this->id) {
2199
                $category = &$cats[$catid];
2200
            }
2201
        }
2202
 
2203
        unset($items); // not needed
2204
        unset($cats); // not needed
2205
 
2206
        $children_array = array();
2207
        if (is_object($category)) {
2208
            $children_array = grade_category::_get_children_recursion($category);
2209
            ksort($children_array);
2210
        }
2211
 
2212
        return $children_array;
2213
 
2214
    }
2215
 
2216
    /**
2217
     * Private method used to retrieve all children of this category recursively
2218
     *
2219
     * @param grade_category $category Source of current recursion
2220
     * @return array An array of child grade categories
2221
     */
2222
    private static function _get_children_recursion($category) {
2223
 
2224
        $children_array = array();
2225
        foreach ($category->children as $sortorder=>$child) {
2226
 
2227
            if (property_exists($child, 'itemtype')) {
2228
                $grade_item = new grade_item($child, false);
2229
 
2230
                if (in_array($grade_item->itemtype, array('course', 'category'))) {
2231
                    $type  = $grade_item->itemtype.'item';
2232
                    $depth = $category->depth;
2233
 
2234
                } else {
2235
                    $type  = 'item';
2236
                    $depth = $category->depth; // we use this to set the same colour
2237
                }
2238
                $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);
2239
 
2240
            } else {
2241
                $children = grade_category::_get_children_recursion($child);
2242
                $grade_category = new grade_category($child, false);
2243
 
2244
                if (empty($children)) {
2245
                    $children = array();
2246
                }
2247
                $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
2248
            }
2249
        }
2250
 
2251
        // sort the array
2252
        ksort($children_array);
2253
 
2254
        return $children_array;
2255
    }
2256
 
2257
    /**
2258
     * Uses {@link get_grade_item()} to load or create a grade_item, then saves it as $this->grade_item.
2259
     *
2260
     * @return grade_item
2261
     */
2262
    public function load_grade_item() {
2263
        if (empty($this->grade_item)) {
2264
            $this->grade_item = $this->get_grade_item();
2265
        }
2266
        return $this->grade_item;
2267
    }
2268
 
2269
    /**
2270
     * Retrieves this grade categories' associated grade_item from the database
2271
     *
2272
     * If no grade_item exists yet, creates one.
2273
     *
2274
     * @return grade_item
2275
     */
2276
    public function get_grade_item() {
2277
        if (empty($this->id)) {
2278
            debugging("Attempt to obtain a grade_category's associated grade_item without the category's ID being set.");
2279
            return false;
2280
        }
2281
 
2282
        if (empty($this->parent)) {
2283
            $params = array('courseid'=>$this->courseid, 'itemtype'=>'course', 'iteminstance'=>$this->id);
2284
 
2285
        } else {
2286
            $params = array('courseid'=>$this->courseid, 'itemtype'=>'category', 'iteminstance'=>$this->id);
2287
        }
2288
 
2289
        if (!$grade_items = grade_item::fetch_all($params)) {
2290
            // create a new one
2291
            $grade_item = new grade_item($params, false);
2292
            $grade_item->gradetype = GRADE_TYPE_VALUE;
2293
            $grade_item->insert('system');
2294
 
2295
        } else if (count($grade_items) == 1) {
2296
            // found existing one
2297
            $grade_item = reset($grade_items);
2298
 
2299
        } else {
2300
            debugging("Found more than one grade_item attached to category id:".$this->id);
2301
            // return first one
2302
            $grade_item = reset($grade_items);
2303
        }
2304
 
2305
        return $grade_item;
2306
    }
2307
 
2308
    /**
2309
     * Uses $this->parent to instantiate $this->parent_category based on the referenced record in the DB
2310
     *
2311
     * @return grade_category The parent category
2312
     */
2313
    public function load_parent_category() {
2314
        if (empty($this->parent_category) && !empty($this->parent)) {
2315
            $this->parent_category = $this->get_parent_category();
2316
        }
2317
        return $this->parent_category;
2318
    }
2319
 
2320
    /**
2321
     * Uses $this->parent to instantiate and return a grade_category object
2322
     *
2323
     * @return grade_category Returns the parent category or null if this category has no parent
2324
     */
2325
    public function get_parent_category() {
2326
        if (!empty($this->parent)) {
2327
            $parent_category = new grade_category(array('id' => $this->parent));
2328
            return $parent_category;
2329
        } else {
2330
            return null;
2331
        }
2332
    }
2333
 
2334
    /**
2335
     * Returns the most descriptive field for this grade category
2336
     *
2337
     * @return string name
2338
     * @param bool $escape Whether the returned category name is to be HTML escaped or not.
2339
     */
2340
    public function get_name($escape = true) {
2341
        global $DB;
2342
        // For a course category, we return the course name if the fullname is set to '?' in the DB (empty in the category edit form)
2343
        if (empty($this->parent) && $this->fullname == '?') {
2344
            $course = $DB->get_record('course', array('id'=> $this->courseid));
2345
            return format_string($course->fullname, false, ['context' => context_course::instance($this->courseid),
2346
                'escape' => $escape]);
2347
 
2348
        } else {
2349
            // Grade categories can't be set up at system context (unlike scales and outcomes)
2350
            // We therefore must have a courseid, and don't need to handle system contexts when filtering.
2351
            return format_string($this->fullname, false, ['context' => context_course::instance($this->courseid),
2352
                'escape' => $escape]);
2353
        }
2354
    }
2355
 
2356
    /**
2357
     * Describe the aggregation settings for this category so the reports make more sense.
2358
     *
2359
     * @return string description
2360
     */
2361
    public function get_description() {
2362
        $allhelp = array();
2363
        if ($this->aggregation != GRADE_AGGREGATE_SUM) {
2364
            $aggrstrings = grade_helper::get_aggregation_strings();
2365
            $allhelp[] = $aggrstrings[$this->aggregation];
2366
        }
2367
 
2368
        if ($this->droplow && $this->can_apply_limit_rules()) {
2369
            $allhelp[] = get_string('droplowestvalues', 'grades', $this->droplow);
2370
        }
2371
        if ($this->keephigh && $this->can_apply_limit_rules()) {
2372
            $allhelp[] = get_string('keephighestvalues', 'grades', $this->keephigh);
2373
        }
2374
        if (!$this->aggregateonlygraded) {
2375
            $allhelp[] = get_string('aggregatenotonlygraded', 'grades');
2376
        }
2377
        if ($allhelp) {
2378
            return implode('. ', $allhelp) . '.';
2379
        }
2380
        return '';
2381
    }
2382
 
2383
    /**
2384
     * Sets this category's parent id
2385
     *
2386
     * @param int $parentid The ID of the category that is the new parent to $this
2387
     * @param string $source From where was the object updated (mod/forum, manual, etc.)
2388
     * @return bool success
2389
     */
2390
    public function set_parent($parentid, $source=null) {
2391
        if ($this->parent == $parentid) {
2392
            return true;
2393
        }
2394
 
2395
        if ($parentid == $this->id) {
2396
            throw new \moodle_exception('cannotassignselfasparent');
2397
        }
2398
 
2399
        if (empty($this->parent) and $this->is_course_category()) {
2400
            throw new \moodle_exception('cannothaveparentcate');
2401
        }
2402
 
2403
        // find parent and check course id
2404
        if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
2405
            return false;
2406
        }
2407
 
2408
        $this->force_regrading();
2409
 
2410
        // set new parent category
2411
        $this->parent          = $parent_category->id;
2412
        $this->parent_category =& $parent_category;
2413
        $this->path            = null;       // remove old path and depth - will be recalculated in update()
2414
        $this->depth           = 0;          // remove old path and depth - will be recalculated in update()
2415
        $this->update($source);
2416
 
2417
        return $this->update($source);
2418
    }
2419
 
2420
    /**
2421
     * Returns the final grade values for this grade category.
2422
     *
2423
     * @param int $userid Optional user ID to retrieve a single user's final grade
2424
     * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
2425
     */
2426
    public function get_final($userid=null) {
2427
        $this->load_grade_item();
2428
        return $this->grade_item->get_final($userid);
2429
    }
2430
 
2431
    /**
2432
     * Returns the sortorder of the grade categories' associated grade_item
2433
     *
2434
     * This method is also available in grade_item for cases where the object type is not known.
2435
     *
2436
     * @return int Sort order
2437
     */
2438
    public function get_sortorder() {
2439
        $this->load_grade_item();
2440
        return $this->grade_item->get_sortorder();
2441
    }
2442
 
2443
    /**
2444
     * Returns the idnumber of the grade categories' associated grade_item.
2445
     *
2446
     * This method is also available in grade_item for cases where the object type is not known.
2447
     *
2448
     * @return string idnumber
2449
     */
2450
    public function get_idnumber() {
2451
        $this->load_grade_item();
2452
        return $this->grade_item->get_idnumber();
2453
    }
2454
 
2455
    /**
2456
     * Sets the sortorder variable for this category.
2457
     *
2458
     * This method is also available in grade_item, for cases where the object type is not know.
2459
     *
2460
     * @param int $sortorder The sortorder to assign to this category
2461
     */
2462
    public function set_sortorder($sortorder) {
2463
        $this->load_grade_item();
2464
        $this->grade_item->set_sortorder($sortorder);
2465
    }
2466
 
2467
    /**
2468
     * Move this category after the given sortorder
2469
     *
2470
     * Does not change the parent
2471
     *
2472
     * @param int $sortorder to place after.
2473
     * @return void
2474
     */
2475
    public function move_after_sortorder($sortorder) {
2476
        $this->load_grade_item();
2477
        $this->grade_item->move_after_sortorder($sortorder);
2478
    }
2479
 
2480
    /**
2481
     * Return true if this is the top most category that represents the total course grade.
2482
     *
2483
     * @return bool
2484
     */
2485
    public function is_course_category() {
2486
        $this->load_grade_item();
2487
        return $this->grade_item->is_course_item();
2488
    }
2489
 
2490
    /**
2491
     * Return the course level grade_category object
2492
     *
2493
     * @param int $courseid The Course ID
2494
     * @return grade_category Returns the course level grade_category instance
2495
     */
2496
    public static function fetch_course_category($courseid) {
2497
        if (empty($courseid)) {
2498
            debugging('Missing course id!');
2499
            return false;
2500
        }
2501
 
2502
        // course category has no parent
2503
        if ($course_category = grade_category::fetch(array('courseid'=>$courseid, 'parent'=>null))) {
2504
            return $course_category;
2505
        }
2506
 
2507
        // create a new one
2508
        $course_category = new grade_category();
2509
        $course_category->insert_course_category($courseid);
2510
 
2511
        return $course_category;
2512
    }
2513
 
2514
    /**
2515
     * Is grading object editable?
2516
     *
2517
     * @return bool
2518
     */
2519
    public function is_editable() {
2520
        return true;
2521
    }
2522
 
2523
    /**
2524
     * Returns the locked state/date of the grade categories' associated grade_item.
2525
     *
2526
     * This method is also available in grade_item, for cases where the object type is not known.
2527
     *
2528
     * @return bool
2529
     */
2530
    public function is_locked() {
2531
        $this->load_grade_item();
2532
        return $this->grade_item->is_locked();
2533
    }
2534
 
2535
    /**
2536
     * Sets the grade_item's locked variable and updates the grade_item.
2537
     *
2538
     * Calls set_locked() on the categories' grade_item
2539
     *
2540
     * @param int  $lockedstate 0, 1 or a timestamp int(10) after which date the item will be locked.
2541
     * @param bool $cascade lock/unlock child objects too
2542
     * @param bool $refresh refresh grades when unlocking
2543
     * @return bool success if category locked (not all children mayb be locked though)
2544
     */
2545
    public function set_locked($lockedstate, $cascade=false, $refresh=true) {
2546
        $this->load_grade_item();
2547
 
2548
        $result = $this->grade_item->set_locked($lockedstate, $cascade, true);
2549
 
2550
        // Process all children - items and categories.
2551
        if ($children = grade_item::fetch_all(['categoryid' => $this->id])) {
2552
            foreach ($children as $child) {
2553
                $child->set_locked($lockedstate, $cascade, false);
2554
 
2555
                if (empty($lockedstate) && $refresh) {
2556
                    // Refresh when unlocking.
2557
                    $child->refresh_grades();
2558
                }
2559
            }
2560
        }
2561
 
2562
        if ($children = static::fetch_all(['parent' => $this->id])) {
2563
            foreach ($children as $child) {
2564
                $child->set_locked($lockedstate, $cascade, true);
2565
            }
2566
        }
2567
 
2568
        return $result;
2569
    }
2570
 
2571
    /**
2572
     * Overrides grade_object::set_properties() to add special handling for changes to category aggregation types
2573
     *
2574
     * @param grade_category $instance the object to set the properties on
2575
     * @param array|stdClass $params Either an associative array or an object containing property name, property value pairs
2576
     */
2577
    public static function set_properties(&$instance, $params) {
2578
        global $DB;
2579
 
2580
        $fromaggregation = $instance->aggregation;
2581
 
2582
        parent::set_properties($instance, $params);
2583
 
2584
        // The aggregation method is changing and this category has already been saved.
2585
        if (isset($params->aggregation) && !empty($instance->id)) {
2586
            $achildwasdupdated = false;
2587
 
2588
            // Get all its children.
2589
            $children = $instance->get_children();
2590
            foreach ($children as $child) {
2591
                $item = $child['object'];
2592
                if ($child['type'] == 'category') {
2593
                    $item = $item->load_grade_item();
2594
                }
2595
 
2596
                // Set the new aggregation fields.
2597
                if ($item->set_aggregation_fields_for_aggregation($fromaggregation, $params->aggregation)) {
2598
                    $item->update();
2599
                    $achildwasdupdated = true;
2600
                }
2601
            }
2602
 
2603
            // If this is the course category, it is possible that its grade item was set as needsupdate
2604
            // by one of its children. If we keep a reference to that stale object we might cause the
2605
            // needsupdate flag to be lost. It's safer to just reload the grade_item from the database.
2606
            if ($achildwasdupdated && !empty($instance->grade_item) && $instance->is_course_category()) {
2607
                $instance->grade_item = null;
2608
                $instance->load_grade_item();
2609
            }
2610
        }
2611
    }
2612
 
2613
    /**
2614
     * Sets the grade_item's hidden variable and updates the grade_item.
2615
     *
2616
     * Overrides grade_item::set_hidden() to add cascading of the hidden value to grade items in this grade category
2617
     *
2618
     * @param int $hidden 0 mean always visible, 1 means always hidden and a number > 1 is a timestamp to hide until
2619
     * @param bool $cascade apply to child objects too
2620
     */
2621
    public function set_hidden($hidden, $cascade=false) {
2622
        $this->load_grade_item();
2623
        //this hides the category itself and everything it contains
2624
        parent::set_hidden($hidden, $cascade);
2625
 
2626
        if ($cascade) {
2627
 
2628
            // This hides the associated grade item (the course/category total).
2629
            $this->grade_item->set_hidden($hidden, $cascade);
2630
 
2631
            if ($children = grade_item::fetch_all(array('categoryid'=>$this->id))) {
2632
 
2633
                foreach ($children as $child) {
2634
                    if ($child->can_control_visibility()) {
2635
                        $child->set_hidden($hidden, $cascade);
2636
                    }
2637
                }
2638
            }
2639
 
2640
            if ($children = grade_category::fetch_all(array('parent'=>$this->id))) {
2641
 
2642
                foreach ($children as $child) {
2643
                    $child->set_hidden($hidden, $cascade);
2644
                }
2645
            }
2646
        }
2647
 
2648
        //if marking category visible make sure parent category is visible MDL-21367
2649
        if( !$hidden ) {
2650
            $category_array = grade_category::fetch_all(array('id'=>$this->parent));
2651
            if ($category_array && array_key_exists($this->parent, $category_array)) {
2652
                $category = $category_array[$this->parent];
2653
                //call set_hidden on the category regardless of whether it is hidden as its parent might be hidden
2654
                $category->set_hidden($hidden, false);
2655
            }
2656
        }
2657
    }
2658
 
2659
    /**
2660
     * Applies default settings on this category
2661
     *
2662
     * @return bool True if anything changed
2663
     */
2664
    public function apply_default_settings() {
2665
        global $CFG;
2666
 
2667
        foreach ($this->forceable as $property) {
2668
 
2669
            if (isset($CFG->{"grade_$property"})) {
2670
 
2671
                if ($CFG->{"grade_$property"} == -1) {
2672
                    continue; //temporary bc before version bump
2673
                }
2674
                $this->$property = $CFG->{"grade_$property"};
2675
            }
2676
        }
2677
    }
2678
 
2679
    /**
2680
     * Applies forced settings on this category
2681
     *
2682
     * @return bool True if anything changed
2683
     */
2684
    public function apply_forced_settings() {
2685
        global $CFG;
2686
 
2687
        $updated = false;
2688
 
2689
        foreach ($this->forceable as $property) {
2690
 
2691
            if (isset($CFG->{"grade_$property"}) and isset($CFG->{"grade_{$property}_flag"}) and
2692
                                                    ((int) $CFG->{"grade_{$property}_flag"} & 1)) {
2693
 
2694
                if ($CFG->{"grade_$property"} == -1) {
2695
                    continue; //temporary bc before version bump
2696
                }
2697
                $this->$property = $CFG->{"grade_$property"};
2698
                $updated = true;
2699
            }
2700
        }
2701
 
2702
        return $updated;
2703
    }
2704
 
2705
    /**
2706
     * Notification of change in forced category settings.
2707
     *
2708
     * Causes all course and category grade items to be marked as needing to be updated
2709
     */
2710
    public static function updated_forced_settings() {
2711
        global $CFG, $DB;
2712
        $params = array(1, 'course', 'category');
2713
        $sql = "UPDATE {grade_items} SET needsupdate=? WHERE itemtype=? or itemtype=?";
2714
        $DB->execute($sql, $params);
2715
    }
2716
 
2717
    /**
2718
     * Determine the default aggregation values for a given aggregation method.
2719
     *
2720
     * @param int $aggregationmethod The aggregation method constant value.
2721
     * @return array Containing the keys 'aggregationcoef', 'aggregationcoef2' and 'weightoverride'.
2722
     */
2723
    public static function get_default_aggregation_coefficient_values($aggregationmethod) {
2724
        $defaultcoefficients = array(
2725
            'aggregationcoef' => 0,
2726
            'aggregationcoef2' => 0,
2727
            'weightoverride' => 0
2728
        );
2729
 
2730
        switch ($aggregationmethod) {
2731
            case GRADE_AGGREGATE_WEIGHTED_MEAN:
2732
                $defaultcoefficients['aggregationcoef'] = 1;
2733
                break;
2734
            case GRADE_AGGREGATE_SUM:
2735
                $defaultcoefficients['aggregationcoef2'] = 1;
2736
                break;
2737
        }
2738
 
2739
        return $defaultcoefficients;
2740
    }
2741
 
2742
    /**
2743
     * Cleans the cache.
2744
     *
2745
     * We invalidate them all so it can be completely reloaded.
2746
     *
2747
     * Being conservative here, if there is a new grade_category we purge them, the important part
2748
     * is that this is not purged when there are no changes in grade_categories.
2749
     *
2750
     * @param bool $deleted
2751
     * @return void
2752
     */
2753
    protected function notify_changed($deleted) {
2754
        self::clean_record_set();
2755
    }
2756
 
2757
    /**
2758
     * Generates a unique key per query.
2759
     *
2760
     * Not unique between grade_object children. self::retrieve_record_set and self::set_record_set will be in charge of
2761
     * selecting the appropriate cache.
2762
     *
2763
     * @param array $params An array of conditions like $fieldname => $fieldvalue
2764
     * @return string
2765
     */
2766
    protected static function generate_record_set_key($params) {
2767
        return sha1(json_encode($params));
2768
    }
2769
 
2770
    /**
2771
     * Tries to retrieve a record set from the cache.
2772
     *
2773
     * @param array $params The query params
2774
     * @return grade_object[]|bool An array of grade_objects or false if not found.
2775
     */
2776
    protected static function retrieve_record_set($params) {
2777
        $cache = cache::make('core', 'grade_categories');
2778
        return $cache->get(self::generate_record_set_key($params));
2779
    }
2780
 
2781
    /**
2782
     * Sets a result to the records cache, even if there were no results.
2783
     *
2784
     * @param string $params The query params
2785
     * @param grade_object[]|bool $records An array of grade_objects or false if there are no records matching the $key filters
2786
     * @return void
2787
     */
2788
    protected static function set_record_set($params, $records) {
2789
        $cache = cache::make('core', 'grade_categories');
2790
        return $cache->set(self::generate_record_set_key($params), $records);
2791
    }
2792
 
2793
    /**
2794
     * Cleans the cache.
2795
     *
2796
     * Aggressive deletion to be conservative given the gradebook design.
2797
     * The key is based on the requested params, not easy nor worth to purge selectively.
2798
     *
2799
     * @return void
2800
     */
2801
    public static function clean_record_set() {
2802
        cache_helper::purge_by_event('changesingradecategories');
2803
    }
2804
}