coursecatlib.php 124 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Contains class coursecat reponsible for course category operations
 *
 * @package    core
 * @subpackage course
 * @copyright  2013 Marina Glancy
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

defined('MOODLE_INTERNAL') || die();

/**
 * Class to store, cache, render and manage course category
 *
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
 * @property-read int $id
 * @property-read string $name
 * @property-read string $idnumber
 * @property-read string $description
 * @property-read int $descriptionformat
 * @property-read int $parent
 * @property-read int $sortorder
 * @property-read int $coursecount
 * @property-read int $visible
 * @property-read int $visibleold
 * @property-read int $timemodified
 * @property-read int $depth
 * @property-read string $path
 * @property-read string $theme
 *
46
47
48
49
50
51
52
53
54
55
56
57
58
59
 * @package    core
 * @subpackage course
 * @copyright  2013 Marina Glancy
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class coursecat implements renderable, cacheable_object, IteratorAggregate {
    /** @var coursecat stores pseudo category with id=0. Use coursecat::get(0) to retrieve */
    protected static $coursecat0;

    /** @var array list of all fields and their short name and default value for caching */
    protected static $coursecatfields = array(
        'id' => array('id', 0),
        'name' => array('na', ''),
        'idnumber' => array('in', null),
60
61
        'description' => null, // Not cached.
        'descriptionformat' => null, // Not cached.
62
63
        'parent' => array('pa', 0),
        'sortorder' => array('so', 0),
64
        'coursecount' => array('cc', 0),
65
        'visible' => array('vi', 1),
66
67
        'visibleold' => null, // Not cached.
        'timemodified' => null, // Not cached.
68
69
        'depth' => array('dh', 1),
        'path' => array('ph', null),
70
        'theme' => null, // Not cached.
71
72
73
74
75
76
77
78
79
80
81
82
    );

    /** @var int */
    protected $id;

    /** @var string */
    protected $name = '';

    /** @var string */
    protected $idnumber = null;

    /** @var string */
83
    protected $description = false;
84
85

    /** @var int */
86
    protected $descriptionformat = false;
87
88
89
90
91
92
93
94

    /** @var int */
    protected $parent = 0;

    /** @var int */
    protected $sortorder = 0;

    /** @var int */
95
    protected $coursecount = false;
96
97
98
99
100

    /** @var int */
    protected $visible = 1;

    /** @var int */
101
    protected $visibleold = false;
102
103

    /** @var int */
104
    protected $timemodified = false;
105
106
107
108
109
110
111
112

    /** @var int */
    protected $depth = 0;

    /** @var string */
    protected $path = '';

    /** @var string */
113
    protected $theme = false;
114
115
116
117

    /** @var bool */
    protected $fromcache;

118
119
    /** @var bool */
    protected $hasmanagecapability = null;
