category.php 123 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?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 core_course_category responsible 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
 *
 * @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
 *
 * @package    core
 * @subpackage course
 * @copyright  2013 Marina Glancy
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class core_course_category implements renderable, cacheable_object, IteratorAggregate {
    /** @var core_course_category stores pseudo category with id=0. Use core_course_category::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),
        'description' => null, // Not cached.
        'descriptionformat' => null, // Not cached.
        'parent' => array('pa', 0),
        'sortorder' => array('so', 0),
        'coursecount' => array('cc', 0),
        'visible' => array('vi', 1),
        'visibleold' => null, // Not cached.
        'timemodified' => null, // Not cached.
        'depth' => array('dh', 1),
        'path' => array('ph', null),
        'theme' => null, // Not cached.
    );

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

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

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

    /** @var string */
    protected $description = false;

    /** @var int */
    protected $descriptionformat = false;

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

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

    /** @var int */
    protected $coursecount = false;

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

    /** @var int */
    protected $visibleold = false;

    /** @var int */
    protected $timemodified = false;

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

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

    /** @var string */
    protected $theme = false;

    /** @var bool */
116
    protected $fromcache = false;
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173

    /**
     * Magic setter method, we do not want anybody to modify properties from the outside
     *
     * @param string $name
     * @param mixed $value
     */
    public function __set($name, $value) {
        debugging('Can not change core_course_category instance properties!', DEBUG_DEVELOPER);
    }

    /**
     * Magic method getter, redirects to read only values. Queries from DB the fields that were not cached
     *
     * @param string $name
     * @return mixed
     */
    public function __get($name) {
        global $DB;
        if (array_key_exists($name, self::$coursecatfields)) {
            if ($this->$name === false) {
                // Property was not retrieved from DB, retrieve all not retrieved fields.
                $notretrievedfields = array_diff_key(self::$coursecatfields, array_filter(self::$coursecatfields));
                $record = $DB->get_record('course_categories', array('id' => $this->id),
                        join(',', array_keys($notretrievedfields)), MUST_EXIST);
                foreach ($record as $key => $value) {
                    $this->$key = $value;
                }
            }
            return $this->$name;
        }
        debugging('Invalid core_course_category property accessed! '.$name, DEBUG_DEVELOPER);
        return null;
    }

    /**
     * Full support for isset on our magic read only properties.
     *
     * @param string $name
     * @return bool
     */
    public function __isset($name) {
        if (array_key_exists($name, self::$coursecatfields)) {
            return isset($this->$name);
        }
        return false;
    }

    /**
     * All properties are read only, sorry.
     *
     * @param string $name
     */
    public function __unset($name) {
        debugging('Can not unset core_course_category instance properties!', DEBUG_DEVELOPER);
    }

174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
    /**
     * Get list of plugin callback functions.
     *
     * @param string $name Callback function name.
     * @return [callable] $pluginfunctions
     */
    public function get_plugins_callback_function(string $name) : array {
        $pluginfunctions = [];
        if ($pluginsfunction = get_plugins_with_function($name)) {
            foreach ($pluginsfunction as $plugintype => $plugins) {
                foreach ($plugins as $pluginfunction) {
                    $pluginfunctions[] = $pluginfunction;
                }
            }
        }
        return $pluginfunctions;
    }

192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
    /**
     * Create an iterator because magic vars can't be seen by 'foreach'.
     *
     * implementing method from interface IteratorAggregate
     *
     * @return ArrayIterator
     */
    public function getIterator() {
        $ret = array();
        foreach (self::$coursecatfields as $property => $unused) {
            if ($this->$property !== false) {
                $ret[$property] = $this->$property;
            }
        }
        return new ArrayIterator($ret);
    }

    /**
     * Constructor
     *
     * Constructor is protected, use core_course_category::get($id) to retrieve category
     *
     * @param stdClass $record record from DB (may not contain all fields)
     * @param bool $fromcache whether it is being restored from cache
     */
    protected function __construct(stdClass $record, $fromcache = false) {
        context_helper::preload_from_record($record);
        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 the given user, it is treated as non existing
     * unless $alwaysreturnhidden is set to true
     *
     * 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
     * @param bool $alwaysreturnhidden set to true if you want an object to be
     *     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!
     * @param int|stdClass $user The user id or object. By default (null) checks the visibility to the current user.
     * @return null|self
     * @throws moodle_exception
     */
    public static function get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false, $user = null) {
        if (!$id) {
250
251
252
            // Top-level category.
            if ($alwaysreturnhidden || self::top()->is_uservisible()) {
                return self::top();
253
            }
254
255
256
257
            if ($strictness == MUST_EXIST) {
                throw new moodle_exception('cannotviewcategory');
            }
            return null;
258
        }
259
260

        // Try to get category from cache or retrieve from the DB.
261
262
263
264
265
266
267
268
269
270
        $coursecatrecordcache = cache::make('core', 'coursecatrecords');
        $coursecat = $coursecatrecordcache->get($id);
        if ($coursecat === false) {
            if ($records = self::get_records('cc.id = :id', array('id' => $id))) {
                $record = reset($records);
                $coursecat = new self($record);
                // Store in cache.
                $coursecatrecordcache->set($id, $coursecat);
            }
        }
271
272
273

        if (!$coursecat) {
            // Course category not found.
274
275
276
            if ($strictness == MUST_EXIST) {
                throw new moodle_exception('unknowncategory');
            }
277
278
279
280
281
282
283
            $coursecat = null;
        } else if (!$alwaysreturnhidden && !$coursecat->is_uservisible($user)) {
            // Course category is found but user can not access it.
            if ($strictness == MUST_EXIST) {
                throw new moodle_exception('cannotviewcategory');
            }
            $coursecat = null;
284
        }
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
        return $coursecat;
    }

    /**
     * Returns the pseudo-category representing the whole system (id=0, context_system)
     *
     * @return core_course_category
     */
    public static function top() {
        if (!isset(self::$coursecat0)) {
            $record = new stdClass();
            $record->id = 0;
            $record->visible = 1;
            $record->depth = 0;
            $record->path = '';
            $record->locked = 0;
            self::$coursecat0 = new self($record);
        }
        return self::$coursecat0;
    }

    /**
     * Returns the top-most category for the current user
     *
     * Examples:
     * 1. User can browse courses everywhere - return self::top() - pseudo-category with id=0
     * 2. User does not have capability to browse courses on the system level but
     *    has it in ONE course category - return this course category
     * 3. User has capability to browse courses in two course categories - return self::top()
     *
     * @return core_course_category|null
     */
    public static function user_top() {
        $children = self::top()->get_children();
        if (count($children) == 1) {
            // User has access to only one category on the top level. Return this category as "user top category".
            return reset($children);
        }
        if (count($children) > 1) {
            // User has access to more than one category on the top level. Return the top as "user top category".
325
            // In this case user actually may not have capability 'moodle/category:viewcourselist' on the top level.
326
327
328
329
330
            return self::top();
        }
        // User can not access any categories on the top level.
        // TODO MDL-10965 find ANY/ALL categories in the tree where user has access to.
        return self::get(0, IGNORE_MISSING);
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
    }

    /**
     * Load many core_course_category objects.
     *
     * @param array $ids An array of category ID's to load.
     * @return core_course_category[]
     */
    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 self($record);
                $toset[$record->id] = $categories[$record->id];
            }
            $coursecatrecordcache->set_many($toset);
        }
        return $categories;
    }

    /**
     * Load all core_course_category objects.
     *
     * @param array $options Options:
     *              - returnhidden Return categories even if they are hidden
     * @return  core_course_category[]
     */
    public static function get_all($options = []) {
        global $DB;

        $coursecatrecordcache = cache::make('core', 'coursecatrecords');

        $catcontextsql = \context_helper::get_preload_record_columns_sql('ctx');
        $catsql = "SELECT cc.*, {$catcontextsql}
                     FROM {course_categories} cc
                     JOIN {context} ctx ON cc.id = ctx.instanceid";
        $catsqlwhere = "WHERE ctx.contextlevel = :contextlevel";
        $catsqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC";

        $catrs = $DB->get_recordset_sql("{$catsql} {$catsqlwhere} {$catsqlorder}", [
            'contextlevel' => CONTEXT_COURSECAT,
        ]);

        $types['categories'] = [];
        $categories = [];
        $toset = [];
        foreach ($catrs as $record) {
            $category = new self($record);
            $toset[$category->id] = $category;

            if (!empty($options['returnhidden']) || $category->is_uservisible()) {
                $categories[$record->id] = $category;
            }
        }
        $catrs->close();

        $coursecatrecordcache->set_many($toset);

        return $categories;

    }

    /**
     * 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 core_course_category
     */
    public static function get_default() {
413
        if ($visiblechildren = self::top()->get_children()) {
414
415
416
417
418
419
420
421
422
423
424
425
426
427
            $defcategory = reset($visiblechildren);
        } else {
            $toplevelcategories = self::get_tree(0);
            $defcategoryid = $toplevelcategories[0];
            $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() {
428
429
430
        if (!$this->id) {
            return;
        }
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
        // Update all fields in the current object.
        $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 core_course_category
     * @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 = '';
        // Copy all description* fields regardless of whether this is form data or direct field update.
        foreach ($data as $key => $value) {
            if (preg_match("/^description/", $key)) {
                $newcategory->$key = $value;
            }
        }

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

        // Validate and set idnumber.
        if (isset($data->idnumber)) {
            if (core_text::strlen($data->idnumber) > 100) {
                throw new moodle_exception('idnumbertoolong');
            }
            if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
                throw new moodle_exception('categoryidnumbertaken');
            }
            $newcategory->idnumber = $data->idnumber;
        }

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

        if (empty($data->parent)) {
492
            $parent = self::top();
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
        } else {
            $parent = self::get($data->parent, MUST_EXIST, true);
        }
        $newcategory->parent = $parent->id;
        $newcategory->depth = $parent->depth + 1;

        // By default category is visible, unless visible = 0 is specified or parent category is hidden.
        if (isset($data->visible) && !$data->visible) {
            // Create a hidden category.
            $newcategory->visible = $newcategory->visibleold = 0;
        } else {
            // Create a category that inherits visibility from parent.
            $newcategory->visible = $parent->visible;
            // In case parent is hidden, when it changes visibility this new subcategory will automatically become visible too.
            $newcategory->visibleold = 1;
        }

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

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

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

        fix_course_sortorder();

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

            // Update only fields description and descriptionformat.
            $updatedata = new stdClass();
            $updatedata->id = $newcategory->id;
            $updatedata->description = $newcategory->description;
            $updatedata->descriptionformat = $newcategory->descriptionformat;
            $DB->update_record('course_categories', $updatedata);
        }

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

        cache_helper::purge_by_event('changesincoursecat');

        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.
     *
     * This function calls core_course_category::change_parent_raw if field 'parent' is updated.
     * It also calls core_course_category::hide_raw or core_course_category::show_raw if 'visible' is updated.
     * 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 core_course_category::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) {
            // There is no actual DB record associated with root category.
            return;
        }

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

        // Copy all description* fields regardless of whether this is form data or direct field update.
        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) {
            if (core_text::strlen($data->name) > 255) {
                throw new moodle_exception('categorytoolong');
            }
            $newcategory->name = $data->name;
        }

        if (isset($data->idnumber) && $data->idnumber !== $this->idnumber) {
            if (core_text::strlen($data->idnumber) > 100) {
                throw new moodle_exception('idnumbertoolong');
            }
            if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
                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) {
                $changes = $this->show_raw();
            } else {
                $changes = $this->hide_raw(0);
            }
        }

        if (isset($data->parent) && $data->parent != $this->parent) {
            if ($changes) {
                cache_helper::purge_by_event('changesincoursecat');
            }
            $parentcat = self::get($data->parent, MUST_EXIST, true);
            $this->change_parent_raw($parentcat);
            fix_course_sortorder();
        }

        $newcategory->timemodified = time();

        $categorycontext = $this->get_context();
        if ($editoroptions) {
            $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
                                                           'coursecat', 'description', 0);
        }
        $DB->update_record('course_categories', $newcategory);

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

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

        // Update all fields in the current object.
        $this->restore();
    }


    /**
     * Checks if this course category is visible to a user.
     *
     * Please note that methods core_course_category::get (without 3rd argumet),
     * core_course_category::get_children(), etc. return only visible categories so it is
     * usually not needed to call this function outside of this class
     *
     * @param int|stdClass $user The user id or object. By default (null) checks the visibility to the current user.
     * @return bool
     */
    public function is_uservisible($user = null) {
662
663
664
665
666
667
668
669
670
671
672
673
        return self::can_view_category($this, $user);
    }

    /**
     * Checks if current user has access to the category
     *
     * @param stdClass|core_course_category $category
     * @param int|stdClass $user The user id or object. By default (null) checks access for the current user.
     * @return bool
     */
    public static function can_view_category($category, $user = null) {
        if (!$category->id) {
674
            return has_capability('moodle/category:viewcourselist', context_system::instance(), $user);
675
676
677
678
679
        }
        $context = context_coursecat::instance($category->id);
        if (!$category->visible && !has_capability('moodle/category:viewhiddencategories', $context, $user)) {
            return false;
        }
680
        return has_capability('moodle/category:viewcourselist', $context, $user);
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
    }

    /**
     * Checks if current user can view course information or enrolment page.
     *
     * This method does not check if user is already enrolled in the course
     *
     * @param stdClass $course course object (must have 'id', 'visible' and 'category' fields)
     * @param null|stdClass $user The user id or object. By default (null) checks access for the current user.
     */
    public static function can_view_course_info($course, $user = null) {
        if ($course->id == SITEID) {
            return true;
        }
        if (!$course->visible) {
            $coursecontext = context_course::instance($course->id);
            if (!has_capability('moodle/course:viewhiddencourses', $coursecontext, $user)) {
                return false;
            }
        }
        $categorycontext = isset($course->category) ? context_coursecat::instance($course->category) :
            context_course::instance($course->id)->get_parent_context();
703
        return has_capability('moodle/category:viewcourselist', $categorycontext, $user);
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
    }

    /**
     * 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);
        }
    }

    /**
     * Returns the entry from categories tree and makes sure the application-level tree cache is built
     *
     * The following keys can be requested:
     *
     * '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
731
     *   category with id $id does not exist, or category has no children, returns empty array
732
733
734
735
736
737
     * $id.'i' - array of ids of children categories that have visible=0
     *
     * @param int|string $id
     * @return mixed
     */
    protected static function get_tree($id) {
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
        $all = self::get_cached_cat_tree();
        if (is_null($all) || !isset($all[$id])) {
            // Could not get or rebuild the tree, or requested a non-existant ID.
            return [];
        } else {
            return $all[$id];
        }
    }

    /**
     * Return the course category tree.
     *
     * Returns the category tree array, from the cache if available or rebuilding the cache
     * if required. Uses locking to prevent the cache being rebuilt by multiple requests at once.
     *
     * @return array|null The tree as an array, or null if rebuilding the tree failed due to a lock timeout.
     * @throws coding_exception
     * @throws dml_exception
     * @throws moodle_exception
     */
    private static function get_cached_cat_tree() : ?array {
759
        $coursecattreecache = cache::make('core', 'coursecattree');
760
761
762
        $all = $coursecattreecache->get('all');
        if ($all !== false) {
            return $all;
763
        }
764
765
766
767
768
769
        // Might need to rebuild the tree. Put a lock in place to ensure other requests don't try and do this in parallel.
        $lockfactory = \core\lock\lock_config::get_lock_factory('core_coursecattree');
        $lock = $lockfactory->get_lock('core_coursecattree_cache',
                course_modinfo::COURSE_CACHE_LOCK_WAIT, course_modinfo::COURSE_CACHE_LOCK_EXPIRY);
        if ($lock === false) {
            // Couldn't get a lock to rebuild the tree.
770
            return null;
771
        }
772
773
        $all = $coursecattreecache->get('all');
        if ($all !== false) {
774
775
            // Tree was built while we were waiting for the lock.
            $lock->release();
776
            return $all;
777
        }
778
        // Re-build the tree.
779
780
        try {
            $all = self::rebuild_coursecattree_cache_contents();
781
            $coursecattreecache->set('all', $all);
782
783
784
        } finally {
            $lock->release();
        }
785
        return $all;
786
787
788
789
790
791
792
793
794
795
796
797
    }

    /**
     * Rebuild the course category tree as an array, including an extra "countall" field.
     *
     * @return array
     * @throws coding_exception
     * @throws dml_exception
     * @throws moodle_exception
     */
    private static function rebuild_coursecattree_cache_contents() : array {
        global $DB;
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
        $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)) {
                $all[$record->parent][] = $record->id;
                if (!$record->visible) {
                    $all[$record->parent. 'i'][] = $record->id;
                }
            } else {
                // Parent not found. This is data consistency error but next fix_course_sortorder() should fix it.
                $all[0][] = $record->id;
                if (!$record->visible) {
                    $all['0i'][] = $record->id;
                }
            }
            $count++;
        }
        $rs->close();
        if (!$count) {
            // No categories found.
            // This may happen after upgrade of a very old moodle version.
            // In new versions the default category is created on install.
            $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
            set_config('defaultrequestcategory', $defcoursecat->id);
            $all[0] = array($defcoursecat->id);
            $all[$defcoursecat->id] = array();
            $count++;
        }
        // We must add countall to all in case it was the requested ID.
        $all['countall'] = $count;
