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