120
121
122

    /**
     * Magic setter method, we do not want anybody to modify properties from the outside
123
     *
124
125
126
127
128
129
130
131
     * @param string $name
     * @param mixed $value
     */
    public function __set($name, $value) {
        debugging('Can not change coursecat instance properties!', DEBUG_DEVELOPER);
    }

    /**
132
     * Magic method getter, redirects to read only values. Queries from DB the fields that were not cached
133
     *
134
135
136
137
     * @param string $name
     * @return mixed
     */
    public function __get($name) {
138
        global $DB;
139
        if (array_key_exists($name, self::$coursecatfields)) {
140
            if ($this->$name === false) {
141
                // Property was not retrieved from DB, retrieve all not retrieved fields.
142
                $notretrievedfields = array_diff_key(self::$coursecatfields, array_filter(self::$coursecatfields));
143
144
145
146
147
148
                $record = $DB->get_record('course_categories', array('id' => $this->id),
                        join(',', array_keys($notretrievedfields)), MUST_EXIST);
                foreach ($record as $key => $value) {
                    $this->$key = $value;
                }
            }
149
150
151
152
153
154
155
156
            return $this->$name;
        }
        debugging('Invalid coursecat property accessed! '.$name, DEBUG_DEVELOPER);
        return null;
    }

    /**
     * Full support for isset on our magic read only properties.
157
     *
158
159
160
161
162
163
164
165
166
167
168
     * @param string $name
     * @return bool
     */
    public function __isset($name) {
        if (array_key_exists($name, self::$coursecatfields)) {
            return isset($this->$name);
        }
        return false;
    }

    /**
169
170
     * All properties are read only, sorry.
     *
171
172
173
174
175
176
177
178
     * @param string $name
     */
    public function __unset($name) {
        debugging('Can not unset coursecat instance properties!', DEBUG_DEVELOPER);
    }

    /**
     * Create an iterator because magic vars can't be seen by 'foreach'.
179
180
181
182
     *
     * implementing method from interface IteratorAggregate
     *
     * @return ArrayIterator
183
184
185
186
     */
    public function getIterator() {
        $ret = array();
        foreach (self::$coursecatfields as $property => $unused) {
187
188
189
            if ($this->$property !== false) {
                $ret[$property] = $this->$property;
            }
190
191
192
193
194
195
196
197
198
        }
        return new ArrayIterator($ret);
    }

    /**
     * Constructor
     *
     * Constructor is protected, use coursecat::get($id) to retrieve category
     *
199
200
     * @param stdClass $record record from DB (may not contain all fields)
     * @param bool $fromcache whether it is being restored from cache
201
202
     */
    protected function __construct(stdClass $record, $fromcache = false) {
203
        context_helper::preload_from_record($record);
204
205
206
207
208
209
210
211
212
213
214
215
        foreach ($record as $key => $val) {
            if (array_key_exists($key, self::$coursecatfields)) {
                $this->$key = $val;
            }
        }
        $this->fromcache = $fromcache;
    }

    /**
     * Returns coursecat object for requested category
     *
     * If category is not visible to user it is treated as non existing
216
     * unless $alwaysreturnhidden is set to true
217
218
219
220
221
222
223
224
     *
     * If id is 0, the pseudo object for root category is returned (convenient
     * for calling other functions such as get_children())
     *
     * @param int $id category id
     * @param int $strictness whether to throw an exception (MUST_EXIST) or
     *     return null (IGNORE_MISSING) in case the category is not found or
     *     not visible to current user
225
     * @param bool $alwaysreturnhidden set to true if you want an object to be
226
227
228
     *     returned even if this category is not visible to the current user
     *     (category is hidden and user does not have
     *     'moodle/category:viewhiddencategories' capability). Use with care!
229
     * @return null|coursecat
230
     * @throws moodle_exception
231
     */
232
    public static function get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false) {
233
234
        if (!$id) {
            if (!isset(self::$coursecat0)) {
235
236
237
238
239
240
                $record = new stdClass();
                $record->id = 0;
                $record->visible = 1;
                $record->depth = 0;
                $record->path = '';
                self::$coursecat0 = new coursecat($record);
241
242
243
            }
            return self::$coursecat0;
        }
244
245
        $coursecatrecordcache = cache::make('core', 'coursecatrecords');
        $coursecat = $coursecatrecordcache->get($id);
246
        if ($coursecat === false) {
247
248
249
            if ($records = self::get_records('cc.id = :id', array('id' => $id))) {
                $record = reset($records);
                $coursecat = new coursecat($record);
250
                // Store in cache.
251
                $coursecatrecordcache->set($id, $coursecat);
252
253
            }
        }
254
        if ($coursecat && ($alwaysreturnhidden || $coursecat->is_uservisible())) {
255
256
257
            return $coursecat;
        } else {
            if ($strictness == MUST_EXIST) {
258
                throw new moodle_exception('unknowncategory');
259
260
261
262
263
            }
        }
        return null;
    }

