2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Contains class coursecat reponsible for course category operations
22 * @copyright 2013 Marina Glancy
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
29 * Class to store, cache, render and manage course category
31 * @property-read int $id
32 * @property-read string $name
33 * @property-read string $idnumber
34 * @property-read string $description
35 * @property-read int $descriptionformat
36 * @property-read int $parent
37 * @property-read int $sortorder
38 * @property-read int $coursecount
39 * @property-read int $visible
40 * @property-read int $visibleold
41 * @property-read int $timemodified
42 * @property-read int $depth
43 * @property-read string $path
44 * @property-read string $theme
48 * @copyright 2013 Marina Glancy
49 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
51 class coursecat implements renderable, cacheable_object, IteratorAggregate {
52 /** @var coursecat stores pseudo category with id=0. Use coursecat::get(0) to retrieve */
53 protected static $coursecat0;
55 /** @var array list of all fields and their short name and default value for caching */
56 protected static $coursecatfields = array(
57 'id' => array('id', 0),
58 'name' => array('na', ''),
59 'idnumber' => array('in', null),
60 'description' => null, // Not cached.
61 'descriptionformat' => null, // Not cached.
62 'parent' => array('pa', 0),
63 'sortorder' => array('so', 0),
64 'coursecount' => array('cc', 0),
65 'visible' => array('vi', 1),
66 'visibleold' => null, // Not cached.
67 'timemodified' => null, // Not cached.
68 'depth' => array('dh', 1),
69 'path' => array('ph', null),
70 'theme' => null, // Not cached.
80 protected $idnumber = null;
83 protected $description = false;
86 protected $descriptionformat = false;
89 protected $parent = 0;
92 protected $sortorder = 0;
95 protected $coursecount = false;
98 protected $visible = 1;
101 protected $visibleold = false;
104 protected $timemodified = false;
107 protected $depth = 0;
110 protected $path = '';
113 protected $theme = false;
116 protected $fromcache;
119 protected $hasmanagecapability = null;
122 * Magic setter method, we do not want anybody to modify properties from the outside
124 * @param string $name
125 * @param mixed $value
127 public function __set($name, $value) {
128 debugging('Can not change coursecat instance properties!', DEBUG_DEVELOPER);
132 * Magic method getter, redirects to read only values. Queries from DB the fields that were not cached
134 * @param string $name
137 public function __get($name) {
139 if (array_key_exists($name, self::$coursecatfields)) {
140 if ($this->$name === false) {
141 // Property was not retrieved from DB, retrieve all not retrieved fields.
142 $notretrievedfields = array_diff_key(self::$coursecatfields, array_filter(self::$coursecatfields));
143 $record = $DB->get_record('course_categories', array('id' => $this->id),
144 join(',', array_keys($notretrievedfields)), MUST_EXIST);
145 foreach ($record as $key => $value) {
146 $this->$key = $value;
151 debugging('Invalid coursecat property accessed! '.$name, DEBUG_DEVELOPER);
156 * Full support for isset on our magic read only properties.
158 * @param string $name
161 public function __isset($name) {
162 if (array_key_exists($name, self::$coursecatfields)) {
163 return isset($this->$name);
169 * All properties are read only, sorry.
171 * @param string $name
173 public function __unset($name) {
174 debugging('Can not unset coursecat instance properties!', DEBUG_DEVELOPER);
178 * Create an iterator because magic vars can't be seen by 'foreach'.
180 * implementing method from interface IteratorAggregate
182 * @return ArrayIterator
184 public function getIterator() {
186 foreach (self::$coursecatfields as $property => $unused) {
187 if ($this->$property !== false) {
188 $ret[$property] = $this->$property;
191 return new ArrayIterator($ret);
197 * Constructor is protected, use coursecat::get($id) to retrieve category
199 * @param stdClass $record record from DB (may not contain all fields)
200 * @param bool $fromcache whether it is being restored from cache
202 protected function __construct(stdClass $record, $fromcache = false) {
203 context_helper::preload_from_record($record);
204 foreach ($record as $key => $val) {
205 if (array_key_exists($key, self::$coursecatfields)) {
209 $this->fromcache = $fromcache;
213 * Returns coursecat object for requested category
215 * If category is not visible to user it is treated as non existing
216 * unless $alwaysreturnhidden is set to true
218 * If id is 0, the pseudo object for root category is returned (convenient
219 * for calling other functions such as get_children())
221 * @param int $id category id
222 * @param int $strictness whether to throw an exception (MUST_EXIST) or
223 * return null (IGNORE_MISSING) in case the category is not found or
224 * not visible to current user
225 * @param bool $alwaysreturnhidden set to true if you want an object to be
226 * returned even if this category is not visible to the current user
227 * (category is hidden and user does not have
228 * 'moodle/category:viewhiddencategories' capability). Use with care!
229 * @return null|coursecat
230 * @throws moodle_exception
232 public static function get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false) {
234 if (!isset(self::$coursecat0)) {
235 $record = new stdClass();
237 $record->visible = 1;
240 self::$coursecat0 = new coursecat($record);
242 return self::$coursecat0;
244 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
245 $coursecat = $coursecatrecordcache->get($id);
246 if ($coursecat === false) {
247 if ($records = self::get_records('cc.id = :id', array('id' => $id))) {
248 $record = reset($records);
249 $coursecat = new coursecat($record);
251 $coursecatrecordcache->set($id, $coursecat);
254 if ($coursecat && ($alwaysreturnhidden || $coursecat->is_uservisible())) {
257 if ($strictness == MUST_EXIST) {
258 throw new moodle_exception('unknowncategory');
265 * Load many coursecat objects.
267 * @global moodle_database $DB
268 * @param array $ids An array of category ID's to load.
269 * @return coursecat[]
271 public static function get_many(array $ids) {
273 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
274 $categories = $coursecatrecordcache->get_many($ids);
276 foreach ($categories as $id => $result) {
277 if ($result === false) {
281 if (!empty($toload)) {
282 list($where, $params) = $DB->get_in_or_equal($toload, SQL_PARAMS_NAMED);
283 $records = self::get_records('cc.id '.$where, $params);
285 foreach ($records as $record) {
286 $categories[$record->id] = new coursecat($record);
287 $toset[$record->id] = $categories[$record->id];
289 $coursecatrecordcache->set_many($toset);
295 * Load all coursecat objects.
297 * @param array $options Options:
298 * @param bool $options.returnhidden Return categories even if they are hidden
299 * @return coursecat[]
301 public static function get_all($options = []) {
304 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
306 $catcontextsql = \context_helper::get_preload_record_columns_sql('ctx');
307 $catsql = "SELECT cc.*, {$catcontextsql}
308 FROM {course_categories} cc
309 JOIN {context} ctx ON cc.id = ctx.instanceid";
310 $catsqlwhere = "WHERE ctx.contextlevel = :contextlevel";
311 $catsqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC";
313 $catrs = $DB->get_recordset_sql("{$catsql} {$catsqlwhere} {$catsqlorder}", [
314 'contextlevel' => CONTEXT_COURSECAT,
317 $types['categories'] = [];
320 foreach ($catrs as $record) {
321 $category = new coursecat($record);
322 $toset[$category->id] = $category;
324 if (!empty($options['returnhidden']) || $category->is_uservisible()) {
325 $categories[$record->id] = $category;
330 $coursecatrecordcache->set_many($toset);
337 * Returns the first found category
339 * Note that if there are no categories visible to the current user on the first level,
340 * the invisible category may be returned
344 public static function get_default() {
345 if ($visiblechildren = self::get(0)->get_children()) {
346 $defcategory = reset($visiblechildren);
348 $toplevelcategories = self::get_tree(0);
349 $defcategoryid = $toplevelcategories[0];
350 $defcategory = self::get($defcategoryid, MUST_EXIST, true);
356 * Restores the object after it has been externally modified in DB for example
357 * during {@link fix_course_sortorder()}
359 protected function restore() {
360 // Update all fields in the current object.
361 $newrecord = self::get($this->id, MUST_EXIST, true);
362 foreach (self::$coursecatfields as $key => $unused) {
363 $this->$key = $newrecord->$key;
368 * Creates a new category either from form data or from raw data
370 * Please note that this function does not verify access control.
372 * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
374 * Category visibility is inherited from parent unless $data->visible = 0 is specified
376 * @param array|stdClass $data
377 * @param array $editoroptions if specified, the data is considered to be
378 * form data and file_postupdate_standard_editor() is being called to
379 * process images in description.
381 * @throws moodle_exception
383 public static function create($data, $editoroptions = null) {
385 $data = (object)$data;
386 $newcategory = new stdClass();
388 $newcategory->descriptionformat = FORMAT_MOODLE;
389 $newcategory->description = '';
390 // Copy all description* fields regardless of whether this is form data or direct field update.
391 foreach ($data as $key => $value) {
392 if (preg_match("/^description/", $key)) {
393 $newcategory->$key = $value;
397 if (empty($data->name)) {
398 throw new moodle_exception('categorynamerequired');
400 if (core_text::strlen($data->name) > 255) {
401 throw new moodle_exception('categorytoolong');
403 $newcategory->name = $data->name;
405 // Validate and set idnumber.
406 if (isset($data->idnumber)) {
407 if (core_text::strlen($data->idnumber) > 100) {
408 throw new moodle_exception('idnumbertoolong');
410 if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
411 throw new moodle_exception('categoryidnumbertaken');
413 $newcategory->idnumber = $data->idnumber;
416 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
417 $newcategory->theme = $data->theme;
420 if (empty($data->parent)) {
421 $parent = self::get(0);
423 $parent = self::get($data->parent, MUST_EXIST, true);
425 $newcategory->parent = $parent->id;
426 $newcategory->depth = $parent->depth + 1;
428 // By default category is visible, unless visible = 0 is specified or parent category is hidden.
429 if (isset($data->visible) && !$data->visible) {
430 // Create a hidden category.
431 $newcategory->visible = $newcategory->visibleold = 0;
433 // Create a category that inherits visibility from parent.
434 $newcategory->visible = $parent->visible;
435 // In case parent is hidden, when it changes visibility this new subcategory will automatically become visible too.
436 $newcategory->visibleold = 1;
439 $newcategory->sortorder = 0;
440 $newcategory->timemodified = time();
442 $newcategory->id = $DB->insert_record('course_categories', $newcategory);
444 // Update path (only possible after we know the category id.
445 $path = $parent->path . '/' . $newcategory->id;
446 $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));
448 // We should mark the context as dirty.
449 context_coursecat::instance($newcategory->id)->mark_dirty();
451 fix_course_sortorder();
453 // If this is data from form results, save embedded files and update description.
454 $categorycontext = context_coursecat::instance($newcategory->id);
455 if ($editoroptions) {
456 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
457 'coursecat', 'description', 0);
459 // Update only fields description and descriptionformat.
460 $updatedata = new stdClass();
461 $updatedata->id = $newcategory->id;
462 $updatedata->description = $newcategory->description;
463 $updatedata->descriptionformat = $newcategory->descriptionformat;
464 $DB->update_record('course_categories', $updatedata);
467 $event = \core\event\course_category_created::create(array(
468 'objectid' => $newcategory->id,
469 'context' => $categorycontext
473 cache_helper::purge_by_event('changesincoursecat');
475 return self::get($newcategory->id, MUST_EXIST, true);
479 * Updates the record with either form data or raw data
481 * Please note that this function does not verify access control.
483 * This function calls coursecat::change_parent_raw if field 'parent' is updated.
484 * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
485 * Visibility is changed first and then parent is changed. This means that
486 * if parent category is hidden, the current category will become hidden
487 * too and it may overwrite whatever was set in field 'visible'.
489 * Note that fields 'path' and 'depth' can not be updated manually
490 * Also coursecat::update() can not directly update the field 'sortoder'
492 * @param array|stdClass $data
493 * @param array $editoroptions if specified, the data is considered to be
494 * form data and file_postupdate_standard_editor() is being called to
495 * process images in description.
496 * @throws moodle_exception
498 public function update($data, $editoroptions = null) {
501 // There is no actual DB record associated with root category.
505 $data = (object)$data;
506 $newcategory = new stdClass();
507 $newcategory->id = $this->id;
509 // Copy all description* fields regardless of whether this is form data or direct field update.
510 foreach ($data as $key => $value) {
511 if (preg_match("/^description/", $key)) {
512 $newcategory->$key = $value;
516 if (isset($data->name) && empty($data->name)) {
517 throw new moodle_exception('categorynamerequired');
520 if (!empty($data->name) && $data->name !== $this->name) {
521 if (core_text::strlen($data->name) > 255) {
522 throw new moodle_exception('categorytoolong');
524 $newcategory->name = $data->name;
527 if (isset($data->idnumber) && $data->idnumber !== $this->idnumber) {
528 if (core_text::strlen($data->idnumber) > 100) {
529 throw new moodle_exception('idnumbertoolong');
531 if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
532 throw new moodle_exception('categoryidnumbertaken');
534 $newcategory->idnumber = $data->idnumber;
537 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
538 $newcategory->theme = $data->theme;
542 if (isset($data->visible)) {
543 if ($data->visible) {
544 $changes = $this->show_raw();
546 $changes = $this->hide_raw(0);
550 if (isset($data->parent) && $data->parent != $this->parent) {
552 cache_helper::purge_by_event('changesincoursecat');
554 $parentcat = self::get($data->parent, MUST_EXIST, true);
555 $this->change_parent_raw($parentcat);
556 fix_course_sortorder();
559 $newcategory->timemodified = time();
561 $categorycontext = $this->get_context();
562 if ($editoroptions) {
563 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
564 'coursecat', 'description', 0);
566 $DB->update_record('course_categories', $newcategory);
568 $event = \core\event\course_category_updated::create(array(
569 'objectid' => $newcategory->id,
570 'context' => $categorycontext
574 fix_course_sortorder();
575 // Purge cache even if fix_course_sortorder() did not do it.
576 cache_helper::purge_by_event('changesincoursecat');
578 // Update all fields in the current object.
583 * Checks if this course category is visible to current user
585 * Please note that methods coursecat::get (without 3rd argumet),
586 * coursecat::get_children(), etc. return only visible categories so it is
587 * usually not needed to call this function outside of this class
591 public function is_uservisible() {
592 return !$this->id || $this->visible ||
593 has_capability('moodle/category:viewhiddencategories', $this->get_context());
597 * Returns the complete corresponding record from DB table course_categories
599 * Mostly used in deprecated functions
603 public function get_db_record() {
605 if ($record = $DB->get_record('course_categories', array('id' => $this->id))) {
608 return (object)convert_to_array($this);
613 * Returns the entry from categories tree and makes sure the application-level tree cache is built
615 * The following keys can be requested:
617 * 'countall' - total number of categories in the system (always present)
618 * 0 - array of ids of top-level categories (always present)
619 * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
620 * $id (int) - array of ids of categories that are direct children of category with id $id. If
621 * category with id $id does not exist returns false. If category has no children returns empty array
622 * $id.'i' - array of ids of children categories that have visible=0
624 * @param int|string $id
627 protected static function get_tree($id) {
629 $coursecattreecache = cache::make('core', 'coursecattree');
630 $rv = $coursecattreecache->get($id);
634 // Re-build the tree.
635 $sql = "SELECT cc.id, cc.parent, cc.visible
636 FROM {course_categories} cc
637 ORDER BY cc.sortorder";
638 $rs = $DB->get_recordset_sql($sql, array());
639 $all = array(0 => array(), '0i' => array());
641 foreach ($rs as $record) {
642 $all[$record->id] = array();
643 $all[$record->id. 'i'] = array();
644 if (array_key_exists($record->parent, $all)) {
645 $all[$record->parent][] = $record->id;
646 if (!$record->visible) {
647 $all[$record->parent. 'i'][] = $record->id;
650 // Parent not found. This is data consistency error but next fix_course_sortorder() should fix it.
651 $all[0][] = $record->id;
652 if (!$record->visible) {
653 $all['0i'][] = $record->id;
660 // No categories found.
661 // This may happen after upgrade of a very old moodle version.
662 // In new versions the default category is created on install.
663 $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
664 set_config('defaultrequestcategory', $defcoursecat->id);
665 $all[0] = array($defcoursecat->id);
666 $all[$defcoursecat->id] = array();
669 // We must add countall to all in case it was the requested ID.
670 $all['countall'] = $count;
671 $coursecattreecache->set_many($all);
672 if (array_key_exists($id, $all)) {
675 // Requested non-existing category.
680 * Returns number of ALL categories in the system regardless if
681 * they are visible to current user or not
685 public static function count_all() {
686 return self::get_tree('countall');
690 * Retrieves number of records from course_categories table
692 * Only cached fields are retrieved. Records are ready for preloading context
694 * @param string $whereclause
695 * @param array $params
696 * @return array array of stdClass objects
698 protected static function get_records($whereclause, $params) {
700 // Retrieve from DB only the fields that need to be stored in cache.
701 $fields = array_keys(array_filter(self::$coursecatfields));
702 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
703 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
704 FROM {course_categories} cc
705 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
706 WHERE ". $whereclause." ORDER BY cc.sortorder";
707 return $DB->get_records_sql($sql,
708 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
712 * Resets course contact caches when role assignments were changed
714 * @param int $roleid role id that was given or taken away
715 * @param context $context context where role assignment has been changed
717 public static function role_assignment_changed($roleid, $context) {
720 if ($context->contextlevel > CONTEXT_COURSE) {
721 // No changes to course contacts if role was assigned on the module/block level.
725 if (!$CFG->coursecontact || !in_array($roleid, explode(',', $CFG->coursecontact))) {
726 // The role is not one of course contact roles.
730 // Remove from cache course contacts of all affected courses.
731 $cache = cache::make('core', 'coursecontacts');
732 if ($context->contextlevel == CONTEXT_COURSE) {
733 $cache->delete($context->instanceid);
734 } else if ($context->contextlevel == CONTEXT_SYSTEM) {
737 $sql = "SELECT ctx.instanceid
739 WHERE ctx.path LIKE ? AND ctx.contextlevel = ?";
740 $params = array($context->path . '/%', CONTEXT_COURSE);
741 if ($courses = $DB->get_fieldset_sql($sql, $params)) {
742 $cache->delete_many($courses);
748 * Executed when user enrolment was changed to check if course
749 * contacts cache needs to be cleared
751 * @param int $courseid course id
752 * @param int $userid user id
753 * @param int $status new enrolment status (0 - active, 1 - suspended)
754 * @param int $timestart new enrolment time start
755 * @param int $timeend new enrolment time end
757 public static function user_enrolment_changed($courseid, $userid,
758 $status, $timestart = null, $timeend = null) {
759 $cache = cache::make('core', 'coursecontacts');
760 $contacts = $cache->get($courseid);
761 if ($contacts === false) {
762 // The contacts for the affected course were not cached anyway.
765 $enrolmentactive = ($status == 0) &&
766 (!$timestart || $timestart < time()) &&
767 (!$timeend || $timeend > time());
768 if (!$enrolmentactive) {
769 $isincontacts = false;
770 foreach ($contacts as $contact) {
771 if ($contact->id == $userid) {
772 $isincontacts = true;
775 if (!$isincontacts) {
776 // Changed user's enrolment does not exist or is not active,
777 // and he is not in cached course contacts, no changes to be made.
781 // Either enrolment of manager was deleted/suspended
782 // or user enrolment was added or activated.
783 // In order to see if the course contacts for this course need
784 // changing we would need to make additional queries, they will
785 // slow down bulk enrolment changes. It is better just to remove
786 // course contacts cache for this course.
787 $cache->delete($courseid);
791 * Given list of DB records from table course populates each record with list of users with course contact roles
793 * This function fills the courses with raw information as {@link get_role_users()} would do.
794 * See also {@link course_in_list::get_course_contacts()} for more readable return
796 * $courses[$i]->managers = array(
797 * $roleassignmentid => $roleuser,
801 * where $roleuser is an stdClass with the following properties:
803 * $roleuser->raid - role assignment id
804 * $roleuser->id - user id
805 * $roleuser->username
806 * $roleuser->firstname
807 * $roleuser->lastname
808 * $roleuser->rolecoursealias
809 * $roleuser->rolename
810 * $roleuser->sortorder - role sortorder
812 * $roleuser->roleshortname
814 * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
816 * @param array $courses
818 public static function preload_course_contacts(&$courses) {
820 if (empty($courses) || empty($CFG->coursecontact)) {
823 $managerroles = explode(',', $CFG->coursecontact);
824 $cache = cache::make('core', 'coursecontacts');
825 $cacheddata = $cache->get_many(array_keys($courses));
826 $courseids = array();
827 foreach (array_keys($courses) as $id) {
828 if ($cacheddata[$id] !== false) {
829 $courses[$id]->managers = $cacheddata[$id];
835 // Array $courseids now stores list of ids of courses for which we still need to retrieve contacts.
836 if (empty($courseids)) {
840 // First build the array of all context ids of the courses and their categories.
841 $allcontexts = array();
842 foreach ($courseids as $id) {
843 $context = context_course::instance($id);
844 $courses[$id]->managers = array();
845 foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
846 if (!isset($allcontexts[$ctxid])) {
847 $allcontexts[$ctxid] = array();
849 $allcontexts[$ctxid][] = $id;
853 // Fetch list of all users with course contact roles in any of the courses contexts or parent contexts.
854 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
855 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
856 list($sort, $sortparams) = users_order_by_sql('u');
857 $notdeleted = array('notdeleted'=>0);
858 $allnames = get_all_user_name_fields(true, 'u');
859 $sql = "SELECT ra.contextid, ra.id AS raid,
860 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
861 rn.name AS rolecoursealias, u.id, u.username, $allnames
862 FROM {role_assignments} ra
863 JOIN {user} u ON ra.userid = u.id
864 JOIN {role} r ON ra.roleid = r.id
865 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
866 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
867 ORDER BY r.sortorder, $sort";
868 $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
869 $checkenrolments = array();
870 foreach ($rs as $ra) {
871 foreach ($allcontexts[$ra->contextid] as $id) {
872 $courses[$id]->managers[$ra->raid] = $ra;
873 if (!isset($checkenrolments[$id])) {
874 $checkenrolments[$id] = array();
876 $checkenrolments[$id][] = $ra->id;
881 // Remove from course contacts users who are not enrolled in the course.
882 $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
883 foreach ($checkenrolments as $id => $userids) {
884 if (empty($enrolleduserids[$id])) {
885 $courses[$id]->managers = array();
886 } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
887 foreach ($courses[$id]->managers as $raid => $ra) {
888 if (in_array($ra->id, $notenrolled)) {
889 unset($courses[$id]->managers[$raid]);
897 foreach ($courseids as $id) {
898 $values[$id] = $courses[$id]->managers;
900 $cache->set_many($values);
904 * Verify user enrollments for multiple course-user combinations
906 * @param array $courseusers array where keys are course ids and values are array
907 * of users in this course whose enrolment we wish to verify
908 * @return array same structure as input array but values list only users from input
909 * who are enrolled in the course
911 protected static function ensure_users_enrolled($courseusers) {
913 // If the input array is too big, split it into chunks.
914 $maxcoursesinquery = 20;
915 if (count($courseusers) > $maxcoursesinquery) {
917 for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
918 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
919 $rv = $rv + self::ensure_users_enrolled($chunk);
924 // Create a query verifying valid user enrolments for the number of courses.
925 $sql = "SELECT DISTINCT e.courseid, ue.userid
926 FROM {user_enrolments} ue
927 JOIN {enrol} e ON e.id = ue.enrolid
928 WHERE ue.status = :active
929 AND e.status = :enabled
930 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
931 $now = round(time(), -2); // Rounding helps caching in DB.
932 $params = array('enabled' => ENROL_INSTANCE_ENABLED,
933 'active' => ENROL_USER_ACTIVE,
934 'now1' => $now, 'now2' => $now);
938 foreach ($courseusers as $id => $userids) {
939 $enrolled[$id] = array();
940 if (count($userids)) {
941 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
942 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
943 $params = $params + array('courseid'.$cnt => $id) + $params2;
947 if (count($subsqls)) {
948 $sql .= "AND (". join(' OR ', $subsqls).")";
949 $rs = $DB->get_recordset_sql($sql, $params);
950 foreach ($rs as $record) {
951 $enrolled[$record->courseid][] = $record->userid;
959 * Retrieves number of records from course table
961 * Not all fields are retrieved. Records are ready for preloading context
963 * @param string $whereclause
964 * @param array $params
965 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
966 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
967 * on not visible courses
968 * @return array array of stdClass objects
970 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
972 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
973 $fields = array('c.id', 'c.category', 'c.sortorder',
974 'c.shortname', 'c.fullname', 'c.idnumber',
975 'c.startdate', 'c.enddate', 'c.visible', 'c.cacherev');
976 if (!empty($options['summary'])) {
977 $fields[] = 'c.summary';
978 $fields[] = 'c.summaryformat';
980 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
982 $sql = "SELECT ". join(',', $fields). ", $ctxselect
984 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
985 WHERE ". $whereclause." ORDER BY c.sortorder";
986 $list = $DB->get_records_sql($sql,
987 array('contextcourse' => CONTEXT_COURSE) + $params);
989 if ($checkvisibility) {
990 // Loop through all records and make sure we only return the courses accessible by user.
991 foreach ($list as $course) {
992 if (isset($list[$course->id]->hassummary)) {
993 $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
995 if (empty($course->visible)) {
996 // Load context only if we need to check capability.
997 context_helper::preload_from_record($course);
998 if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
999 unset($list[$course->id]);
1005 // Preload course contacts if necessary.
1006 if (!empty($options['coursecontacts'])) {
1007 self::preload_course_contacts($list);
1013 * Returns array of ids of children categories that current user can not see
1015 * This data is cached in user session cache
1019 protected function get_not_visible_children_ids() {
1021 $coursecatcache = cache::make('core', 'coursecat');
1022 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
1023 // We never checked visible children before.
1024 $hidden = self::get_tree($this->id.'i');
1025 $invisibleids = array();
1027 // Preload categories contexts.
1028 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
1029 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1030 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
1031 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
1032 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
1033 foreach ($contexts as $record) {
1034 context_helper::preload_from_record($record);
1036 // Check that user has 'viewhiddencategories' capability for each hidden category.
1037 foreach ($hidden as $id) {
1038 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
1039 $invisibleids[] = $id;
1043 $coursecatcache->set('ic'. $this->id, $invisibleids);
1045 return $invisibleids;
1049 * Sorts list of records by several fields
1051 * @param array $records array of stdClass objects
1052 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
1055 protected static function sort_records(&$records, $sortfields) {
1056 if (empty($records)) {
1059 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname).
1060 if (array_key_exists('displayname', $sortfields)) {
1061 foreach ($records as $key => $record) {
1062 if (!isset($record->displayname)) {
1063 $records[$key]->displayname = get_course_display_name_for_list($record);
1067 // Sorting by one field - use core_collator.
1068 if (count($sortfields) == 1) {
1069 $property = key($sortfields);
1070 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
1071 $sortflag = core_collator::SORT_NUMERIC;
1072 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
1073 $sortflag = core_collator::SORT_STRING;
1075 $sortflag = core_collator::SORT_REGULAR;
1077 core_collator::asort_objects_by_property($records, $property, $sortflag);
1078 if ($sortfields[$property] < 0) {
1079 $records = array_reverse($records, true);
1083 $records = coursecat_sortable_records::sort($records, $sortfields);
1087 * Returns array of children categories visible to the current user
1089 * @param array $options options for retrieving children
1090 * - sort - list of fields to sort. Example
1091 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
1092 * will sort by idnumber asc, name asc and id desc.
1093 * Default: array('sortorder' => 1)
1094 * Only cached fields may be used for sorting!
1096 * - limit - maximum number of children to return, 0 or null for no limit
1097 * @return coursecat[] Array of coursecat objects indexed by category id
1099 public function get_children($options = array()) {
1101 $coursecatcache = cache::make('core', 'coursecat');
1103 // Get default values for options.
1104 if (!empty($options['sort']) && is_array($options['sort'])) {
1105 $sortfields = $options['sort'];
1107 $sortfields = array('sortorder' => 1);
1110 if (!empty($options['limit']) && (int)$options['limit']) {
1111 $limit = (int)$options['limit'];
1114 if (!empty($options['offset']) && (int)$options['offset']) {
1115 $offset = (int)$options['offset'];
1118 // First retrieve list of user-visible and sorted children ids from cache.
1119 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
1120 if ($sortedids === false) {
1121 $sortfieldskeys = array_keys($sortfields);
1122 if ($sortfieldskeys[0] === 'sortorder') {
1123 // No DB requests required to build the list of ids sorted by sortorder.
1124 // We can easily ignore other sort fields because sortorder is always different.
1125 $sortedids = self::get_tree($this->id);
1126 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
1127 $sortedids = array_diff($sortedids, $invisibleids);
1128 if ($sortfields['sortorder'] == -1) {
1129 $sortedids = array_reverse($sortedids, true);
1133 // We need to retrieve and sort all children. Good thing that it is done only on first request.
1134 if ($invisibleids = $this->get_not_visible_children_ids()) {
1135 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
1136 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
1137 array('parent' => $this->id) + $params);
1139 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
1141 self::sort_records($records, $sortfields);
1142 $sortedids = array_keys($records);
1144 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
1147 if (empty($sortedids)) {
1151 // Now retrieive and return categories.
1152 if ($offset || $limit) {
1153 $sortedids = array_slice($sortedids, $offset, $limit);
1155 if (isset($records)) {
1156 // Easy, we have already retrieved records.
1157 if ($offset || $limit) {
1158 $records = array_slice($records, $offset, $limit, true);
1161 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
1162 $records = self::get_records('cc.id '. $sql, array('parent' => $this->id) + $params);
1166 foreach ($sortedids as $id) {
1167 if (isset($records[$id])) {
1168 $rv[$id] = new coursecat($records[$id]);
1175 * Returns true if the user has the manage capability on any category.
1177 * This method uses the coursecat cache and an entry `has_manage_capability` to speed up
1178 * calls to this method.
1182 public static function has_manage_capability_on_any() {
1183 return self::has_capability_on_any('moodle/category:manage');
1187 * Checks if the user has at least one of the given capabilities on any category.
1189 * @param array|string $capabilities One or more capabilities to check. Check made is an OR.
1192 public static function has_capability_on_any($capabilities) {
1194 if (!isloggedin() || isguestuser()) {
1198 if (!is_array($capabilities)) {
1199 $capabilities = array($capabilities);
1202 foreach ($capabilities as $capability) {
1203 $keys[$capability] = sha1($capability);
1206 /* @var cache_session $cache */
1207 $cache = cache::make('core', 'coursecat');
1208 $hascapability = $cache->get_many($keys);
1209 $needtoload = false;
1210 foreach ($hascapability as $capability) {
1211 if ($capability === '1') {
1213 } else if ($capability === false) {
1217 if ($needtoload === false) {
1218 // All capabilities were retrieved and the user didn't have any.
1223 $fields = context_helper::get_preload_record_columns_sql('ctx');
1224 $sql = "SELECT ctx.instanceid AS categoryid, $fields
1226 WHERE contextlevel = :contextlevel
1227 ORDER BY depth ASC";
1228 $params = array('contextlevel' => CONTEXT_COURSECAT);
1229 $recordset = $DB->get_recordset_sql($sql, $params);
1230 foreach ($recordset as $context) {
1231 context_helper::preload_from_record($context);
1232 $context = context_coursecat::instance($context->categoryid);
1233 foreach ($capabilities as $capability) {
1234 if (has_capability($capability, $context)) {
1235 $haskey = $capability;
1240 $recordset->close();
1241 if ($haskey === null) {
1243 foreach ($keys as $key) {
1246 $cache->set_many($data);
1249 $cache->set($haskey, '1');
1255 * Returns true if the user can resort any category.
1258 public static function can_resort_any() {
1259 return self::has_manage_capability_on_any();
1263 * Returns true if the user can change the parent of any category.
1266 public static function can_change_parent_any() {
1267 return self::has_manage_capability_on_any();
1271 * Returns number of subcategories visible to the current user
1275 public function get_children_count() {
1276 $sortedids = self::get_tree($this->id);
1277 $invisibleids = $this->get_not_visible_children_ids();
1278 return count($sortedids) - count($invisibleids);
1282 * Returns true if the category has ANY children, including those not visible to the user
1286 public function has_children() {
1287 $allchildren = self::get_tree($this->id);
1288 return !empty($allchildren);
1292 * Returns true if the category has courses in it (count does not include courses
1293 * in child categories)
1297 public function has_courses() {
1299 return $DB->record_exists_sql("select 1 from {course} where category = ?",
1304 * Get the link used to view this course category.
1306 * @return \moodle_url
1308 public function get_view_link() {
1309 return new \moodle_url('/course/index.php', [
1310 'categoryid' => $this->id,
1317 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1318 * to this when somebody edits courses or categories, however it is very
1319 * difficult to keep track of all possible changes that may affect list of courses.
1321 * @param array $search contains search criterias, such as:
1322 * - search - search string
1323 * - blocklist - id of block (if we are searching for courses containing specific block0
1324 * - modulelist - name of module (if we are searching for courses containing specific module
1325 * - tagid - id of tag
1326 * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
1327 * search is always category-independent
1328 * @param array $requiredcapabilites List of capabilities required to see return course.
1329 * @return course_in_list[]
1331 public static function search_courses($search, $options = array(), $requiredcapabilities = array()) {
1333 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1334 $limit = !empty($options['limit']) ? $options['limit'] : null;
1335 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1337 $coursecatcache = cache::make('core', 'coursecat');
1338 $cachekey = 's-'. serialize(
1339 $search + array('sort' => $sortfields) + array('requiredcapabilities' => $requiredcapabilities)
1341 $cntcachekey = 'scnt-'. serialize($search);
1343 $ids = $coursecatcache->get($cachekey);
1344 if ($ids !== false) {
1345 // We already cached last search result.
1346 $ids = array_slice($ids, $offset, $limit);
1349 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1350 $records = self::get_course_records("c.id ". $sql, $params, $options);
1351 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1352 if (!empty($options['coursecontacts'])) {
1353 self::preload_course_contacts($records);
1355 // If option 'idonly' is specified no further action is needed, just return list of ids.
1356 if (!empty($options['idonly'])) {
1357 return array_keys($records);
1359 // Prepare the list of course_in_list objects.
1360 foreach ($ids as $id) {
1361 $courses[$id] = new course_in_list($records[$id]);
1367 $preloadcoursecontacts = !empty($options['coursecontacts']);
1368 unset($options['coursecontacts']);
1370 // Empty search string will return all results.
1371 if (!isset($search['search'])) {
1372 $search['search'] = '';
1375 if (empty($search['blocklist']) && empty($search['modulelist']) && empty($search['tagid'])) {
1376 // Search courses that have specified words in their names/summaries.
1377 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1379 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount, $requiredcapabilities);
1380 self::sort_records($courselist, $sortfields);
1381 $coursecatcache->set($cachekey, array_keys($courselist));
1382 $coursecatcache->set($cntcachekey, $totalcount);
1383 $records = array_slice($courselist, $offset, $limit, true);
1385 if (!empty($search['blocklist'])) {
1386 // Search courses that have block with specified id.
1387 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1388 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1389 WHERE bi.blockname = :blockname)';
1390 $params = array('blockname' => $blockname);
1391 } else if (!empty($search['modulelist'])) {
1392 // Search courses that have module with specified name.
1393 $where = "c.id IN (SELECT DISTINCT module.course ".
1394 "FROM {".$search['modulelist']."} module)";
1396 } else if (!empty($search['tagid'])) {
1397 // Search courses that are tagged with the specified tag.
1398 $where = "c.id IN (SELECT t.itemid ".
1399 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype AND t.component = :component)";
1400 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course', 'component' => 'core');
1401 if (!empty($search['ctx'])) {
1402 $rec = isset($search['rec']) ? $search['rec'] : true;
1403 $parentcontext = context::instance_by_id($search['ctx']);
1404 if ($parentcontext->contextlevel == CONTEXT_SYSTEM && $rec) {
1405 // Parent context is system context and recursive is set to yes.
1406 // Nothing to filter - all courses fall into this condition.
1408 // Filter all courses in the parent context at any level.
1409 $where .= ' AND ctx.path LIKE :contextpath';
1410 $params['contextpath'] = $parentcontext->path . '%';
1411 } else if ($parentcontext->contextlevel == CONTEXT_COURSECAT) {
1412 // All courses in the given course category.
1413 $where .= ' AND c.category = :category';
1414 $params['category'] = $parentcontext->instanceid;
1416 // No courses will satisfy the context criterion, do not bother searching.
1421 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1424 $courselist = self::get_course_records($where, $params, $options, true);
1425 if (!empty($requiredcapabilities)) {
1426 foreach ($courselist as $key => $course) {
1427 context_helper::preload_from_record($course);
1428 $coursecontext = context_course::instance($course->id);
1429 if (!has_all_capabilities($requiredcapabilities, $coursecontext)) {
1430 unset($courselist[$key]);
1434 self::sort_records($courselist, $sortfields);
1435 $coursecatcache->set($cachekey, array_keys($courselist));
1436 $coursecatcache->set($cntcachekey, count($courselist));
1437 $records = array_slice($courselist, $offset, $limit, true);
1440 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1441 if (!empty($preloadcoursecontacts)) {
1442 self::preload_course_contacts($records);
1444 // If option 'idonly' is specified no further action is needed, just return list of ids.
1445 if (!empty($options['idonly'])) {
1446 return array_keys($records);
1448 // Prepare the list of course_in_list objects.
1450 foreach ($records as $record) {
1451 $courses[$record->id] = new course_in_list($record);
1457 * Returns number of courses in the search results
1459 * It is recommended to call this function after {@link coursecat::search_courses()}
1460 * and not before because only course ids are cached. Otherwise search_courses() may
1461 * perform extra DB queries.
1463 * @param array $search search criteria, see method search_courses() for more details
1464 * @param array $options display options. They do not affect the result but
1465 * the 'sort' property is used in cache key for storing list of course ids
1466 * @param array $requiredcapabilites List of capabilities required to see return course.
1469 public static function search_courses_count($search, $options = array(), $requiredcapabilities = array()) {
1470 $coursecatcache = cache::make('core', 'coursecat');
1471 $cntcachekey = 'scnt-'. serialize($search) . serialize($requiredcapabilities);
1472 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1473 // Cached value not found. Retrieve ALL courses and return their count.
1474 unset($options['offset']);
1475 unset($options['limit']);
1476 unset($options['summary']);
1477 unset($options['coursecontacts']);
1478 $options['idonly'] = true;
1479 $courses = self::search_courses($search, $options, $requiredcapabilities);
1480 $cnt = count($courses);
1486 * Retrieves the list of courses accessible by user
1488 * Not all information is cached, try to avoid calling this method
1489 * twice in the same request.
1491 * The following fields are always retrieved:
1492 * - id, visible, fullname, shortname, idnumber, category, sortorder
1494 * If you plan to use properties/methods course_in_list::$summary and/or
1495 * course_in_list::get_course_contacts()
1496 * you can preload this information using appropriate 'options'. Otherwise
1497 * they will be retrieved from DB on demand and it may end with bigger DB load.
1499 * Note that method course_in_list::has_summary() will not perform additional
1500 * DB queries even if $options['summary'] is not specified
1502 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1503 * to this when somebody edits courses or categories, however it is very
1504 * difficult to keep track of all possible changes that may affect list of courses.
1506 * @param array $options options for retrieving children
1507 * - recursive - return courses from subcategories as well. Use with care,
1508 * this may be a huge list!
1509 * - summary - preloads fields 'summary' and 'summaryformat'
1510 * - coursecontacts - preloads course contacts
1511 * - sort - list of fields to sort. Example
1512 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1513 * will sort by idnumber asc, shortname asc and id desc.
1514 * Default: array('sortorder' => 1)
1515 * Only cached fields may be used for sorting!
1517 * - limit - maximum number of children to return, 0 or null for no limit
1518 * - idonly - returns the array or course ids instead of array of objects
1519 * used only in get_courses_count()
1520 * @return course_in_list[]
1522 public function get_courses($options = array()) {
1524 $recursive = !empty($options['recursive']);
1525 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1526 $limit = !empty($options['limit']) ? $options['limit'] : null;
1527 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1529 // Check if this category is hidden.
1530 // Also 0-category never has courses unless this is recursive call.
1531 if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1535 $coursecatcache = cache::make('core', 'coursecat');
1536 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1537 '-'. serialize($sortfields);
1538 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1540 // Check if we have already cached results.
1541 $ids = $coursecatcache->get($cachekey);
1542 if ($ids !== false) {
1543 // We already cached last search result and it did not expire yet.
1544 $ids = array_slice($ids, $offset, $limit);
1547 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1548 $records = self::get_course_records("c.id ". $sql, $params, $options);
1549 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1550 if (!empty($options['coursecontacts'])) {
1551 self::preload_course_contacts($records);
1553 // If option 'idonly' is specified no further action is needed, just return list of ids.
1554 if (!empty($options['idonly'])) {
1555 return array_keys($records);
1557 // Prepare the list of course_in_list objects.
1558 foreach ($ids as $id) {
1559 $courses[$id] = new course_in_list($records[$id]);
1565 // Retrieve list of courses in category.
1566 $where = 'c.id <> :siteid';
1567 $params = array('siteid' => SITEID);
1570 $context = context_coursecat::instance($this->id);
1571 $where .= ' AND ctx.path like :path';
1572 $params['path'] = $context->path. '/%';
1575 $where .= ' AND c.category = :categoryid';
1576 $params['categoryid'] = $this->id;
1578 // Get list of courses without preloaded coursecontacts because we don't need them for every course.
1579 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1581 // Sort and cache list.
1582 self::sort_records($list, $sortfields);
1583 $coursecatcache->set($cachekey, array_keys($list));
1584 $coursecatcache->set($cntcachekey, count($list));
1586 // Apply offset/limit, convert to course_in_list and return.
1589 if ($offset || $limit) {
1590 $list = array_slice($list, $offset, $limit, true);
1592 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1593 if (!empty($options['coursecontacts'])) {
1594 self::preload_course_contacts($list);
1596 // If option 'idonly' is specified no further action is needed, just return list of ids.
1597 if (!empty($options['idonly'])) {
1598 return array_keys($list);
1600 // Prepare the list of course_in_list objects.
1601 foreach ($list as $record) {
1602 $courses[$record->id] = new course_in_list($record);
1609 * Returns number of courses visible to the user
1611 * @param array $options similar to get_courses() except some options do not affect
1612 * number of courses (i.e. sort, summary, offset, limit etc.)
1615 public function get_courses_count($options = array()) {
1616 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1617 $coursecatcache = cache::make('core', 'coursecat');
1618 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1619 // Cached value not found. Retrieve ALL courses and return their count.
1620 unset($options['offset']);
1621 unset($options['limit']);
1622 unset($options['summary']);
1623 unset($options['coursecontacts']);
1624 $options['idonly'] = true;
1625 $courses = $this->get_courses($options);
1626 $cnt = count($courses);
1632 * Returns true if the user is able to delete this category.
1634 * Note if this category contains any courses this isn't a full check, it will need to be accompanied by a call to either
1635 * {@link coursecat::can_delete_full()} or {@link coursecat::can_move_content_to()} depending upon what the user wished to do.
1639 public function can_delete() {
1640 if (!$this->has_manage_capability()) {
1643 return $this->parent_has_manage_capability();
1647 * Returns true if user can delete current category and all its contents
1649 * To be able to delete course category the user must have permission
1650 * 'moodle/category:manage' in ALL child course categories AND
1651 * be able to delete all courses
1655 public function can_delete_full() {
1662 $context = $this->get_context();
1663 if (!$this->is_uservisible() ||
1664 !has_capability('moodle/category:manage', $context)) {
1668 // Check all child categories (not only direct children).
1669 $sql = context_helper::get_preload_record_columns_sql('ctx');
1670 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1671 ' FROM {context} ctx '.
1672 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1673 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1674 array($context->path. '/%', CONTEXT_COURSECAT));
1675 foreach ($childcategories as $childcat) {
1676 context_helper::preload_from_record($childcat);
1677 $childcontext = context_coursecat::instance($childcat->id);
1678 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1679 !has_capability('moodle/category:manage', $childcontext)) {
1685 $sql = context_helper::get_preload_record_columns_sql('ctx');
1686 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1687 $sql. ' FROM {context} ctx '.
1688 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1689 array('pathmask' => $context->path. '/%',
1690 'courselevel' => CONTEXT_COURSE));
1691 foreach ($coursescontexts as $ctxrecord) {
1692 context_helper::preload_from_record($ctxrecord);
1693 if (!can_delete_course($ctxrecord->courseid)) {
1702 * Recursively delete category including all subcategories and courses
1704 * Function {@link coursecat::can_delete_full()} MUST be called prior
1705 * to calling this function because there is no capability check
1706 * inside this function
1708 * @param boolean $showfeedback display some notices
1709 * @return array return deleted courses
1710 * @throws moodle_exception
1712 public function delete_full($showfeedback = true) {
1715 require_once($CFG->libdir.'/gradelib.php');
1716 require_once($CFG->libdir.'/questionlib.php');
1717 require_once($CFG->dirroot.'/cohort/lib.php');
1719 // Make sure we won't timeout when deleting a lot of courses.
1720 $settimeout = core_php_time_limit::raise();
1722 // Allow plugins to use this category before we completely delete it.
1723 if ($pluginsfunction = get_plugins_with_function('pre_course_category_delete')) {
1724 $category = $this->get_db_record();
1725 foreach ($pluginsfunction as $plugintype => $plugins) {
1726 foreach ($plugins as $pluginfunction) {
1727 $pluginfunction($category);
1732 $deletedcourses = array();
1734 // Get children. Note, we don't want to use cache here because it would be rebuilt too often.
1735 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1736 foreach ($children as $record) {
1737 $coursecat = new coursecat($record);
1738 $deletedcourses += $coursecat->delete_full($showfeedback);
1741 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1742 foreach ($courses as $course) {
1743 if (!delete_course($course, false)) {
1744 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1746 $deletedcourses[] = $course;
1750 // Move or delete cohorts in this context.
1751 cohort_delete_category($this);
1753 // Now delete anything that may depend on course category context.
1754 grade_course_category_delete($this->id, 0, $showfeedback);
1755 if (!question_delete_course_category($this, 0, $showfeedback)) {
1756 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1759 // Finally delete the category and it's context.
1760 $DB->delete_records('course_categories', array('id' => $this->id));
1762 $coursecatcontext = context_coursecat::instance($this->id);
1763 $coursecatcontext->delete();
1765 cache_helper::purge_by_event('changesincoursecat');
1767 // Trigger a course category deleted event.
1768 /* @var \core\event\course_category_deleted $event */
1769 $event = \core\event\course_category_deleted::create(array(
1770 'objectid' => $this->id,
1771 'context' => $coursecatcontext,
1772 'other' => array('name' => $this->name)
1774 $event->set_coursecat($this);
1777 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1778 if ($this->id == $CFG->defaultrequestcategory) {
1779 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1781 return $deletedcourses;
1785 * Checks if user can delete this category and move content (courses, subcategories and questions)
1786 * to another category. If yes returns the array of possible target categories names
1788 * If user can not manage this category or it is completely empty - empty array will be returned
1792 public function move_content_targets_list() {
1794 require_once($CFG->libdir . '/questionlib.php');
1795 $context = $this->get_context();
1796 if (!$this->is_uservisible() ||
1797 !has_capability('moodle/category:manage', $context)) {
1798 // User is not able to manage current category, he is not able to delete it.
1799 // No possible target categories.
1803 $testcaps = array();
1804 // If this category has courses in it, user must have 'course:create' capability in target category.
1805 if ($this->has_courses()) {
1806 $testcaps[] = 'moodle/course:create';
1808 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1809 if ($this->has_children() || question_context_has_any_questions($context)) {
1810 $testcaps[] = 'moodle/category:manage';
1812 if (!empty($testcaps)) {
1813 // Return list of categories excluding this one and it's children.
1814 return self::make_categories_list($testcaps, $this->id);
1817 // Category is completely empty, no need in target for contents.
1822 * Checks if user has capability to move all category content to the new parent before
1823 * removing this category
1825 * @param int $newcatid
1828 public function can_move_content_to($newcatid) {
1830 require_once($CFG->libdir . '/questionlib.php');
1831 $context = $this->get_context();
1832 if (!$this->is_uservisible() ||
1833 !has_capability('moodle/category:manage', $context)) {
1836 $testcaps = array();
1837 // If this category has courses in it, user must have 'course:create' capability in target category.
1838 if ($this->has_courses()) {
1839 $testcaps[] = 'moodle/course:create';
1841 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1842 if ($this->has_children() || question_context_has_any_questions($context)) {
1843 $testcaps[] = 'moodle/category:manage';
1845 if (!empty($testcaps)) {
1846 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1849 // There is no content but still return true.
1854 * Deletes a category and moves all content (children, courses and questions) to the new parent
1856 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1857 * must be called prior
1859 * @param int $newparentid
1860 * @param bool $showfeedback
1863 public function delete_move($newparentid, $showfeedback = false) {
1864 global $CFG, $DB, $OUTPUT;
1866 require_once($CFG->libdir.'/gradelib.php');
1867 require_once($CFG->libdir.'/questionlib.php');
1868 require_once($CFG->dirroot.'/cohort/lib.php');
1870 // Get all objects and lists because later the caches will be reset so.
1871 // We don't need to make extra queries.
1872 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1873 $catname = $this->get_formatted_name();
1874 $children = $this->get_children();
1875 $params = array('category' => $this->id);
1876 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', $params);
1877 $context = $this->get_context();
1880 foreach ($children as $childcat) {
1881 $childcat->change_parent_raw($newparentcat);
1883 $event = \core\event\course_category_updated::create(array(
1884 'objectid' => $childcat->id,
1885 'context' => $childcat->get_context()
1887 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $childcat->id,
1891 fix_course_sortorder();
1895 require_once($CFG->dirroot.'/course/lib.php');
1896 if (!move_courses($coursesids, $newparentid)) {
1897 if ($showfeedback) {
1898 echo $OUTPUT->notification("Error moving courses");
1902 if ($showfeedback) {
1903 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1907 // Move or delete cohorts in this context.
1908 cohort_delete_category($this);
1910 // Now delete anything that may depend on course category context.
1911 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1912 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1913 if ($showfeedback) {
1914 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1919 // Finally delete the category and it's context.
1920 $DB->delete_records('course_categories', array('id' => $this->id));
1923 // Trigger a course category deleted event.
1924 /* @var \core\event\course_category_deleted $event */
1925 $event = \core\event\course_category_deleted::create(array(
1926 'objectid' => $this->id,
1927 'context' => $context,
1928 'other' => array('name' => $this->name)
1930 $event->set_coursecat($this);
1933 cache_helper::purge_by_event('changesincoursecat');
1935 if ($showfeedback) {
1936 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1939 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1940 if ($this->id == $CFG->defaultrequestcategory) {
1941 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1947 * Checks if user can move current category to the new parent
1949 * This checks if new parent category exists, user has manage cap there
1950 * and new parent is not a child of this category
1952 * @param int|stdClass|coursecat $newparentcat
1955 public function can_change_parent($newparentcat) {
1956 if (!has_capability('moodle/category:manage', $this->get_context())) {
1959 if (is_object($newparentcat)) {
1960 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1962 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1964 if (!$newparentcat) {
1967 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1968 // Can not move to itself or it's own child.
1971 if ($newparentcat->id) {
1972 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
1974 return has_capability('moodle/category:manage', context_system::instance());
1979 * Moves the category under another parent category. All associated contexts are moved as well
1981 * This is protected function, use change_parent() or update() from outside of this class
1983 * @see coursecat::change_parent()
1984 * @see coursecat::update()
1986 * @param coursecat $newparentcat
1987 * @throws moodle_exception
1989 protected function change_parent_raw(coursecat $newparentcat) {
1992 $context = $this->get_context();
1995 if (empty($newparentcat->id)) {
1996 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1997 $newparent = context_system::instance();
1999 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
2000 // Can not move to itself or it's own child.
2001 throw new moodle_exception('cannotmovecategory');
2003 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
2004 $newparent = context_coursecat::instance($newparentcat->id);
2006 if (!$newparentcat->visible and $this->visible) {
2007 // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children
2008 // will be restored properly.
2012 $this->parent = $newparentcat->id;
2014 $context->update_moved($newparent);
2016 // Now make it last in new category.
2017 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
2020 fix_course_sortorder();
2022 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must
2023 // become visible again.
2029 * Efficiently moves a category - NOTE that this can have
2030 * a huge impact access-control-wise...
2032 * Note that this function does not check capabilities.
2035 * $coursecat = coursecat::get($categoryid);
2036 * if ($coursecat->can_change_parent($newparentcatid)) {
2037 * $coursecat->change_parent($newparentcatid);
2040 * This function does not update field course_categories.timemodified
2041 * If you want to update timemodified, use
2042 * $coursecat->update(array('parent' => $newparentcat));
2044 * @param int|stdClass|coursecat $newparentcat
2046 public function change_parent($newparentcat) {
2047 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
2048 if (is_object($newparentcat)) {
2049 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
2051 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
2053 if ($newparentcat->id != $this->parent) {
2054 $this->change_parent_raw($newparentcat);
2055 fix_course_sortorder();
2056 cache_helper::purge_by_event('changesincoursecat');
2059 $event = \core\event\course_category_updated::create(array(
2060 'objectid' => $this->id,
2061 'context' => $this->get_context()
2063 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $this->id, $this->id));
2069 * Hide course category and child course and subcategories
2071 * If this category has changed the parent and is moved under hidden
2072 * category we will want to store it's current visibility state in
2073 * the field 'visibleold'. If admin clicked 'hide' for this particular
2074 * category, the field 'visibleold' should become 0.
2076 * All subcategories and courses will have their current visibility in the field visibleold
2078 * This is protected function, use hide() or update() from outside of this class
2080 * @see coursecat::hide()
2081 * @see coursecat::update()
2083 * @param int $visibleold value to set in field $visibleold for this category
2084 * @return bool whether changes have been made and caches need to be purged afterwards
2086 protected function hide_raw($visibleold = 0) {
2090 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing.
2091 if ($this->id && $this->__get('visibleold') != $visibleold) {
2092 $this->visibleold = $visibleold;
2093 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
2096 if (!$this->visible || !$this->id) {
2097 // Already hidden or can not be hidden.
2102 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
2103 // Store visible flag so that we can return to it if we immediately unhide.
2104 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id));
2105 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
2106 // Get all child categories and hide too.
2107 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
2108 foreach ($subcats as $cat) {
2109 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
2110 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
2111 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
2112 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
2119 * Hide course category and child course and subcategories
2121 * Note that there is no capability check inside this function
2123 * This function does not update field course_categories.timemodified
2124 * If you want to update timemodified, use
2125 * $coursecat->update(array('visible' => 0));
2127 public function hide() {
2128 if ($this->hide_raw(0)) {
2129 cache_helper::purge_by_event('changesincoursecat');
2131 $event = \core\event\course_category_updated::create(array(
2132 'objectid' => $this->id,
2133 'context' => $this->get_context()
2135 $event->set_legacy_logdata(array(SITEID, 'category', 'hide', 'editcategory.php?id=' . $this->id, $this->id));
2141 * Show course category and restores visibility for child course and subcategories
2143 * Note that there is no capability check inside this function
2145 * This is protected function, use show() or update() from outside of this class
2147 * @see coursecat::show()
2148 * @see coursecat::update()
2150 * @return bool whether changes have been made and caches need to be purged afterwards
2152 protected function show_raw() {
2155 if ($this->visible) {
2161 $this->visibleold = 1;
2162 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
2163 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
2164 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
2165 // Get all child categories and unhide too.
2166 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
2167 foreach ($subcats as $cat) {
2168 if ($cat->visibleold) {
2169 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
2171 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
2178 * Show course category and restores visibility for child course and subcategories
2180 * Note that there is no capability check inside this function
2182 * This function does not update field course_categories.timemodified
2183 * If you want to update timemodified, use
2184 * $coursecat->update(array('visible' => 1));
2186 public function show() {
2187 if ($this->show_raw()) {
2188 cache_helper::purge_by_event('changesincoursecat');
2190 $event = \core\event\course_category_updated::create(array(
2191 'objectid' => $this->id,
2192 'context' => $this->get_context()
2194 $event->set_legacy_logdata(array(SITEID, 'category', 'show', 'editcategory.php?id=' . $this->id, $this->id));
2200 * Returns name of the category formatted as a string
2202 * @param array $options formatting options other than context
2205 public function get_formatted_name($options = array()) {
2207 $context = $this->get_context();
2208 return format_string($this->name, true, array('context' => $context) + $options);
2210 return get_string('top');
2215 * Get the nested name of this category, with all of it's parents.
2217 * @param bool $includelinks Whether to wrap each name in the view link for that category.
2218 * @param string $separator The string between each name.
2219 * @param array $options Formatting options.
2222 public function get_nested_name($includelinks = true, $separator = ' / ', $options = []) {
2223 // Get the name of hierarchical name of this category.
2224 $parents = $this->get_parents();
2225 $categories = static::get_many($parents);
2226 $categories[] = $this;
2228 $names = array_map(function($category) use ($options, $includelinks) {
2229 if ($includelinks) {
2230 return html_writer::link($category->get_view_link(), $category->get_formatted_name($options));
2232 return $category->get_formatted_name($options);
2237 return implode($separator, $names);
2241 * Returns ids of all parents of the category. Last element in the return array is the direct parent
2243 * For example, if you have a tree of categories like:
2244 * Miscellaneous (id = 1)
2245 * Subcategory (id = 2)
2246 * Sub-subcategory (id = 4)
2247 * Other category (id = 3)
2249 * coursecat::get(1)->get_parents() == array()
2250 * coursecat::get(2)->get_parents() == array(1)
2251 * coursecat::get(4)->get_parents() == array(1, 2);
2253 * Note that this method does not check if all parents are accessible by current user
2255 * @return array of category ids
2257 public function get_parents() {
2258 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
2259 array_pop($parents);
2264 * This function returns a nice list representing category tree
2265 * for display or to use in a form <select> element
2267 * List is cached for 10 minutes
2269 * For example, if you have a tree of categories like:
2270 * Miscellaneous (id = 1)
2271 * Subcategory (id = 2)
2272 * Sub-subcategory (id = 4)
2273 * Other category (id = 3)
2274 * Then after calling this function you will have
2275 * array(1 => 'Miscellaneous',
2276 * 2 => 'Miscellaneous / Subcategory',
2277 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2278 * 3 => 'Other category');
2280 * If you specify $requiredcapability, then only categories where the current
2281 * user has that capability will be added to $list.
2282 * If you only have $requiredcapability in a child category, not the parent,
2283 * then the child catgegory will still be included.
2285 * If you specify the option $excludeid, then that category, and all its children,
2286 * are omitted from the tree. This is useful when you are doing something like
2287 * moving categories, where you do not want to allow people to move a category
2288 * to be the child of itself.
2290 * See also {@link make_categories_options()}
2292 * @param string/array $requiredcapability if given, only categories where the current
2293 * user has this capability will be returned. Can also be an array of capabilities,
2294 * in which case they are all required.
2295 * @param integer $excludeid Exclude this category and its children from the lists built.
2296 * @param string $separator string to use as a separator between parent and child category. Default ' / '
2297 * @return array of strings
2299 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
2301 $coursecatcache = cache::make('core', 'coursecat');
2303 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids
2304 // with requried cap ($thislist).
2305 $currentlang = current_language();
2306 $basecachekey = $currentlang . '_catlist';
2307 $baselist = $coursecatcache->get($basecachekey);
2309 $thiscachekey = null;
2310 if (!empty($requiredcapability)) {
2311 $requiredcapability = (array)$requiredcapability;
2312 $thiscachekey = 'catlist:'. serialize($requiredcapability);
2313 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
2314 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
2316 } else if ($baselist !== false) {
2317 $thislist = array_keys($baselist);
2320 if ($baselist === false) {
2321 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
2322 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2323 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
2324 FROM {course_categories} cc
2325 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
2326 ORDER BY cc.sortorder";
2327 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2328 $baselist = array();
2329 $thislist = array();
2330 foreach ($rs as $record) {
2331 // If the category's parent is not visible to the user, it is not visible as well.
2332 if (!$record->parent || isset($baselist[$record->parent])) {
2333 context_helper::preload_from_record($record);
2334 $context = context_coursecat::instance($record->id);
2335 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
2336 // No cap to view category, added to neither $baselist nor $thislist.
2339 $baselist[$record->id] = array(
2340 'name' => format_string($record->name, true, array('context' => $context)),
2341 'path' => $record->path
2343 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
2344 // No required capability, added to $baselist but not to $thislist.
2347 $thislist[] = $record->id;
2351 $coursecatcache->set($basecachekey, $baselist);
2352 if (!empty($requiredcapability)) {
2353 $coursecatcache->set($thiscachekey, join(',', $thislist));
2355 } else if ($thislist === false) {
2356 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
2357 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2358 $sql = "SELECT ctx.instanceid AS id, $ctxselect
2359 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
2360 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2361 $thislist = array();
2362 foreach (array_keys($baselist) as $id) {
2363 context_helper::preload_from_record($contexts[$id]);
2364 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
2368 $coursecatcache->set($thiscachekey, join(',', $thislist));
2371 // Now build the array of strings to return, mind $separator and $excludeid.
2373 foreach ($thislist as $id) {
2374 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
2375 if (!$excludeid || !in_array($excludeid, $path)) {
2376 $namechunks = array();
2377 foreach ($path as $parentid) {
2378 $namechunks[] = $baselist[$parentid]['name'];
2380 $names[$id] = join($separator, $namechunks);
2387 * Prepares the object for caching. Works like the __sleep method.
2389 * implementing method from interface cacheable_object
2391 * @return array ready to be cached
2393 public function prepare_to_cache() {
2395 foreach (self::$coursecatfields as $property => $cachedirectives) {
2396 if ($cachedirectives !== null) {
2397 list($shortname, $defaultvalue) = $cachedirectives;
2398 if ($this->$property !== $defaultvalue) {
2399 $a[$shortname] = $this->$property;
2403 $context = $this->get_context();
2404 $a['xi'] = $context->id;
2405 $a['xp'] = $context->path;
2410 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2412 * implementing method from interface cacheable_object
2417 public static function wake_from_cache($a) {
2418 $record = new stdClass;
2419 foreach (self::$coursecatfields as $property => $cachedirectives) {
2420 if ($cachedirectives !== null) {
2421 list($shortname, $defaultvalue) = $cachedirectives;
2422 if (array_key_exists($shortname, $a)) {
2423 $record->$property = $a[$shortname];
2425 $record->$property = $defaultvalue;
2429 $record->ctxid = $a['xi'];
2430 $record->ctxpath = $a['xp'];
2431 $record->ctxdepth = $record->depth + 1;
2432 $record->ctxlevel = CONTEXT_COURSECAT;
2433 $record->ctxinstance = $record->id;
2434 return new coursecat($record, true);
2438 * Returns true if the user is able to create a top level category.
2441 public static function can_create_top_level_category() {
2442 return has_capability('moodle/category:manage', context_system::instance());
2446 * Returns the category context.
2447 * @return context_coursecat
2449 public function get_context() {
2450 if ($this->id === 0) {
2451 // This is the special top level category object.
2452 return context_system::instance();
2454 return context_coursecat::instance($this->id);
2459 * Returns true if the user is able to manage this category.
2462 public function has_manage_capability() {
2463 if ($this->hasmanagecapability === null) {
2464 $this->hasmanagecapability = has_capability('moodle/category:manage', $this->get_context());
2466 return $this->hasmanagecapability;
2470 * Returns true if the user has the manage capability on the parent category.
2473 public function parent_has_manage_capability() {
2474 return has_capability('moodle/category:manage', get_category_or_system_context($this->parent));
2478 * Returns true if the current user can create subcategories of this category.
2481 public function can_create_subcategory() {
2482 return $this->has_manage_capability();
2486 * Returns true if the user can resort this categories sub categories and courses.
2487 * Must have manage capability and be able to see all subcategories.
2490 public function can_resort_subcategories() {
2491 return $this->has_manage_capability() && !$this->get_not_visible_children_ids();
2495 * Returns true if the user can resort the courses within this category.
2496 * Must have manage capability and be able to see all courses.
2499 public function can_resort_courses() {
2500 return $this->has_manage_capability() && $this->coursecount == $this->get_courses_count();
2504 * Returns true of the user can change the sortorder of this category (resort in the parent category)
2507 public function can_change_sortorder() {
2508 return $this->id && $this->get_parent_coursecat()->can_resort_subcategories();
2512 * Returns true if the current user can create a course within this category.
2515 public function can_create_course() {
2516 return has_capability('moodle/course:create', $this->get_context());
2520 * Returns true if the current user can edit this categories settings.
2523 public function can_edit() {
2524 return $this->has_manage_capability();
2528 * Returns true if the current user can review role assignments for this category.
2531 public function can_review_roles() {
2532 return has_capability('moodle/role:assign', $this->get_context());
2536 * Returns true if the current user can review permissions for this category.
2539 public function can_review_permissions() {
2540 return has_any_capability(array(
2541 'moodle/role:assign',
2542 'moodle/role:safeoverride',
2543 'moodle/role:override',
2544 'moodle/role:assign'
2545 ), $this->get_context());
2549 * Returns true if the current user can review cohorts for this category.
2552 public function can_review_cohorts() {
2553 return has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->get_context());
2557 * Returns true if the current user can review filter settings for this category.
2560 public function can_review_filters() {
2561 return has_capability('moodle/filter:manage', $this->get_context()) &&
2562 count(filter_get_available_in_context($this->get_context()))>0;
2566 * Returns true if the current user is able to change the visbility of this category.
2569 public function can_change_visibility() {
2570 return $this->parent_has_manage_capability();
2574 * Returns true if the user can move courses out of this category.
2577 public function can_move_courses_out_of() {
2578 return $this->has_manage_capability();
2582 * Returns true if the user can move courses into this category.
2585 public function can_move_courses_into() {
2586 return $this->has_manage_capability();
2590 * Returns true if the user is able to restore a course into this category as a new course.
2593 public function can_restore_courses_into() {
2594 return has_capability('moodle/restore:restorecourse', $this->get_context());
2598 * Resorts the sub categories of this category by the given field.
2600 * @param string $field One of name, idnumber or descending values of each (appended desc)
2601 * @param bool $cleanup If true cleanup will be done, if false you will need to do it manually later.
2602 * @return bool True on success.
2603 * @throws coding_exception
2605 public function resort_subcategories($field, $cleanup = true) {
2608 if (substr($field, -4) === "desc") {
2610 $field = substr($field, 0, -4); // Remove "desc" from field name.
2612 if ($field !== 'name' && $field !== 'idnumber') {
2613 throw new coding_exception('Invalid field requested');
2615 $children = $this->get_children();
2616 core_collator::asort_objects_by_property($children, $field, core_collator::SORT_NATURAL);
2617 if (!empty($desc)) {
2618 $children = array_reverse($children);
2621 foreach ($children as $cat) {
2623 $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id));
2624 $i += $cat->coursecount;
2627 self::resort_categories_cleanup();
2633 * Cleans things up after categories have been resorted.
2634 * @param bool $includecourses If set to true we know courses have been resorted as well.
2636 public static function resort_categories_cleanup($includecourses = false) {
2637 // This should not be needed but we do it just to be safe.
2638 fix_course_sortorder();
2639 cache_helper::purge_by_event('changesincoursecat');
2640 if ($includecourses) {
2641 cache_helper::purge_by_event('changesincourse');
2646 * Resort the courses within this category by the given field.
2648 * @param string $field One of fullname, shortname, idnumber or descending values of each (appended desc)
2649 * @param bool $cleanup
2650 * @return bool True for success.
2651 * @throws coding_exception
2653 public function resort_courses($field, $cleanup = true) {
2656 if (substr($field, -4) === "desc") {
2658 $field = substr($field, 0, -4); // Remove "desc" from field name.
2660 if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber' && $field !== 'timecreated') {
2661 // This is ultra important as we use $field in an SQL statement below this.
2662 throw new coding_exception('Invalid field requested');
2664 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
2665 $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields
2667 LEFT JOIN {context} ctx ON ctx.instanceid = c.id
2668 WHERE ctx.contextlevel = :ctxlevel AND
2669 c.category = :categoryid";
2671 'ctxlevel' => CONTEXT_COURSE,
2672 'categoryid' => $this->id
2674 $courses = $DB->get_records_sql($sql, $params);
2675 if (count($courses) > 0) {
2676 foreach ($courses as $courseid => $course) {
2677 context_helper::preload_from_record($course);
2678 if ($field === 'idnumber') {
2679 $course->sortby = $course->idnumber;
2681 // It'll require formatting.
2683 'context' => context_course::instance($course->id)
2685 // We format the string first so that it appears as the user would see it.
2686 // This ensures the sorting makes sense to them. However it won't necessarily make
2687 // sense to everyone if things like multilang filters are enabled.
2688 // We then strip any tags as we don't want things such as image tags skewing the
2690 $course->sortby = strip_tags(format_string($course->$field, true, $options));
2692 // We set it back here rather than using references as there is a bug with using
2693 // references in a foreach before passing as an arg by reference.
2694 $courses[$courseid] = $course;
2696 // Sort the courses.
2697 core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL);
2698 if (!empty($desc)) {
2699 $courses = array_reverse($courses);
2702 foreach ($courses as $course) {
2703 $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id));
2707 // This should not be needed but we do it just to be safe.
2708 fix_course_sortorder();
2709 cache_helper::purge_by_event('changesincourse');
2716 * Changes the sort order of this categories parent shifting this category up or down one.
2718 * @global \moodle_database $DB
2719 * @param bool $up If set to true the category is shifted up one spot, else its moved down.
2720 * @return bool True on success, false otherwise.
2722 public function change_sortorder_by_one($up) {
2724 $params = array($this->sortorder, $this->parent);
2726 $select = 'sortorder < ? AND parent = ?';
2727 $sort = 'sortorder DESC';
2729 $select = 'sortorder > ? AND parent = ?';
2730 $sort = 'sortorder ASC';
2732 fix_course_sortorder();
2733 $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1);
2734 $swapcategory = reset($swapcategory);
2735 if ($swapcategory) {
2736 $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id));
2737 $DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id));
2738 $this->sortorder = $swapcategory->sortorder;
2740 $event = \core\event\course_category_updated::create(array(
2741 'objectid' => $this->id,
2742 'context' => $this->get_context()
2744 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'management.php?categoryid=' . $this->id,
2748 // Finally reorder courses.
2749 fix_course_sortorder();
2750 cache_helper::purge_by_event('changesincoursecat');
2757 * Returns the parent coursecat object for this category.
2761 public function get_parent_coursecat() {
2762 return self::get($this->parent);
2767 * Returns true if the user is able to request a new course be created.
2770 public function can_request_course() {
2772 if (empty($CFG->enablecourserequests) || $this->id != $CFG->defaultrequestcategory) {
2775 return !$this->can_create_course() && has_capability('moodle/course:request', $this->get_context());
2779 * Returns true if the user can approve course requests.
2782 public static function can_approve_course_requests() {
2784 if (empty($CFG->enablecourserequests)) {
2787 $context = context_system::instance();
2788 if (!has_capability('moodle/site:approvecourse', $context)) {
2791 if (!$DB->record_exists('course_request', array())) {
2799 * Class to store information about one course in a list of courses
2801 * Not all information may be retrieved when object is created but
2802 * it will be retrieved on demand when appropriate property or method is
2805 * Instances of this class are usually returned by functions
2806 * {@link coursecat::search_courses()}
2808 * {@link coursecat::get_courses()}
2810 * @property-read int $id
2811 * @property-read int $category Category ID
2812 * @property-read int $sortorder
2813 * @property-read string $fullname
2814 * @property-read string $shortname
2815 * @property-read string $idnumber
2816 * @property-read string $summary Course summary. Field is present if coursecat::get_courses()
2817 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2818 * @property-read int $summaryformat Summary format. Field is present if coursecat::get_courses()
2819 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2820 * @property-read string $format Course format. Retrieved from DB on first request
2821 * @property-read int $showgrades Retrieved from DB on first request
2822 * @property-read int $newsitems Retrieved from DB on first request
2823 * @property-read int $startdate
2824 * @property-read int $enddate
2825 * @property-read int $marker Retrieved from DB on first request
2826 * @property-read int $maxbytes Retrieved from DB on first request
2827 * @property-read int $legacyfiles Retrieved from DB on first request
2828 * @property-read int $showreports Retrieved from DB on first request
2829 * @property-read int $visible
2830 * @property-read int $visibleold Retrieved from DB on first request
2831 * @property-read int $groupmode Retrieved from DB on first request
2832 * @property-read int $groupmodeforce Retrieved from DB on first request
2833 * @property-read int $defaultgroupingid Retrieved from DB on first request
2834 * @property-read string $lang Retrieved from DB on first request
2835 * @property-read string $theme Retrieved from DB on first request
2836 * @property-read int $timecreated Retrieved from DB on first request
2837 * @property-read int $timemodified Retrieved from DB on first request
2838 * @property-read int $requested Retrieved from DB on first request
2839 * @property-read int $enablecompletion Retrieved from DB on first request
2840 * @property-read int $completionnotify Retrieved from DB on first request
2841 * @property-read int $cacherev
2844 * @subpackage course
2845 * @copyright 2013 Marina Glancy
2846 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2848 class course_in_list implements IteratorAggregate {
2850 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2853 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2854 protected $coursecontacts;
2856 /** @var bool true if the current user can access the course, false otherwise. */
2857 protected $canaccess = null;
2860 * Creates an instance of the class from record
2862 * @param stdClass $record except fields from course table it may contain
2863 * field hassummary indicating that summary field is not empty.
2864 * Also it is recommended to have context fields here ready for
2865 * context preloading
2867 public function __construct(stdClass $record) {
2868 context_helper::preload_from_record($record);
2869 $this->record = new stdClass();
2870 foreach ($record as $key => $value) {
2871 $this->record->$key = $value;
2876 * Indicates if the course has non-empty summary field
2880 public function has_summary() {
2881 if (isset($this->record->hassummary)) {
2882 return !empty($this->record->hassummary);
2884 if (!isset($this->record->summary)) {
2885 // We need to retrieve summary.
2886 $this->__get('summary');
2888 return !empty($this->record->summary);
2892 * Indicates if the course have course contacts to display
2896 public function has_course_contacts() {
2897 if (!isset($this->record->managers)) {
2898 $courses = array($this->id => &$this->record);
2899 coursecat::preload_course_contacts($courses);
2901 return !empty($this->record->managers);
2905 * Returns list of course contacts (usually teachers) to display in course link
2907 * Roles to display are set up in $CFG->coursecontact
2909 * The result is the list of users where user id is the key and the value
2910 * is an array with elements:
2911 * - 'user' - object containing basic user information
2912 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2913 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2914 * - 'username' => fullname($user, $canviewfullnames)
2918 public function get_course_contacts() {
2920 if (empty($CFG->coursecontact)) {
2921 // No roles are configured to be displayed as course contacts.
2924 if ($this->coursecontacts === null) {
2925 $this->coursecontacts = array();
2926 $context = context_course::instance($this->id);
2928 if (!isset($this->record->managers)) {
2929 // Preload course contacts from DB.
2930 $courses = array($this->id => &$this->record);
2931 coursecat::preload_course_contacts($courses);
2934 // Build return array with full roles names (for this course context) and users names.
2935 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2936 foreach ($this->record->managers as $ruser) {
2937 if (isset($this->coursecontacts[$ruser->id])) {
2938 // Only display a user once with the highest sortorder role.
2941 $user = new stdClass();
2942 $user = username_load_fields_from_object($user, $ruser, null, array('id', 'username'));
2943 $role = new stdClass();
2944 $role->id = $ruser->roleid;
2945 $role->name = $ruser->rolename;
2946 $role->shortname = $ruser->roleshortname;
2947 $role->coursealias = $ruser->rolecoursealias;
2949 $this->coursecontacts[$user->id] = array(
2952 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2953 'username' => fullname($user, $canviewfullnames)
2957 return $this->coursecontacts;
2961 * Checks if course has any associated overview files
2965 public function has_course_overviewfiles() {
2967 if (empty($CFG->courseoverviewfileslimit)) {
2970 $fs = get_file_storage();
2971 $context = context_course::instance($this->id);
2972 return !$fs->is_area_empty($context->id, 'course', 'overviewfiles');
2976 * Returns all course overview files
2978 * @return array array of stored_file objects
2980 public function get_course_overviewfiles() {
2982 if (empty($CFG->courseoverviewfileslimit)) {
2985 require_once($CFG->libdir. '/filestorage/file_storage.php');
2986 require_once($CFG->dirroot. '/course/lib.php');
2987 $fs = get_file_storage();
2988 $context = context_course::instance($this->id);
2989 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2990 if (count($files)) {
2991 $overviewfilesoptions = course_overviewfiles_options($this->id);
2992 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2993 if ($acceptedtypes !== '*') {
2994 // Filter only files with allowed extensions.
2995 require_once($CFG->libdir. '/filelib.php');
2996 foreach ($files as $key => $file) {
2997 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2998 unset($files[$key]);
3002 if (count($files) > $CFG->courseoverviewfileslimit) {
3003 // Return no more than $CFG->courseoverviewfileslimit files.
3004 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
3011 * Magic method to check if property is set
3013 * @param string $name
3016 public function __isset($name) {
3017 return isset($this->record->$name);
3021 * Magic method to get a course property
3023 * Returns any field from table course (retrieves it from DB if it was not retrieved before)
3025 * @param string $name
3028 public function __get($name) {
3030 if (property_exists($this->record, $name)) {
3031 return $this->record->$name;
3032 } else if ($name === 'summary' || $name === 'summaryformat') {
3033 // Retrieve fields summary and summaryformat together because they are most likely to be used together.
3034 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
3035 $this->record->summary = $record->summary;
3036 $this->record->summaryformat = $record->summaryformat;
3037 return $this->record->$name;
3038 } else if (array_key_exists($name, $DB->get_columns('course'))) {
3039 // Another field from table 'course' that was not retrieved.
3040 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
3041 return $this->record->$name;
3043 debugging('Invalid course property accessed! '.$name);
3048 * All properties are read only, sorry.
3050 * @param string $name
3052 public function __unset($name) {
3053 debugging('Can not unset '.get_class($this).' instance properties!');
3057 * Magic setter method, we do not want anybody to modify properties from the outside
3059 * @param string $name
3060 * @param mixed $value
3062 public function __set($name, $value) {
3063 debugging('Can not change '.get_class($this).' instance properties!');
3067 * Create an iterator because magic vars can't be seen by 'foreach'.
3068 * Exclude context fields
3070 * Implementing method from interface IteratorAggregate
3072 * @return ArrayIterator
3074 public function getIterator() {
3075 $ret = array('id' => $this->record->id);
3076 foreach ($this->record as $property => $value) {
3077 $ret[$property] = $value;
3079 return new ArrayIterator($ret);
3083 * Returns the name of this course as it should be displayed within a list.
3086 public function get_formatted_name() {
3087 return format_string(get_course_display_name_for_list($this), true, $this->get_context());
3091 * Returns the formatted fullname for this course.
3094 public function get_formatted_fullname() {
3095 return format_string($this->__get('fullname'), true, $this->get_context());
3099 * Returns the formatted shortname for this course.
3102 public function get_formatted_shortname() {
3103 return format_string($this->__get('shortname'), true, $this->get_context());
3107 * Returns true if the current user can access this course.
3110 public function can_access() {
3111 if ($this->canaccess === null) {
3112 $this->canaccess = can_access_course($this->record);
3114 return $this->canaccess;
3118 * Returns true if the user can edit this courses settings.
3120 * Note: this function does not check that the current user can access the course.
3121 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3125 public function can_edit() {
3126 return has_capability('moodle/course:update', $this->get_context());
3130 * Returns true if the user can change the visibility of this course.
3132 * Note: this function does not check that the current user can access the course.
3133 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3137 public function can_change_visibility() {
3138 // You must be able to both hide a course and view the hidden course.
3139 return has_all_capabilities(array('moodle/course:visibility', 'moodle/course:viewhiddencourses'), $this->get_context());
3143 * Returns the context for this course.
3144 * @return context_course
3146 public function get_context() {
3147 return context_course::instance($this->__get('id'));
3151 * Returns true if this course is visible to the current user.
3154 public function is_uservisible() {
3155 return $this->visible || has_capability('moodle/course:viewhiddencourses', $this->get_context());
3159 * Returns true if the current user can review enrolments for this course.
3161 * Note: this function does not check that the current user can access the course.
3162 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3166 public function can_review_enrolments() {
3167 return has_capability('moodle/course:enrolreview', $this->get_context());
3171 * Returns true if the current user can delete this course.
3173 * Note: this function does not check that the current user can access the course.
3174 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3178 public function can_delete() {
3179 return can_delete_course($this->id);
3183 * Returns true if the current user can backup this course.
3185 * Note: this function does not check that the current user can access the course.
3186 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3190 public function can_backup() {
3191 return has_capability('moodle/backup:backupcourse', $this->get_context());
3195 * Returns true if the current user can restore this course.
3197 * Note: this function does not check that the current user can access the course.
3198 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3202 public function can_restore() {
3203 return has_capability('moodle/restore:restorecourse', $this->get_context());
3208 * An array of records that is sortable by many fields.
3210 * For more info on the ArrayObject class have a look at php.net.
3213 * @subpackage course
3214 * @copyright 2013 Sam Hemelryk
3215 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3217 class coursecat_sortable_records extends ArrayObject {
3220 * An array of sortable fields.
3221 * Gets set temporarily when sort is called.
3224 protected $sortfields = array();
3227 * Sorts this array using the given fields.
3229 * @param array $records
3230 * @param array $fields
3233 public static function sort(array $records, array $fields) {
3234 $records = new coursecat_sortable_records($records);
3235 $records->sortfields = $fields;
3236 $records->uasort(array($records, 'sort_by_many_fields'));
3237 return $records->getArrayCopy();
3241 * Sorts the two records based upon many fields.
3243 * This method should not be called itself, please call $sort instead.
3244 * It has been marked as access private as such.
3247 * @param stdClass $a
3248 * @param stdClass $b
3251 public function sort_by_many_fields($a, $b) {
3252 foreach ($this->sortfields as $field => $mult) {
3254 if (is_null($a->$field) && !is_null($b->$field)) {
3257 if (is_null($b->$field) && !is_null($a->$field)) {
3261 if (is_string($a->$field) || is_string($b->$field)) {
3263 if ($cmp = strcoll($a->$field, $b->$field)) {
3264 return $mult * $cmp;
3268 if ($a->$field > $b->$field) {
3271 if ($a->$field < $b->$field) {