Merge branch 'wip-MDL-41578-master' of git://github.com/marinaglancy/moodle
[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     const CACHE_COURSE_CONTACTS_TTL = 3600; // do not fetch course contacts more often than once per hour
57     /** @var array list of all fields and their short name and default value for caching */
58     protected static $coursecatfields = array(
59         'id' => array('id', 0),
60         'name' => array('na', ''),
61         'idnumber' => array('in', null),
62         'description' => null, // not cached
63         'descriptionformat' => null, // not cached
64         'parent' => array('pa', 0),
65         'sortorder' => array('so', 0),
66         'coursecount' => array('cc', 0),
67         'visible' => array('vi', 1),
68         'visibleold' => null, // not cached
69         'timemodified' => null, // not cached
70         'depth' => array('dh', 1),
71         'path' => array('ph', null),
72         'theme' => null, // not cached
73     );
75     /** @var int */
76     protected $id;
78     /** @var string */
79     protected $name = '';
81     /** @var string */
82     protected $idnumber = null;
84     /** @var string */
85     protected $description = false;
87     /** @var int */
88     protected $descriptionformat = false;
90     /** @var int */
91     protected $parent = 0;
93     /** @var int */
94     protected $sortorder = 0;
96     /** @var int */
97     protected $coursecount = false;
99     /** @var int */
100     protected $visible = 1;
102     /** @var int */
103     protected $visibleold = false;
105     /** @var int */
106     protected $timemodified = false;
108     /** @var int */
109     protected $depth = 0;
111     /** @var string */
112     protected $path = '';
114     /** @var string */
115     protected $theme = false;
117     /** @var bool */
118     protected $fromcache;
120     // ====== magic methods =======
122     /**
123      * Magic setter method, we do not want anybody to modify properties from the outside
124      *
125      * @param string $name
126      * @param mixed $value
127      */
128     public function __set($name, $value) {
129         debugging('Can not change coursecat instance properties!', DEBUG_DEVELOPER);
130     }
132     /**
133      * Magic method getter, redirects to read only values. Queries from DB the fields that were not cached
134      *
135      * @param string $name
136      * @return mixed
137      */
138     public function __get($name) {
139         global $DB;
140         if (array_key_exists($name, self::$coursecatfields)) {
141             if ($this->$name === false) {
142                 // property was not retrieved from DB, retrieve all not retrieved fields
143                 $notretrievedfields = array_diff_key(self::$coursecatfields, array_filter(self::$coursecatfields));
144                 $record = $DB->get_record('course_categories', array('id' => $this->id),
145                         join(',', array_keys($notretrievedfields)), MUST_EXIST);
146                 foreach ($record as $key => $value) {
147                     $this->$key = $value;
148                 }
149             }
150             return $this->$name;
151         }
152         debugging('Invalid coursecat property accessed! '.$name, DEBUG_DEVELOPER);
153         return null;
154     }
156     /**
157      * Full support for isset on our magic read only properties.
158      *
159      * @param string $name
160      * @return bool
161      */
162     public function __isset($name) {
163         if (array_key_exists($name, self::$coursecatfields)) {
164             return isset($this->$name);
165         }
166         return false;
167     }
169     /**
170      * All properties are read only, sorry.
171      *
172      * @param string $name
173      */
174     public function __unset($name) {
175         debugging('Can not unset coursecat instance properties!', DEBUG_DEVELOPER);
176     }
178     /**
179      * Create an iterator because magic vars can't be seen by 'foreach'.
180      *
181      * implementing method from interface IteratorAggregate
182      *
183      * @return ArrayIterator
184      */
185     public function getIterator() {
186         $ret = array();
187         foreach (self::$coursecatfields as $property => $unused) {
188             if ($this->$property !== false) {
189                 $ret[$property] = $this->$property;
190             }
191         }
192         return new ArrayIterator($ret);
193     }
195     /**
196      * Constructor
197      *
198      * Constructor is protected, use coursecat::get($id) to retrieve category
199      *
200      * @param stdClass $record record from DB (may not contain all fields)
201      * @param bool $fromcache whether it is being restored from cache
202      */
203     protected function __construct(stdClass $record, $fromcache = false) {
204         context_helper::preload_from_record($record);
205         foreach ($record as $key => $val) {
206             if (array_key_exists($key, self::$coursecatfields)) {
207                 $this->$key = $val;
208             }
209         }
210         $this->fromcache = $fromcache;
211     }
213     /**
214      * Returns coursecat object for requested category
215      *
216      * If category is not visible to user it is treated as non existing
217      * unless $alwaysreturnhidden is set to true
218      *
219      * If id is 0, the pseudo object for root category is returned (convenient
220      * for calling other functions such as get_children())
221      *
222      * @param int $id category id
223      * @param int $strictness whether to throw an exception (MUST_EXIST) or
224      *     return null (IGNORE_MISSING) in case the category is not found or
225      *     not visible to current user
226      * @param bool $alwaysreturnhidden set to true if you want an object to be
227      *     returned even if this category is not visible to the current user
228      *     (category is hidden and user does not have
229      *     'moodle/category:viewhiddencategories' capability). Use with care!
230      * @return null|coursecat
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('unknowcategory');
259             }
260         }
261         return null;
262     }
264     /**
265      * Returns the first found category
266      *
267      * Note that if there are no categories visible to the current user on the first level,
268      * the invisible category may be returned
269      *
270      * @return coursecat
271      */
272     public static function get_default() {
273         if ($visiblechildren = self::get(0)->get_children()) {
274             $defcategory = reset($visiblechildren);
275         } else {
276             $toplevelcategories = self::get_tree(0);
277             $defcategoryid = $toplevelcategories[0];
278             $defcategory = self::get($defcategoryid, MUST_EXIST, true);
279         }
280         return $defcategory;
281     }
283     /**
284      * Restores the object after it has been externally modified in DB for example
285      * during {@link fix_course_sortorder()}
286      */
287     protected function restore() {
288         // update all fields in the current object
289         $newrecord = self::get($this->id, MUST_EXIST, true);
290         foreach (self::$coursecatfields as $key => $unused) {
291             $this->$key = $newrecord->$key;
292         }
293     }
295     /**
296      * Creates a new category either from form data or from raw data
297      *
298      * Please note that this function does not verify access control.
299      *
300      * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
301      *
302      * Category visibility is inherited from parent unless $data->visible = 0 is specified
303      *
304      * @param array|stdClass $data
305      * @param array $editoroptions if specified, the data is considered to be
306      *    form data and file_postupdate_standard_editor() is being called to
307      *    process images in description.
308      * @return coursecat
309      * @throws moodle_exception
310      */
311     public static function create($data, $editoroptions = null) {
312         global $DB, $CFG;
313         $data = (object)$data;
314         $newcategory = new stdClass();
316         $newcategory->descriptionformat = FORMAT_MOODLE;
317         $newcategory->description = '';
318         // copy all description* fields regardless of whether this is form data or direct field update
319         foreach ($data as $key => $value) {
320             if (preg_match("/^description/", $key)) {
321                 $newcategory->$key = $value;
322             }
323         }
325         if (empty($data->name)) {
326             throw new moodle_exception('categorynamerequired');
327         }
328         if (core_text::strlen($data->name) > 255) {
329             throw new moodle_exception('categorytoolong');
330         }
331         $newcategory->name = $data->name;
333         // validate and set idnumber
334         if (!empty($data->idnumber)) {
335             if (core_text::strlen($data->idnumber) > 100) {
336                 throw new moodle_exception('idnumbertoolong');
337             }
338             if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
339                 throw new moodle_exception('categoryidnumbertaken');
340             }
341         }
342         if (isset($data->idnumber)) {
343             $newcategory->idnumber = $data->idnumber;
344         }
346         if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
347             $newcategory->theme = $data->theme;
348         }
350         if (empty($data->parent)) {
351             $parent = self::get(0);
352         } else {
353             $parent = self::get($data->parent, MUST_EXIST, true);
354         }
355         $newcategory->parent = $parent->id;
356         $newcategory->depth = $parent->depth + 1;
358         // By default category is visible, unless visible = 0 is specified or parent category is hidden
359         if (isset($data->visible) && !$data->visible) {
360             // create a hidden category
361             $newcategory->visible = $newcategory->visibleold = 0;
362         } else {
363             // create a category that inherits visibility from parent
364             $newcategory->visible = $parent->visible;
365             // in case parent is hidden, when it changes visibility this new subcategory will automatically become visible too
366             $newcategory->visibleold = 1;
367         }
369         $newcategory->sortorder = 0;
370         $newcategory->timemodified = time();
372         $newcategory->id = $DB->insert_record('course_categories', $newcategory);
374         // update path (only possible after we know the category id
375         $path = $parent->path . '/' . $newcategory->id;
376         $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));
378         // We should mark the context as dirty
379         context_coursecat::instance($newcategory->id)->mark_dirty();
381         fix_course_sortorder();
383         // if this is data from form results, save embedded files and update description
384         $categorycontext = context_coursecat::instance($newcategory->id);
385         if ($editoroptions) {
386             $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext, 'coursecat', 'description', 0);
388             // update only fields description and descriptionformat
389             $updatedata = new stdClass();
390             $updatedata->id = $newcategory->id;
391             $updatedata->description = $newcategory->description;
392             $updatedata->descriptionformat = $newcategory->descriptionformat;
393             $DB->update_record('course_categories', $updatedata);
394         }
396         add_to_log(SITEID, "category", 'add', "editcategory.php?id=$newcategory->id", $newcategory->id);
397         cache_helper::purge_by_event('changesincoursecat');
399         return self::get($newcategory->id, MUST_EXIST, true);
400     }
402     /**
403      * Updates the record with either form data or raw data
404      *
405      * Please note that this function does not verify access control.
406      *
407      * This function calls coursecat::change_parent_raw if field 'parent' is updated.
408      * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
409      * Visibility is changed first and then parent is changed. This means that
410      * if parent category is hidden, the current category will become hidden
411      * too and it may overwrite whatever was set in field 'visible'.
412      *
413      * Note that fields 'path' and 'depth' can not be updated manually
414      * Also coursecat::update() can not directly update the field 'sortoder'
415      *
416      * @param array|stdClass $data
417      * @param array $editoroptions if specified, the data is considered to be
418      *    form data and file_postupdate_standard_editor() is being called to
419      *    process images in description.
420      * @throws moodle_exception
421      */
422     public function update($data, $editoroptions = null) {
423         global $DB, $CFG;
424         if (!$this->id) {
425             // there is no actual DB record associated with root category
426             return;
427         }
429         $data = (object)$data;
430         $newcategory = new stdClass();
431         $newcategory->id = $this->id;
433         // copy all description* fields regardless of whether this is form data or direct field update
434         foreach ($data as $key => $value) {
435             if (preg_match("/^description/", $key)) {
436                 $newcategory->$key = $value;
437             }
438         }
440         if (isset($data->name) && empty($data->name)) {
441             throw new moodle_exception('categorynamerequired');
442         }
444         if (!empty($data->name) && $data->name !== $this->name) {
445             if (core_text::strlen($data->name) > 255) {
446                 throw new moodle_exception('categorytoolong');
447             }
448             $newcategory->name = $data->name;
449         }
451         if (isset($data->idnumber) && $data->idnumber != $this->idnumber) {
452             if (core_text::strlen($data->idnumber) > 100) {
453                 throw new moodle_exception('idnumbertoolong');
454             }
455             if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
456                 throw new moodle_exception('categoryidnumbertaken');
457             }
458             $newcategory->idnumber = $data->idnumber;
459         }
461         if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
462             $newcategory->theme = $data->theme;
463         }
465         $changes = false;
466         if (isset($data->visible)) {
467             if ($data->visible) {
468                 $changes = $this->show_raw();
469             } else {
470                 $changes = $this->hide_raw(0);
471             }
472         }
474         if (isset($data->parent) && $data->parent != $this->parent) {
475             if ($changes) {
476                 cache_helper::purge_by_event('changesincoursecat');
477             }
478             $parentcat = self::get($data->parent, MUST_EXIST, true);
479             $this->change_parent_raw($parentcat);
480             fix_course_sortorder();
481         }
483         $newcategory->timemodified = time();
485         if ($editoroptions) {
486             $categorycontext = context_coursecat::instance($this->id);
487             $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext, 'coursecat', 'description', 0);
488         }
489         $DB->update_record('course_categories', $newcategory);
490         add_to_log(SITEID, "category", 'update', "editcategory.php?id=$this->id", $this->id);
491         fix_course_sortorder();
492         // purge cache even if fix_course_sortorder() did not do it
493         cache_helper::purge_by_event('changesincoursecat');
495         // update all fields in the current object
496         $this->restore();
497     }
499     /**
500      * Checks if this course category is visible to current user
501      *
502      * Please note that methods coursecat::get (without 3rd argumet),
503      * coursecat::get_children(), etc. return only visible categories so it is
504      * usually not needed to call this function outside of this class
505      *
506      * @return bool
507      */
508     public function is_uservisible() {
509         return !$this->id || $this->visible ||
510                 has_capability('moodle/category:viewhiddencategories',
511                         context_coursecat::instance($this->id));
512     }
514     /**
515      * Returns all categories visible to the current user
516      *
517      * This is a generic function that returns an array of
518      * (category id => coursecat object) sorted by sortorder
519      *
520      * @see coursecat::get_children()
521      * @see coursecat::get_all_parents()
522      *
523      * @return cacheable_object_array array of coursecat objects
524      */
525     public static function get_all_visible() {
526         global $USER;
527         $coursecatcache = cache::make('core', 'coursecat');
528         $ids = $coursecatcache->get('user'. $USER->id);
529         if ($ids === false) {
530             $all = self::get_all_ids();
531             $parentvisible = $all[0];
532             $rv = array();
533             foreach ($all as $id => $children) {
534                 if ($id && in_array($id, $parentvisible) &&
535                         ($coursecat = self::get($id, IGNORE_MISSING)) &&
536                         (!$coursecat->parent || isset($rv[$coursecat->parent]))) {
537                     $rv[$id] = $coursecat;
538                     $parentvisible += $children;
539                 }
540             }
541             $coursecatcache->set('user'. $USER->id, array_keys($rv));
542         } else {
543             $rv = array();
544             foreach ($ids as $id) {
545                 if ($coursecat = self::get($id, IGNORE_MISSING)) {
546                     $rv[$id] = $coursecat;
547                 }
548             }
549         }
550         return $rv;
551     }
553     /**
554      * Returns the entry from categories tree and makes sure the application-level tree cache is built
555      *
556      * The following keys can be requested:
557      *
558      * 'countall' - total number of categories in the system (always present)
559      * 0 - array of ids of top-level categories (always present)
560      * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
561      * $id (int) - array of ids of categories that are direct children of category with id $id. If
562      *   category with id $id does not exist returns false. If category has no children returns empty array
563      * $id.'i' - array of ids of children categories that have visible=0
564      *
565      * @param int|string $id
566      * @return mixed
567      */
568     protected static function get_tree($id) {
569         global $DB;
570         $coursecattreecache = cache::make('core', 'coursecattree');
571         $rv = $coursecattreecache->get($id);
572         if ($rv !== false) {
573             return $rv;
574         }
575         // We did not find the entry in cache but it also can mean that tree is not built.
576         // The keys 0 and 'countall' must always be present if tree is built.
577         if ($id !== 0 && $id !== 'countall' && $coursecattreecache->has('countall')) {
578             // Tree was built, it means the non-existing $id was requested.
579             return false;
580         }
581         // Re-build the tree.
582         $sql = "SELECT cc.id, cc.parent, cc.visible
583                 FROM {course_categories} cc
584                 ORDER BY cc.sortorder";
585         $rs = $DB->get_recordset_sql($sql, array());
586         $all = array(0 => array(), '0i' => array());
587         $count = 0;
588         foreach ($rs as $record) {
589             $all[$record->id] = array();
590             $all[$record->id. 'i'] = array();
591             if (array_key_exists($record->parent, $all)) {
592                 $all[$record->parent][] = $record->id;
593                 if (!$record->visible) {
594                     $all[$record->parent. 'i'][] = $record->id;
595                 }
596             } else {
597                 // parent not found. This is data consistency error but next fix_course_sortorder() should fix it
598                 $all[0][] = $record->id;
599             }
600             $count++;
601         }
602         $rs->close();
603         if (!$count) {
604             // No categories found.
605             // This may happen after upgrade from very old moodle version. In new versions the default category is created on install.
606             $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
607             set_config('defaultrequestcategory', $defcoursecat->id);
608             $all[0] = array($defcoursecat->id);
609             $all[$defcoursecat->id] = array();
610             $count++;
611         }
612         $all['countall'] = $count;
613         foreach ($all as $key => $children) {
614             $coursecattreecache->set($key, $children);
615         }
616         if (array_key_exists($id, $all)) {
617             return $all[$id];
618         }
619         return false;
620     }
622     /**
623      * Returns number of ALL categories in the system regardless if
624      * they are visible to current user or not
625      *
626      * @return int
627      */
628     public static function count_all() {
629         return self::get_tree('countall');
630     }
632     /**
633      * Retrieves number of records from course_categories table
634      *
635      * Only cached fields are retrieved. Records are ready for preloading context
636      *
637      * @param string $whereclause
638      * @param array $params
639      * @return array array of stdClass objects
640      */
641     protected static function get_records($whereclause, $params) {
642         global $DB;
643         // Retrieve from DB only the fields that need to be stored in cache
644         $fields = array_keys(array_filter(self::$coursecatfields));
645         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
646         $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
647                 FROM {course_categories} cc
648                 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
649                 WHERE ". $whereclause." ORDER BY cc.sortorder";
650         return $DB->get_records_sql($sql,
651                 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
652     }
654     /**
655      * Given list of DB records from table course populates each record with list of users with course contact roles
656      *
657      * This function fills the courses with raw information as {@link get_role_users()} would do.
658      * See also {@link course_in_list::get_course_contacts()} for more readable return
659      *
660      * $courses[$i]->managers = array(
661      *   $roleassignmentid => $roleuser,
662      *   ...
663      * );
664      *
665      * where $roleuser is an stdClass with the following properties:
666      *
667      * $roleuser->raid - role assignment id
668      * $roleuser->id - user id
669      * $roleuser->username
670      * $roleuser->firstname
671      * $roleuser->lastname
672      * $roleuser->rolecoursealias
673      * $roleuser->rolename
674      * $roleuser->sortorder - role sortorder
675      * $roleuser->roleid
676      * $roleuser->roleshortname
677      *
678      * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
679      *
680      * @param array $courses
681      */
682     public static function preload_course_contacts(&$courses) {
683         global $CFG, $DB;
684         if (empty($courses) || empty($CFG->coursecontact)) {
685             return;
686         }
687         $managerroles = explode(',', $CFG->coursecontact);
688         $cache = cache::make('core', 'coursecontacts');
689         $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
690         // check if cache was set for the current course contacts and it is not yet expired
691         if (empty($cacheddata['basic']) || $cacheddata['basic']['roles'] !== $CFG->coursecontact ||
692                 $cacheddata['basic']['lastreset'] < time() - self::CACHE_COURSE_CONTACTS_TTL) {
693             // reset cache
694             $cache->purge();
695             $cache->set('basic', array('roles' => $CFG->coursecontact, 'lastreset' => time()));
696             $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
697         }
698         $courseids = array();
699         foreach (array_keys($courses) as $id) {
700             if ($cacheddata[$id] !== false) {
701                 $courses[$id]->managers = $cacheddata[$id];
702             } else {
703                 $courseids[] = $id;
704             }
705         }
707         // $courseids now stores list of ids of courses for which we still need to retrieve contacts
708         if (empty($courseids)) {
709             return;
710         }
712         // first build the array of all context ids of the courses and their categories
713         $allcontexts = array();
714         foreach ($courseids as $id) {
715             $context = context_course::instance($id);
716             $courses[$id]->managers = array();
717             foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
718                 if (!isset($allcontexts[$ctxid])) {
719                     $allcontexts[$ctxid] = array();
720                 }
721                 $allcontexts[$ctxid][] = $id;
722             }
723         }
725         // fetch list of all users with course contact roles in any of the courses contexts or parent contexts
726         list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
727         list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
728         list($sort, $sortparams) = users_order_by_sql('u');
729         $notdeleted = array('notdeleted'=>0);
730         $allnames = get_all_user_name_fields(true, 'u');
731         $sql = "SELECT ra.contextid, ra.id AS raid,
732                        r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
733                        rn.name AS rolecoursealias, u.id, u.username, $allnames
734                   FROM {role_assignments} ra
735                   JOIN {user} u ON ra.userid = u.id
736                   JOIN {role} r ON ra.roleid = r.id
737              LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
738                 WHERE  ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
739              ORDER BY r.sortorder, $sort";
740         $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
741         $checkenrolments = array();
742         foreach($rs as $ra) {
743             foreach ($allcontexts[$ra->contextid] as $id) {
744                 $courses[$id]->managers[$ra->raid] = $ra;
745                 if (!isset($checkenrolments[$id])) {
746                     $checkenrolments[$id] = array();
747                 }
748                 $checkenrolments[$id][] = $ra->id;
749             }
750         }
751         $rs->close();
753         // remove from course contacts users who are not enrolled in the course
754         $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
755         foreach ($checkenrolments as $id => $userids) {
756             if (empty($enrolleduserids[$id])) {
757                 $courses[$id]->managers = array();
758             } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
759                 foreach ($courses[$id]->managers as $raid => $ra) {
760                     if (in_array($ra->id, $notenrolled)) {
761                         unset($courses[$id]->managers[$raid]);
762                     }
763                 }
764             }
765         }
767         // set the cache
768         $values = array();
769         foreach ($courseids as $id) {
770             $values[$id] = $courses[$id]->managers;
771         }
772         $cache->set_many($values);
773     }
775     /**
776      * Verify user enrollments for multiple course-user combinations
777      *
778      * @param array $courseusers array where keys are course ids and values are array
779      *     of users in this course whose enrolment we wish to verify
780      * @return array same structure as input array but values list only users from input
781      *     who are enrolled in the course
782      */
783     protected static function ensure_users_enrolled($courseusers) {
784         global $DB;
785         // If the input array is too big, split it into chunks
786         $maxcoursesinquery = 20;
787         if (count($courseusers) > $maxcoursesinquery) {
788             $rv = array();
789             for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
790                 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
791                 $rv = $rv + self::ensure_users_enrolled($chunk);
792             }
793             return $rv;
794         }
796         // create a query verifying valid user enrolments for the number of courses
797         $sql = "SELECT DISTINCT e.courseid, ue.userid
798           FROM {user_enrolments} ue
799           JOIN {enrol} e ON e.id = ue.enrolid
800           WHERE ue.status = :active
801             AND e.status = :enabled
802             AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
803         $now = round(time(), -2); // rounding helps caching in DB
804         $params = array('enabled' => ENROL_INSTANCE_ENABLED,
805             'active' => ENROL_USER_ACTIVE,
806             'now1' => $now, 'now2' => $now);
807         $cnt = 0;
808         $subsqls = array();
809         $enrolled = array();
810         foreach ($courseusers as $id => $userids) {
811             $enrolled[$id] = array();
812             if (count($userids)) {
813                 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
814                 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
815                 $params = $params + array('courseid'.$cnt => $id) + $params2;
816                 $cnt++;
817             }
818         }
819         if (count($subsqls)) {
820             $sql .= "AND (". join(' OR ', $subsqls).")";
821             $rs = $DB->get_recordset_sql($sql, $params);
822             foreach ($rs as $record) {
823                 $enrolled[$record->courseid][] = $record->userid;
824             }
825             $rs->close();
826         }
827         return $enrolled;
828     }
830     /**
831      * Retrieves number of records from course table
832      *
833      * Not all fields are retrieved. Records are ready for preloading context
834      *
835      * @param string $whereclause
836      * @param array $params
837      * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
838      * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
839      *     on not visible courses
840      * @return array array of stdClass objects
841      */
842     protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
843         global $DB;
844         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
845         $fields = array('c.id', 'c.category', 'c.sortorder',
846                         'c.shortname', 'c.fullname', 'c.idnumber',
847                         'c.startdate', 'c.visible', 'c.cacherev');
848         if (!empty($options['summary'])) {
849             $fields[] = 'c.summary';
850             $fields[] = 'c.summaryformat';
851         } else {
852             $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
853         }
854         $sql = "SELECT ". join(',', $fields). ", $ctxselect
855                 FROM {course} c
856                 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
857                 WHERE ". $whereclause." ORDER BY c.sortorder";
858         $list = $DB->get_records_sql($sql,
859                 array('contextcourse' => CONTEXT_COURSE) + $params);
861         if ($checkvisibility) {
862             // Loop through all records and make sure we only return the courses accessible by user.
863             foreach ($list as $course) {
864                 if (isset($list[$course->id]->hassummary)) {
865                     $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
866                 }
867                 if (empty($course->visible)) {
868                     // load context only if we need to check capability
869                     context_helper::preload_from_record($course);
870                     if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
871                         unset($list[$course->id]);
872                     }
873                 }
874             }
875         }
877         // preload course contacts if necessary
878         if (!empty($options['coursecontacts'])) {
879             self::preload_course_contacts($list);
880         }
881         return $list;
882     }
884     /**
885      * Returns array of ids of children categories that current user can not see
886      *
887      * This data is cached in user session cache
888      *
889      * @return array
890      */
891     protected function get_not_visible_children_ids() {
892         global $DB;
893         $coursecatcache = cache::make('core', 'coursecat');
894         if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
895             // we never checked visible children before
896             $hidden = self::get_tree($this->id.'i');
897             $invisibleids = array();
898             if ($hidden) {
899                 // preload categories contexts
900                 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
901                 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
902                 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
903                     WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
904                         array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
905                 foreach ($contexts as $record) {
906                     context_helper::preload_from_record($record);
907                 }
908                 // check that user has 'viewhiddencategories' capability for each hidden category
909                 foreach ($hidden as $id) {
910                     if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
911                         $invisibleids[] = $id;
912                     }
913                 }
914             }
915             $coursecatcache->set('ic'. $this->id, $invisibleids);
916         }
917         return $invisibleids;
918     }
920     /**
921      * Sorts list of records by several fields
922      *
923      * @param array $records array of stdClass objects
924      * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
925      * @return int
926      */
927     protected static function sort_records(&$records, $sortfields) {
928         if (empty($records)) {
929             return;
930         }
931         // If sorting by course display name, calculate it (it may be fullname or shortname+fullname)
932         if (array_key_exists('displayname', $sortfields)) {
933             foreach ($records as $key => $record) {
934                 if (!isset($record->displayname)) {
935                     $records[$key]->displayname = get_course_display_name_for_list($record);
936                 }
937             }
938         }
939         // sorting by one field - use core_collator
940         if (count($sortfields) == 1) {
941             $property = key($sortfields);
942             if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
943                 $sortflag = core_collator::SORT_NUMERIC;
944             } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
945                 $sortflag = core_collator::SORT_STRING;
946             } else {
947                 $sortflag = core_collator::SORT_REGULAR;
948             }
949             core_collator::asort_objects_by_property($records, $property, $sortflag);
950             if ($sortfields[$property] < 0) {
951                 $records = array_reverse($records, true);
952             }
953             return;
954         }
955         $records = coursecat_sortable_records::sort($records, $sortfields);
956     }
958     /**
959      * Returns array of children categories visible to the current user
960      *
961      * @param array $options options for retrieving children
962      *    - sort - list of fields to sort. Example
963      *             array('idnumber' => 1, 'name' => 1, 'id' => -1)
964      *             will sort by idnumber asc, name asc and id desc.
965      *             Default: array('sortorder' => 1)
966      *             Only cached fields may be used for sorting!
967      *    - offset
968      *    - limit - maximum number of children to return, 0 or null for no limit
969      * @return array of coursecat objects indexed by category id
970      */
971     public function get_children($options = array()) {
972         global $DB;
973         $coursecatcache = cache::make('core', 'coursecat');
975         // get default values for options
976         if (!empty($options['sort']) && is_array($options['sort'])) {
977             $sortfields = $options['sort'];
978         } else {
979             $sortfields = array('sortorder' => 1);
980         }
981         $limit = null;
982         if (!empty($options['limit']) && (int)$options['limit']) {
983             $limit = (int)$options['limit'];
984         }
985         $offset = 0;
986         if (!empty($options['offset']) && (int)$options['offset']) {
987             $offset = (int)$options['offset'];
988         }
990         // first retrieve list of user-visible and sorted children ids from cache
991         $sortedids = $coursecatcache->get('c'. $this->id. ':'.  serialize($sortfields));
992         if ($sortedids === false) {
993             $sortfieldskeys = array_keys($sortfields);
994             if ($sortfieldskeys[0] === 'sortorder') {
995                 // no DB requests required to build the list of ids sorted by sortorder.
996                 // We can easily ignore other sort fields because sortorder is always different
997                 $sortedids = self::get_tree($this->id);
998                 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
999                     $sortedids = array_diff($sortedids, $invisibleids);
1000                     if ($sortfields['sortorder'] == -1) {
1001                         $sortedids = array_reverse($sortedids, true);
1002                     }
1003                 }
1004             } else {
1005                 // we need to retrieve and sort all children. Good thing that it is done only on first request
1006                 if ($invisibleids = $this->get_not_visible_children_ids()) {
1007                     list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
1008                     $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
1009                             array('parent' => $this->id) + $params);
1010                 } else {
1011                     $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
1012                 }
1013                 self::sort_records($records, $sortfields);
1014                 $sortedids = array_keys($records);
1015             }
1016             $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
1017         }
1019         if (empty($sortedids)) {
1020             return array();
1021         }
1023         // now retrieive and return categories
1024         if ($offset || $limit) {
1025             $sortedids = array_slice($sortedids, $offset, $limit);
1026         }
1027         if (isset($records)) {
1028             // easy, we have already retrieved records
1029             if ($offset || $limit) {
1030                 $records = array_slice($records, $offset, $limit, true);
1031             }
1032         } else {
1033             list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
1034             $records = self::get_records('cc.id '. $sql,
1035                     array('parent' => $this->id) + $params);
1036         }
1038         $rv = array();
1039         foreach ($sortedids as $id) {
1040             if (isset($records[$id])) {
1041                 $rv[$id] = new coursecat($records[$id]);
1042             }
1043         }
1044         return $rv;
1045     }
1047     /**
1048      * Returns number of subcategories visible to the current user
1049      *
1050      * @return int
1051      */
1052     public function get_children_count() {
1053         $sortedids = self::get_tree($this->id);
1054         $invisibleids = $this->get_not_visible_children_ids();
1055         return count($sortedids) - count($invisibleids);
1056     }
1058     /**
1059      * Returns true if the category has ANY children, including those not visible to the user
1060      *
1061      * @return boolean
1062      */
1063     public function has_children() {
1064         $allchildren = self::get_tree($this->id);
1065         return !empty($allchildren);
1066     }
1068     /**
1069      * Returns true if the category has courses in it (count does not include courses
1070      * in child categories)
1071      *
1072      * @return bool
1073      */
1074     public function has_courses() {
1075         global $DB;
1076         return $DB->record_exists_sql("select 1 from {course} where category = ?",
1077                 array($this->id));
1078     }
1080     /**
1081      * Searches courses
1082      *
1083      * List of found course ids is cached for 10 minutes. Cache may be purged prior
1084      * to this when somebody edits courses or categories, however it is very
1085      * difficult to keep track of all possible changes that may affect list of courses.
1086      *
1087      * @param array $search contains search criterias, such as:
1088      *     - search - search string
1089      *     - blocklist - id of block (if we are searching for courses containing specific block0
1090      *     - modulelist - name of module (if we are searching for courses containing specific module
1091      *     - tagid - id of tag
1092      * @param array $options display options, same as in get_courses() except 'recursive' is ignored - search is always category-independent
1093      * @return course_in_list[]
1094      */
1095     public static function search_courses($search, $options = array()) {
1096         global $DB;
1097         $offset = !empty($options['offset']) ? $options['offset'] : 0;
1098         $limit = !empty($options['limit']) ? $options['limit'] : null;
1099         $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1101         $coursecatcache = cache::make('core', 'coursecat');
1102         $cachekey = 's-'. serialize($search + array('sort' => $sortfields));
1103         $cntcachekey = 'scnt-'. serialize($search);
1105         $ids = $coursecatcache->get($cachekey);
1106         if ($ids !== false) {
1107             // we already cached last search result
1108             $ids = array_slice($ids, $offset, $limit);
1109             $courses = array();
1110             if (!empty($ids)) {
1111                 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1112                 $records = self::get_course_records("c.id ". $sql, $params, $options);
1113                 foreach ($ids as $id) {
1114                     $courses[$id] = new course_in_list($records[$id]);
1115                 }
1116             }
1117             return $courses;
1118         }
1120         $preloadcoursecontacts = !empty($options['coursecontacts']);
1121         unset($options['coursecontacts']);
1123         if (!empty($search['search'])) {
1124             // search courses that have specified words in their names/summaries
1125             $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1126             $searchterms = array_filter($searchterms, create_function('$v', 'return strlen($v) > 1;'));
1127             $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount);
1128             self::sort_records($courselist, $sortfields);
1129             $coursecatcache->set($cachekey, array_keys($courselist));
1130             $coursecatcache->set($cntcachekey, $totalcount);
1131             $records = array_slice($courselist, $offset, $limit, true);
1132         } else {
1133             if (!empty($search['blocklist'])) {
1134                 // search courses that have block with specified id
1135                 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1136                 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1137                     WHERE bi.blockname = :blockname)';
1138                 $params = array('blockname' => $blockname);
1139             } else if (!empty($search['modulelist'])) {
1140                 // search courses that have module with specified name
1141                 $where = "c.id IN (SELECT DISTINCT module.course ".
1142                         "FROM {".$search['modulelist']."} module)";
1143                 $params = array();
1144             } else if (!empty($search['tagid'])) {
1145                 // search courses that are tagged with the specified tag
1146                 $where = "c.id IN (SELECT t.itemid ".
1147                         "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype)";
1148                 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course');
1149             } else {
1150                 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1151                 return array();
1152             }
1153             $courselist = self::get_course_records($where, $params, $options, true);
1154             self::sort_records($courselist, $sortfields);
1155             $coursecatcache->set($cachekey, array_keys($courselist));
1156             $coursecatcache->set($cntcachekey, count($courselist));
1157             $records = array_slice($courselist, $offset, $limit, true);
1158         }
1160         // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1161         if (!empty($preloadcoursecontacts)) {
1162             self::preload_course_contacts($records);
1163         }
1164         $courses = array();
1165         foreach ($records as $record) {
1166             $courses[$record->id] = new course_in_list($record);
1167         }
1168         return $courses;
1169     }
1171     /**
1172      * Returns number of courses in the search results
1173      *
1174      * It is recommended to call this function after {@link coursecat::search_courses()}
1175      * and not before because only course ids are cached. Otherwise search_courses() may
1176      * perform extra DB queries.
1177      *
1178      * @param array $search search criteria, see method search_courses() for more details
1179      * @param array $options display options. They do not affect the result but
1180      *     the 'sort' property is used in cache key for storing list of course ids
1181      * @return int
1182      */
1183     public static function search_courses_count($search, $options = array()) {
1184         $coursecatcache = cache::make('core', 'coursecat');
1185         $cntcachekey = 'scnt-'. serialize($search);
1186         if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1187             self::search_courses($search, $options);
1188             $cnt = $coursecatcache->get($cntcachekey);
1189         }
1190         return $cnt;
1191     }
1193     /**
1194      * Retrieves the list of courses accessible by user
1195      *
1196      * Not all information is cached, try to avoid calling this method
1197      * twice in the same request.
1198      *
1199      * The following fields are always retrieved:
1200      * - id, visible, fullname, shortname, idnumber, category, sortorder
1201      *
1202      * If you plan to use properties/methods course_in_list::$summary and/or
1203      * course_in_list::get_course_contacts()
1204      * you can preload this information using appropriate 'options'. Otherwise
1205      * they will be retrieved from DB on demand and it may end with bigger DB load.
1206      *
1207      * Note that method course_in_list::has_summary() will not perform additional
1208      * DB queries even if $options['summary'] is not specified
1209      *
1210      * List of found course ids is cached for 10 minutes. Cache may be purged prior
1211      * to this when somebody edits courses or categories, however it is very
1212      * difficult to keep track of all possible changes that may affect list of courses.
1213      *
1214      * @param array $options options for retrieving children
1215      *    - recursive - return courses from subcategories as well. Use with care,
1216      *      this may be a huge list!
1217      *    - summary - preloads fields 'summary' and 'summaryformat'
1218      *    - coursecontacts - preloads course contacts
1219      *    - sort - list of fields to sort. Example
1220      *             array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1221      *             will sort by idnumber asc, shortname asc and id desc.
1222      *             Default: array('sortorder' => 1)
1223      *             Only cached fields may be used for sorting!
1224      *    - offset
1225      *    - limit - maximum number of children to return, 0 or null for no limit
1226      * @return course_in_list[]
1227      */
1228     public function get_courses($options = array()) {
1229         global $DB;
1230         $recursive = !empty($options['recursive']);
1231         $offset = !empty($options['offset']) ? $options['offset'] : 0;
1232         $limit = !empty($options['limit']) ? $options['limit'] : null;
1233         $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1235         // Check if this category is hidden.
1236         // Also 0-category never has courses unless this is recursive call.
1237         if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1238             return array();
1239         }
1241         $coursecatcache = cache::make('core', 'coursecat');
1242         $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1243                  '-'. serialize($sortfields);
1244         $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1246         // check if we have already cached results
1247         $ids = $coursecatcache->get($cachekey);
1248         if ($ids !== false) {
1249             // we already cached last search result and it did not expire yet
1250             $ids = array_slice($ids, $offset, $limit);
1251             $courses = array();
1252             if (!empty($ids)) {
1253                 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1254                 $records = self::get_course_records("c.id ". $sql, $params, $options);
1255                 foreach ($ids as $id) {
1256                     $courses[$id] = new course_in_list($records[$id]);
1257                 }
1258             }
1259             return $courses;
1260         }
1262         // retrieve list of courses in category
1263         $where = 'c.id <> :siteid';
1264         $params = array('siteid' => SITEID);
1265         if ($recursive) {
1266             if ($this->id) {
1267                 $context = context_coursecat::instance($this->id);
1268                 $where .= ' AND ctx.path like :path';
1269                 $params['path'] = $context->path. '/%';
1270             }
1271         } else {
1272             $where .= ' AND c.category = :categoryid';
1273             $params['categoryid'] = $this->id;
1274         }
1275         // get list of courses without preloaded coursecontacts because we don't need them for every course
1276         $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1278         // sort and cache list
1279         self::sort_records($list, $sortfields);
1280         $coursecatcache->set($cachekey, array_keys($list));
1281         $coursecatcache->set($cntcachekey, count($list));
1283         // Apply offset/limit, convert to course_in_list and return.
1284         $courses = array();
1285         if (isset($list)) {
1286             if ($offset || $limit) {
1287                 $list = array_slice($list, $offset, $limit, true);
1288             }
1289             // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1290             if (!empty($options['coursecontacts'])) {
1291                 self::preload_course_contacts($list);
1292             }
1293             foreach ($list as $record) {
1294                 $courses[$record->id] = new course_in_list($record);
1295             }
1296         }
1297         return $courses;
1298     }
1300     /**
1301      * Returns number of courses visible to the user
1302      *
1303      * @param array $options similar to get_courses() except some options do not affect
1304      *     number of courses (i.e. sort, summary, offset, limit etc.)
1305      * @return int
1306      */
1307     public function get_courses_count($options = array()) {
1308         $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1309         $coursecatcache = cache::make('core', 'coursecat');
1310         if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1311             $this->get_courses($options);
1312             $cnt = $coursecatcache->get($cntcachekey);
1313         }
1314         return $cnt;
1315     }
1317     /**
1318      * Returns true if user can delete current category and all its contents
1319      *
1320      * To be able to delete course category the user must have permission
1321      * 'moodle/category:manage' in ALL child course categories AND
1322      * be able to delete all courses
1323      *
1324      * @return bool
1325      */
1326     public function can_delete_full() {
1327         global $DB;
1328         if (!$this->id) {
1329             // fool-proof
1330             return false;
1331         }
1333         $context = context_coursecat::instance($this->id);
1334         if (!$this->is_uservisible() ||
1335                 !has_capability('moodle/category:manage', $context)) {
1336             return false;
1337         }
1339         // Check all child categories (not only direct children)
1340         $sql = context_helper::get_preload_record_columns_sql('ctx');
1341         $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1342             ' FROM {context} ctx '.
1343             ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1344             ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1345                 array($context->path. '/%', CONTEXT_COURSECAT));
1346         foreach ($childcategories as $childcat) {
1347             context_helper::preload_from_record($childcat);
1348             $childcontext = context_coursecat::instance($childcat->id);
1349             if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1350                     !has_capability('moodle/category:manage', $childcontext)) {
1351                 return false;
1352             }
1353         }
1355         // Check courses
1356         $sql = context_helper::get_preload_record_columns_sql('ctx');
1357         $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1358                     $sql. ' FROM {context} ctx '.
1359                     'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1360                 array('pathmask' => $context->path. '/%',
1361                     'courselevel' => CONTEXT_COURSE));
1362         foreach ($coursescontexts as $ctxrecord) {
1363             context_helper::preload_from_record($ctxrecord);
1364             if (!can_delete_course($ctxrecord->courseid)) {
1365                 return false;
1366             }
1367         }
1369         return true;
1370     }
1372     /**
1373      * Recursively delete category including all subcategories and courses
1374      *
1375      * Function {@link coursecat::can_delete_full()} MUST be called prior
1376      * to calling this function because there is no capability check
1377      * inside this function
1378      *
1379      * @param boolean $showfeedback display some notices
1380      * @return array return deleted courses
1381      */
1382     public function delete_full($showfeedback = true) {
1383         global $CFG, $DB;
1385         require_once($CFG->libdir.'/gradelib.php');
1386         require_once($CFG->libdir.'/questionlib.php');
1387         require_once($CFG->dirroot.'/cohort/lib.php');
1389         $deletedcourses = array();
1391         // Get children. Note, we don't want to use cache here because
1392         // it would be rebuilt too often
1393         $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1394         foreach ($children as $record) {
1395             $coursecat = new coursecat($record);
1396             $deletedcourses += $coursecat->delete_full($showfeedback);
1397         }
1399         if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1400             foreach ($courses as $course) {
1401                 if (!delete_course($course, false)) {
1402                     throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1403                 }
1404                 $deletedcourses[] = $course;
1405             }
1406         }
1408         // move or delete cohorts in this context
1409         cohort_delete_category($this);
1411         // now delete anything that may depend on course category context
1412         grade_course_category_delete($this->id, 0, $showfeedback);
1413         if (!question_delete_course_category($this, 0, $showfeedback)) {
1414             throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1415         }
1417         // finally delete the category and it's context
1418         $DB->delete_records('course_categories', array('id' => $this->id));
1420         $coursecatcontext = context_coursecat::instance($this->id);
1421         $coursecatcontext->delete();
1423         cache_helper::purge_by_event('changesincoursecat');
1425         // Trigger a course category deleted event.
1426         $event = \core\event\course_category_deleted::create(array(
1427             'objectid' => $this->id,
1428             'context' => $coursecatcontext,
1429             'other' => array('name' => $this->name)
1430         ));
1431         $event->set_legacy_eventdata($this);
1432         $event->trigger();
1434         // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1435         if ($this->id == $CFG->defaultrequestcategory) {
1436             set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1437         }
1438         return $deletedcourses;
1439     }
1441     /**
1442      * Checks if user can delete this category and move content (courses, subcategories and questions)
1443      * to another category. If yes returns the array of possible target categories names
1444      *
1445      * If user can not manage this category or it is completely empty - empty array will be returned
1446      *
1447      * @return array
1448      */
1449     public function move_content_targets_list() {
1450         global $CFG;
1451         require_once($CFG->libdir . '/questionlib.php');
1452         $context = context_coursecat::instance($this->id);
1453         if (!$this->is_uservisible() ||
1454                 !has_capability('moodle/category:manage', $context)) {
1455             // User is not able to manage current category, he is not able to delete it.
1456             // No possible target categories.
1457             return array();
1458         }
1460         $testcaps = array();
1461         // If this category has courses in it, user must have 'course:create' capability in target category.
1462         if ($this->has_courses()) {
1463             $testcaps[] = 'moodle/course:create';
1464         }
1465         // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1466         if ($this->has_children() || question_context_has_any_questions($context)) {
1467             $testcaps[] = 'moodle/category:manage';
1468         }
1469         if (!empty($testcaps)) {
1470             // return list of categories excluding this one and it's children
1471             return self::make_categories_list($testcaps, $this->id);
1472         }
1474         // Category is completely empty, no need in target for contents.
1475         return array();
1476     }
1478     /**
1479      * Checks if user has capability to move all category content to the new parent before
1480      * removing this category
1481      *
1482      * @param int $newcatid
1483      * @return bool
1484      */
1485     public function can_move_content_to($newcatid) {
1486         global $CFG;
1487         require_once($CFG->libdir . '/questionlib.php');
1488         $context = context_coursecat::instance($this->id);
1489         if (!$this->is_uservisible() ||
1490                 !has_capability('moodle/category:manage', $context)) {
1491             return false;
1492         }
1493         $testcaps = array();
1494         // If this category has courses in it, user must have 'course:create' capability in target category.
1495         if ($this->has_courses()) {
1496             $testcaps[] = 'moodle/course:create';
1497         }
1498         // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1499         if ($this->has_children() || question_context_has_any_questions($context)) {
1500             $testcaps[] = 'moodle/category:manage';
1501         }
1502         if (!empty($testcaps)) {
1503             return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1504         }
1506         // there is no content but still return true
1507         return true;
1508     }
1510     /**
1511      * Deletes a category and moves all content (children, courses and questions) to the new parent
1512      *
1513      * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1514      * must be called prior
1515      *
1516      * @param int $newparentid
1517      * @param bool $showfeedback
1518      * @return bool
1519      */
1520     public function delete_move($newparentid, $showfeedback = false) {
1521         global $CFG, $DB, $OUTPUT;
1523         require_once($CFG->libdir.'/gradelib.php');
1524         require_once($CFG->libdir.'/questionlib.php');
1525         require_once($CFG->dirroot.'/cohort/lib.php');
1527         // get all objects and lists because later the caches will be reset so
1528         // we don't need to make extra queries
1529         $newparentcat = self::get($newparentid, MUST_EXIST, true);
1530         $catname = $this->get_formatted_name();
1531         $children = $this->get_children();
1532         $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', array('category' => $this->id));
1533         $context = context_coursecat::instance($this->id);
1535         if ($children) {
1536             foreach ($children as $childcat) {
1537                 $childcat->change_parent_raw($newparentcat);
1538                 // Log action.
1539                 add_to_log(SITEID, "category", "move", "editcategory.php?id=$childcat->id", $childcat->id);
1540             }
1541             fix_course_sortorder();
1542         }
1544         if ($coursesids) {
1545             if (!move_courses($coursesids, $newparentid)) {
1546                 if ($showfeedback) {
1547                     echo $OUTPUT->notification("Error moving courses");
1548                 }
1549                 return false;
1550             }
1551             if ($showfeedback) {
1552                 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1553             }
1554         }
1556         // move or delete cohorts in this context
1557         cohort_delete_category($this);
1559         // now delete anything that may depend on course category context
1560         grade_course_category_delete($this->id, $newparentid, $showfeedback);
1561         if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1562             if ($showfeedback) {
1563                 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1564             }
1565             return false;
1566         }
1568         // finally delete the category and it's context
1569         $DB->delete_records('course_categories', array('id' => $this->id));
1570         $context->delete();
1572         // Trigger a course category deleted event.
1573         $event = \core\event\course_category_deleted::create(array(
1574             'objectid' => $this->id,
1575             'context' => $context,
1576             'other' => array('name' => $this->name)
1577         ));
1578         $event->set_legacy_eventdata($this);
1579         $event->trigger();
1581         cache_helper::purge_by_event('changesincoursecat');
1583         if ($showfeedback) {
1584             echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1585         }
1587         // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1588         if ($this->id == $CFG->defaultrequestcategory) {
1589             set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1590         }
1591         return true;
1592     }
1594     /**
1595      * Checks if user can move current category to the new parent
1596      *
1597      * This checks if new parent category exists, user has manage cap there
1598      * and new parent is not a child of this category
1599      *
1600      * @param int|stdClass|coursecat $newparentcat
1601      * @return bool
1602      */
1603     public function can_change_parent($newparentcat) {
1604         if (!has_capability('moodle/category:manage', context_coursecat::instance($this->id))) {
1605             return false;
1606         }
1607         if (is_object($newparentcat)) {
1608             $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1609         } else {
1610             $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1611         }
1612         if (!$newparentcat) {
1613             return false;
1614         }
1615         if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1616             // can not move to itself or it's own child
1617             return false;
1618         }
1619         if ($newparentcat->id) {
1620             return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
1621         } else {
1622             return has_capability('moodle/category:manage', context_system::instance());
1623         }
1624     }
1626     /**
1627      * Moves the category under another parent category. All associated contexts are moved as well
1628      *
1629      * This is protected function, use change_parent() or update() from outside of this class
1630      *
1631      * @see coursecat::change_parent()
1632      * @see coursecat::update()
1633      *
1634      * @param coursecat $newparentcat
1635      */
1636      protected function change_parent_raw(coursecat $newparentcat) {
1637         global $DB;
1639         $context = context_coursecat::instance($this->id);
1641         $hidecat = false;
1642         if (empty($newparentcat->id)) {
1643             $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1644             $newparent = context_system::instance();
1645         } else {
1646             if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1647                 // can not move to itself or it's own child
1648                 throw new moodle_exception('cannotmovecategory');
1649             }
1650             $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
1651             $newparent = context_coursecat::instance($newparentcat->id);
1653             if (!$newparentcat->visible and $this->visible) {
1654                 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
1655                 $hidecat = true;
1656             }
1657         }
1658         $this->parent = $newparentcat->id;
1660         $context->update_moved($newparent);
1662         // now make it last in new category
1663         $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
1665         if ($hidecat) {
1666             fix_course_sortorder();
1667             $this->restore();
1668             // Hide object but store 1 in visibleold, because when parent category visibility changes this category must become visible again.
1669             $this->hide_raw(1);
1670         }
1671     }
1673     /**
1674      * Efficiently moves a category - NOTE that this can have
1675      * a huge impact access-control-wise...
1676      *
1677      * Note that this function does not check capabilities.
1678      *
1679      * Example of usage:
1680      * $coursecat = coursecat::get($categoryid);
1681      * if ($coursecat->can_change_parent($newparentcatid)) {
1682      *     $coursecat->change_parent($newparentcatid);
1683      * }
1684      *
1685      * This function does not update field course_categories.timemodified
1686      * If you want to update timemodified, use
1687      * $coursecat->update(array('parent' => $newparentcat));
1688      *
1689      * @param int|stdClass|coursecat $newparentcat
1690      */
1691     public function change_parent($newparentcat) {
1692         // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1693         if (is_object($newparentcat)) {
1694             $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
1695         } else {
1696             $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
1697         }
1698         if ($newparentcat->id != $this->parent) {
1699             $this->change_parent_raw($newparentcat);
1700             fix_course_sortorder();
1701             cache_helper::purge_by_event('changesincoursecat');
1702             $this->restore();
1703             add_to_log(SITEID, "category", "move", "editcategory.php?id=$this->id", $this->id);
1704         }
1705     }
1707     /**
1708      * Hide course category and child course and subcategories
1709      *
1710      * If this category has changed the parent and is moved under hidden
1711      * category we will want to store it's current visibility state in
1712      * the field 'visibleold'. If admin clicked 'hide' for this particular
1713      * category, the field 'visibleold' should become 0.
1714      *
1715      * All subcategories and courses will have their current visibility in the field visibleold
1716      *
1717      * This is protected function, use hide() or update() from outside of this class
1718      *
1719      * @see coursecat::hide()
1720      * @see coursecat::update()
1721      *
1722      * @param int $visibleold value to set in field $visibleold for this category
1723      * @return bool whether changes have been made and caches need to be purged afterwards
1724      */
1725     protected function hide_raw($visibleold = 0) {
1726         global $DB;
1727         $changes = false;
1729         // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing
1730         if ($this->id && $this->__get('visibleold') != $visibleold) {
1731             $this->visibleold = $visibleold;
1732             $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
1733             $changes = true;
1734         }
1735         if (!$this->visible || !$this->id) {
1736             // already hidden or can not be hidden
1737             return $changes;
1738         }
1740         $this->visible = 0;
1741         $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
1742         $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id)); // store visible flag so that we can return to it if we immediately unhide
1743         $DB->set_field('course', 'visible', 0, array('category' => $this->id));
1744         // get all child categories and hide too
1745         if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
1746             foreach ($subcats as $cat) {
1747                 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
1748                 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
1749                 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
1750                 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
1751             }
1752         }
1753         return true;
1754     }
1756     /**
1757      * Hide course category and child course and subcategories
1758      *
1759      * Note that there is no capability check inside this function
1760      *
1761      * This function does not update field course_categories.timemodified
1762      * If you want to update timemodified, use
1763      * $coursecat->update(array('visible' => 0));
1764      */
1765     public function hide() {
1766         if ($this->hide_raw(0)) {
1767             cache_helper::purge_by_event('changesincoursecat');
1768             add_to_log(SITEID, "category", "hide", "editcategory.php?id=$this->id", $this->id);
1769         }
1770     }
1772     /**
1773      * Show course category and restores visibility for child course and subcategories
1774      *
1775      * Note that there is no capability check inside this function
1776      *
1777      * This is protected function, use show() or update() from outside of this class
1778      *
1779      * @see coursecat::show()
1780      * @see coursecat::update()
1781      *
1782      * @return bool whether changes have been made and caches need to be purged afterwards
1783      */
1784     protected function show_raw() {
1785         global $DB;
1787         if ($this->visible) {
1788             // already visible
1789             return false;
1790         }
1792         $this->visible = 1;
1793         $this->visibleold = 1;
1794         $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
1795         $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
1796         $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
1797         // get all child categories and unhide too
1798         if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
1799             foreach ($subcats as $cat) {
1800                 if ($cat->visibleold) {
1801                     $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
1802                 }
1803                 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
1804             }
1805         }
1806         return true;
1807     }
1809     /**
1810      * Show course category and restores visibility for child course and subcategories
1811      *
1812      * Note that there is no capability check inside this function
1813      *
1814      * This function does not update field course_categories.timemodified
1815      * If you want to update timemodified, use
1816      * $coursecat->update(array('visible' => 1));
1817      */
1818     public function show() {
1819         if ($this->show_raw()) {
1820             cache_helper::purge_by_event('changesincoursecat');
1821             add_to_log(SITEID, "category", "show", "editcategory.php?id=$this->id", $this->id);
1822         }
1823     }
1825     /**
1826      * Returns name of the category formatted as a string
1827      *
1828      * @param array $options formatting options other than context
1829      * @return string
1830      */
1831     public function get_formatted_name($options = array()) {
1832         if ($this->id) {
1833             $context = context_coursecat::instance($this->id);
1834             return format_string($this->name, true, array('context' => $context) + $options);
1835         } else {
1836             return ''; // TODO 'Top'?
1837         }
1838     }
1840     /**
1841      * Returns ids of all parents of the category. Last element in the return array is the direct parent
1842      *
1843      * For example, if you have a tree of categories like:
1844      *   Miscellaneous (id = 1)
1845      *      Subcategory (id = 2)
1846      *         Sub-subcategory (id = 4)
1847      *   Other category (id = 3)
1848      *
1849      * coursecat::get(1)->get_parents() == array()
1850      * coursecat::get(2)->get_parents() == array(1)
1851      * coursecat::get(4)->get_parents() == array(1, 2);
1852      *
1853      * Note that this method does not check if all parents are accessible by current user
1854      *
1855      * @return array of category ids
1856      */
1857     public function get_parents() {
1858         $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
1859         array_pop($parents);
1860         return $parents;
1861     }
1863     /**
1864      * This function returns a nice list representing category tree
1865      * for display or to use in a form <select> element
1866      *
1867      * List is cached for 10 minutes
1868      *
1869      * For example, if you have a tree of categories like:
1870      *   Miscellaneous (id = 1)
1871      *      Subcategory (id = 2)
1872      *         Sub-subcategory (id = 4)
1873      *   Other category (id = 3)
1874      * Then after calling this function you will have
1875      * array(1 => 'Miscellaneous',
1876      *       2 => 'Miscellaneous / Subcategory',
1877      *       4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1878      *       3 => 'Other category');
1879      *
1880      * If you specify $requiredcapability, then only categories where the current
1881      * user has that capability will be added to $list.
1882      * If you only have $requiredcapability in a child category, not the parent,
1883      * then the child catgegory will still be included.
1884      *
1885      * If you specify the option $excludeid, then that category, and all its children,
1886      * are omitted from the tree. This is useful when you are doing something like
1887      * moving categories, where you do not want to allow people to move a category
1888      * to be the child of itself.
1889      *
1890      * See also {@link make_categories_options()}
1891      *
1892      * @param string/array $requiredcapability if given, only categories where the current
1893      *      user has this capability will be returned. Can also be an array of capabilities,
1894      *      in which case they are all required.
1895      * @param integer $excludeid Exclude this category and its children from the lists built.
1896      * @param string $separator string to use as a separator between parent and child category. Default ' / '
1897      * @return array of strings
1898      */
1899     public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
1900         global $DB;
1901         $coursecatcache = cache::make('core', 'coursecat');
1903         // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids with requried cap ($thislist).
1904         $basecachekey = 'catlist';
1905         $baselist = $coursecatcache->get($basecachekey);
1906         $thislist = false;
1907         if (!empty($requiredcapability)) {
1908             $requiredcapability = (array)$requiredcapability;
1909             $thiscachekey = 'catlist:'. serialize($requiredcapability);
1910             if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
1911                 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
1912             }
1913         } else if ($baselist !== false) {
1914             $thislist = array_keys($baselist);
1915         }
1917         if ($baselist === false) {
1918             // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
1919             $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1920             $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
1921                     FROM {course_categories} cc
1922                     JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
1923                     ORDER BY cc.sortorder";
1924             $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
1925             $baselist = array();
1926             $thislist = array();
1927             foreach ($rs as $record) {
1928                 // If the category's parent is not visible to the user, it is not visible as well.
1929                 if (!$record->parent || isset($baselist[$record->parent])) {
1930                     context_helper::preload_from_record($record);
1931                     $context = context_coursecat::instance($record->id);
1932                     if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
1933                         // No cap to view category, added to neither $baselist nor $thislist
1934                         continue;
1935                     }
1936                     $baselist[$record->id] = array(
1937                         'name' => format_string($record->name, true, array('context' => $context)),
1938                         'path' => $record->path
1939                     );
1940                     if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
1941                         // No required capability, added to $baselist but not to $thislist.
1942                         continue;
1943                     }
1944                     $thislist[] = $record->id;
1945                 }
1946             }
1947             $rs->close();
1948             $coursecatcache->set($basecachekey, $baselist);
1949             if (!empty($requiredcapability)) {
1950                 $coursecatcache->set($thiscachekey, join(',', $thislist));
1951             }
1952         } else if ($thislist === false) {
1953             // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
1954             $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1955             $sql = "SELECT ctx.instanceid AS id, $ctxselect
1956                     FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
1957             $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
1958             $thislist = array();
1959             foreach (array_keys($baselist) as $id) {
1960                 context_helper::preload_from_record($contexts[$id]);
1961                 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
1962                     $thislist[] = $id;
1963                 }
1964             }
1965             $coursecatcache->set($thiscachekey, join(',', $thislist));
1966         }
1968         // Now build the array of strings to return, mind $separator and $excludeid.
1969         $names = array();
1970         foreach ($thislist as $id) {
1971             $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
1972             if (!$excludeid || !in_array($excludeid, $path)) {
1973                 $namechunks = array();
1974                 foreach ($path as $parentid) {
1975                     $namechunks[] = $baselist[$parentid]['name'];
1976                 }
1977                 $names[$id] = join($separator, $namechunks);
1978             }
1979         }
1980         return $names;
1981     }
1983     /**
1984      * Prepares the object for caching. Works like the __sleep method.
1985      *
1986      * implementing method from interface cacheable_object
1987      *
1988      * @return array ready to be cached
1989      */
1990     public function prepare_to_cache() {
1991         $a = array();
1992         foreach (self::$coursecatfields as $property => $cachedirectives) {
1993             if ($cachedirectives !== null) {
1994                 list($shortname, $defaultvalue) = $cachedirectives;
1995                 if ($this->$property !== $defaultvalue) {
1996                     $a[$shortname] = $this->$property;
1997                 }
1998             }
1999         }
2000         $context = context_coursecat::instance($this->id);
2001         $a['xi'] = $context->id;
2002         $a['xp'] = $context->path;
2003         return $a;
2004     }
2006     /**
2007      * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2008      *
2009      * implementing method from interface cacheable_object
2010      *
2011      * @param array $a
2012      * @return coursecat
2013      */
2014     public static function wake_from_cache($a) {
2015         $record = new stdClass;
2016         foreach (self::$coursecatfields as $property => $cachedirectives) {
2017             if ($cachedirectives !== null) {
2018                 list($shortname, $defaultvalue) = $cachedirectives;
2019                 if (array_key_exists($shortname, $a)) {
2020                     $record->$property = $a[$shortname];
2021                 } else {
2022                     $record->$property = $defaultvalue;
2023                 }
2024             }
2025         }
2026         $record->ctxid = $a['xi'];
2027         $record->ctxpath = $a['xp'];
2028         $record->ctxdepth = $record->depth + 1;
2029         $record->ctxlevel = CONTEXT_COURSECAT;
2030         $record->ctxinstance = $record->id;
2031         return new coursecat($record, true);
2032     }
2035 /**
2036  * Class to store information about one course in a list of courses
2037  *
2038  * Not all information may be retrieved when object is created but
2039  * it will be retrieved on demand when appropriate property or method is
2040  * called.
2041  *
2042  * Instances of this class are usually returned by functions
2043  * {@link coursecat::search_courses()}
2044  * and
2045  * {@link coursecat::get_courses()}
2046  *
2047  * @property-read int $id
2048  * @property-read int $category Category ID
2049  * @property-read int $sortorder
2050  * @property-read string $fullname
2051  * @property-read string $shortname
2052  * @property-read string $idnumber
2053  * @property-read string $summary Course summary. Field is present if coursecat::get_courses()
2054  *     was called with option 'summary'. Otherwise will be retrieved from DB on first request
2055  * @property-read int $summaryformat Summary format. Field is present if coursecat::get_courses()
2056  *     was called with option 'summary'. Otherwise will be retrieved from DB on first request
2057  * @property-read string $format Course format. Retrieved from DB on first request
2058  * @property-read int $showgrades Retrieved from DB on first request
2059  * @property-read int $newsitems Retrieved from DB on first request
2060  * @property-read int $startdate
2061  * @property-read int $marker Retrieved from DB on first request
2062  * @property-read int $maxbytes Retrieved from DB on first request
2063  * @property-read int $legacyfiles Retrieved from DB on first request
2064  * @property-read int $showreports Retrieved from DB on first request
2065  * @property-read int $visible
2066  * @property-read int $visibleold Retrieved from DB on first request
2067  * @property-read int $groupmode Retrieved from DB on first request
2068  * @property-read int $groupmodeforce Retrieved from DB on first request
2069  * @property-read int $defaultgroupingid Retrieved from DB on first request
2070  * @property-read string $lang Retrieved from DB on first request
2071  * @property-read string $theme Retrieved from DB on first request
2072  * @property-read int $timecreated Retrieved from DB on first request
2073  * @property-read int $timemodified Retrieved from DB on first request
2074  * @property-read int $requested Retrieved from DB on first request
2075  * @property-read int $enablecompletion Retrieved from DB on first request
2076  * @property-read int $completionnotify Retrieved from DB on first request
2077  * @property-read int $cacherev
2078  *
2079  * @package    core
2080  * @subpackage course
2081  * @copyright  2013 Marina Glancy
2082  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2083  */
2084 class course_in_list implements IteratorAggregate {
2086     /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2087     protected $record;
2089     /** @var array array of course contacts - stores result of call to get_course_contacts() */
2090     protected $coursecontacts;
2092     /**
2093      * Creates an instance of the class from record
2094      *
2095      * @param stdClass $record except fields from course table it may contain
2096      *     field hassummary indicating that summary field is not empty.
2097      *     Also it is recommended to have context fields here ready for
2098      *     context preloading
2099      */
2100     public function __construct(stdClass $record) {
2101         context_helper::preload_from_record($record);
2102         $this->record = new stdClass();
2103         foreach ($record as $key => $value) {
2104             $this->record->$key = $value;
2105         }
2106     }
2108     /**
2109      * Indicates if the course has non-empty summary field
2110      *
2111      * @return bool
2112      */
2113     public function has_summary() {
2114         if (isset($this->record->hassummary)) {
2115             return !empty($this->record->hassummary);
2116         }
2117         if (!isset($this->record->summary)) {
2118             // we need to retrieve summary
2119             $this->__get('summary');
2120         }
2121         return !empty($this->record->summary);
2122     }
2124     /**
2125      * Indicates if the course have course contacts to display
2126      *
2127      * @return bool
2128      */
2129     public function has_course_contacts() {
2130         if (!isset($this->record->managers)) {
2131             $courses = array($this->id => &$this->record);
2132             coursecat::preload_course_contacts($courses);
2133         }
2134         return !empty($this->record->managers);
2135     }
2137     /**
2138      * Returns list of course contacts (usually teachers) to display in course link
2139      *
2140      * Roles to display are set up in $CFG->coursecontact
2141      *
2142      * The result is the list of users where user id is the key and the value
2143      * is an array with elements:
2144      *  - 'user' - object containing basic user information
2145      *  - 'role' - object containing basic role information (id, name, shortname, coursealias)
2146      *  - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2147      *  - 'username' => fullname($user, $canviewfullnames)
2148      *
2149      * @return array
2150      */
2151     public function get_course_contacts() {
2152         global $CFG;
2153         if (empty($CFG->coursecontact)) {
2154             // no roles are configured to be displayed as course contacts
2155             return array();
2156         }
2157         if ($this->coursecontacts === null) {
2158             $this->coursecontacts = array();
2159             $context = context_course::instance($this->id);
2161             if (!isset($this->record->managers)) {
2162                 // preload course contacts from DB
2163                 $courses = array($this->id => &$this->record);
2164                 coursecat::preload_course_contacts($courses);
2165             }
2167             // build return array with full roles names (for this course context) and users names
2168             $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2169             foreach ($this->record->managers as $ruser) {
2170                 if (isset($this->coursecontacts[$ruser->id])) {
2171                     //  only display a user once with the highest sortorder role
2172                     continue;
2173                 }
2174                 $user = new stdClass();
2175                 $user->id = $ruser->id;
2176                 $user->username = $ruser->username;
2177                 foreach (get_all_user_name_fields() as $addname) {
2178                     $user->$addname = $ruser->$addname;
2179                 }
2180                 $role = new stdClass();
2181                 $role->id = $ruser->roleid;
2182                 $role->name = $ruser->rolename;
2183                 $role->shortname = $ruser->roleshortname;
2184                 $role->coursealias = $ruser->rolecoursealias;
2186                 $this->coursecontacts[$user->id] = array(
2187                     'user' => $user,
2188                     'role' => $role,
2189                     'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2190                     'username' => fullname($user, $canviewfullnames)
2191                 );
2192             }
2193         }
2194         return $this->coursecontacts;
2195     }
2197     /**
2198      * Checks if course has any associated overview files
2199      *
2200      * @return bool
2201      */
2202     public function has_course_overviewfiles() {
2203         global $CFG;
2204         if (empty($CFG->courseoverviewfileslimit)) {
2205             return false;
2206         }
2207         $fs = get_file_storage();
2208         $context = context_course::instance($this->id);
2209         return !$fs->is_area_empty($context->id, 'course', 'overviewfiles');
2210     }
2212     /**
2213      * Returns all course overview files
2214      *
2215      * @return array array of stored_file objects
2216      */
2217     public function get_course_overviewfiles() {
2218         global $CFG;
2219         if (empty($CFG->courseoverviewfileslimit)) {
2220             return array();
2221         }
2222         require_once($CFG->libdir. '/filestorage/file_storage.php');
2223         require_once($CFG->dirroot. '/course/lib.php');
2224         $fs = get_file_storage();
2225         $context = context_course::instance($this->id);
2226         $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2227         if (count($files)) {
2228             $overviewfilesoptions = course_overviewfiles_options($this->id);
2229             $acceptedtypes = $overviewfilesoptions['accepted_types'];
2230             if ($acceptedtypes !== '*') {
2231                 // filter only files with allowed extensions
2232                 require_once($CFG->libdir. '/filelib.php');
2233                 foreach ($files as $key => $file) {
2234                     if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2235                         unset($files[$key]);
2236                     }
2237                 }
2238             }
2239             if (count($files) > $CFG->courseoverviewfileslimit) {
2240                 // return no more than $CFG->courseoverviewfileslimit files
2241                 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
2242             }
2243         }
2244         return $files;
2245     }
2247     // ====== magic methods =======
2249     public function __isset($name) {
2250         return isset($this->record->$name);
2251     }
2253     /**
2254      * Magic method to get a course property
2255      *
2256      * Returns any field from table course (from cache or from DB) and/or special field 'hassummary'
2257      *
2258      * @param string $name
2259      * @return mixed
2260      */
2261     public function __get($name) {
2262         global $DB;
2263         if (property_exists($this->record, $name)) {
2264             return $this->record->$name;
2265         } else if ($name === 'summary' || $name === 'summaryformat') {
2266             // retrieve fields summary and summaryformat together because they are most likely to be used together
2267             $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
2268             $this->record->summary = $record->summary;
2269             $this->record->summaryformat = $record->summaryformat;
2270             return $this->record->$name;
2271         } else if (array_key_exists($name, $DB->get_columns('course'))) {
2272             // another field from table 'course' that was not retrieved
2273             $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
2274             return $this->record->$name;
2275         }
2276         debugging('Invalid course property accessed! '.$name);
2277         return null;
2278     }
2280     /**
2281      * ALl properties are read only, sorry.
2282      * @param string $name
2283      */
2284     public function __unset($name) {
2285         debugging('Can not unset '.get_class($this).' instance properties!');
2286     }
2288     /**
2289      * Magic setter method, we do not want anybody to modify properties from the outside
2290      * @param string $name
2291      * @param mixed $value
2292      */
2293     public function __set($name, $value) {
2294         debugging('Can not change '.get_class($this).' instance properties!');
2295     }
2297     // ====== implementing method from interface IteratorAggregate ======
2299     /**
2300      * Create an iterator because magic vars can't be seen by 'foreach'.
2301      * Exclude context fields
2302      */
2303     public function getIterator() {
2304         $ret = array('id' => $this->record->id);
2305         foreach ($this->record as $property => $value) {
2306             $ret[$property] = $value;
2307         }
2308         return new ArrayIterator($ret);
2309     }
2312 /**
2313  * An array of records that is sortable by many fields.
2314  *
2315  * For more info on the ArrayObject class have a look at php.net.
2316  *
2317  * @package    core
2318  * @subpackage course
2319  * @copyright  2013 Sam Hemelryk
2320  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2321  */
2322 class coursecat_sortable_records extends ArrayObject {
2324     /**
2325      * An array of sortable fields.
2326      * Gets set temporarily when sort is called.
2327      * @var array
2328      */
2329     protected $sortfields = array();
2331     /**
2332      * Sorts this array using the given fields.
2333      *
2334      * @param array $records
2335      * @param array $fields
2336      * @return array
2337      */
2338     public static function sort(array $records, array $fields) {
2339         $records = new coursecat_sortable_records($records);
2340         $records->sortfields = $fields;
2341         $records->uasort(array($records, 'sort_by_many_fields'));
2342         return $records->getArrayCopy();
2343     }
2345     /**
2346      * Sorts the two records based upon many fields.
2347      *
2348      * This method should not be called itself, please call $sort instead.
2349      * It has been marked as access private as such.
2350      *
2351      * @access private
2352      * @param stdClass $a
2353      * @param stdClass $b
2354      * @return int
2355      */
2356     public function sort_by_many_fields($a, $b) {
2357         foreach ($this->sortfields as $field => $mult) {
2358             // nulls first
2359             if (is_null($a->$field) && !is_null($b->$field)) {
2360                 return -$mult;
2361             }
2362             if (is_null($b->$field) && !is_null($a->$field)) {
2363                 return $mult;
2364             }
2366             if (is_string($a->$field) || is_string($b->$field)) {
2367                 // string fields
2368                 if ($cmp = strcoll($a->$field, $b->$field)) {
2369                     return $mult * $cmp;
2370                 }
2371             } else {
2372                 // int fields
2373                 if ($a->$field > $b->$field) {
2374                     return $mult;
2375                 }
2376                 if ($a->$field < $b->$field) {
2377                     return -$mult;
2378                 }
2379             }
2380         }
2381         return 0;
2382     }