264
265
266
267
268
    /**
     * Load many coursecat objects.
     *
     * @global moodle_database $DB
     * @param array $ids An array of category ID's to load.
269
     * @return coursecat[]
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
     */
    public static function get_many(array $ids) {
        global $DB;
        $coursecatrecordcache = cache::make('core', 'coursecatrecords');
        $categories = $coursecatrecordcache->get_many($ids);
        $toload = array();
        foreach ($categories as $id => $result) {
            if ($result === false) {
                $toload[] = $id;
            }
        }
        if (!empty($toload)) {
            list($where, $params) = $DB->get_in_or_equal($toload, SQL_PARAMS_NAMED);
            $records = self::get_records('cc.id '.$where, $params);
            $toset = array();
            foreach ($records as $record) {
                $categories[$record->id] = new coursecat($record);
                $toset[$record->id] = $categories[$record->id];
            }
            $coursecatrecordcache->set_many($toset);
        }
        return $categories;
    }

294
295
296
297
298
299
300
301
302
303
304
305
    /**
     * Returns the first found category
     *
     * Note that if there are no categories visible to the current user on the first level,
     * the invisible category may be returned
     *
     * @return coursecat
     */
    public static function get_default() {
        if ($visiblechildren = self::get(0)->get_children()) {
            $defcategory = reset($visiblechildren);
        } else {
306
307
            $toplevelcategories = self::get_tree(0);
            $defcategoryid = $toplevelcategories[0];
308
309
310
311
312
313
314
315
316
317
            $defcategory = self::get($defcategoryid, MUST_EXIST, true);
        }
        return $defcategory;
    }

    /**
     * Restores the object after it has been externally modified in DB for example
     * during {@link fix_course_sortorder()}
     */
    protected function restore() {
318
        // Update all fields in the current object.
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
        $newrecord = self::get($this->id, MUST_EXIST, true);
        foreach (self::$coursecatfields as $key => $unused) {
            $this->$key = $newrecord->$key;
        }
    }

    /**
     * Creates a new category either from form data or from raw data
     *
     * Please note that this function does not verify access control.
     *
     * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
     *
     * Category visibility is inherited from parent unless $data->visible = 0 is specified
     *
     * @param array|stdClass $data
     * @param array $editoroptions if specified, the data is considered to be
     *    form data and file_postupdate_standard_editor() is being called to
     *    process images in description.
     * @return coursecat
     * @throws moodle_exception
     */
    public static function create($data, $editoroptions = null) {
        global $DB, $CFG;
        $data = (object)$data;
        $newcategory = new stdClass();

        $newcategory->descriptionformat = FORMAT_MOODLE;
        $newcategory->description = '';
348
        // Copy all description* fields regardless of whether this is form data or direct field update.
349
350
351
352
353
354
355
356
357
        foreach ($data as $key => $value) {
            if (preg_match("/^description/", $key)) {
                $newcategory->$key = $value;
            }
        }

        if (empty($data->name)) {
            throw new moodle_exception('categorynamerequired');
        }
358
        if (core_text::strlen($data->name) > 255) {
359
360
361
362
            throw new moodle_exception('categorytoolong');
        }
        $newcategory->name = $data->name;

363
        // Validate and set idnumber.
364
        if (isset($data->idnumber)) {
365
            if (core_text::strlen($data->idnumber) > 100) {
366
367
                throw new moodle_exception('idnumbertoolong');
            }
368
            if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
369
370
                throw new moodle_exception('categoryidnumbertaken');
            }
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
            $newcategory->idnumber = $data->idnumber;
        }

        if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
            $newcategory->theme = $data->theme;
        }

        if (empty($data->parent)) {
            $parent = self::get(0);
        } else {
            $parent = self::get($data->parent, MUST_EXIST, true);
        }
        $newcategory->parent = $parent->id;
        $newcategory->depth = $parent->depth + 1;

386
        // By default category is visible, unless visible = 0 is specified or parent category is hidden.
387
        if (isset($data->visible) && !$data->visible) {
388
            // Create a hidden category.
389
390
            $newcategory->visible = $newcategory->visibleold = 0;
        } else {
391
            // Create a category that inherits visibility from parent.
392
            $newcategory->visible = $parent->visible;
393
            // In case parent is hidden, when it changes visibility this new subcategory will automatically become visible too.
394
395
396
397
398
399
400
401
            $newcategory->visibleold = 1;
        }

        $newcategory->sortorder = 0;
        $newcategory->timemodified = time();

        $newcategory->id = $DB->insert_record('course_categories', $newcategory);

