MDL-59890 coursecat: Add helper to fetch nested view of coursecat
[moodle.git] / lib / coursecatlib.php
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/>.
17 /**
18  * Contains class coursecat reponsible for course category operations
19  *
20  * @package    core
21  * @subpackage course
22  * @copyright  2013 Marina Glancy
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
28 /**
29  * Class to store, cache, render and manage course category
30  *
31  * @property-read int $id
32  * @property-read string $name
33  * @property-read string $idnumber
34  * @property-read string $description
35  * @property-read int $descriptionformat
36  * @property-read int $parent
37  * @property-read int $sortorder
38  * @property-read int $coursecount
39  * @property-read int $visible
40  * @property-read int $visibleold
41  * @property-read int $timemodified
42  * @property-read int $depth
43  * @property-read string $path
44  * @property-read string $theme
45  *
46  * @package    core
47  * @subpackage course
48  * @copyright  2013 Marina Glancy
49  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50  */
51 class coursecat implements renderable, cacheable_object, IteratorAggregate {
52     /** @var coursecat stores pseudo category with id=0. Use coursecat::get(0) to retrieve */
53     protected static $coursecat0;
55     /** @var array list of all fields and their short name and default value for caching */
56     protected static $coursecatfields = array(
57         'id' => array('id', 0),
58         'name' => array('na', ''),
59         'idnumber' => array('in', null),
60         'description' => null, // Not cached.
61         'descriptionformat' => null, // Not cached.
62         'parent' => array('pa', 0),
63         'sortorder' => array('so', 0),
64         'coursecount' => array('cc', 0),
65         'visible' => array('vi', 1),
66         'visibleold' => null, // Not cached.
67         'timemodified' => null, // Not cached.
68         'depth' => array('dh', 1),
69         'path' => array('ph', null),
70         'theme' => null, // Not cached.
71     );
73     /** @var int */
74     protected $id;
76     /** @var string */
77     protected $name = '';
79     /** @var string */
80     protected $idnumber = null;
82     /** @var string */
83     protected $description = false;
85     /** @var int */
86     protected $descriptionformat = false;
88     /** @var int */
89     protected $parent = 0;
91     /** @var int */
92     protected $sortorder = 0;
94     /** @var int */
95     protected $coursecount = false;
97     /** @var int */
98     protected $visible = 1;
100     /** @var int */
101     protected $visibleold = false;
103     /** @var int */
104     protected $timemodified = false;
106     /** @var int */
107     protected $depth = 0;
109     /** @var string */
110     protected $path = '';
112     /** @var string */
113     protected $theme = false;
115     /** @var bool */
116     protected $fromcache;
118     /** @var bool */
119     protected $hasmanagecapability = null;
121     /**
122      * Magic setter method, we do not want anybody to modify properties from the outside
123      *
124      * @param string $name
125      * @param mixed $value
126      */
127     public function __set($name, $value) {
128         debugging('Can not change coursecat instance properties!', DEBUG_DEVELOPER);
129     }
131     /**
132      * Magic method getter, redirects to read only values. Queries from DB the fields that were not cached
133      *
134      * @param string $name
135      * @return mixed
136      */
137     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                 $record = $DB->get_record('course_categories', array('id' => $this->id),
144                         join(',', array_keys($notretrievedfields)), MUST_EXIST);
145                 foreach ($record as $key => $value) {
146                     $this->$key = $value;
147                 }
148             }
149             return $this->$name;
150         }
151         debugging('Invalid coursecat property accessed! '.$name, DEBUG_DEVELOPER);
152         return null;
153     }
155     /**
156      * Full support for isset on our magic read only properties.
157      *
158      * @param string $name
159      * @return bool
160      */
161     public function __isset($name) {
162         if (array_key_exists($name, self::$coursecatfields)) {
163             return isset($this->$name);
164         }
165         return false;
166     }
168     /**
169      * All properties are read only, sorry.
170      *
171      * @param string $name
172      */
173     public function __unset($name) {
174         debugging('Can not unset coursecat instance properties!', DEBUG_DEVELOPER);
175     }
177     /**
178      * Create an iterator because magic vars can't be seen by 'foreach'.
179      *
180      * implementing method from interface IteratorAggregate
181      *
182      * @return ArrayIterator
183      */
184     public function getIterator() {
185         $ret = array();
186         foreach (self::$coursecatfields as $property => $unused) {
187             if ($this->$property !== false) {
188                 $ret[$property] = $this->$property;
189             }
190         }
191         return new ArrayIterator($ret);
192     }
194     /**
195      * Constructor
196      *
197      * Constructor is protected, use coursecat::get($id) to retrieve category
198      *
199      * @param stdClass $record record from DB (may not contain all fields)
200      * @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         foreach ($record as $key => $val) {
205             if (array_key_exists($key, self::$coursecatfields)) {
206                 $this->$key = $val;
207             }
208         }
209         $this->fromcache = $fromcache;
210     }
212     /**
213      * Returns coursecat object for requested category
214      *
215      * If category is not visible to user it is treated as non existing
216      * unless $alwaysreturnhidden is set to true
217      *
218      * If id is 0, the pseudo object for root category is returned (convenient
219      * for calling other functions such as get_children())
220      *
221      * @param int $id category id
222      * @param int $strictness whether to throw an exception (MUST_EXIST) or
223      *     return null (IGNORE_MISSING) in case the category is not found or
224      *     not visible to current user
225      * @param bool $alwaysreturnhidden set to true if you want an object to be
226      *     returned even if this category is not visible to the current user
227      *     (category is hidden and user does not have
228      *     '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         if (!$id) {
234             if (!isset(self::$coursecat0)) {
235                 $record = new stdClass();
236                 $record->id = 0;
237                 $record->visible = 1;
238                 $record->depth = 0;
239                 $record->path = '';
240                 self::$coursecat0 = new coursecat($record);
241             }
242             return self::$coursecat0;
243         }
244         $coursecatrecordcache = cache::make('core', 'coursecatrecords');
245         $coursecat = $coursecatrecordcache->get($id);
246         if ($coursecat === false) {
247             if ($records = self::get_records('cc.id = :id', array('id' => $id))) {
248                 $record = reset($records);
249                 $coursecat = new coursecat($record);
250                 // Store in cache.
251                 $coursecatrecordcache->set($id, $coursecat);
252             }
253         }
254         if ($coursecat && ($alwaysreturnhidden || $coursecat->is_uservisible())) {
255             return $coursecat;
256         } else {
257             if ($strictness == MUST_EXIST) {
258                 throw new moodle_exception('unknowncategory');
259             }
260         }
261         return null;
262     }
264     /**
265      * Load many coursecat objects.
266      *
267      * @global moodle_database $DB
268      * @param array $ids An array of category ID's to load.
269      * @return coursecat[]
270      */
271     public static function get_many(array $ids) {
272         global $DB;
273         $coursecatrecordcache = cache::make('core', 'coursecatrecords');
274         $categories = $coursecatrecordcache->get_many($ids);
275         $toload = array();
276         foreach ($categories as $id => $result) {
277             if ($result === false) {
278                 $toload[] = $id;
279             }
280         }
281         if (!empty($toload)) {
282             list($where, $params) = $DB->get_in_or_equal($toload, SQL_PARAMS_NAMED);
283             $records = self::get_records('cc.id '.$where, $params);
284             $toset = array();
285             foreach ($records as $record) {
286                 $categories[$record->id] = new coursecat($record);
287                 $toset[$record->id] = $categories[$record->id];
288             }
289             $coursecatrecordcache->set_many($toset);
290         }
291         return $categories;
292     }
294     /**
295      * Load all coursecat objects.
296      *
297      * @param   array   $options Options:
298      * @param   bool    $options.returnhidden Return categories even if they are hidden
299      * @return  coursecat[]
300      */
301     public static function get_all($options = []) {
302         global $DB;
304         $coursecatrecordcache = cache::make('core', 'coursecatrecords');
306         $catcontextsql = \context_helper::get_preload_record_columns_sql('ctx');
307         $catsql = "SELECT cc.*, {$catcontextsql}
308                      FROM {course_categories} cc
309                      JOIN {context} ctx ON cc.id = ctx.instanceid";
310         $catsqlwhere = "WHERE ctx.contextlevel = :contextlevel";
311         $catsqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC";
313         $catrs = $DB->get_recordset_sql("{$catsql} {$catsqlwhere} {$catsqlorder}", [
314             'contextlevel' => CONTEXT_COURSECAT,
315         ]);
317         $types['categories'] = [];
318         $categories = [];
319         $toset = [];
320         foreach ($catrs as $record) {
321             $category = new coursecat($record);
322             $toset[$category->id] = $category;
324             if (!empty($options['returnhidden']) || $category->is_uservisible()) {
325                 $categories[$record->id] = $category;
326             }
327         }
328         $catrs->close();
330         $coursecatrecordcache->set_many($toset);
332         return $categories;
334     }
336     /**
337      * Returns the first found category
338      *
339      * Note that if there are no categories visible to the current user on the first level,
340      * the invisible category may be returned
341      *
342      * @return coursecat
343      */
344     public static function get_default() {
345         if ($visiblechildren = self::get(0)->get_children()) {
346             $defcategory = reset($visiblechildren);
347         } else {
348             $toplevelcategories = self::get_tree(0);
349             $defcategoryid = $toplevelcategories[0];
350             $defcategory = self::get($defcategoryid, MUST_EXIST, true);
351         }
352         return $defcategory;
353     }
355     /**
356      * Restores the object after it has been externally modified in DB for example
357      * during {@link fix_course_sortorder()}
358      */
359     protected function restore() {
360         // Update all fields in the current object.
361         $newrecord = self::get($this->id, MUST_EXIST, true);
362         foreach (self::$coursecatfields as $key => $unused) {
363             $this->$key = $newrecord->$key;
364         }
365     }
367     /**
368      * Creates a new category either from form data or from raw data
369      *
370      * Please note that this function does not verify access control.
371      *
372      * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
373      *
374      * Category visibility is inherited from parent unless $data->visible = 0 is specified
375      *
376      * @param array|stdClass $data
377      * @param array $editoroptions if specified, the data is considered to be
378      *    form data and file_postupdate_standard_editor() is being called to
379      *    process images in description.
380      * @return coursecat
381      * @throws moodle_exception
382      */
383     public static function create($data, $editoroptions = null) {
384         global $DB, $CFG;
385         $data = (object)$data;
386         $newcategory = new stdClass();
388         $newcategory->descriptionformat = FORMAT_MOODLE;
389         $newcategory->description = '';
390         // Copy all description* fields regardless of whether this is form data or direct field update.
391         foreach ($data as $key => $value) {
392             if (preg_match("/^description/", $key)) {
393                 $newcategory->$key = $value;
394             }
395         }
397         if (empty($data->name)) {
398             throw new moodle_exception('categorynamerequired');
399         }
400         if (core_text::strlen($data->name) > 255) {
401             throw new moodle_exception('categorytoolong');
402         }
403         $newcategory->name = $data->name;
405         // Validate and set idnumber.
406         if (isset($data->idnumber)) {
407             if (core_text::strlen($data->idnumber) > 100) {
408                 throw new moodle_exception('idnumbertoolong');
409             }
410             if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
411                 throw new moodle_exception('categoryidnumbertaken');
412             }
413             $newcategory->idnumber = $data->idnumber;
414         }
416         if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
417             $newcategory->theme = $data->theme;
418         }
420         if (empty($data->parent)) {
421             $parent = self::get(0);
422         } else {
423             $parent = self::get($data->parent, MUST_EXIST, true);
424         }
425         $newcategory->parent = $parent->id;
426         $newcategory->depth = $parent->depth + 1;
428         // By default category is visible, unless visible = 0 is specified or parent category is hidden.
429         if (isset($data->visible) && !$data->visible) {
430             // Create a hidden category.
431             $newcategory->visible = $newcategory->visibleold = 0;
432         } else {
433             // Create a category that inherits visibility from parent.
434             $newcategory->visible = $parent->visible;
435             // In case parent is hidden, when it changes visibility this new subcategory will automatically become visible too.
436             $newcategory->visibleold = 1;
437         }
439         $newcategory->sortorder = 0;
440         $newcategory->timemodified = time();
442         $newcategory->id = $DB->insert_record('course_categories', $newcategory);
444         // Update path (only possible after we know the category id.
445         $path = $parent->path . '/' . $newcategory->id;
446         $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));
448         // We should mark the context as dirty.
449         context_coursecat::instance($newcategory->id)->mark_dirty();
451         fix_course_sortorder();
453         // If this is data from form results, save embedded files and update description.
454         $categorycontext = context_coursecat::instance($newcategory->id);
455         if ($editoroptions) {
456             $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
457                                                            'coursecat', 'description', 0);
459             // Update only fields description and descriptionformat.
460             $updatedata = new stdClass();
461             $updatedata->id = $newcategory->id;
462             $updatedata->description = $newcategory->description;
463             $updatedata->descriptionformat = $newcategory->descriptionformat;
464             $DB->update_record('course_categories', $updatedata);
465         }
467         $event = \core\event\course_category_created::create(array(
468             'objectid' => $newcategory->id,
469             'context' => $categorycontext
470         ));
471         $event->trigger();
473         cache_helper::purge_by_event('changesincoursecat');
475         return self::get($newcategory->id, MUST_EXIST, true);
476     }
478     /**
479      * Updates the record with either form data or raw data
480      *
481      * Please note that this function does not verify access control.
482      *
483      * This function calls coursecat::change_parent_raw if field 'parent' is updated.
484      * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
485      * Visibility is changed first and then parent is changed. This means that
486      * if parent category is hidden, the current category will become hidden
487      * too and it may overwrite whatever was set in field 'visible'.
488      *
489      * Note that fields 'path' and 'depth' can not be updated manually
490      * Also coursecat::update() can not directly update the field 'sortoder'
491      *
492      * @param array|stdClass $data
493      * @param array $editoroptions if specified, the data is considered to be
494      *    form data and file_postupdate_standard_editor() is being called to
495      *    process images in description.
496      * @throws moodle_exception
497      */
498     public function update($data, $editoroptions = null) {
499         global $DB, $CFG;
500         if (!$this->id) {
501             // There is no actual DB record associated with root category.
502             return;
503         }
505         $data = (object)$data;
506         $newcategory = new stdClass();
507         $newcategory->id = $this->id;
509         // Copy all description* fields regardless of whether this is form data or direct field update.
510         foreach ($data as $key => $value) {
511             if (preg_match("/^description/", $key)) {
512                 $newcategory->$key = $value;
513             }
514         }
516         if (isset($data->name) && empty($data->name)) {
517             throw new moodle_exception('categorynamerequired');
518         }
520         if (!empty($data->name) && $data->name !== $this->name) {
521             if (core_text::strlen($data->name) > 255) {
522                 throw new moodle_exception('categorytoolong');
523             }
524             $newcategory->name = $data->name;
525         }
527         if (isset($data->idnumber) && $data->idnumber !== $this->idnumber) {
528             if (core_text::strlen($data->idnumber) > 100) {
529                 throw new moodle_exception('idnumbertoolong');
530             }
531             if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
532                 throw new moodle_exception('categoryidnumbertaken');
533             }
534             $newcategory->idnumber = $data->idnumber;
535         }
537         if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
538             $newcategory->theme = $data->theme;
539         }
541         $changes = false;
542         if (isset($data->visible)) {
543             if ($data->visible) {
544                 $changes = $this->show_raw();
545             } else {
546                 $changes = $this->hide_raw(0);
547             }
548         }
550         if (isset($data->parent) && $data->parent != $this->parent) {
551             if ($changes) {
552                 cache_helper::purge_by_event('changesincoursecat');
553             }
554             $parentcat = self::get($data->parent, MUST_EXIST, true);
555             $this->change_parent_raw($parentcat);
556             fix_course_sortorder();
557         }
559         $newcategory->timemodified = time();
561         $categorycontext = $this->get_context();
562         if ($editoroptions) {
563             $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
564                                                            'coursecat', 'description', 0);
565         }
566         $DB->update_record('course_categories', $newcategory);
568         $event = \core\event\course_category_updated::create(array(
569             'objectid' => $newcategory->id,
570             'context' => $categorycontext
571         ));
572         $event->trigger();
574         fix_course_sortorder();
575         // Purge cache even if fix_course_sortorder() did not do it.
576         cache_helper::purge_by_event('changesincoursecat');
578         // Update all fields in the current object.
579         $this->restore();
580     }
582     /**
583      * Checks if this course category is visible to current user
584      *
585      * Please note that methods coursecat::get (without 3rd argumet),
586      * coursecat::get_children(), etc. return only visible categories so it is
587      * usually not needed to call this function outside of this class
588      *
589      * @return bool
590      */
591     public function is_uservisible() {
592         return !$this->id || $this->visible ||
593                 has_capability('moodle/category:viewhiddencategories', $this->get_context());
594     }
596     /**
597      * Returns the complete corresponding record from DB table course_categories
598      *
599      * Mostly used in deprecated functions
600      *
601      * @return stdClass
602      */
603     public function get_db_record() {
604         global $DB;
605         if ($record = $DB->get_record('course_categories', array('id' => $this->id))) {
606             return $record;
607         } else {
608             return (object)convert_to_array($this);
609         }
610     }
612     /**
613      * Returns the entry from categories tree and makes sure the application-level tree cache is built
614      *
615      * The following keys can be requested:
616      *
617      * 'countall' - total number of categories in the system (always present)
618      * 0 - array of ids of top-level categories (always present)
619      * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
620      * $id (int) - array of ids of categories that are direct children of category with id $id. If
621      *   category with id $id does not exist returns false. If category has no children returns empty array
622      * $id.'i' - array of ids of children categories that have visible=0
623      *
624      * @param int|string $id
625      * @return mixed
626      */
627     protected static function get_tree($id) {
628         global $DB;
629         $coursecattreecache = cache::make('core', 'coursecattree');
630         $rv = $coursecattreecache->get($id);
631         if ($rv !== false) {
632             return $rv;
633         }
634         // Re-build the tree.
635         $sql = "SELECT cc.id, cc.parent, cc.visible
636                 FROM {course_categories} cc
637                 ORDER BY cc.sortorder";
638         $rs = $DB->get_recordset_sql($sql, array());
639         $all = array(0 => array(), '0i' => array());
640         $count = 0;
641         foreach ($rs as $record) {
642             $all[$record->id] = array();
643             $all[$record->id. 'i'] = array();
644             if (array_key_exists($record->parent, $all)) {
645                 $all[$record->parent][] = $record->id;
646                 if (!$record->visible) {
647                     $all[$record->parent. 'i'][] = $record->id;
648                 }
649             } else {
650                 // Parent not found. This is data consistency error but next fix_course_sortorder() should fix it.
651                 $all[0][] = $record->id;
652                 if (!$record->visible) {
653                     $all['0i'][] = $record->id;
654                 }
655             }
656             $count++;
657         }
658         $rs->close();
659         if (!$count) {
660             // No categories found.
661             // This may happen after upgrade of a very old moodle version.
662             // In new versions the default category is created on install.
663             $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
664             set_config('defaultrequestcategory', $defcoursecat->id);
665             $all[0] = array($defcoursecat->id);
666             $all[$defcoursecat->id] = array();
667             $count++;
668         }
669         // We must add countall to all in case it was the requested ID.
670         $all['countall'] = $count;
671         $coursecattreecache->set_many($all);
672         if (array_key_exists($id, $all)) {
673             return $all[$id];
674         }
675         // Requested non-existing category.
676         return array();
677     }
679     /**
680      * Returns number of ALL categories in the system regardless if
681      * they are visible to current user or not
682      *
683      * @return int
684      */
685     public static function count_all() {
686         return self::get_tree('countall');
687     }
689     /**
690      * Retrieves number of records from course_categories table
691      *
692      * Only cached fields are retrieved. Records are ready for preloading context
693      *
694      * @param string $whereclause
695      * @param array $params
696      * @return array array of stdClass objects
697      */
698     protected static function get_records($whereclause, $params) {
699         global $DB;
700         // Retrieve from DB only the fields that need to be stored in cache.
701         $fields = array_keys(array_filter(self::$coursecatfields));
702         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
703         $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
704                 FROM {course_categories} cc
705                 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
706                 WHERE ". $whereclause." ORDER BY cc.sortorder";
707         return $DB->get_records_sql($sql,
708                 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
709     }
711     /**
712      * Resets course contact caches when role assignments were changed
713      *
714      * @param int $roleid role id that was given or taken away
715      * @param context $context context where role assignment has been changed
716      */
717     public static function role_assignment_changed($roleid, $context) {
718         global $CFG, $DB;
720         if ($context->contextlevel > CONTEXT_COURSE) {
721             // No changes to course contacts if role was assigned on the module/block level.
722             return;
723         }
725         if (!$CFG->coursecontact || !in_array($roleid, explode(',', $CFG->coursecontact))) {
726             // The role is not one of course contact roles.
727             return;
728         }
730         // Remove from cache course contacts of all affected courses.
731         $cache = cache::make('core', 'coursecontacts');
732         if ($context->contextlevel == CONTEXT_COURSE) {
733             $cache->delete($context->instanceid);
734         } else if ($context->contextlevel == CONTEXT_SYSTEM) {
735             $cache->purge();
736         } else {
737             $sql = "SELECT ctx.instanceid
738                     FROM {context} ctx
739                     WHERE ctx.path LIKE ? AND ctx.contextlevel = ?";
740             $params = array($context->path . '/%', CONTEXT_COURSE);
741             if ($courses = $DB->get_fieldset_sql($sql, $params)) {
742                 $cache->delete_many($courses);
743             }
744         }
745     }
747     /**
748      * Executed when user enrolment was changed to check if course
749      * contacts cache needs to be cleared
750      *
751      * @param int $courseid course id
752      * @param int $userid user id
753      * @param int $status new enrolment status (0 - active, 1 - suspended)
754      * @param int $timestart new enrolment time start
755      * @param int $timeend new enrolment time end
756      */
757     public static function user_enrolment_changed($courseid, $userid,
758             $status, $timestart = null, $timeend = null) {
759         $cache = cache::make('core', 'coursecontacts');
760         $contacts = $cache->get($courseid);
761         if ($contacts === false) {
762             // The contacts for the affected course were not cached anyway.
763             return;
764         }
765         $enrolmentactive = ($status == 0) &&
766                 (!$timestart || $timestart < time()) &&
767                 (!$timeend || $timeend > time());
768         if (!$enrolmentactive) {
769             $isincontacts = false;
770             foreach ($contacts as $contact) {
771                 if ($contact->id == $userid) {
772                     $isincontacts = true;
773                 }
774             }
775             if (!$isincontacts) {
776                 // Changed user's enrolment does not exist or is not active,
777                 // and he is not in cached course contacts, no changes to be made.
778                 return;
779             }
780         }
781         // Either enrolment of manager was deleted/suspended
782         // or user enrolment was added or activated.
783         // In order to see if the course contacts for this course need
784         // changing we would need to make additional queries, they will
785         // slow down bulk enrolment changes. It is better just to remove
786         // course contacts cache for this course.
787         $cache->delete($courseid);
788     }
790     /**
791      * Given list of DB records from table course populates each record with list of users with course contact roles
792      *
793      * This function fills the courses with raw information as {@link get_role_users()} would do.
794      * See also {@link course_in_list::get_course_contacts()} for more readable return
795      *
796      * $courses[$i]->managers = array(
797      *   $roleassignmentid => $roleuser,
798      *   ...
799      * );
800      *
801      * where $roleuser is an stdClass with the following properties:
802      *
803      * $roleuser->raid - role assignment id
804      * $roleuser->id - user id
805      * $roleuser->username
806      * $roleuser->firstname
807      * $roleuser->lastname
808      * $roleuser->rolecoursealias
809      * $roleuser->rolename
810      * $roleuser->sortorder - role sortorder
811      * $roleuser->roleid
812      * $roleuser->roleshortname
813      *
814      * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
815      *
816      * @param array $courses
817      */
818     public static function preload_course_contacts(&$courses) {
819         global $CFG, $DB;
820         if (empty($courses) || empty($CFG->coursecontact)) {
821             return;
822         }
823         $managerroles = explode(',', $CFG->coursecontact);
824         $cache = cache::make('core', 'coursecontacts');
825         $cacheddata = $cache->get_many(array_keys($courses));
826         $courseids = array();
827         foreach (array_keys($courses) as $id) {
828             if ($cacheddata[$id] !== false) {
829                 $courses[$id]->managers = $cacheddata[$id];
830             } else {
831                 $courseids[] = $id;
832             }
833         }
835         // Array $courseids now stores list of ids of courses for which we still need to retrieve contacts.
836         if (empty($courseids)) {
837             return;
838         }
840         // First build the array of all context ids of the courses and their categories.
841         $allcontexts = array();
842         foreach ($courseids as $id) {
843             $context = context_course::instance($id);
844             $courses[$id]->managers = array();
845             foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
846                 if (!isset($allcontexts[$ctxid])) {
847                     $allcontexts[$ctxid] = array();
848                 }
849                 $allcontexts[$ctxid][] = $id;
850             }
851         }
853         // Fetch list of all users with course contact roles in any of the courses contexts or parent contexts.
854         list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
855         list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
856         list($sort, $sortparams) = users_order_by_sql('u');
857         $notdeleted = array('notdeleted'=>0);
858         $allnames = get_all_user_name_fields(true, 'u');
859         $sql = "SELECT ra.contextid, ra.id AS raid,
860                        r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
861                        rn.name AS rolecoursealias, u.id, u.username, $allnames
862                   FROM {role_assignments} ra
863                   JOIN {user} u ON ra.userid = u.id
864                   JOIN {role} r ON ra.roleid = r.id
865              LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
866                 WHERE  ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
867              ORDER BY r.sortorder, $sort";
868         $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
869         $checkenrolments = array();
870         foreach ($rs as $ra) {
871             foreach ($allcontexts[$ra->contextid] as $id) {
872                 $courses[$id]->managers[$ra->raid] = $ra;
873                 if (!isset($checkenrolments[$id])) {
874                     $checkenrolments[$id] = array();
875                 }
876                 $checkenrolments[$id][] = $ra->id;
877             }
878         }
879         $rs->close();
881         // Remove from course contacts users who are not enrolled in the course.
882         $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
883         foreach ($checkenrolments as $id => $userids) {
884             if (empty($enrolleduserids[$id])) {
885                 $courses[$id]->managers = array();
886             } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
887                 foreach ($courses[$id]->managers as $raid => $ra) {
888                     if (in_array($ra->id, $notenrolled)) {
889                         unset($courses[$id]->managers[$raid]);
890                     }
891                 }
892             }
893         }
895         // Set the cache.
896         $values = array();
897         foreach ($courseids as $id) {
898             $values[$id] = $courses[$id]->managers;
899         }
900         $cache->set_many($values);
901     }
903     /**
904      * Verify user enrollments for multiple course-user combinations
905      *
906      * @param array $courseusers array where keys are course ids and values are array
907      *     of users in this course whose enrolment we wish to verify
908      * @return array same structure as input array but values list only users from input
909      *     who are enrolled in the course
910      */
911     protected static function ensure_users_enrolled($courseusers) {
912         global $DB;
913         // If the input array is too big, split it into chunks.
914         $maxcoursesinquery = 20;
915         if (count($courseusers) > $maxcoursesinquery) {
916             $rv = array();
917             for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
918                 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
919                 $rv = $rv + self::ensure_users_enrolled($chunk);
920             }
921             return $rv;
922         }
924         // Create a query verifying valid user enrolments for the number of courses.
925         $sql = "SELECT DISTINCT e.courseid, ue.userid
926           FROM {user_enrolments} ue
927           JOIN {enrol} e ON e.id = ue.enrolid
928           WHERE ue.status = :active
929             AND e.status = :enabled
930             AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
931         $now = round(time(), -2); // Rounding helps caching in DB.
932         $params = array('enabled' => ENROL_INSTANCE_ENABLED,
933             'active' => ENROL_USER_ACTIVE,
934             'now1' => $now, 'now2' => $now);
935         $cnt = 0;
936         $subsqls = array();
937         $enrolled = array();
938         foreach ($courseusers as $id => $userids) {
939             $enrolled[$id] = array();
940             if (count($userids)) {
941                 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
942                 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
943                 $params = $params + array('courseid'.$cnt => $id) + $params2;
944                 $cnt++;
945             }
946         }
947         if (count($subsqls)) {
948             $sql .= "AND (". join(' OR ', $subsqls).")";
949             $rs = $DB->get_recordset_sql($sql, $params);
950             foreach ($rs as $record) {
951                 $enrolled[$record->courseid][] = $record->userid;
952             }
953             $rs->close();
954         }
955         return $enrolled;
956     }
958     /**
959      * Retrieves number of records from course table
960      *
961      * Not all fields are retrieved. Records are ready for preloading context
962      *
963      * @param string $whereclause
964      * @param array $params
965      * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
966      * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
967      *     on not visible courses
968      * @return array array of stdClass objects
969      */
970     protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
971         global $DB;
972         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
973         $fields = array('c.id', 'c.category', 'c.sortorder',
974                         'c.shortname', 'c.fullname', 'c.idnumber',
975                         'c.startdate', 'c.enddate', 'c.visible', 'c.cacherev');
976         if (!empty($options['summary'])) {
977             $fields[] = 'c.summary';
978             $fields[] = 'c.summaryformat';
979         } else {
980             $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
981         }
982         $sql = "SELECT ". join(',', $fields). ", $ctxselect
983                 FROM {course} c
984                 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
985                 WHERE ". $whereclause." ORDER BY c.sortorder";
986         $list = $DB->get_records_sql($sql,
987                 array('contextcourse' => CONTEXT_COURSE) + $params);
989         if ($checkvisibility) {
990             // Loop through all records and make sure we only return the courses accessible by user.
991             foreach ($list as $course) {
992                 if (isset($list[$course->id]->hassummary)) {
993                     $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
994                 }
995                 if (empty($course->visible)) {
996                     // Load context only if we need to check capability.
997                     context_helper::preload_from_record($course);
998                     if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
999                         unset($list[$course->id]);
1000                     }
1001                 }
1002             }
1003         }
1005         // Preload course contacts if necessary.
1006         if (!empty($options['coursecontacts'])) {
1007             self::preload_course_contacts($list);
1008         }
1009         return $list;
1010     }
1012     /**
1013      * Returns array of ids of children categories that current user can not see
1014      *
1015      * This data is cached in user session cache
1016      *
1017      * @return array
1018      */
1019     protected function get_not_visible_children_ids() {
1020         global $DB;
1021         $coursecatcache = cache::make('core', 'coursecat');
1022         if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
1023             // We never checked visible children before.
1024             $hidden = self::get_tree($this->id.'i');
1025             $invisibleids = array();
1026             if ($hidden) {
1027                 // Preload categories contexts.
1028                 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
1029                 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1030                 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
1031                     WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
1032                         array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
1033                 foreach ($contexts as $record) {
1034                     context_helper::preload_from_record($record);
1035                 }
1036                 // Check that user has 'viewhiddencategories' capability for each hidden category.
1037                 foreach ($hidden as $id) {
1038                     if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
1039                         $invisibleids[] = $id;
1040                     }
1041                 }
1042             }
1043             $coursecatcache->set('ic'. $this->id, $invisibleids);
1044         }
1045         return $invisibleids;
1046     }
1048     /**
1049      * Sorts list of records by several fields
1050      *
1051      * @param array $records array of stdClass objects
1052      * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
1053      * @return int
1054      */
1055     protected static function sort_records(&$records, $sortfields) {
1056         if (empty($records)) {
1057             return;
1058         }
1059         // If sorting by course display name, calculate it (it may be fullname or shortname+fullname).
1060         if (array_key_exists('displayname', $sortfields)) {
1061             foreach ($records as $key => $record) {
1062                 if (!isset($record->displayname)) {
1063                     $records[$key]->displayname = get_course_display_name_for_list($record);
1064                 }
1065             }
1066         }
1067         // Sorting by one field - use core_collator.
1068         if (count($sortfields) == 1) {
1069             $property = key($sortfields);
1070             if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
1071                 $sortflag = core_collator::SORT_NUMERIC;
1072             } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
1073                 $sortflag = core_collator::SORT_STRING;
1074             } else {
1075                 $sortflag = core_collator::SORT_REGULAR;
1076             }
1077             core_collator::asort_objects_by_property($records, $property, $sortflag);
1078             if ($sortfields[$property] < 0) {
1079                 $records = array_reverse($records, true);
1080             }
1081             return;
1082         }
1083         $records = coursecat_sortable_records::sort($records, $sortfields);
1084     }
1086     /**
1087      * Returns array of children categories visible to the current user
1088      *
1089      * @param array $options options for retrieving children
1090      *    - sort - list of fields to sort. Example
1091      *             array('idnumber' => 1, 'name' => 1, 'id' => -1)
1092      *             will sort by idnumber asc, name asc and id desc.
1093      *             Default: array('sortorder' => 1)
1094      *             Only cached fields may be used for sorting!
1095      *    - offset
1096      *    - limit - maximum number of children to return, 0 or null for no limit
1097      * @return coursecat[] Array of coursecat objects indexed by category id
1098      */
1099     public function get_children($options = array()) {
1100         global $DB;
1101         $coursecatcache = cache::make('core', 'coursecat');
1103         // Get default values for options.
1104         if (!empty($options['sort']) && is_array($options['sort'])) {
1105             $sortfields = $options['sort'];
1106         } else {
1107             $sortfields = array('sortorder' => 1);
1108         }
1109         $limit = null;
1110         if (!empty($options['limit']) && (int)$options['limit']) {
1111             $limit = (int)$options['limit'];
1112         }
1113         $offset = 0;
1114         if (!empty($options['offset']) && (int)$options['offset']) {
1115             $offset = (int)$options['offset'];
1116         }
1118         // First retrieve list of user-visible and sorted children ids from cache.
1119         $sortedids = $coursecatcache->get('c'. $this->id. ':'.  serialize($sortfields));
1120         if ($sortedids === false) {
1121             $sortfieldskeys = array_keys($sortfields);
1122             if ($sortfieldskeys[0] === 'sortorder') {
1123                 // No DB requests required to build the list of ids sorted by sortorder.
1124                 // We can easily ignore other sort fields because sortorder is always different.
1125                 $sortedids = self::get_tree($this->id);
1126                 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
1127                     $sortedids = array_diff($sortedids, $invisibleids);
1128                     if ($sortfields['sortorder'] == -1) {
1129                         $sortedids = array_reverse($sortedids, true);
1130                     }
1131                 }
1132             } else {
1133                 // We need to retrieve and sort all children. Good thing that it is done only on first request.
1134                 if ($invisibleids = $this->get_not_visible_children_ids()) {
1135                     list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
1136                     $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
1137                             array('parent' => $this->id) + $params);
1138                 } else {
1139                     $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
1140                 }
1141                 self::sort_records($records, $sortfields);
1142                 $sortedids = array_keys($records);
1143             }
1144             $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
1145         }
1147         if (empty($sortedids)) {
1148             return array();
1149         }
1151         // Now retrieive and return categories.
1152         if ($offset || $limit) {
1153             $sortedids = array_slice($sortedids, $offset, $limit);
1154         }
1155         if (isset($records)) {
1156             // Easy, we have already retrieved records.
1157             if ($offset || $limit) {
1158                 $records = array_slice($records, $offset, $limit, true);
1159             }
1160         } else {
1161             list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
1162             $records = self::get_records('cc.id '. $sql, array('parent' => $this->id) + $params);
1163         }
1165         $rv = array();
1166         foreach ($sortedids as $id) {
1167             if (isset($records[$id])) {
1168                 $rv[$id] = new coursecat($records[$id]);
1169             }
1170         }
1171         return $rv;
1172     }
1174     /**
1175      * Returns true if the user has the manage capability on any category.
1176      *
1177      * This method uses the coursecat cache and an entry `has_manage_capability` to speed up
1178      * calls to this method.
1179      *
1180      * @return bool
1181      */
1182     public static function has_manage_capability_on_any() {
1183         return self::has_capability_on_any('moodle/category:manage');
1184     }
1186     /**
1187      * Checks if the user has at least one of the given capabilities on any category.
1188      *
1189      * @param array|string $capabilities One or more capabilities to check. Check made is an OR.
1190      * @return bool
1191      */
1192     public static function has_capability_on_any($capabilities) {
1193         global $DB;
1194         if (!isloggedin() || isguestuser()) {
1195             return false;
1196         }
1198         if (!is_array($capabilities)) {
1199             $capabilities = array($capabilities);
1200         }
1201         $keys = array();
1202         foreach ($capabilities as $capability) {
1203             $keys[$capability] = sha1($capability);
1204         }
1206         /* @var cache_session $cache */
1207         $cache = cache::make('core', 'coursecat');
1208         $hascapability = $cache->get_many($keys);
1209         $needtoload = false;
1210         foreach ($hascapability as $capability) {
1211             if ($capability === '1') {
1212                 return true;
1213             } else if ($capability === false) {
1214                 $needtoload = true;
1215             }
1216         }
1217         if ($needtoload === false) {
1218             // All capabilities were retrieved and the user didn't have any.
1219             return false;
1220         }
1222         $haskey = null;
1223         $fields = context_helper::get_preload_record_columns_sql('ctx');
1224         $sql = "SELECT ctx.instanceid AS categoryid, $fields
1225                       FROM {context} ctx
1226                      WHERE contextlevel = :contextlevel
1227                   ORDER BY depth ASC";
1228         $params = array('contextlevel' => CONTEXT_COURSECAT);
1229         $recordset = $DB->get_recordset_sql($sql, $params);
1230         foreach ($recordset as $context) {
1231             context_helper::preload_from_record($context);
1232             $context = context_coursecat::instance($context->categoryid);
1233             foreach ($capabilities as $capability) {
1234                 if (has_capability($capability, $context)) {
1235                     $haskey = $capability;
1236                     break 2;
1237                 }
1238             }
1239         }
1240         $recordset->close();
1241         if ($haskey === null) {
1242             $data = array();
1243             foreach ($keys as $key) {
1244                 $data[$key] = '0';
1245             }
1246             $cache->set_many($data);
1247             return false;
1248         } else {
1249             $cache->set($haskey, '1');
1250             return true;
1251         }
1252     }
1254     /**
1255      * Returns true if the user can resort any category.
1256      * @return bool
1257      */
1258     public static function can_resort_any() {
1259         return self::has_manage_capability_on_any();
1260     }
1262     /**
1263      * Returns true if the user can change the parent of any category.
1264      * @return bool
1265      */
1266     public static function can_change_parent_any() {
1267         return self::has_manage_capability_on_any();
1268     }
1270     /**
1271      * Returns number of subcategories visible to the current user
1272      *
1273      * @return int
1274      */
1275     public function get_children_count() {
1276         $sortedids = self::get_tree($this->id);
1277         $invisibleids = $this->get_not_visible_children_ids();
1278         return count($sortedids) - count($invisibleids);
1279     }
1281     /**
1282      * Returns true if the category has ANY children, including those not visible to the user
1283      *
1284      * @return boolean
1285      */
1286     public function has_children() {
1287         $allchildren = self::get_tree($this->id);
1288         return !empty($allchildren);
1289     }
1291     /**
1292      * Returns true if the category has courses in it (count does not include courses
1293      * in child categories)
1294      *
1295      * @return bool
1296      */
1297     public function has_courses() {
1298         global $DB;
1299         return $DB->record_exists_sql("select 1 from {course} where category = ?",
1300                 array($this->id));
1301     }
1303     /**
1304      * Get the link used to view this course category.
1305      *
1306      * @return  \moodle_url
1307      */
1308     public function get_view_link() {
1309         return new \moodle_url('/course/index.php', [
1310             'categoryid' => $this->id,
1311         ]);
1312     }
1314     /**
1315      * Searches courses
1316      *
1317      * List of found course ids is cached for 10 minutes. Cache may be purged prior
1318      * to this when somebody edits courses or categories, however it is very
1319      * difficult to keep track of all possible changes that may affect list of courses.
1320      *
1321      * @param array $search contains search criterias, such as:
1322      *     - search - search string
1323      *     - blocklist - id of block (if we are searching for courses containing specific block0
1324      *     - modulelist - name of module (if we are searching for courses containing specific module
1325      *     - tagid - id of tag
1326      * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
1327      *                       search is always category-independent
1328      * @param array $requiredcapabilites List of capabilities required to see return course.
1329      * @return course_in_list[]
1330      */
1331     public static function search_courses($search, $options = array(), $requiredcapabilities = array()) {
1332         global $DB;
1333         $offset = !empty($options['offset']) ? $options['offset'] : 0;
1334         $limit = !empty($options['limit']) ? $options['limit'] : null;
1335         $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1337         $coursecatcache = cache::make('core', 'coursecat');
1338         $cachekey = 's-'. serialize(
1339             $search + array('sort' => $sortfields) + array('requiredcapabilities' => $requiredcapabilities)
1340         );
1341         $cntcachekey = 'scnt-'. serialize($search);
1343         $ids = $coursecatcache->get($cachekey);
1344         if ($ids !== false) {
1345             // We already cached last search result.
1346             $ids = array_slice($ids, $offset, $limit);
1347             $courses = array();
1348             if (!empty($ids)) {
1349                 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1350                 $records = self::get_course_records("c.id ". $sql, $params, $options);
1351                 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1352                 if (!empty($options['coursecontacts'])) {
1353                     self::preload_course_contacts($records);
1354                 }
1355                 // If option 'idonly' is specified no further action is needed, just return list of ids.
1356                 if (!empty($options['idonly'])) {
1357                     return array_keys($records);
1358                 }
1359                 // Prepare the list of course_in_list objects.
1360                 foreach ($ids as $id) {
1361                     $courses[$id] = new course_in_list($records[$id]);
1362                 }
1363             }
1364             return $courses;
1365         }
1367         $preloadcoursecontacts = !empty($options['coursecontacts']);
1368         unset($options['coursecontacts']);
1370         // Empty search string will return all results.
1371         if (!isset($search['search'])) {
1372             $search['search'] = '';
1373         }
1375         if (empty($search['blocklist']) && empty($search['modulelist']) && empty($search['tagid'])) {
1376             // Search courses that have specified words in their names/summaries.
1377             $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1379             $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount, $requiredcapabilities);
1380             self::sort_records($courselist, $sortfields);
1381             $coursecatcache->set($cachekey, array_keys($courselist));
1382             $coursecatcache->set($cntcachekey, $totalcount);
1383             $records = array_slice($courselist, $offset, $limit, true);
1384         } else {
1385             if (!empty($search['blocklist'])) {
1386                 // Search courses that have block with specified id.
1387                 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1388                 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1389                     WHERE bi.blockname = :blockname)';
1390                 $params = array('blockname' => $blockname);
1391             } else if (!empty($search['modulelist'])) {
1392                 // Search courses that have module with specified name.
1393                 $where = "c.id IN (SELECT DISTINCT module.course ".
1394                         "FROM {".$search['modulelist']."} module)";
1395                 $params = array();
1396             } else if (!empty($search['tagid'])) {
1397                 // Search courses that are tagged with the specified tag.
1398                 $where = "c.id IN (SELECT t.itemid ".
1399                         "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype AND t.component = :component)";
1400                 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course', 'component' => 'core');
1401                 if (!empty($search['ctx'])) {
1402                     $rec = isset($search['rec']) ? $search['rec'] : true;
1403                     $parentcontext = context::instance_by_id($search['ctx']);
1404                     if ($parentcontext->contextlevel == CONTEXT_SYSTEM && $rec) {
1405                         // Parent context is system context and recursive is set to yes.
1406                         // Nothing to filter - all courses fall into this condition.
1407                     } else if ($rec) {
1408                         // Filter all courses in the parent context at any level.
1409                         $where .= ' AND ctx.path LIKE :contextpath';
1410                         $params['contextpath'] = $parentcontext->path . '%';
1411                     } else if ($parentcontext->contextlevel == CONTEXT_COURSECAT) {
1412                         // All courses in the given course category.
1413                         $where .= ' AND c.category = :category';
1414                         $params['category'] = $parentcontext->instanceid;
1415                     } else {
1416                         // No courses will satisfy the context criterion, do not bother searching.
1417                         $where = '1=0';
1418                     }
1419                 }
1420             } else {
1421                 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1422                 return array();
1423             }
1424             $courselist = self::get_course_records($where, $params, $options, true);
1425             if (!empty($requiredcapabilities)) {
1426                 foreach ($courselist as $key => $course) {
1427                     context_helper::preload_from_record($course);
1428                     $coursecontext = context_course::instance($course->id);
1429                     if (!has_all_capabilities($requiredcapabilities, $coursecontext)) {
1430                         unset($courselist[$key]);
1431                     }
1432                 }
1433             }
1434             self::sort_records($courselist, $sortfields);
1435             $coursecatcache->set($cachekey, array_keys($courselist));
1436             $coursecatcache->set($cntcachekey, count($courselist));
1437             $records = array_slice($courselist, $offset, $limit, true);
1438         }
1440         // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1441         if (!empty($preloadcoursecontacts)) {
1442             self::preload_course_contacts($records);
1443         }
1444         // If option 'idonly' is specified no further action is needed, just return list of ids.
1445         if (!empty($options['idonly'])) {
1446             return array_keys($records);
1447         }
1448         // Prepare the list of course_in_list objects.
1449         $courses = array();
1450         foreach ($records as $record) {
1451             $courses[$record->id] = new course_in_list($record);
1452         }
1453         return $courses;
1454     }
1456     /**
1457      * Returns number of courses in the search results
1458      *
1459      * It is recommended to call this function after {@link coursecat::search_courses()}
1460      * and not before because only course ids are cached. Otherwise search_courses() may
1461      * perform extra DB queries.
1462      *
1463      * @param array $search search criteria, see method search_courses() for more details
1464      * @param array $options display options. They do not affect the result but
1465      *     the 'sort' property is used in cache key for storing list of course ids
1466      * @param array $requiredcapabilites List of capabilities required to see return course.
1467      * @return int
1468      */
1469     public static function search_courses_count($search, $options = array(), $requiredcapabilities = array()) {
1470         $coursecatcache = cache::make('core', 'coursecat');
1471         $cntcachekey = 'scnt-'. serialize($search) . serialize($requiredcapabilities);
1472         if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1473             // Cached value not found. Retrieve ALL courses and return their count.
1474             unset($options['offset']);
1475             unset($options['limit']);
1476             unset($options['summary']);
1477             unset($options['coursecontacts']);
1478             $options['idonly'] = true;
1479             $courses = self::search_courses($search, $options, $requiredcapabilities);
1480             $cnt = count($courses);
1481         }
1482         return $cnt;
1483     }
1485     /**
1486      * Retrieves the list of courses accessible by user
1487      *
1488      * Not all information is cached, try to avoid calling this method
1489      * twice in the same request.
1490      *
1491      * The following fields are always retrieved:
1492      * - id, visible, fullname, shortname, idnumber, category, sortorder
1493      *
1494      * If you plan to use properties/methods course_in_list::$summary and/or
1495      * course_in_list::get_course_contacts()
1496      * you can preload this information using appropriate 'options'. Otherwise
1497      * they will be retrieved from DB on demand and it may end with bigger DB load.
1498      *
1499      * Note that method course_in_list::has_summary() will not perform additional
1500      * DB queries even if $options['summary'] is not specified
1501      *
1502      * List of found course ids is cached for 10 minutes. Cache may be purged prior
1503      * to this when somebody edits courses or categories, however it is very
1504      * difficult to keep track of all possible changes that may affect list of courses.
1505      *
1506      * @param array $options options for retrieving children
1507      *    - recursive - return courses from subcategories as well. Use with care,
1508      *      this may be a huge list!
1509      *    - summary - preloads fields 'summary' and 'summaryformat'
1510      *    - coursecontacts - preloads course contacts
1511      *    - sort - list of fields to sort. Example
1512      *             array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1513      *             will sort by idnumber asc, shortname asc and id desc.
1514      *             Default: array('sortorder' => 1)
1515      *             Only cached fields may be used for sorting!
1516      *    - offset
1517      *    - limit - maximum number of children to return, 0 or null for no limit
1518      *    - idonly - returns the array or course ids instead of array of objects
1519      *               used only in get_courses_count()
1520      * @return course_in_list[]
1521      */
1522     public function get_courses($options = array()) {
1523         global $DB;
1524         $recursive = !empty($options['recursive']);
1525         $offset = !empty($options['offset']) ? $options['offset'] : 0;
1526         $limit = !empty($options['limit']) ? $options['limit'] : null;
1527         $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1529         // Check if this category is hidden.
1530         // Also 0-category never has courses unless this is recursive call.
1531         if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1532             return array();
1533         }
1535         $coursecatcache = cache::make('core', 'coursecat');
1536         $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1537                  '-'. serialize($sortfields);
1538         $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1540         // Check if we have already cached results.
1541         $ids = $coursecatcache->get($cachekey);
1542         if ($ids !== false) {
1543             // We already cached last search result and it did not expire yet.
1544             $ids = array_slice($ids, $offset, $limit);
1545             $courses = array();
1546             if (!empty($ids)) {
1547                 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1548                 $records = self::get_course_records("c.id ". $sql, $params, $options);
1549                 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1550                 if (!empty($options['coursecontacts'])) {
1551                     self::preload_course_contacts($records);
1552                 }
1553                 // If option 'idonly' is specified no further action is needed, just return list of ids.
1554                 if (!empty($options['idonly'])) {
1555                     return array_keys($records);
1556                 }
1557                 // Prepare the list of course_in_list objects.
1558                 foreach ($ids as $id) {
1559                     $courses[$id] = new course_in_list($records[$id]);
1560                 }
1561             }
1562             return $courses;
1563         }
1565         // Retrieve list of courses in category.
1566         $where = 'c.id <> :siteid';
1567         $params = array('siteid' => SITEID);
1568         if ($recursive) {
1569             if ($this->id) {
1570                 $context = context_coursecat::instance($this->id);
1571                 $where .= ' AND ctx.path like :path';
1572                 $params['path'] = $context->path. '/%';
1573             }
1574         } else {
1575             $where .= ' AND c.category = :categoryid';
1576             $params['categoryid'] = $this->id;
1577         }
1578         // Get list of courses without preloaded coursecontacts because we don't need them for every course.
1579         $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1581         // Sort and cache list.
1582         self::sort_records($list, $sortfields);
1583         $coursecatcache->set($cachekey, array_keys($list));
1584         $coursecatcache->set($cntcachekey, count($list));
1586         // Apply offset/limit, convert to course_in_list and return.
1587         $courses = array();
1588         if (isset($list)) {
1589             if ($offset || $limit) {
1590                 $list = array_slice($list, $offset, $limit, true);
1591             }
1592             // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1593             if (!empty($options['coursecontacts'])) {
1594                 self::preload_course_contacts($list);
1595             }
1596             // If option 'idonly' is specified no further action is needed, just return list of ids.
1597             if (!empty($options['idonly'])) {
1598                 return array_keys($list);
1599             }
1600             // Prepare the list of course_in_list objects.
1601             foreach ($list as $record) {
1602                 $courses[$record->id] = new course_in_list($record);
1603             }
1604         }
1605         return $courses;
1606     }
1608     /**
1609      * Returns number of courses visible to the user
1610      *
1611      * @param array $options similar to get_courses() except some options do not affect
1612      *     number of courses (i.e. sort, summary, offset, limit etc.)
1613      * @return int
1614      */
1615     public function get_courses_count($options = array()) {
1616         $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1617         $coursecatcache = cache::make('core', 'coursecat');
1618         if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1619             // Cached value not found. Retrieve ALL courses and return their count.
1620             unset($options['offset']);
1621             unset($options['limit']);
1622             unset($options['summary']);
1623             unset($options['coursecontacts']);
1624             $options['idonly'] = true;
1625             $courses = $this->get_courses($options);
1626             $cnt = count($courses);
1627         }
1628         return $cnt;
1629     }
1631     /**
1632      * Returns true if the user is able to delete this category.
1633      *
1634      * Note if this category contains any courses this isn't a full check, it will need to be accompanied by a call to either
1635      * {@link coursecat::can_delete_full()} or {@link coursecat::can_move_content_to()} depending upon what the user wished to do.
1636      *
1637      * @return boolean
1638      */
1639     public function can_delete() {
1640         if (!$this->has_manage_capability()) {
1641             return false;
1642         }
1643         return $this->parent_has_manage_capability();
1644     }
1646     /**
1647      * Returns true if user can delete current category and all its contents
1648      *
1649      * To be able to delete course category the user must have permission
1650      * 'moodle/category:manage' in ALL child course categories AND
1651      * be able to delete all courses
1652      *
1653      * @return bool
1654      */
1655     public function can_delete_full() {
1656         global $DB;
1657         if (!$this->id) {
1658             // Fool-proof.
1659             return false;
1660         }
1662         $context = $this->get_context();
1663         if (!$this->is_uservisible() ||
1664                 !has_capability('moodle/category:manage', $context)) {
1665             return false;
1666         }
1668         // Check all child categories (not only direct children).
1669         $sql = context_helper::get_preload_record_columns_sql('ctx');
1670         $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1671             ' FROM {context} ctx '.
1672             ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1673             ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1674                 array($context->path. '/%', CONTEXT_COURSECAT));
1675         foreach ($childcategories as $childcat) {
1676             context_helper::preload_from_record($childcat);
1677             $childcontext = context_coursecat::instance($childcat->id);
1678             if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1679                     !has_capability('moodle/category:manage', $childcontext)) {
1680                 return false;
1681             }
1682         }
1684         // Check courses.
1685         $sql = context_helper::get_preload_record_columns_sql('ctx');
1686         $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1687                     $sql. ' FROM {context} ctx '.
1688                     'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1689                 array('pathmask' => $context->path. '/%',
1690                     'courselevel' => CONTEXT_COURSE));
1691         foreach ($coursescontexts as $ctxrecord) {
1692             context_helper::preload_from_record($ctxrecord);
1693             if (!can_delete_course($ctxrecord->courseid)) {
1694                 return false;
1695             }
1696         }
1698         return true;
1699     }
1701     /**
1702      * Recursively delete category including all subcategories and courses
1703      *
1704      * Function {@link coursecat::can_delete_full()} MUST be called prior
1705      * to calling this function because there is no capability check
1706      * inside this function
1707      *
1708      * @param boolean $showfeedback display some notices
1709      * @return array return deleted courses
1710      * @throws moodle_exception
1711      */
1712     public function delete_full($showfeedback = true) {
1713         global $CFG, $DB;
1715         require_once($CFG->libdir.'/gradelib.php');
1716         require_once($CFG->libdir.'/questionlib.php');
1717         require_once($CFG->dirroot.'/cohort/lib.php');
1719         // Make sure we won't timeout when deleting a lot of courses.
1720         $settimeout = core_php_time_limit::raise();
1722         // Allow plugins to use this category before we completely delete it.
1723         if ($pluginsfunction = get_plugins_with_function('pre_course_category_delete')) {
1724             $category = $this->get_db_record();
1725             foreach ($pluginsfunction as $plugintype => $plugins) {
1726                 foreach ($plugins as $pluginfunction) {
1727                     $pluginfunction($category);
1728                 }
1729             }
1730         }
1732         $deletedcourses = array();
1734         // Get children. Note, we don't want to use cache here because it would be rebuilt too often.
1735         $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1736         foreach ($children as $record) {
1737             $coursecat = new coursecat($record);
1738             $deletedcourses += $coursecat->delete_full($showfeedback);
1739         }
1741         if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1742             foreach ($courses as $course) {
1743                 if (!delete_course($course, false)) {
1744                     throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1745                 }
1746                 $deletedcourses[] = $course;
1747             }
1748         }
1750         // Move or delete cohorts in this context.
1751         cohort_delete_category($this);
1753         // Now delete anything that may depend on course category context.
1754         grade_course_category_delete($this->id, 0, $showfeedback);
1755         if (!question_delete_course_category($this, 0, $showfeedback)) {
1756             throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1757         }
1759         // Finally delete the category and it's context.
1760         $DB->delete_records('course_categories', array('id' => $this->id));
1762         $coursecatcontext = context_coursecat::instance($this->id);
1763         $coursecatcontext->delete();
1765         cache_helper::purge_by_event('changesincoursecat');
1767         // Trigger a course category deleted event.
1768         /* @var \core\event\course_category_deleted $event */
1769         $event = \core\event\course_category_deleted::create(array(
1770             'objectid' => $this->id,
1771             'context' => $coursecatcontext,
1772             'other' => array('name' => $this->name)
1773         ));
1774         $event->set_coursecat($this);
1775         $event->trigger();
1777         // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1778         if ($this->id == $CFG->defaultrequestcategory) {
1779             set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1780         }
1781         return $deletedcourses;
1782     }
1784     /**
1785      * Checks if user can delete this category and move content (courses, subcategories and questions)
1786      * to another category. If yes returns the array of possible target categories names
1787      *
1788      * If user can not manage this category or it is completely empty - empty array will be returned
1789      *
1790      * @return array
1791      */
1792     public function move_content_targets_list() {
1793         global $CFG;
1794         require_once($CFG->libdir . '/questionlib.php');
1795         $context = $this->get_context();
1796         if (!$this->is_uservisible() ||
1797                 !has_capability('moodle/category:manage', $context)) {
1798             // User is not able to manage current category, he is not able to delete it.
1799             // No possible target categories.
1800             return array();
1801         }
1803         $testcaps = array();
1804         // If this category has courses in it, user must have 'course:create' capability in target category.
1805         if ($this->has_courses()) {
1806             $testcaps[] = 'moodle/course:create';
1807         }
1808         // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1809         if ($this->has_children() || question_context_has_any_questions($context)) {
1810             $testcaps[] = 'moodle/category:manage';
1811         }
1812         if (!empty($testcaps)) {
1813             // Return list of categories excluding this one and it's children.
1814             return self::make_categories_list($testcaps, $this->id);
1815         }
1817         // Category is completely empty, no need in target for contents.
1818         return array();
1819     }
1821     /**
1822      * Checks if user has capability to move all category content to the new parent before
1823      * removing this category
1824      *
1825      * @param int $newcatid
1826      * @return bool
1827      */
1828     public function can_move_content_to($newcatid) {
1829         global $CFG;
1830         require_once($CFG->libdir . '/questionlib.php');
1831         $context = $this->get_context();
1832         if (!$this->is_uservisible() ||
1833                 !has_capability('moodle/category:manage', $context)) {
1834             return false;
1835         }
1836         $testcaps = array();
1837         // If this category has courses in it, user must have 'course:create' capability in target category.
1838         if ($this->has_courses()) {
1839             $testcaps[] = 'moodle/course:create';
1840         }
1841         // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1842         if ($this->has_children() || question_context_has_any_questions($context)) {
1843             $testcaps[] = 'moodle/category:manage';
1844         }
1845         if (!empty($testcaps)) {
1846             return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1847         }
1849         // There is no content but still return true.
1850         return true;
1851     }
1853     /**
1854      * Deletes a category and moves all content (children, courses and questions) to the new parent
1855      *
1856      * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1857      * must be called prior
1858      *
1859      * @param int $newparentid
1860      * @param bool $showfeedback
1861      * @return bool
1862      */
1863     public function delete_move($newparentid, $showfeedback = false) {
1864         global $CFG, $DB, $OUTPUT;
1866         require_once($CFG->libdir.'/gradelib.php');
1867         require_once($CFG->libdir.'/questionlib.php');
1868         require_once($CFG->dirroot.'/cohort/lib.php');
1870         // Get all objects and lists because later the caches will be reset so.
1871         // We don't need to make extra queries.
1872         $newparentcat = self::get($newparentid, MUST_EXIST, true);
1873         $catname = $this->get_formatted_name();
1874         $children = $this->get_children();
1875         $params = array('category' => $this->id);
1876         $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', $params);
1877         $context = $this->get_context();
1879         if ($children) {
1880             foreach ($children as $childcat) {
1881                 $childcat->change_parent_raw($newparentcat);
1882                 // Log action.
1883                 $event = \core\event\course_category_updated::create(array(
1884                     'objectid' => $childcat->id,
1885                     'context' => $childcat->get_context()
1886                 ));
1887                 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $childcat->id,
1888                     $childcat->id));
1889                 $event->trigger();
1890             }
1891             fix_course_sortorder();
1892         }
1894         if ($coursesids) {
1895             require_once($CFG->dirroot.'/course/lib.php');
1896             if (!move_courses($coursesids, $newparentid)) {
1897                 if ($showfeedback) {
1898                     echo $OUTPUT->notification("Error moving courses");
1899                 }
1900                 return false;
1901             }
1902             if ($showfeedback) {
1903                 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1904             }
1905         }
1907         // Move or delete cohorts in this context.
1908         cohort_delete_category($this);
1910         // Now delete anything that may depend on course category context.
1911         grade_course_category_delete($this->id, $newparentid, $showfeedback);
1912         if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1913             if ($showfeedback) {
1914                 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1915             }
1916             return false;
1917         }
1919         // Finally delete the category and it's context.
1920         $DB->delete_records('course_categories', array('id' => $this->id));
1921         $context->delete();
1923         // Trigger a course category deleted event.
1924         /* @var \core\event\course_category_deleted $event */
1925         $event = \core\event\course_category_deleted::create(array(
1926             'objectid' => $this->id,
1927             'context' => $context,
1928             'other' => array('name' => $this->name)
1929         ));
1930         $event->set_coursecat($this);
1931         $event->trigger();
1933         cache_helper::purge_by_event('changesincoursecat');
1935         if ($showfeedback) {
1936             echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1937         }
1939         // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1940         if ($this->id == $CFG->defaultrequestcategory) {
1941             set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1942         }
1943         return true;
1944     }
1946     /**
1947      * Checks if user can move current category to the new parent
1948      *
1949      * This checks if new parent category exists, user has manage cap there
1950      * and new parent is not a child of this category
1951      *
1952      * @param int|stdClass|coursecat $newparentcat
1953      * @return bool
1954      */
1955     public function can_change_parent($newparentcat) {
1956         if (!has_capability('moodle/category:manage', $this->get_context())) {
1957             return false;
1958         }
1959         if (is_object($newparentcat)) {
1960             $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1961         } else {
1962             $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1963         }
1964         if (!$newparentcat) {
1965             return false;
1966         }
1967         if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1968             // Can not move to itself or it's own child.
1969             return false;
1970         }
1971         if ($newparentcat->id) {
1972             return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
1973         } else {
1974             return has_capability('moodle/category:manage', context_system::instance());
1975         }
1976     }
1978     /**
1979      * Moves the category under another parent category. All associated contexts are moved as well
1980      *
1981      * This is protected function, use change_parent() or update() from outside of this class
1982      *
1983      * @see coursecat::change_parent()
1984      * @see coursecat::update()
1985      *
1986      * @param coursecat $newparentcat
1987      * @throws moodle_exception
1988      */
1989     protected function change_parent_raw(coursecat $newparentcat) {
1990         global $DB;
1992         $context = $this->get_context();
1994         $hidecat = false;
1995         if (empty($newparentcat->id)) {
1996             $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1997             $newparent = context_system::instance();
1998         } else {
1999             if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
2000                 // Can not move to itself or it's own child.
2001                 throw new moodle_exception('cannotmovecategory');
2002             }
2003             $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
2004             $newparent = context_coursecat::instance($newparentcat->id);
2006             if (!$newparentcat->visible and $this->visible) {
2007                 // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children
2008                 // will be restored properly.
2009                 $hidecat = true;
2010             }
2011         }
2012         $this->parent = $newparentcat->id;
2014         $context->update_moved($newparent);
2016         // Now make it last in new category.
2017         $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
2019         if ($hidecat) {
2020             fix_course_sortorder();
2021             $this->restore();
2022             // Hide object but store 1 in visibleold, because when parent category visibility changes this category must
2023             // become visible again.
2024             $this->hide_raw(1);
2025         }
2026     }
2028     /**
2029      * Efficiently moves a category - NOTE that this can have
2030      * a huge impact access-control-wise...
2031      *
2032      * Note that this function does not check capabilities.
2033      *
2034      * Example of usage:
2035      * $coursecat = coursecat::get($categoryid);
2036      * if ($coursecat->can_change_parent($newparentcatid)) {
2037      *     $coursecat->change_parent($newparentcatid);
2038      * }
2039      *
2040      * This function does not update field course_categories.timemodified
2041      * If you want to update timemodified, use
2042      * $coursecat->update(array('parent' => $newparentcat));
2043      *
2044      * @param int|stdClass|coursecat $newparentcat
2045      */
2046     public function change_parent($newparentcat) {
2047         // Make sure parent category exists but do not check capabilities here that it is visible to current user.
2048         if (is_object($newparentcat)) {
2049             $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
2050         } else {
2051             $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
2052         }
2053         if ($newparentcat->id != $this->parent) {
2054             $this->change_parent_raw($newparentcat);
2055             fix_course_sortorder();
2056             cache_helper::purge_by_event('changesincoursecat');
2057             $this->restore();
2059             $event = \core\event\course_category_updated::create(array(
2060                 'objectid' => $this->id,
2061                 'context' => $this->get_context()
2062             ));
2063             $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $this->id, $this->id));
2064             $event->trigger();
2065         }
2066     }
2068     /**
2069      * Hide course category and child course and subcategories
2070      *
2071      * If this category has changed the parent and is moved under hidden
2072      * category we will want to store it's current visibility state in
2073      * the field 'visibleold'. If admin clicked 'hide' for this particular
2074      * category, the field 'visibleold' should become 0.
2075      *
2076      * All subcategories and courses will have their current visibility in the field visibleold
2077      *
2078      * This is protected function, use hide() or update() from outside of this class
2079      *
2080      * @see coursecat::hide()
2081      * @see coursecat::update()
2082      *
2083      * @param int $visibleold value to set in field $visibleold for this category
2084      * @return bool whether changes have been made and caches need to be purged afterwards
2085      */
2086     protected function hide_raw($visibleold = 0) {
2087         global $DB;
2088         $changes = false;
2090         // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing.
2091         if ($this->id && $this->__get('visibleold') != $visibleold) {
2092             $this->visibleold = $visibleold;
2093             $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
2094             $changes = true;
2095         }
2096         if (!$this->visible || !$this->id) {
2097             // Already hidden or can not be hidden.
2098             return $changes;
2099         }
2101         $this->visible = 0;
2102         $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
2103         // Store visible flag so that we can return to it if we immediately unhide.
2104         $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id));
2105         $DB->set_field('course', 'visible', 0, array('category' => $this->id));
2106         // Get all child categories and hide too.
2107         if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
2108             foreach ($subcats as $cat) {
2109                 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
2110                 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
2111                 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
2112                 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
2113             }
2114         }
2115         return true;
2116     }
2118     /**
2119      * Hide course category and child course and subcategories
2120      *
2121      * Note that there is no capability check inside this function
2122      *
2123      * This function does not update field course_categories.timemodified
2124      * If you want to update timemodified, use
2125      * $coursecat->update(array('visible' => 0));
2126      */
2127     public function hide() {
2128         if ($this->hide_raw(0)) {
2129             cache_helper::purge_by_event('changesincoursecat');
2131             $event = \core\event\course_category_updated::create(array(
2132                 'objectid' => $this->id,
2133                 'context' => $this->get_context()
2134             ));
2135             $event->set_legacy_logdata(array(SITEID, 'category', 'hide', 'editcategory.php?id=' . $this->id, $this->id));
2136             $event->trigger();
2137         }
2138     }
2140     /**
2141      * Show course category and restores visibility for child course and subcategories
2142      *
2143      * Note that there is no capability check inside this function
2144      *
2145      * This is protected function, use show() or update() from outside of this class
2146      *
2147      * @see coursecat::show()
2148      * @see coursecat::update()
2149      *
2150      * @return bool whether changes have been made and caches need to be purged afterwards
2151      */
2152     protected function show_raw() {
2153         global $DB;
2155         if ($this->visible) {
2156             // Already visible.
2157             return false;
2158         }
2160         $this->visible = 1;
2161         $this->visibleold = 1;
2162         $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
2163         $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
2164         $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
2165         // Get all child categories and unhide too.
2166         if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
2167             foreach ($subcats as $cat) {
2168                 if ($cat->visibleold) {
2169                     $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
2170                 }
2171                 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
2172             }
2173         }
2174         return true;
2175     }
2177     /**
2178      * Show course category and restores visibility for child course and subcategories
2179      *
2180      * Note that there is no capability check inside this function
2181      *
2182      * This function does not update field course_categories.timemodified
2183      * If you want to update timemodified, use
2184      * $coursecat->update(array('visible' => 1));
2185      */
2186     public function show() {
2187         if ($this->show_raw()) {
2188             cache_helper::purge_by_event('changesincoursecat');
2190             $event = \core\event\course_category_updated::create(array(
2191                 'objectid' => $this->id,
2192                 'context' => $this->get_context()
2193             ));
2194             $event->set_legacy_logdata(array(SITEID, 'category', 'show', 'editcategory.php?id=' . $this->id, $this->id));
2195             $event->trigger();
2196         }
2197     }
2199     /**
2200      * Returns name of the category formatted as a string
2201      *
2202      * @param array $options formatting options other than context
2203      * @return string
2204      */
2205     public function get_formatted_name($options = array()) {
2206         if ($this->id) {
2207             $context = $this->get_context();
2208             return format_string($this->name, true, array('context' => $context) + $options);
2209         } else {
2210             return get_string('top');
2211         }
2212     }
2214     /**
2215      * Get the nested name of this category, with all of it's parents.
2216      *
2217      * @param   bool    $includelinks Whether to wrap each name in the view link for that category.
2218      * @param   string  $separator The string between each name.
2219      * @param   array   $options Formatting options.
2220      * @return  string
2221      */
2222     public function get_nested_name($includelinks = true, $separator = ' / ', $options = []) {
2223         // Get the name of hierarchical name of this category.
2224         $parents = $this->get_parents();
2225         $categories = static::get_many($parents);
2226         $categories[] = $this;
2228         $names = array_map(function($category) use ($options, $includelinks) {
2229             if ($includelinks) {
2230                 return html_writer::link($category->get_view_link(), $category->get_formatted_name($options));
2231             } else {
2232                 return $category->get_formatted_name($options);
2233             }
2235         }, $categories);
2237         return implode($separator, $names);
2238     }
2240     /**
2241      * Returns ids of all parents of the category. Last element in the return array is the direct parent
2242      *
2243      * For example, if you have a tree of categories like:
2244      *   Miscellaneous (id = 1)
2245      *      Subcategory (id = 2)
2246      *         Sub-subcategory (id = 4)
2247      *   Other category (id = 3)
2248      *
2249      * coursecat::get(1)->get_parents() == array()
2250      * coursecat::get(2)->get_parents() == array(1)
2251      * coursecat::get(4)->get_parents() == array(1, 2);
2252      *
2253      * Note that this method does not check if all parents are accessible by current user
2254      *
2255      * @return array of category ids
2256      */
2257     public function get_parents() {
2258         $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
2259         array_pop($parents);
2260         return $parents;
2261     }
2263     /**
2264      * This function returns a nice list representing category tree
2265      * for display or to use in a form <select> element
2266      *
2267      * List is cached for 10 minutes
2268      *
2269      * For example, if you have a tree of categories like:
2270      *   Miscellaneous (id = 1)
2271      *      Subcategory (id = 2)
2272      *         Sub-subcategory (id = 4)
2273      *   Other category (id = 3)
2274      * Then after calling this function you will have
2275      * array(1 => 'Miscellaneous',
2276      *       2 => 'Miscellaneous / Subcategory',
2277      *       4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2278      *       3 => 'Other category');
2279      *
2280      * If you specify $requiredcapability, then only categories where the current
2281      * user has that capability will be added to $list.
2282      * If you only have $requiredcapability in a child category, not the parent,
2283      * then the child catgegory will still be included.
2284      *
2285      * If you specify the option $excludeid, then that category, and all its children,
2286      * are omitted from the tree. This is useful when you are doing something like
2287      * moving categories, where you do not want to allow people to move a category
2288      * to be the child of itself.
2289      *
2290      * See also {@link make_categories_options()}
2291      *
2292      * @param string/array $requiredcapability if given, only categories where the current
2293      *      user has this capability will be returned. Can also be an array of capabilities,
2294      *      in which case they are all required.
2295      * @param integer $excludeid Exclude this category and its children from the lists built.
2296      * @param string $separator string to use as a separator between parent and child category. Default ' / '
2297      * @return array of strings
2298      */
2299     public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
2300         global $DB;
2301         $coursecatcache = cache::make('core', 'coursecat');
2303         // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids
2304         // with requried cap ($thislist).
2305         $currentlang = current_language();
2306         $basecachekey = $currentlang . '_catlist';
2307         $baselist = $coursecatcache->get($basecachekey);
2308         $thislist = false;
2309         $thiscachekey = null;
2310         if (!empty($requiredcapability)) {
2311             $requiredcapability = (array)$requiredcapability;
2312             $thiscachekey = 'catlist:'. serialize($requiredcapability);
2313             if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
2314                 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
2315             }
2316         } else if ($baselist !== false) {
2317             $thislist = array_keys($baselist);
2318         }
2320         if ($baselist === false) {
2321             // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
2322             $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2323             $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
2324                     FROM {course_categories} cc
2325                     JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
2326                     ORDER BY cc.sortorder";
2327             $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2328             $baselist = array();
2329             $thislist = array();
2330             foreach ($rs as $record) {
2331                 // If the category's parent is not visible to the user, it is not visible as well.
2332                 if (!$record->parent || isset($baselist[$record->parent])) {
2333                     context_helper::preload_from_record($record);
2334                     $context = context_coursecat::instance($record->id);
2335                     if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
2336                         // No cap to view category, added to neither $baselist nor $thislist.
2337                         continue;
2338                     }
2339                     $baselist[$record->id] = array(
2340                         'name' => format_string($record->name, true, array('context' => $context)),
2341                         'path' => $record->path
2342                     );
2343                     if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
2344                         // No required capability, added to $baselist but not to $thislist.
2345                         continue;
2346                     }
2347                     $thislist[] = $record->id;
2348                 }
2349             }
2350             $rs->close();
2351             $coursecatcache->set($basecachekey, $baselist);
2352             if (!empty($requiredcapability)) {
2353                 $coursecatcache->set($thiscachekey, join(',', $thislist));
2354             }
2355         } else if ($thislist === false) {
2356             // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
2357             $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2358             $sql = "SELECT ctx.instanceid AS id, $ctxselect
2359                     FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
2360             $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2361             $thislist = array();
2362             foreach (array_keys($baselist) as $id) {
2363                 context_helper::preload_from_record($contexts[$id]);
2364                 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
2365                     $thislist[] = $id;
2366                 }
2367             }
2368             $coursecatcache->set($thiscachekey, join(',', $thislist));
2369         }
2371         // Now build the array of strings to return, mind $separator and $excludeid.
2372         $names = array();
2373         foreach ($thislist as $id) {
2374             $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
2375             if (!$excludeid || !in_array($excludeid, $path)) {
2376                 $namechunks = array();
2377                 foreach ($path as $parentid) {
2378                     $namechunks[] = $baselist[$parentid]['name'];
2379                 }
2380                 $names[$id] = join($separator, $namechunks);
2381             }
2382         }
2383         return $names;
2384     }
2386     /**
2387      * Prepares the object for caching. Works like the __sleep method.
2388      *
2389      * implementing method from interface cacheable_object
2390      *
2391      * @return array ready to be cached
2392      */
2393     public function prepare_to_cache() {
2394         $a = array();
2395         foreach (self::$coursecatfields as $property => $cachedirectives) {
2396             if ($cachedirectives !== null) {
2397                 list($shortname, $defaultvalue) = $cachedirectives;
2398                 if ($this->$property !== $defaultvalue) {
2399                     $a[$shortname] = $this->$property;
2400                 }
2401             }
2402         }
2403         $context = $this->get_context();
2404         $a['xi'] = $context->id;
2405         $a['xp'] = $context->path;
2406         return $a;
2407     }
2409     /**
2410      * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2411      *
2412      * implementing method from interface cacheable_object
2413      *
2414      * @param array $a
2415      * @return coursecat
2416      */
2417     public static function wake_from_cache($a) {
2418         $record = new stdClass;
2419         foreach (self::$coursecatfields as $property => $cachedirectives) {
2420             if ($cachedirectives !== null) {
2421                 list($shortname, $defaultvalue) = $cachedirectives;
2422                 if (array_key_exists($shortname, $a)) {
2423                     $record->$property = $a[$shortname];
2424                 } else {
2425                     $record->$property = $defaultvalue;
2426                 }
2427             }
2428         }
2429         $record->ctxid = $a['xi'];
2430         $record->ctxpath = $a['xp'];
2431         $record->ctxdepth = $record->depth + 1;
2432         $record->ctxlevel = CONTEXT_COURSECAT;
2433         $record->ctxinstance = $record->id;
2434         return new coursecat($record, true);
2435     }
2437     /**
2438      * Returns true if the user is able to create a top level category.
2439      * @return bool
2440      */
2441     public static function can_create_top_level_category() {
2442         return has_capability('moodle/category:manage', context_system::instance());
2443     }
2445     /**
2446      * Returns the category context.
2447      * @return context_coursecat
2448      */
2449     public function get_context() {
2450         if ($this->id === 0) {
2451             // This is the special top level category object.
2452             return context_system::instance();
2453         } else {
2454             return context_coursecat::instance($this->id);
2455         }
2456     }
2458     /**
2459      * Returns true if the user is able to manage this category.
2460      * @return bool
2461      */
2462     public function has_manage_capability() {
2463         if ($this->hasmanagecapability === null) {
2464             $this->hasmanagecapability = has_capability('moodle/category:manage', $this->get_context());
2465         }
2466         return $this->hasmanagecapability;
2467     }
2469     /**
2470      * Returns true if the user has the manage capability on the parent category.
2471      * @return bool
2472      */
2473     public function parent_has_manage_capability() {
2474         return has_capability('moodle/category:manage', get_category_or_system_context($this->parent));
2475     }
2477     /**
2478      * Returns true if the current user can create subcategories of this category.
2479      * @return bool
2480      */
2481     public function can_create_subcategory() {
2482         return $this->has_manage_capability();
2483     }
2485     /**
2486      * Returns true if the user can resort this categories sub categories and courses.
2487      * Must have manage capability and be able to see all subcategories.
2488      * @return bool
2489      */
2490     public function can_resort_subcategories() {
2491         return $this->has_manage_capability() && !$this->get_not_visible_children_ids();
2492     }
2494     /**
2495      * Returns true if the user can resort the courses within this category.
2496      * Must have manage capability and be able to see all courses.
2497      * @return bool
2498      */
2499     public function can_resort_courses() {
2500         return $this->has_manage_capability() && $this->coursecount == $this->get_courses_count();
2501     }
2503     /**
2504      * Returns true of the user can change the sortorder of this category (resort in the parent category)
2505      * @return bool
2506      */
2507     public function can_change_sortorder() {
2508         return $this->id && $this->get_parent_coursecat()->can_resort_subcategories();
2509     }
2511     /**
2512      * Returns true if the current user can create a course within this category.
2513      * @return bool
2514      */
2515     public function can_create_course() {
2516         return has_capability('moodle/course:create', $this->get_context());
2517     }
2519     /**
2520      * Returns true if the current user can edit this categories settings.
2521      * @return bool
2522      */
2523     public function can_edit() {
2524         return $this->has_manage_capability();
2525     }
2527     /**
2528      * Returns true if the current user can review role assignments for this category.
2529      * @return bool
2530      */
2531     public function can_review_roles() {
2532         return has_capability('moodle/role:assign', $this->get_context());
2533     }
2535     /**
2536      * Returns true if the current user can review permissions for this category.
2537      * @return bool
2538      */
2539     public function can_review_permissions() {
2540         return has_any_capability(array(
2541             'moodle/role:assign',
2542             'moodle/role:safeoverride',
2543             'moodle/role:override',
2544             'moodle/role:assign'
2545         ), $this->get_context());
2546     }
2548     /**
2549      * Returns true if the current user can review cohorts for this category.
2550      * @return bool
2551      */
2552     public function can_review_cohorts() {
2553         return has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->get_context());
2554     }
2556     /**
2557      * Returns true if the current user can review filter settings for this category.
2558      * @return bool
2559      */
2560     public function can_review_filters() {
2561         return has_capability('moodle/filter:manage', $this->get_context()) &&
2562                count(filter_get_available_in_context($this->get_context()))>0;
2563     }
2565     /**
2566      * Returns true if the current user is able to change the visbility of this category.
2567      * @return bool
2568      */
2569     public function can_change_visibility() {
2570         return $this->parent_has_manage_capability();
2571     }
2573     /**
2574      * Returns true if the user can move courses out of this category.
2575      * @return bool
2576      */
2577     public function can_move_courses_out_of() {
2578         return $this->has_manage_capability();
2579     }
2581     /**
2582      * Returns true if the user can move courses into this category.
2583      * @return bool
2584      */
2585     public function can_move_courses_into() {
2586         return $this->has_manage_capability();
2587     }
2589     /**
2590      * Returns true if the user is able to restore a course into this category as a new course.
2591      * @return bool
2592      */
2593     public function can_restore_courses_into() {
2594         return has_capability('moodle/restore:restorecourse', $this->get_context());
2595     }
2597     /**
2598      * Resorts the sub categories of this category by the given field.
2599      *
2600      * @param string $field One of name, idnumber or descending values of each (appended desc)
2601      * @param bool $cleanup If true cleanup will be done, if false you will need to do it manually later.
2602      * @return bool True on success.
2603      * @throws coding_exception
2604      */
2605     public function resort_subcategories($field, $cleanup = true) {
2606         global $DB;
2607         $desc = false;
2608         if (substr($field, -4) === "desc") {
2609             $desc = true;
2610             $field = substr($field, 0, -4);  // Remove "desc" from field name.
2611         }
2612         if ($field !== 'name' && $field !== 'idnumber') {
2613             throw new coding_exception('Invalid field requested');
2614         }
2615         $children = $this->get_children();
2616         core_collator::asort_objects_by_property($children, $field, core_collator::SORT_NATURAL);
2617         if (!empty($desc)) {
2618             $children = array_reverse($children);
2619         }
2620         $i = 1;
2621         foreach ($children as $cat) {
2622             $i++;
2623             $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id));
2624             $i += $cat->coursecount;
2625         }
2626         if ($cleanup) {
2627             self::resort_categories_cleanup();
2628         }
2629         return true;
2630     }
2632     /**
2633      * Cleans things up after categories have been resorted.
2634      * @param bool $includecourses If set to true we know courses have been resorted as well.
2635      */
2636     public static function resort_categories_cleanup($includecourses = false) {
2637         // This should not be needed but we do it just to be safe.
2638         fix_course_sortorder();
2639         cache_helper::purge_by_event('changesincoursecat');
2640         if ($includecourses) {
2641             cache_helper::purge_by_event('changesincourse');
2642         }
2643     }
2645     /**
2646      * Resort the courses within this category by the given field.
2647      *
2648      * @param string $field One of fullname, shortname, idnumber or descending values of each (appended desc)
2649      * @param bool $cleanup
2650      * @return bool True for success.
2651      * @throws coding_exception
2652      */
2653     public function resort_courses($field, $cleanup = true) {
2654         global $DB;
2655         $desc = false;
2656         if (substr($field, -4) === "desc") {
2657             $desc = true;
2658             $field = substr($field, 0, -4);  // Remove "desc" from field name.
2659         }
2660         if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber' && $field !== 'timecreated') {
2661             // This is ultra important as we use $field in an SQL statement below this.
2662             throw new coding_exception('Invalid field requested');
2663         }
2664         $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
2665         $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields
2666                   FROM {course} c
2667              LEFT JOIN {context} ctx ON ctx.instanceid = c.id
2668                  WHERE ctx.contextlevel = :ctxlevel AND
2669                        c.category = :categoryid";
2670         $params = array(
2671             'ctxlevel' => CONTEXT_COURSE,
2672             'categoryid' => $this->id
2673         );
2674         $courses = $DB->get_records_sql($sql, $params);
2675         if (count($courses) > 0) {
2676             foreach ($courses as $courseid => $course) {
2677                 context_helper::preload_from_record($course);
2678                 if ($field === 'idnumber') {
2679                     $course->sortby = $course->idnumber;
2680                 } else {
2681                     // It'll require formatting.
2682                     $options = array(
2683                         'context' => context_course::instance($course->id)
2684                     );
2685                     // We format the string first so that it appears as the user would see it.
2686                     // This ensures the sorting makes sense to them. However it won't necessarily make
2687                     // sense to everyone if things like multilang filters are enabled.
2688                     // We then strip any tags as we don't want things such as image tags skewing the
2689                     // sort results.
2690                     $course->sortby = strip_tags(format_string($course->$field, true, $options));
2691                 }
2692                 // We set it back here rather than using references as there is a bug with using
2693                 // references in a foreach before passing as an arg by reference.
2694                 $courses[$courseid] = $course;
2695             }
2696             // Sort the courses.
2697             core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL);
2698             if (!empty($desc)) {
2699                 $courses = array_reverse($courses);
2700             }
2701             $i = 1;
2702             foreach ($courses as $course) {
2703                 $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id));
2704                 $i++;
2705             }
2706             if ($cleanup) {
2707                 // This should not be needed but we do it just to be safe.
2708                 fix_course_sortorder();
2709                 cache_helper::purge_by_event('changesincourse');
2710             }
2711         }
2712         return true;
2713     }
2715     /**
2716      * Changes the sort order of this categories parent shifting this category up or down one.
2717      *
2718      * @global \moodle_database $DB
2719      * @param bool $up If set to true the category is shifted up one spot, else its moved down.
2720      * @return bool True on success, false otherwise.
2721      */
2722     public function change_sortorder_by_one($up) {
2723         global $DB;
2724         $params = array($this->sortorder, $this->parent);
2725         if ($up) {
2726             $select = 'sortorder < ? AND parent = ?';
2727             $sort = 'sortorder DESC';
2728         } else {
2729             $select = 'sortorder > ? AND parent = ?';
2730             $sort = 'sortorder ASC';
2731         }
2732         fix_course_sortorder();
2733         $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1);
2734         $swapcategory = reset($swapcategory);
2735         if ($swapcategory) {
2736             $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id));
2737             $DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id));
2738             $this->sortorder = $swapcategory->sortorder;
2740             $event = \core\event\course_category_updated::create(array(
2741                 'objectid' => $this->id,
2742                 'context' => $this->get_context()
2743             ));
2744             $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'management.php?categoryid=' . $this->id,
2745                 $this->id));
2746             $event->trigger();
2748             // Finally reorder courses.
2749             fix_course_sortorder();
2750             cache_helper::purge_by_event('changesincoursecat');
2751             return true;
2752         }
2753         return false;
2754     }
2756     /**
2757      * Returns the parent coursecat object for this category.
2758      *
2759      * @return coursecat
2760      */
2761     public function get_parent_coursecat() {
2762         return self::get($this->parent);
2763     }
2766     /**
2767      * Returns true if the user is able to request a new course be created.
2768      * @return bool
2769      */
2770     public function can_request_course() {
2771         global $CFG;
2772         if (empty($CFG->enablecourserequests) || $this->id != $CFG->defaultrequestcategory) {
2773             return false;
2774         }
2775         return !$this->can_create_course() && has_capability('moodle/course:request', $this->get_context());
2776     }
2778     /**
2779      * Returns true if the user can approve course requests.
2780      * @return bool
2781      */
2782     public static function can_approve_course_requests() {
2783         global $CFG, $DB;
2784         if (empty($CFG->enablecourserequests)) {
2785             return false;
2786         }
2787         $context = context_system::instance();
2788         if (!has_capability('moodle/site:approvecourse', $context)) {
2789             return false;
2790         }
2791         if (!$DB->record_exists('course_request', array())) {
2792             return false;
2793         }
2794         return true;
2795     }
2798 /**
2799  * Class to store information about one course in a list of courses
2800  *
2801  * Not all information may be retrieved when object is created but
2802  * it will be retrieved on demand when appropriate property or method is
2803  * called.
2804  *
2805  * Instances of this class are usually returned by functions
2806  * {@link coursecat::search_courses()}
2807  * and
2808  * {@link coursecat::get_courses()}
2809  *
2810  * @property-read int $id
2811  * @property-read int $category Category ID
2812  * @property-read int $sortorder
2813  * @property-read string $fullname
2814  * @property-read string $shortname
2815  * @property-read string $idnumber
2816  * @property-read string $summary Course summary. Field is present if coursecat::get_courses()
2817  *     was called with option 'summary'. Otherwise will be retrieved from DB on first request
2818  * @property-read int $summaryformat Summary format. Field is present if coursecat::get_courses()
2819  *     was called with option 'summary'. Otherwise will be retrieved from DB on first request
2820  * @property-read string $format Course format. Retrieved from DB on first request
2821  * @property-read int $showgrades Retrieved from DB on first request
2822  * @property-read int $newsitems Retrieved from DB on first request
2823  * @property-read int $startdate
2824  * @property-read int $enddate
2825  * @property-read int $marker Retrieved from DB on first request
2826  * @property-read int $maxbytes Retrieved from DB on first request
2827  * @property-read int $legacyfiles Retrieved from DB on first request
2828  * @property-read int $showreports Retrieved from DB on first request
2829  * @property-read int $visible
2830  * @property-read int $visibleold Retrieved from DB on first request
2831  * @property-read int $groupmode Retrieved from DB on first request
2832  * @property-read int $groupmodeforce Retrieved from DB on first request
2833  * @property-read int $defaultgroupingid Retrieved from DB on first request
2834  * @property-read string $lang Retrieved from DB on first request
2835  * @property-read string $theme Retrieved from DB on first request
2836  * @property-read int $timecreated Retrieved from DB on first request
2837  * @property-read int $timemodified Retrieved from DB on first request
2838  * @property-read int $requested Retrieved from DB on first request
2839  * @property-read int $enablecompletion Retrieved from DB on first request
2840  * @property-read int $completionnotify Retrieved from DB on first request
2841  * @property-read int $cacherev
2842  *
2843  * @package    core
2844  * @subpackage course
2845  * @copyright  2013 Marina Glancy
2846  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2847  */
2848 class course_in_list implements IteratorAggregate {
2850     /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2851     protected $record;
2853     /** @var array array of course contacts - stores result of call to get_course_contacts() */
2854     protected $coursecontacts;
2856     /** @var bool true if the current user can access the course, false otherwise. */
2857     protected $canaccess = null;
2859     /**
2860      * Creates an instance of the class from record
2861      *
2862      * @param stdClass $record except fields from course table it may contain
2863      *     field hassummary indicating that summary field is not empty.
2864      *     Also it is recommended to have context fields here ready for
2865      *     context preloading
2866      */
2867     public function __construct(stdClass $record) {
2868         context_helper::preload_from_record($record);
2869         $this->record = new stdClass();
2870         foreach ($record as $key => $value) {
2871             $this->record->$key = $value;
2872         }
2873     }
2875     /**
2876      * Indicates if the course has non-empty summary field
2877      *
2878      * @return bool
2879      */
2880     public function has_summary() {
2881         if (isset($this->record->hassummary)) {
2882             return !empty($this->record->hassummary);
2883         }
2884         if (!isset($this->record->summary)) {
2885             // We need to retrieve summary.
2886             $this->__get('summary');
2887         }
2888         return !empty($this->record->summary);
2889     }
2891     /**
2892      * Indicates if the course have course contacts to display
2893      *
2894      * @return bool
2895      */
2896     public function has_course_contacts() {
2897         if (!isset($this->record->managers)) {
2898             $courses = array($this->id => &$this->record);
2899             coursecat::preload_course_contacts($courses);
2900         }
2901         return !empty($this->record->managers);
2902     }
2904     /**
2905      * Returns list of course contacts (usually teachers) to display in course link
2906      *
2907      * Roles to display are set up in $CFG->coursecontact
2908      *
2909      * The result is the list of users where user id is the key and the value
2910      * is an array with elements:
2911      *  - 'user' - object containing basic user information
2912      *  - 'role' - object containing basic role information (id, name, shortname, coursealias)
2913      *  - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2914      *  - 'username' => fullname($user, $canviewfullnames)
2915      *
2916      * @return array
2917      */
2918     public function get_course_contacts() {
2919         global $CFG;
2920         if (empty($CFG->coursecontact)) {
2921             // No roles are configured to be displayed as course contacts.
2922             return array();
2923         }
2924         if ($this->coursecontacts === null) {
2925             $this->coursecontacts = array();
2926             $context = context_course::instance($this->id);
2928             if (!isset($this->record->managers)) {
2929                 // Preload course contacts from DB.
2930                 $courses = array($this->id => &$this->record);
2931                 coursecat::preload_course_contacts($courses);
2932             }
2934             // Build return array with full roles names (for this course context) and users names.
2935             $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2936             foreach ($this->record->managers as $ruser) {
2937                 if (isset($this->coursecontacts[$ruser->id])) {
2938                     // Only display a user once with the highest sortorder role.
2939                     continue;
2940                 }
2941                 $user = new stdClass();
2942                 $user = username_load_fields_from_object($user, $ruser, null, array('id', 'username'));
2943                 $role = new stdClass();
2944                 $role->id = $ruser->roleid;
2945                 $role->name = $ruser->rolename;
2946                 $role->shortname = $ruser->roleshortname;
2947                 $role->coursealias = $ruser->rolecoursealias;
2949                 $this->coursecontacts[$user->id] = array(
2950                     'user' => $user,
2951                     'role' => $role,
2952                     'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2953                     'username' => fullname($user, $canviewfullnames)
2954                 );
2955             }
2956         }
2957         return $this->coursecontacts;
2958     }
2960     /**
2961      * Checks if course has any associated overview files
2962      *
2963      * @return bool
2964      */
2965     public function has_course_overviewfiles() {
2966         global $CFG;
2967         if (empty($CFG->courseoverviewfileslimit)) {
2968             return false;
2969         }
2970         $fs = get_file_storage();
2971         $context = context_course::instance($this->id);
2972         return !$fs->is_area_empty($context->id, 'course', 'overviewfiles');
2973     }
2975     /**
2976      * Returns all course overview files
2977      *
2978      * @return array array of stored_file objects
2979      */
2980     public function get_course_overviewfiles() {
2981         global $CFG;
2982         if (empty($CFG->courseoverviewfileslimit)) {
2983             return array();
2984         }
2985         require_once($CFG->libdir. '/filestorage/file_storage.php');
2986         require_once($CFG->dirroot. '/course/lib.php');
2987         $fs = get_file_storage();
2988         $context = context_course::instance($this->id);
2989         $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2990         if (count($files)) {
2991             $overviewfilesoptions = course_overviewfiles_options($this->id);
2992             $acceptedtypes = $overviewfilesoptions['accepted_types'];
2993             if ($acceptedtypes !== '*') {
2994                 // Filter only files with allowed extensions.
2995                 require_once($CFG->libdir. '/filelib.php');
2996                 foreach ($files as $key => $file) {
2997                     if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2998                         unset($files[$key]);
2999                     }
3000                 }
3001             }
3002             if (count($files) > $CFG->courseoverviewfileslimit) {
3003                 // Return no more than $CFG->courseoverviewfileslimit files.
3004                 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
3005             }
3006         }
3007         return $files;
3008     }
3010     /**
3011      * Magic method to check if property is set
3012      *
3013      * @param string $name
3014      * @return bool
3015      */
3016     public function __isset($name) {
3017         return isset($this->record->$name);
3018     }
3020     /**
3021      * Magic method to get a course property
3022      *
3023      * Returns any field from table course (retrieves it from DB if it was not retrieved before)
3024      *
3025      * @param string $name
3026      * @return mixed
3027      */
3028     public function __get($name) {
3029         global $DB;
3030         if (property_exists($this->record, $name)) {
3031             return $this->record->$name;
3032         } else if ($name === 'summary' || $name === 'summaryformat') {
3033             // Retrieve fields summary and summaryformat together because they are most likely to be used together.
3034             $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
3035             $this->record->summary = $record->summary;
3036             $this->record->summaryformat = $record->summaryformat;
3037             return $this->record->$name;
3038         } else if (array_key_exists($name, $DB->get_columns('course'))) {
3039             // Another field from table 'course' that was not retrieved.
3040             $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
3041             return $this->record->$name;
3042         }
3043         debugging('Invalid course property accessed! '.$name);
3044         return null;
3045     }
3047     /**
3048      * All properties are read only, sorry.
3049      *
3050      * @param string $name
3051      */
3052     public function __unset($name) {
3053         debugging('Can not unset '.get_class($this).' instance properties!');
3054     }
3056     /**
3057      * Magic setter method, we do not want anybody to modify properties from the outside
3058      *
3059      * @param string $name
3060      * @param mixed $value
3061      */
3062     public function __set($name, $value) {
3063         debugging('Can not change '.get_class($this).' instance properties!');
3064     }
3066     /**
3067      * Create an iterator because magic vars can't be seen by 'foreach'.
3068      * Exclude context fields
3069      *
3070      * Implementing method from interface IteratorAggregate
3071      *
3072      * @return ArrayIterator
3073      */
3074     public function getIterator() {
3075         $ret = array('id' => $this->record->id);
3076         foreach ($this->record as $property => $value) {
3077             $ret[$property] = $value;
3078         }
3079         return new ArrayIterator($ret);
3080     }
3082     /**
3083      * Returns the name of this course as it should be displayed within a list.
3084      * @return string
3085      */
3086     public function get_formatted_name() {
3087         return format_string(get_course_display_name_for_list($this), true, $this->get_context());
3088     }
3090     /**
3091      * Returns the formatted fullname for this course.
3092      * @return string
3093      */
3094     public function get_formatted_fullname() {
3095         return format_string($this->__get('fullname'), true, $this->get_context());
3096     }
3098     /**
3099      * Returns the formatted shortname for this course.
3100      * @return string
3101      */
3102     public function get_formatted_shortname() {
3103         return format_string($this->__get('shortname'), true, $this->get_context());
3104     }
3106     /**
3107      * Returns true if the current user can access this course.
3108      * @return bool
3109      */
3110     public function can_access() {
3111         if ($this->canaccess === null) {
3112             $this->canaccess = can_access_course($this->record);
3113         }
3114         return $this->canaccess;
3115     }
3117     /**
3118      * Returns true if the user can edit this courses settings.
3119      *
3120      * Note: this function does not check that the current user can access the course.
3121      * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3122      *
3123      * @return bool
3124      */
3125     public function can_edit() {
3126         return has_capability('moodle/course:update', $this->get_context());
3127     }
3129     /**
3130      * Returns true if the user can change the visibility of this course.
3131      *
3132      * Note: this function does not check that the current user can access the course.
3133      * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3134      *
3135      * @return bool
3136      */
3137     public function can_change_visibility() {
3138         // You must be able to both hide a course and view the hidden course.
3139         return has_all_capabilities(array('moodle/course:visibility', 'moodle/course:viewhiddencourses'), $this->get_context());
3140     }
3142     /**
3143      * Returns the context for this course.
3144      * @return context_course
3145      */
3146     public function get_context() {
3147         return context_course::instance($this->__get('id'));
3148     }
3150     /**
3151      * Returns true if this course is visible to the current user.
3152      * @return bool
3153      */
3154     public function is_uservisible() {
3155         return $this->visible || has_capability('moodle/course:viewhiddencourses', $this->get_context());
3156     }
3158     /**
3159      * Returns true if the current user can review enrolments for this course.
3160      *
3161      * Note: this function does not check that the current user can access the course.
3162      * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3163      *
3164      * @return bool
3165      */
3166     public function can_review_enrolments() {
3167         return has_capability('moodle/course:enrolreview', $this->get_context());
3168     }
3170     /**
3171      * Returns true if the current user can delete this course.
3172      *
3173      * Note: this function does not check that the current user can access the course.
3174      * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3175      *
3176      * @return bool
3177      */
3178     public function can_delete() {
3179         return can_delete_course($this->id);
3180     }
3182     /**
3183      * Returns true if the current user can backup this course.
3184      *
3185      * Note: this function does not check that the current user can access the course.
3186      * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3187      *
3188      * @return bool
3189      */
3190     public function can_backup() {
3191         return has_capability('moodle/backup:backupcourse', $this->get_context());
3192     }
3194     /**
3195      * Returns true if the current user can restore this course.
3196      *
3197      * Note: this function does not check that the current user can access the course.
3198      * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3199      *
3200      * @return bool
3201      */
3202     public function can_restore() {
3203         return has_capability('moodle/restore:restorecourse', $this->get_context());
3204     }
3207 /**
3208  * An array of records that is sortable by many fields.
3209  *
3210  * For more info on the ArrayObject class have a look at php.net.
3211  *
3212  * @package    core
3213  * @subpackage course
3214  * @copyright  2013 Sam Hemelryk
3215  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3216  */
3217 class coursecat_sortable_records extends ArrayObject {
3219     /**
3220      * An array of sortable fields.
3221      * Gets set temporarily when sort is called.
3222      * @var array
3223      */
3224     protected $sortfields = array();
3226     /**
3227      * Sorts this array using the given fields.
3228      *
3229      * @param array $records
3230      * @param array $fields
3231      * @return array
3232      */
3233     public static function sort(array $records, array $fields) {
3234         $records = new coursecat_sortable_records($records);
3235         $records->sortfields = $fields;
3236         $records->uasort(array($records, 'sort_by_many_fields'));
3237         return $records->getArrayCopy();
3238     }
3240     /**
3241      * Sorts the two records based upon many fields.
3242      *
3243      * This method should not be called itself, please call $sort instead.
3244      * It has been marked as access private as such.
3245      *
3246      * @access private
3247      * @param stdClass $a
3248      * @param stdClass $b
3249      * @return int
3250      */
3251     public function sort_by_many_fields($a, $b) {
3252         foreach ($this->sortfields as $field => $mult) {
3253             // Nulls first.
3254             if (is_null($a->$field) && !is_null($b->$field)) {
3255                 return -$mult;
3256             }
3257             if (is_null($b->$field) && !is_null($a->$field)) {
3258                 return $mult;
3259             }
3261             if (is_string($a->$field) || is_string($b->$field)) {
3262                 // String fields.
3263                 if ($cmp = strcoll($a->$field, $b->$field)) {
3264                     return $mult * $cmp;
3265                 }
3266             } else {
3267                 // Int fields.
3268                 if ($a->$field > $b->$field) {
3269                     return $mult;
3270                 }
3271                 if ($a->$field < $b->$field) {
3272                     return -$mult;
3273                 }
3274             }
3275         }
3276         return 0;
3277     }