834
        return $all;
835
836
837
838
839
840
    }

    /**
     * Returns number of ALL categories in the system regardless if
     * they are visible to current user or not
     *
841
     * @deprecated since Moodle 3.7
842
843
844
     * @return int
     */
    public static function count_all() {
845
846
        debugging('Method core_course_category::count_all() is deprecated. Please use ' .
            'core_course_category::is_simple_site()', DEBUG_DEVELOPER);
847
848
849
        return self::get_tree('countall');
    }

850
851
852
853
854
855
856
857
858
859
860
861
862
863
    /**
     * Checks if the site has only one category and it is visible and available.
     *
     * In many situations we won't show this category at all
     * @return bool
     */
    public static function is_simple_site() {
        if (self::get_tree('countall') != 1) {
            return false;
        }
        $default = self::get_default();
        return $default->visible && $default->is_uservisible();
    }

864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    /**
     * 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;
        // Retrieve from DB only the fields that need to be stored in cache.
        $fields = array_keys(array_filter(self::$coursecatfields));
        $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);
    }

    /**
     * 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;
        }

        // Trigger a purge for all caches listening for changes to category enrolment.
        cache_helper::purge_by_event('changesincategoryenrolment');

        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);
    }

    /**
     * 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 core_course_list_element::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;
        }