402
        // Update path (only possible after we know the category id.
403
404
405
        $path = $parent->path . '/' . $newcategory->id;
        $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));

406
        // We should mark the context as dirty.
407
408
409
410
        context_coursecat::instance($newcategory->id)->mark_dirty();

        fix_course_sortorder();

411
        // If this is data from form results, save embedded files and update description.
412
413
        $categorycontext = context_coursecat::instance($newcategory->id);
        if ($editoroptions) {
414
415
            $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
                                                           'coursecat', 'description', 0);
416

417
            // Update only fields description and descriptionformat.
418
419
420
421
            $updatedata = new stdClass();
            $updatedata->id = $newcategory->id;
            $updatedata->description = $newcategory->description;
            $updatedata->descriptionformat = $newcategory->descriptionformat;
422
423
424
            $DB->update_record('course_categories', $updatedata);
        }

425
426
427
428
429
430
        $event = \core\event\course_category_created::create(array(
            'objectid' => $newcategory->id,
            'context' => $categorycontext
        ));
        $event->trigger();

431
        cache_helper::purge_by_event('changesincoursecat');
432
433
434
435
436
437
438
439
440

        return self::get($newcategory->id, MUST_EXIST, true);
    }

    /**
     * Updates the record with either form data or raw data
     *
     * Please note that this function does not verify access control.
     *
441
442
     * This function calls coursecat::change_parent_raw if field 'parent' is updated.
     * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
     * Visibility is changed first and then parent is changed. This means that
     * if parent category is hidden, the current category will become hidden
     * too and it may overwrite whatever was set in field 'visible'.
     *
     * Note that fields 'path' and 'depth' can not be updated manually
     * Also coursecat::update() can not directly update the field 'sortoder'
     *
     * @param array|stdClass $data
     * @param array $editoroptions if specified, the data is considered to be
     *    form data and file_postupdate_standard_editor() is being called to
     *    process images in description.
     * @throws moodle_exception
     */
    public function update($data, $editoroptions = null) {
        global $DB, $CFG;
        if (!$this->id) {
459
            // There is no actual DB record associated with root category.
460
461
462
463
464
465
466
            return;
        }

        $data = (object)$data;
        $newcategory = new stdClass();
        $newcategory->id = $this->id;

467
        // Copy all description* fields regardless of whether this is form data or direct field update.
468
469
470
471
472
473
474
475
476
477
478
        foreach ($data as $key => $value) {
            if (preg_match("/^description/", $key)) {
                $newcategory->$key = $value;
            }
        }

        if (isset($data->name) && empty($data->name)) {
            throw new moodle_exception('categorynamerequired');
        }

        if (!empty($data->name) && $data->name !== $this->name) {
479
            if (core_text::strlen($data->name) > 255) {
480
481
482
483
484
                throw new moodle_exception('categorytoolong');
            }
            $newcategory->name = $data->name;
        }

485
        if (isset($data->idnumber) && $data->idnumber !== $this->idnumber) {
486
            if (core_text::strlen($data->idnumber) > 100) {
487
488
                throw new moodle_exception('idnumbertoolong');
            }
489
            if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
490
491
492
493
494
495
496
497
498
499
500
501
                throw new moodle_exception('categoryidnumbertaken');
            }
            $newcategory->idnumber = $data->idnumber;
        }

        if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
            $newcategory->theme = $data->theme;
        }

        $changes = false;
        if (isset($data->visible)) {
            if ($data->visible) {
502
                $changes = $this->show_raw();
503
            } else {
504
                $changes = $this->hide_raw(0);
505
506
507
508
509
            }
        }

        if (isset($data->parent) && $data->parent != $this->parent) {
            if ($changes) {
510
                cache_helper::purge_by_event('changesincoursecat');
511
512
            }
            $parentcat = self::get($data->parent, MUST_EXIST, true);
513
            $this->change_parent_raw($parentcat);
514
515
516
517
518
            fix_course_sortorder();
        }

        $newcategory->timemodified = time();

