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