519
        $categorycontext = $this->get_context();
520
        if ($editoroptions) {
521
522
            $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
                                                           'coursecat', 'description', 0);
523
524
        }
        $DB->update_record('course_categories', $newcategory);
525
526
527
528
529
530
531

        $event = \core\event\course_category_updated::create(array(
            'objectid' => $newcategory->id,
            'context' => $categorycontext
        ));
        $event->trigger();

532
        fix_course_sortorder();
533
        // Purge cache even if fix_course_sortorder() did not do it.
534
        cache_helper::purge_by_event('changesincoursecat');
535

536
        // Update all fields in the current object.
537
538
539
540
541
542
543
544
545
546
547
548
549
550
        $this->restore();
    }

    /**
     * Checks if this course category is visible to current user
     *
     * Please note that methods coursecat::get (without 3rd argumet),
     * coursecat::get_children(), etc. return only visible categories so it is
     * usually not needed to call this function outside of this class
     *
     * @return bool
     */
    public function is_uservisible() {
        return !$this->id || $this->visible ||
551
                has_capability('moodle/category:viewhiddencategories', $this->get_context());
552
553
    }

554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
    /**
     * Returns the complete corresponding record from DB table course_categories
     *
     * Mostly used in deprecated functions
     *
     * @return stdClass
     */
    public function get_db_record() {
        global $DB;
        if ($record = $DB->get_record('course_categories', array('id' => $this->id))) {
            return $record;
        } else {
            return (object)convert_to_array($this);
        }
    }

570
    /**
571
     * Returns the entry from categories tree and makes sure the application-level tree cache is built
572
     *
573
     * The following keys can be requested:
574
     *
575
576
577
578
579
580
581
582
583
     * 'countall' - total number of categories in the system (always present)
     * 0 - array of ids of top-level categories (always present)
     * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
     * $id (int) - array of ids of categories that are direct children of category with id $id. If
     *   category with id $id does not exist returns false. If category has no children returns empty array
     * $id.'i' - array of ids of children categories that have visible=0
     *
     * @param int|string $id
     * @return mixed
584
     */
585
    protected static function get_tree($id) {
586
        global $DB;
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
        $coursecattreecache = cache::make('core', 'coursecattree');
        $rv = $coursecattreecache->get($id);
        if ($rv !== false) {
            return $rv;
        }
        // Re-build the tree.
        $sql = "SELECT cc.id, cc.parent, cc.visible
                FROM {course_categories} cc
                ORDER BY cc.sortorder";
        $rs = $DB->get_recordset_sql($sql, array());
        $all = array(0 => array(), '0i' => array());
        $count = 0;
        foreach ($rs as $record) {
            $all[$record->id] = array();
            $all[$record->id. 'i'] = array();
            if (array_key_exists($record->parent, $all)) {
603
                $all[$record->parent][] = $record->id;
604
605
606
607
                if (!$record->visible) {
                    $all[$record->parent. 'i'][] = $record->id;
                }
            } else {
608
                // Parent not found. This is data consistency error but next fix_course_sortorder() should fix it.
609
                $all[0][] = $record->id;
610
611
612
                if (!$record->visible) {
                    $all['0i'][] = $record->id;
                }
613
            }
614
615
616
617
618
            $count++;
        }
        $rs->close();
        if (!$count) {
            // No categories found.
619
620
            // This may happen after upgrade of a very old moodle version.
            // In new versions the default category is created on install.
621
622
623
624
625
            $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
            set_config('defaultrequestcategory', $defcoursecat->id);
            $all[0] = array($defcoursecat->id);
            $all[$defcoursecat->id] = array();
            $count++;
626
        }
627
        // We must add countall to all in case it was the requested ID.
628
        $all['countall'] = $count;
629
        $coursecattreecache->set_many($all);
630
631
632
        if (array_key_exists($id, $all)) {
            return $all[$id];
        }
633
634
        // Requested non-existing category.
        return array();
635
636
637
638
639
640
641
642
    }

    /**
     * Returns number of ALL categories in the system regardless if
     * they are visible to current user or not
     *
     * @return int
     */
643
    public static function count_all() {
644
645
646
647
648
649
650
651
652
653
654
655
656
657
        return self::get_tree('countall');
    }

    /**
     * Retrieves number of records from course_categories table
     *
     * Only cached fields are retrieved. Records are ready for preloading context
     *
     * @param string $whereclause
     * @param array $params
     * @return array array of stdClass objects
     */
    protected static function get_records($whereclause, $params) {
        global $DB;
658
        // Retrieve from DB only the fields that need to be stored in cache.
659
        $fields = array_keys(array_filter(self::$coursecatfields));
660
661
662
663
664
665
666
667
668
        $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
        $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
                FROM {course_categories} cc
                JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
                WHERE ". $whereclause." ORDER BY cc.sortorder";
        return $DB->get_records_sql($sql,
                array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
    }

669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
    /**
     * Resets course contact caches when role assignments were changed
     *
     * @param int $roleid role id that was given or taken away
     * @param context $context context where role assignment has been changed
     */
    public static function role_assignment_changed($roleid, $context) {
        global $CFG, $DB;

        if ($context->contextlevel > CONTEXT_COURSE) {
            // No changes to course contacts if role was assigned on the module/block level.
            return;
        }

        if (!$CFG->coursecontact || !in_array($roleid, explode(',', $CFG->coursecontact))) {
            // The role is not one of course contact roles.
            return;
        }

        // Remove from cache course contacts of all affected courses.
        $cache = cache::make('core', 'coursecontacts');
        if ($context->contextlevel == CONTEXT_COURSE) {
            $cache->delete($context->instanceid);
        } else if ($context->contextlevel == CONTEXT_SYSTEM) {
            $cache->purge();
        } else {
            $sql = "SELECT ctx.instanceid
                    FROM {context} ctx
                    WHERE ctx.path LIKE ? AND ctx.contextlevel = ?";
            $params = array($context->path . '/%', CONTEXT_COURSE);
            if ($courses = $DB->get_fieldset_sql($sql, $params)) {
                $cache->delete_many($courses);
            }
        }
    }

    /**
     * Executed when user enrolment was changed to check if course
     * contacts cache needs to be cleared
     *
     * @param int $courseid course id
     * @param int $userid user id
     * @param int $status new enrolment status (0 - active, 1 - suspended)
     * @param int $timestart new enrolment time start
     * @param int $timeend new enrolment time end
     */
    public static function user_enrolment_changed($courseid, $userid,
            $status, $timestart = null, $timeend = null) {
        $cache = cache::make('core', 'coursecontacts');
        $contacts = $cache->get($courseid);
        if ($contacts === false) {
            // The contacts for the affected course were not cached anyway.
            return;
        }
        $enrolmentactive = ($status == 0) &&
                (!$timestart || $timestart < time()) &&
                (!$timeend || $timeend > time());
        if (!$enrolmentactive) {
            $isincontacts = false;
            foreach ($contacts as $contact) {
                if ($contact->id == $userid) {
                    $isincontacts = true;
                }
            }
            if (!$isincontacts) {
                // Changed user's enrolment does not exist or is not active,
                // and he is not in cached course contacts, no changes to be made.
                return;
            }
        }
        // Either enrolment of manager was deleted/suspended
        // or user enrolment was added or activated.
        // In order to see if the course contacts for this course need
        // changing we would need to make additional queries, they will
        // slow down bulk enrolment changes. It is better just to remove
        // course contacts cache for this course.
        $cache->delete($courseid);
    }

748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
    /**
     * Given list of DB records from table course populates each record with list of users with course contact roles
     *
     * This function fills the courses with raw information as {@link get_role_users()} would do.
     * See also {@link course_in_list::get_course_contacts()} for more readable return
     *
     * $courses[$i]->managers = array(
     *   $roleassignmentid => $roleuser,
     *   ...
     * );
     *
     * where $roleuser is an stdClass with the following properties:
     *
     * $roleuser->raid - role assignment id
     * $roleuser->id - user id
     * $roleuser->username
     * $roleuser->firstname
     * $roleuser->lastname
     * $roleuser->rolecoursealias
     * $roleuser->rolename
     * $roleuser->sortorder - role sortorder
     * $roleuser->roleid
     * $roleuser->roleshortname
     *
     * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
     *
     * @param array $courses
     */
    public static function preload_course_contacts(&$courses) {
        global $CFG, $DB;
        if (empty($courses) || empty($CFG->coursecontact)) {
            return;
        }
        $managerroles = explode(',', $CFG->coursecontact);
782
        $cache = cache::make('core', 'coursecontacts');
783
        $cacheddata = $cache->get_many(array_keys($courses));
784
785
786
787
788
789
790
791
        $courseids = array();
        foreach (array_keys($courses) as $id) {
            if ($cacheddata[$id] !== false) {
                $courses[$id]->managers = $cacheddata[$id];
            } else {
                $courseids[] = $id;
            }
        }
792

793
        // Array $courseids now stores list of ids of courses for which we still need to retrieve contacts.
794
795
796
        if (empty($courseids)) {
            return;
        }
797

798
        // First build the array of all context ids of the courses and their categories.
799
        $allcontexts = array();
800
        foreach ($courseids as $id) {
801
802
803
804
805
806
807
808
809
810
            $context = context_course::instance($id);
            $courses[$id]->managers = array();
            foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
                if (!isset($allcontexts[$ctxid])) {
                    $allcontexts[$ctxid] = array();
                }
                $allcontexts[$ctxid][] = $id;
            }
        }

811
        // Fetch list of all users with course contact roles in any of the courses contexts or parent contexts.
812
813
814
        list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
        list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
        list($sort, $sortparams) = users_order_by_sql('u');
815
        $notdeleted = array('notdeleted'=>0);
816
        $allnames = get_all_user_name_fields(true, 'u');
817
818
        $sql = "SELECT ra.contextid, ra.id AS raid,
                       r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
819
                       rn.name AS rolecoursealias, u.id, u.username, $allnames
820
821
822
823
                  FROM {role_assignments} ra
                  JOIN {user} u ON ra.userid = u.id
                  JOIN {role} r ON ra.roleid = r.id
             LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
824
                WHERE  ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
825
             ORDER BY r.sortorder, $sort";
826
        $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
827
        $checkenrolments = array();
828
        foreach ($rs as $ra) {
829
830
            foreach ($allcontexts[$ra->contextid] as $id) {
                $courses[$id]->managers[$ra->raid] = $ra;
831
832
833
834
                if (!isset($checkenrolments[$id])) {
                    $checkenrolments[$id] = array();
                }
                $checkenrolments[$id][] = $ra->id;
835
836
837
            }
        }
        $rs->close();
838

839
        // Remove from course contacts users who are not enrolled in the course.
840
841
842
843
844
845
846
847
848
849
850
851
        $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
        foreach ($checkenrolments as $id => $userids) {
            if (empty($enrolleduserids[$id])) {
                $courses[$id]->managers = array();
            } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
                foreach ($courses[$id]->managers as $raid => $ra) {
                    if (in_array($ra->id, $notenrolled)) {
                        unset($courses[$id]->managers[$raid]);
                    }
                }
            }
        }
852

853
        // Set the cache.
854
855
856
857
858
        $values = array();
        foreach ($courseids as $id) {
            $values[$id] = $courses[$id]->managers;
        }
        $cache->set_many($values);
859
860
861
862
863
864
865
866
867
868
869
870
    }

    /**
     * Verify user enrollments for multiple course-user combinations
     *
     * @param array $courseusers array where keys are course ids and values are array
     *     of users in this course whose enrolment we wish to verify
     * @return array same structure as input array but values list only users from input
     *     who are enrolled in the course
     */
    protected static function ensure_users_enrolled($courseusers) {
        global $DB;
871
        // If the input array is too big, split it into chunks.
872
873
874
875
876
877
878
879
880
881
        $maxcoursesinquery = 20;
        if (count($courseusers) > $maxcoursesinquery) {
            $rv = array();
            for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
                $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
                $rv = $rv + self::ensure_users_enrolled($chunk);
            }
            return $rv;
        }

882
        // Create a query verifying valid user enrolments for the number of courses.
883
884
885
886
887
888
        $sql = "SELECT DISTINCT e.courseid, ue.userid
          FROM {user_enrolments} ue
          JOIN {enrol} e ON e.id = ue.enrolid
          WHERE ue.status = :active
            AND e.status = :enabled
            AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
889
        $now = round(time(), -2); // Rounding helps caching in DB.
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
        $params = array('enabled' => ENROL_INSTANCE_ENABLED,
            'active' => ENROL_USER_ACTIVE,
            'now1' => $now, 'now2' => $now);
        $cnt = 0;
        $subsqls = array();
        $enrolled = array();
        foreach ($courseusers as $id => $userids) {
            $enrolled[$id] = array();
            if (count($userids)) {
                list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
                $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
                $params = $params + array('courseid'.$cnt => $id) + $params2;
                $cnt++;
            }
        }
        if (count($subsqls)) {
            $sql .= "AND (". join(' OR ', $subsqls).")";
            $rs = $DB->get_recordset_sql($sql, $params);
            foreach ($rs as $record) {
                $enrolled[$record->courseid][] = $record->userid;
            }
            $rs->close();
912
        }
913
        return $enrolled;
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
    }

    /**
     * Retrieves number of records from course table
     *
     * Not all fields are retrieved. Records are ready for preloading context
     *
     * @param string $whereclause
     * @param array $params
     * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
     * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
     *     on not visible courses
     * @return array array of stdClass objects
     */
    protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
        global $DB;
        $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
        $fields = array('c.id', 'c.category', 'c.sortorder',
                        'c.shortname', 'c.fullname', 'c.idnumber',
933
                        'c.startdate', 'c.enddate', 'c.visible', 'c.cacherev');
934
935
936
937
        if (!empty($options['summary'])) {
            $fields[] = 'c.summary';
            $fields[] = 'c.summaryformat';
        } else {
938
            $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
939
940
941
942
943
944
945
946
947
948
949
        }
        $sql = "SELECT ". join(',', $fields). ", $ctxselect
                FROM {course} c
                JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
                WHERE ". $whereclause." ORDER BY c.sortorder";
        $list = $DB->get_records_sql($sql,
                array('contextcourse' => CONTEXT_COURSE) + $params);

        if ($checkvisibility) {
            // Loop through all records and make sure we only return the courses accessible by user.
            foreach ($list as $course) {
950
951
952
                if (isset($list[$course->id]->hassummary)) {
                    $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
                }
953
                if (empty($course->visible)) {
954
                    // Load context only if we need to check capability.
955
956
957
958
959
960
961
962
                    context_helper::preload_from_record($course);
                    if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
                        unset($list[$course->id]);
                    }
                }
            }
        }

963
        // Preload course contacts if necessary.
964
965
966
967
968
969
        if (!empty($options['coursecontacts'])) {
            self::preload_course_contacts($list);
        }
        return $list;
    }

970
971
972
973
974
975
976
977
978
979
980
    /**
     * Returns array of ids of children categories that current user can not see
     *
     * This data is cached in user session cache
     *
     * @return array
     */
    protected function get_not_visible_children_ids() {
        global $DB;
        $coursecatcache = cache::make('core', 'coursecat');
        if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
981
            // We never checked visible children before.
982
983
984
            $hidden = self::get_tree($this->id.'i');
            $invisibleids = array();
            if ($hidden) {
985
                // Preload categories contexts.
986
987
988
989
990
991
992
993
                list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
                $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
                $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
                    WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
                        array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
                foreach ($contexts as $record) {
                    context_helper::preload_from_record($record);
                }
994
                // Check that user has 'viewhiddencategories' capability for each hidden category.
995
996
997
998
999
1000
                foreach ($hidden as $id) {
                    if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
                        $invisibleids[] = $id;
                    }
                }
            }
For faster browsing, not all history is shown. View entire blame