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 * Returns the first found category
297 * Note that if there are no categories visible to the current user on the first level,
298 * the invisible category may be returned
302 public static function get_default() {
303 if ($visiblechildren = self::get(0)->get_children()) {
304 $defcategory = reset($visiblechildren);
306 $toplevelcategories = self::get_tree(0);
307 $defcategoryid = $toplevelcategories[0];
308 $defcategory = self::get($defcategoryid, MUST_EXIST, true);
314 * Restores the object after it has been externally modified in DB for example
315 * during {@link fix_course_sortorder()}
317 protected function restore() {
318 // Update all fields in the current object.
319 $newrecord = self::get($this->id, MUST_EXIST, true);
320 foreach (self::$coursecatfields as $key => $unused) {
321 $this->$key = $newrecord->$key;
326 * Creates a new category either from form data or from raw data
328 * Please note that this function does not verify access control.
330 * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
332 * Category visibility is inherited from parent unless $data->visible = 0 is specified
334 * @param array|stdClass $data
335 * @param array $editoroptions if specified, the data is considered to be
336 * form data and file_postupdate_standard_editor() is being called to
337 * process images in description.
339 * @throws moodle_exception
341 public static function create($data, $editoroptions = null) {
343 $data = (object)$data;
344 $newcategory = new stdClass();
346 $newcategory->descriptionformat = FORMAT_MOODLE;
347 $newcategory->description = '';
348 // Copy all description* fields regardless of whether this is form data or direct field update.
349 foreach ($data as $key => $value) {
350 if (preg_match("/^description/", $key)) {
351 $newcategory->$key = $value;
355 if (empty($data->name)) {
356 throw new moodle_exception('categorynamerequired');
358 if (core_text::strlen($data->name) > 255) {
359 throw new moodle_exception('categorytoolong');
361 $newcategory->name = $data->name;
363 // Validate and set idnumber.
364 if (isset($data->idnumber)) {
365 if (core_text::strlen($data->idnumber) > 100) {
366 throw new moodle_exception('idnumbertoolong');
368 if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
369 throw new moodle_exception('categoryidnumbertaken');
371 $newcategory->idnumber = $data->idnumber;
374 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
375 $newcategory->theme = $data->theme;
378 if (empty($data->parent)) {
379 $parent = self::get(0);
381 $parent = self::get($data->parent, MUST_EXIST, true);
383 $newcategory->parent = $parent->id;
384 $newcategory->depth = $parent->depth + 1;
386 // By default category is visible, unless visible = 0 is specified or parent category is hidden.
387 if (isset($data->visible) && !$data->visible) {
388 // Create a hidden category.
389 $newcategory->visible = $newcategory->visibleold = 0;
391 // Create a category that inherits visibility from parent.
392 $newcategory->visible = $parent->visible;
393 // In case parent is hidden, when it changes visibility this new subcategory will automatically become visible too.
394 $newcategory->visibleold = 1;
397 $newcategory->sortorder = 0;
398 $newcategory->timemodified = time();
400 $newcategory->id = $DB->insert_record('course_categories', $newcategory);
402 // Update path (only possible after we know the category id.
403 $path = $parent->path . '/' . $newcategory->id;
404 $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));
406 // We should mark the context as dirty.
407 context_coursecat::instance($newcategory->id)->mark_dirty();
409 fix_course_sortorder();
411 // If this is data from form results, save embedded files and update description.
412 $categorycontext = context_coursecat::instance($newcategory->id);
413 if ($editoroptions) {
414 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
415 'coursecat', 'description', 0);
417 // Update only fields description and descriptionformat.
418 $updatedata = new stdClass();
419 $updatedata->id = $newcategory->id;
420 $updatedata->description = $newcategory->description;
421 $updatedata->descriptionformat = $newcategory->descriptionformat;
422 $DB->update_record('course_categories', $updatedata);
425 $event = \core\event\course_category_created::create(array(
426 'objectid' => $newcategory->id,
427 'context' => $categorycontext
431 cache_helper::purge_by_event('changesincoursecat');
433 return self::get($newcategory->id, MUST_EXIST, true);
437 * Updates the record with either form data or raw data
439 * Please note that this function does not verify access control.
441 * This function calls coursecat::change_parent_raw if field 'parent' is updated.
442 * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
443 * Visibility is changed first and then parent is changed. This means that
444 * if parent category is hidden, the current category will become hidden
445 * too and it may overwrite whatever was set in field 'visible'.
447 * Note that fields 'path' and 'depth' can not be updated manually
448 * Also coursecat::update() can not directly update the field 'sortoder'
450 * @param array|stdClass $data
451 * @param array $editoroptions if specified, the data is considered to be
452 * form data and file_postupdate_standard_editor() is being called to
453 * process images in description.
454 * @throws moodle_exception
456 public function update($data, $editoroptions = null) {
459 // There is no actual DB record associated with root category.
463 $data = (object)$data;
464 $newcategory = new stdClass();
465 $newcategory->id = $this->id;
467 // Copy all description* fields regardless of whether this is form data or direct field update.
468 foreach ($data as $key => $value) {
469 if (preg_match("/^description/", $key)) {
470 $newcategory->$key = $value;
474 if (isset($data->name) && empty($data->name)) {
475 throw new moodle_exception('categorynamerequired');
478 if (!empty($data->name) && $data->name !== $this->name) {
479 if (core_text::strlen($data->name) > 255) {
480 throw new moodle_exception('categorytoolong');
482 $newcategory->name = $data->name;
485 if (isset($data->idnumber) && $data->idnumber !== $this->idnumber) {
486 if (core_text::strlen($data->idnumber) > 100) {
487 throw new moodle_exception('idnumbertoolong');
489 if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
490 throw new moodle_exception('categoryidnumbertaken');
492 $newcategory->idnumber = $data->idnumber;
495 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
496 $newcategory->theme = $data->theme;
500 if (isset($data->visible)) {
501 if ($data->visible) {
502 $changes = $this->show_raw();
504 $changes = $this->hide_raw(0);
508 if (isset($data->parent) && $data->parent != $this->parent) {
510 cache_helper::purge_by_event('changesincoursecat');
512 $parentcat = self::get($data->parent, MUST_EXIST, true);
513 $this->change_parent_raw($parentcat);
514 fix_course_sortorder();
517 $newcategory->timemodified = time();
519 $categorycontext = $this->get_context();
520 if ($editoroptions) {
521 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
522 'coursecat', 'description', 0);
524 $DB->update_record('course_categories', $newcategory);
526 $event = \core\event\course_category_updated::create(array(
527 'objectid' => $newcategory->id,
528 'context' => $categorycontext
532 fix_course_sortorder();
533 // Purge cache even if fix_course_sortorder() did not do it.
534 cache_helper::purge_by_event('changesincoursecat');
536 // Update all fields in the current object.
541 * Checks if this course category is visible to current user
543 * Please note that methods coursecat::get (without 3rd argumet),
544 * coursecat::get_children(), etc. return only visible categories so it is
545 * usually not needed to call this function outside of this class
549 public function is_uservisible() {
550 return !$this->id || $this->visible ||
551 has_capability('moodle/category:viewhiddencategories', $this->get_context());
555 * Returns the complete corresponding record from DB table course_categories
557 * Mostly used in deprecated functions
561 public function get_db_record() {
563 if ($record = $DB->get_record('course_categories', array('id' => $this->id))) {
566 return (object)convert_to_array($this);
571 * Returns the entry from categories tree and makes sure the application-level tree cache is built
573 * The following keys can be requested:
575 * 'countall' - total number of categories in the system (always present)
576 * 0 - array of ids of top-level categories (always present)
577 * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
578 * $id (int) - array of ids of categories that are direct children of category with id $id. If
579 * category with id $id does not exist returns false. If category has no children returns empty array
580 * $id.'i' - array of ids of children categories that have visible=0
582 * @param int|string $id
585 protected static function get_tree($id) {
587 $coursecattreecache = cache::make('core', 'coursecattree');
588 $rv = $coursecattreecache->get($id);
592 // Re-build the tree.
593 $sql = "SELECT cc.id, cc.parent, cc.visible
594 FROM {course_categories} cc
595 ORDER BY cc.sortorder";
596 $rs = $DB->get_recordset_sql($sql, array());
597 $all = array(0 => array(), '0i' => array());
599 foreach ($rs as $record) {
600 $all[$record->id] = array();
601 $all[$record->id. 'i'] = array();
602 if (array_key_exists($record->parent, $all)) {
603 $all[$record->parent][] = $record->id;
604 if (!$record->visible) {
605 $all[$record->parent. 'i'][] = $record->id;
608 // Parent not found. This is data consistency error but next fix_course_sortorder() should fix it.
609 $all[0][] = $record->id;
610 if (!$record->visible) {
611 $all['0i'][] = $record->id;
618 // No categories found.
619 // This may happen after upgrade of a very old moodle version.
620 // In new versions the default category is created on install.
621 $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
622 set_config('defaultrequestcategory', $defcoursecat->id);
623 $all[0] = array($defcoursecat->id);
624 $all[$defcoursecat->id] = array();
627 // We must add countall to all in case it was the requested ID.
628 $all['countall'] = $count;
629 $coursecattreecache->set_many($all);
630 if (array_key_exists($id, $all)) {
633 // Requested non-existing category.
638 * Returns number of ALL categories in the system regardless if
639 * they are visible to current user or not
643 public static function count_all() {
644 return self::get_tree('countall');
648 * Retrieves number of records from course_categories table
650 * Only cached fields are retrieved. Records are ready for preloading context
652 * @param string $whereclause
653 * @param array $params
654 * @return array array of stdClass objects
656 protected static function get_records($whereclause, $params) {
658 // Retrieve from DB only the fields that need to be stored in cache.
659 $fields = array_keys(array_filter(self::$coursecatfields));
660 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
661 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
662 FROM {course_categories} cc
663 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
664 WHERE ". $whereclause." ORDER BY cc.sortorder";
665 return $DB->get_records_sql($sql,
666 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
670 * Resets course contact caches when role assignments were changed
672 * @param int $roleid role id that was given or taken away
673 * @param context $context context where role assignment has been changed
675 public static function role_assignment_changed($roleid, $context) {
678 if ($context->contextlevel > CONTEXT_COURSE) {
679 // No changes to course contacts if role was assigned on the module/block level.
683 if (!$CFG->coursecontact || !in_array($roleid, explode(',', $CFG->coursecontact))) {
684 // The role is not one of course contact roles.
688 // Remove from cache course contacts of all affected courses.
689 $cache = cache::make('core', 'coursecontacts');
690 if ($context->contextlevel == CONTEXT_COURSE) {
691 $cache->delete($context->instanceid);
692 } else if ($context->contextlevel == CONTEXT_SYSTEM) {
695 $sql = "SELECT ctx.instanceid
697 WHERE ctx.path LIKE ? AND ctx.contextlevel = ?";
698 $params = array($context->path . '/%', CONTEXT_COURSE);
699 if ($courses = $DB->get_fieldset_sql($sql, $params)) {
700 $cache->delete_many($courses);
706 * Executed when user enrolment was changed to check if course
707 * contacts cache needs to be cleared
709 * @param int $courseid course id
710 * @param int $userid user id
711 * @param int $status new enrolment status (0 - active, 1 - suspended)
712 * @param int $timestart new enrolment time start
713 * @param int $timeend new enrolment time end
715 public static function user_enrolment_changed($courseid, $userid,
716 $status, $timestart = null, $timeend = null) {
717 $cache = cache::make('core', 'coursecontacts');
718 $contacts = $cache->get($courseid);
719 if ($contacts === false) {
720 // The contacts for the affected course were not cached anyway.
723 $enrolmentactive = ($status == 0) &&
724 (!$timestart || $timestart < time()) &&
725 (!$timeend || $timeend > time());
726 if (!$enrolmentactive) {
727 $isincontacts = false;
728 foreach ($contacts as $contact) {
729 if ($contact->id == $userid) {
730 $isincontacts = true;
733 if (!$isincontacts) {
734 // Changed user's enrolment does not exist or is not active,
735 // and he is not in cached course contacts, no changes to be made.
739 // Either enrolment of manager was deleted/suspended
740 // or user enrolment was added or activated.
741 // In order to see if the course contacts for this course need
742 // changing we would need to make additional queries, they will
743 // slow down bulk enrolment changes. It is better just to remove
744 // course contacts cache for this course.
745 $cache->delete($courseid);
749 * Given list of DB records from table course populates each record with list of users with course contact roles
751 * This function fills the courses with raw information as {@link get_role_users()} would do.
752 * See also {@link course_in_list::get_course_contacts()} for more readable return
754 * $courses[$i]->managers = array(
755 * $roleassignmentid => $roleuser,
759 * where $roleuser is an stdClass with the following properties:
761 * $roleuser->raid - role assignment id
762 * $roleuser->id - user id
763 * $roleuser->username
764 * $roleuser->firstname
765 * $roleuser->lastname
766 * $roleuser->rolecoursealias
767 * $roleuser->rolename
768 * $roleuser->sortorder - role sortorder
770 * $roleuser->roleshortname
772 * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
774 * @param array $courses
776 public static function preload_course_contacts(&$courses) {
778 if (empty($courses) || empty($CFG->coursecontact)) {
781 $managerroles = explode(',', $CFG->coursecontact);
782 $cache = cache::make('core', 'coursecontacts');
783 $cacheddata = $cache->get_many(array_keys($courses));
784 $courseids = array();
785 foreach (array_keys($courses) as $id) {
786 if ($cacheddata[$id] !== false) {
787 $courses[$id]->managers = $cacheddata[$id];
793 // Array $courseids now stores list of ids of courses for which we still need to retrieve contacts.
794 if (empty($courseids)) {
798 // First build the array of all context ids of the courses and their categories.
799 $allcontexts = array();
800 foreach ($courseids as $id) {
801 $context = context_course::instance($id);
802 $courses[$id]->managers = array();
803 foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
804 if (!isset($allcontexts[$ctxid])) {
805 $allcontexts[$ctxid] = array();
807 $allcontexts[$ctxid][] = $id;
811 // Fetch list of all users with course contact roles in any of the courses contexts or parent contexts.
812 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
813 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
814 list($sort, $sortparams) = users_order_by_sql('u');
815 $notdeleted = array('notdeleted'=>0);
816 $allnames = get_all_user_name_fields(true, 'u');
817 $sql = "SELECT ra.contextid, ra.id AS raid,
818 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
819 rn.name AS rolecoursealias, u.id, u.username, $allnames
820 FROM {role_assignments} ra
821 JOIN {user} u ON ra.userid = u.id
822 JOIN {role} r ON ra.roleid = r.id
823 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
824 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
825 ORDER BY r.sortorder, $sort";
826 $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
827 $checkenrolments = array();
828 foreach ($rs as $ra) {
829 foreach ($allcontexts[$ra->contextid] as $id) {
830 $courses[$id]->managers[$ra->raid] = $ra;
831 if (!isset($checkenrolments[$id])) {
832 $checkenrolments[$id] = array();
834 $checkenrolments[$id][] = $ra->id;
839 // Remove from course contacts users who are not enrolled in the course.
840 $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
841 foreach ($checkenrolments as $id => $userids) {
842 if (empty($enrolleduserids[$id])) {
843 $courses[$id]->managers = array();
844 } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
845 foreach ($courses[$id]->managers as $raid => $ra) {
846 if (in_array($ra->id, $notenrolled)) {
847 unset($courses[$id]->managers[$raid]);
855 foreach ($courseids as $id) {
856 $values[$id] = $courses[$id]->managers;
858 $cache->set_many($values);
862 * Verify user enrollments for multiple course-user combinations
864 * @param array $courseusers array where keys are course ids and values are array
865 * of users in this course whose enrolment we wish to verify
866 * @return array same structure as input array but values list only users from input
867 * who are enrolled in the course
869 protected static function ensure_users_enrolled($courseusers) {
871 // If the input array is too big, split it into chunks.
872 $maxcoursesinquery = 20;
873 if (count($courseusers) > $maxcoursesinquery) {
875 for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
876 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
877 $rv = $rv + self::ensure_users_enrolled($chunk);
882 // Create a query verifying valid user enrolments for the number of courses.
883 $sql = "SELECT DISTINCT e.courseid, ue.userid
884 FROM {user_enrolments} ue
885 JOIN {enrol} e ON e.id = ue.enrolid
886 WHERE ue.status = :active
887 AND e.status = :enabled
888 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
889 $now = round(time(), -2); // Rounding helps caching in DB.
890 $params = array('enabled' => ENROL_INSTANCE_ENABLED,
891 'active' => ENROL_USER_ACTIVE,
892 'now1' => $now, 'now2' => $now);
896 foreach ($courseusers as $id => $userids) {
897 $enrolled[$id] = array();
898 if (count($userids)) {
899 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
900 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
901 $params = $params + array('courseid'.$cnt => $id) + $params2;
905 if (count($subsqls)) {
906 $sql .= "AND (". join(' OR ', $subsqls).")";
907 $rs = $DB->get_recordset_sql($sql, $params);
908 foreach ($rs as $record) {
909 $enrolled[$record->courseid][] = $record->userid;
917 * Retrieves number of records from course table
919 * Not all fields are retrieved. Records are ready for preloading context
921 * @param string $whereclause
922 * @param array $params
923 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
924 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
925 * on not visible courses
926 * @return array array of stdClass objects
928 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
930 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
931 $fields = array('c.id', 'c.category', 'c.sortorder',
932 'c.shortname', 'c.fullname', 'c.idnumber',
933 'c.startdate', 'c.enddate', 'c.visible', 'c.cacherev');
934 if (!empty($options['summary'])) {
935 $fields[] = 'c.summary';
936 $fields[] = 'c.summaryformat';
938 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
940 $sql = "SELECT ". join(',', $fields). ", $ctxselect
942 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
943 WHERE ". $whereclause." ORDER BY c.sortorder";
944 $list = $DB->get_records_sql($sql,
945 array('contextcourse' => CONTEXT_COURSE) + $params);
947 if ($checkvisibility) {
948 // Loop through all records and make sure we only return the courses accessible by user.
949 foreach ($list as $course) {
950 if (isset($list[$course->id]->hassummary)) {
951 $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
953 if (empty($course->visible)) {
954 // Load context only if we need to check capability.
955 context_helper::preload_from_record($course);
956 if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
957 unset($list[$course->id]);
963 // Preload course contacts if necessary.
964 if (!empty($options['coursecontacts'])) {
965 self::preload_course_contacts($list);
971 * Returns array of ids of children categories that current user can not see
973 * This data is cached in user session cache
977 protected function get_not_visible_children_ids() {
979 $coursecatcache = cache::make('core', 'coursecat');
980 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
981 // We never checked visible children before.
982 $hidden = self::get_tree($this->id.'i');
983 $invisibleids = array();
985 // Preload categories contexts.
986 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
987 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
988 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
989 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
990 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
991 foreach ($contexts as $record) {
992 context_helper::preload_from_record($record);
994 // Check that user has 'viewhiddencategories' capability for each hidden category.
995 foreach ($hidden as $id) {
996 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
997 $invisibleids[] = $id;
1001 $coursecatcache->set('ic'. $this->id, $invisibleids);
1003 return $invisibleids;
1007 * Sorts list of records by several fields
1009 * @param array $records array of stdClass objects
1010 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
1013 protected static function sort_records(&$records, $sortfields) {
1014 if (empty($records)) {
1017 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname).
1018 if (array_key_exists('displayname', $sortfields)) {
1019 foreach ($records as $key => $record) {
1020 if (!isset($record->displayname)) {
1021 $records[$key]->displayname = get_course_display_name_for_list($record);
1025 // Sorting by one field - use core_collator.
1026 if (count($sortfields) == 1) {
1027 $property = key($sortfields);
1028 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
1029 $sortflag = core_collator::SORT_NUMERIC;
1030 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
1031 $sortflag = core_collator::SORT_STRING;
1033 $sortflag = core_collator::SORT_REGULAR;
1035 core_collator::asort_objects_by_property($records, $property, $sortflag);
1036 if ($sortfields[$property] < 0) {
1037 $records = array_reverse($records, true);
1041 $records = coursecat_sortable_records::sort($records, $sortfields);
1045 * Returns array of children categories visible to the current user
1047 * @param array $options options for retrieving children
1048 * - sort - list of fields to sort. Example
1049 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
1050 * will sort by idnumber asc, name asc and id desc.
1051 * Default: array('sortorder' => 1)
1052 * Only cached fields may be used for sorting!
1054 * - limit - maximum number of children to return, 0 or null for no limit
1055 * @return coursecat[] Array of coursecat objects indexed by category id
1057 public function get_children($options = array()) {
1059 $coursecatcache = cache::make('core', 'coursecat');
1061 // Get default values for options.
1062 if (!empty($options['sort']) && is_array($options['sort'])) {
1063 $sortfields = $options['sort'];
1065 $sortfields = array('sortorder' => 1);
1068 if (!empty($options['limit']) && (int)$options['limit']) {
1069 $limit = (int)$options['limit'];
1072 if (!empty($options['offset']) && (int)$options['offset']) {
1073 $offset = (int)$options['offset'];
1076 // First retrieve list of user-visible and sorted children ids from cache.
1077 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
1078 if ($sortedids === false) {
1079 $sortfieldskeys = array_keys($sortfields);
1080 if ($sortfieldskeys[0] === 'sortorder') {
1081 // No DB requests required to build the list of ids sorted by sortorder.
1082 // We can easily ignore other sort fields because sortorder is always different.
1083 $sortedids = self::get_tree($this->id);
1084 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
1085 $sortedids = array_diff($sortedids, $invisibleids);
1086 if ($sortfields['sortorder'] == -1) {
1087 $sortedids = array_reverse($sortedids, true);
1091 // We need to retrieve and sort all children. Good thing that it is done only on first request.
1092 if ($invisibleids = $this->get_not_visible_children_ids()) {
1093 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
1094 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
1095 array('parent' => $this->id) + $params);
1097 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
1099 self::sort_records($records, $sortfields);
1100 $sortedids = array_keys($records);
1102 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
1105 if (empty($sortedids)) {
1109 // Now retrieive and return categories.
1110 if ($offset || $limit) {
1111 $sortedids = array_slice($sortedids, $offset, $limit);
1113 if (isset($records)) {
1114 // Easy, we have already retrieved records.
1115 if ($offset || $limit) {
1116 $records = array_slice($records, $offset, $limit, true);
1119 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
1120 $records = self::get_records('cc.id '. $sql, array('parent' => $this->id) + $params);
1124 foreach ($sortedids as $id) {
1125 if (isset($records[$id])) {
1126 $rv[$id] = new coursecat($records[$id]);
1133 * Returns true if the user has the manage capability on any category.
1135 * This method uses the coursecat cache and an entry `has_manage_capability` to speed up
1136 * calls to this method.
1140 public static function has_manage_capability_on_any() {
1141 return self::has_capability_on_any('moodle/category:manage');
1145 * Checks if the user has at least one of the given capabilities on any category.
1147 * @param array|string $capabilities One or more capabilities to check. Check made is an OR.
1150 public static function has_capability_on_any($capabilities) {
1152 if (!isloggedin() || isguestuser()) {
1156 if (!is_array($capabilities)) {
1157 $capabilities = array($capabilities);
1160 foreach ($capabilities as $capability) {
1161 $keys[$capability] = sha1($capability);
1164 /* @var cache_session $cache */
1165 $cache = cache::make('core', 'coursecat');
1166 $hascapability = $cache->get_many($keys);
1167 $needtoload = false;
1168 foreach ($hascapability as $capability) {
1169 if ($capability === '1') {
1171 } else if ($capability === false) {
1175 if ($needtoload === false) {
1176 // All capabilities were retrieved and the user didn't have any.
1181 $fields = context_helper::get_preload_record_columns_sql('ctx');
1182 $sql = "SELECT ctx.instanceid AS categoryid, $fields
1184 WHERE contextlevel = :contextlevel
1185 ORDER BY depth ASC";
1186 $params = array('contextlevel' => CONTEXT_COURSECAT);
1187 $recordset = $DB->get_recordset_sql($sql, $params);
1188 foreach ($recordset as $context) {
1189 context_helper::preload_from_record($context);
1190 $context = context_coursecat::instance($context->categoryid);
1191 foreach ($capabilities as $capability) {
1192 if (has_capability($capability, $context)) {
1193 $haskey = $capability;
1198 $recordset->close();
1199 if ($haskey === null) {
1201 foreach ($keys as $key) {
1204 $cache->set_many($data);
1207 $cache->set($haskey, '1');
1213 * Returns true if the user can resort any category.
1216 public static function can_resort_any() {
1217 return self::has_manage_capability_on_any();
1221 * Returns true if the user can change the parent of any category.
1224 public static function can_change_parent_any() {
1225 return self::has_manage_capability_on_any();
1229 * Returns number of subcategories visible to the current user
1233 public function get_children_count() {
1234 $sortedids = self::get_tree($this->id);
1235 $invisibleids = $this->get_not_visible_children_ids();
1236 return count($sortedids) - count($invisibleids);
1240 * Returns true if the category has ANY children, including those not visible to the user
1244 public function has_children() {
1245 $allchildren = self::get_tree($this->id);
1246 return !empty($allchildren);
1250 * Returns true if the category has courses in it (count does not include courses
1251 * in child categories)
1255 public function has_courses() {
1257 return $DB->record_exists_sql("select 1 from {course} where category = ?",
1264 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1265 * to this when somebody edits courses or categories, however it is very
1266 * difficult to keep track of all possible changes that may affect list of courses.
1268 * @param array $search contains search criterias, such as:
1269 * - search - search string
1270 * - blocklist - id of block (if we are searching for courses containing specific block0
1271 * - modulelist - name of module (if we are searching for courses containing specific module
1272 * - tagid - id of tag
1273 * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
1274 * search is always category-independent
1275 * @param array $requiredcapabilites List of capabilities required to see return course.
1276 * @return course_in_list[]
1278 public static function search_courses($search, $options = array(), $requiredcapabilities = array()) {
1280 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1281 $limit = !empty($options['limit']) ? $options['limit'] : null;
1282 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1284 $coursecatcache = cache::make('core', 'coursecat');
1285 $cachekey = 's-'. serialize(
1286 $search + array('sort' => $sortfields) + array('requiredcapabilities' => $requiredcapabilities)
1288 $cntcachekey = 'scnt-'. serialize($search);
1290 $ids = $coursecatcache->get($cachekey);
1291 if ($ids !== false) {
1292 // We already cached last search result.
1293 $ids = array_slice($ids, $offset, $limit);
1296 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1297 $records = self::get_course_records("c.id ". $sql, $params, $options);
1298 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1299 if (!empty($options['coursecontacts'])) {
1300 self::preload_course_contacts($records);
1302 // If option 'idonly' is specified no further action is needed, just return list of ids.
1303 if (!empty($options['idonly'])) {
1304 return array_keys($records);
1306 // Prepare the list of course_in_list objects.
1307 foreach ($ids as $id) {
1308 $courses[$id] = new course_in_list($records[$id]);
1314 $preloadcoursecontacts = !empty($options['coursecontacts']);
1315 unset($options['coursecontacts']);
1317 // Empty search string will return all results.
1318 if (!isset($search['search'])) {
1319 $search['search'] = '';
1322 if (empty($search['blocklist']) && empty($search['modulelist']) && empty($search['tagid'])) {
1323 // Search courses that have specified words in their names/summaries.
1324 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1326 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount, $requiredcapabilities);
1327 self::sort_records($courselist, $sortfields);
1328 $coursecatcache->set($cachekey, array_keys($courselist));
1329 $coursecatcache->set($cntcachekey, $totalcount);
1330 $records = array_slice($courselist, $offset, $limit, true);
1332 if (!empty($search['blocklist'])) {
1333 // Search courses that have block with specified id.
1334 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1335 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1336 WHERE bi.blockname = :blockname)';
1337 $params = array('blockname' => $blockname);
1338 } else if (!empty($search['modulelist'])) {
1339 // Search courses that have module with specified name.
1340 $where = "c.id IN (SELECT DISTINCT module.course ".
1341 "FROM {".$search['modulelist']."} module)";
1343 } else if (!empty($search['tagid'])) {
1344 // Search courses that are tagged with the specified tag.
1345 $where = "c.id IN (SELECT t.itemid ".
1346 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype AND t.component = :component)";
1347 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course', 'component' => 'core');
1348 if (!empty($search['ctx'])) {
1349 $rec = isset($search['rec']) ? $search['rec'] : true;
1350 $parentcontext = context::instance_by_id($search['ctx']);
1351 if ($parentcontext->contextlevel == CONTEXT_SYSTEM && $rec) {
1352 // Parent context is system context and recursive is set to yes.
1353 // Nothing to filter - all courses fall into this condition.
1355 // Filter all courses in the parent context at any level.
1356 $where .= ' AND ctx.path LIKE :contextpath';
1357 $params['contextpath'] = $parentcontext->path . '%';
1358 } else if ($parentcontext->contextlevel == CONTEXT_COURSECAT) {
1359 // All courses in the given course category.
1360 $where .= ' AND c.category = :category';
1361 $params['category'] = $parentcontext->instanceid;
1363 // No courses will satisfy the context criterion, do not bother searching.
1368 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1371 $courselist = self::get_course_records($where, $params, $options, true);
1372 if (!empty($requiredcapabilities)) {
1373 foreach ($courselist as $key => $course) {
1374 context_helper::preload_from_record($course);
1375 $coursecontext = context_course::instance($course->id);
1376 if (!has_all_capabilities($requiredcapabilities, $coursecontext)) {
1377 unset($courselist[$key]);
1381 self::sort_records($courselist, $sortfields);
1382 $coursecatcache->set($cachekey, array_keys($courselist));
1383 $coursecatcache->set($cntcachekey, count($courselist));
1384 $records = array_slice($courselist, $offset, $limit, true);
1387 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1388 if (!empty($preloadcoursecontacts)) {
1389 self::preload_course_contacts($records);
1391 // If option 'idonly' is specified no further action is needed, just return list of ids.
1392 if (!empty($options['idonly'])) {
1393 return array_keys($records);
1395 // Prepare the list of course_in_list objects.
1397 foreach ($records as $record) {
1398 $courses[$record->id] = new course_in_list($record);
1404 * Returns number of courses in the search results
1406 * It is recommended to call this function after {@link coursecat::search_courses()}
1407 * and not before because only course ids are cached. Otherwise search_courses() may
1408 * perform extra DB queries.
1410 * @param array $search search criteria, see method search_courses() for more details
1411 * @param array $options display options. They do not affect the result but
1412 * the 'sort' property is used in cache key for storing list of course ids
1413 * @param array $requiredcapabilites List of capabilities required to see return course.
1416 public static function search_courses_count($search, $options = array(), $requiredcapabilities = array()) {
1417 $coursecatcache = cache::make('core', 'coursecat');
1418 $cntcachekey = 'scnt-'. serialize($search) . serialize($requiredcapabilities);
1419 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1420 // Cached value not found. Retrieve ALL courses and return their count.
1421 unset($options['offset']);
1422 unset($options['limit']);
1423 unset($options['summary']);
1424 unset($options['coursecontacts']);
1425 $options['idonly'] = true;
1426 $courses = self::search_courses($search, $options, $requiredcapabilities);
1427 $cnt = count($courses);
1433 * Retrieves the list of courses accessible by user
1435 * Not all information is cached, try to avoid calling this method
1436 * twice in the same request.
1438 * The following fields are always retrieved:
1439 * - id, visible, fullname, shortname, idnumber, category, sortorder
1441 * If you plan to use properties/methods course_in_list::$summary and/or
1442 * course_in_list::get_course_contacts()
1443 * you can preload this information using appropriate 'options'. Otherwise
1444 * they will be retrieved from DB on demand and it may end with bigger DB load.
1446 * Note that method course_in_list::has_summary() will not perform additional
1447 * DB queries even if $options['summary'] is not specified
1449 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1450 * to this when somebody edits courses or categories, however it is very
1451 * difficult to keep track of all possible changes that may affect list of courses.
1453 * @param array $options options for retrieving children
1454 * - recursive - return courses from subcategories as well. Use with care,
1455 * this may be a huge list!
1456 * - summary - preloads fields 'summary' and 'summaryformat'
1457 * - coursecontacts - preloads course contacts
1458 * - sort - list of fields to sort. Example
1459 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1460 * will sort by idnumber asc, shortname asc and id desc.
1461 * Default: array('sortorder' => 1)
1462 * Only cached fields may be used for sorting!
1464 * - limit - maximum number of children to return, 0 or null for no limit
1465 * - idonly - returns the array or course ids instead of array of objects
1466 * used only in get_courses_count()
1467 * @return course_in_list[]
1469 public function get_courses($options = array()) {
1471 $recursive = !empty($options['recursive']);
1472 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1473 $limit = !empty($options['limit']) ? $options['limit'] : null;
1474 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1476 // Check if this category is hidden.
1477 // Also 0-category never has courses unless this is recursive call.
1478 if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1482 $coursecatcache = cache::make('core', 'coursecat');
1483 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1484 '-'. serialize($sortfields);
1485 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1487 // Check if we have already cached results.
1488 $ids = $coursecatcache->get($cachekey);
1489 if ($ids !== false) {
1490 // We already cached last search result and it did not expire yet.
1491 $ids = array_slice($ids, $offset, $limit);
1494 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1495 $records = self::get_course_records("c.id ". $sql, $params, $options);
1496 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1497 if (!empty($options['coursecontacts'])) {
1498 self::preload_course_contacts($records);
1500 // If option 'idonly' is specified no further action is needed, just return list of ids.
1501 if (!empty($options['idonly'])) {
1502 return array_keys($records);
1504 // Prepare the list of course_in_list objects.
1505 foreach ($ids as $id) {
1506 $courses[$id] = new course_in_list($records[$id]);
1512 // Retrieve list of courses in category.
1513 $where = 'c.id <> :siteid';
1514 $params = array('siteid' => SITEID);
1517 $context = context_coursecat::instance($this->id);
1518 $where .= ' AND ctx.path like :path';
1519 $params['path'] = $context->path. '/%';
1522 $where .= ' AND c.category = :categoryid';
1523 $params['categoryid'] = $this->id;
1525 // Get list of courses without preloaded coursecontacts because we don't need them for every course.
1526 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1528 // Sort and cache list.
1529 self::sort_records($list, $sortfields);
1530 $coursecatcache->set($cachekey, array_keys($list));
1531 $coursecatcache->set($cntcachekey, count($list));
1533 // Apply offset/limit, convert to course_in_list and return.
1536 if ($offset || $limit) {
1537 $list = array_slice($list, $offset, $limit, true);
1539 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1540 if (!empty($options['coursecontacts'])) {
1541 self::preload_course_contacts($list);
1543 // If option 'idonly' is specified no further action is needed, just return list of ids.
1544 if (!empty($options['idonly'])) {
1545 return array_keys($list);
1547 // Prepare the list of course_in_list objects.
1548 foreach ($list as $record) {
1549 $courses[$record->id] = new course_in_list($record);
1556 * Returns number of courses visible to the user
1558 * @param array $options similar to get_courses() except some options do not affect
1559 * number of courses (i.e. sort, summary, offset, limit etc.)
1562 public function get_courses_count($options = array()) {
1563 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1564 $coursecatcache = cache::make('core', 'coursecat');
1565 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1566 // Cached value not found. Retrieve ALL courses and return their count.
1567 unset($options['offset']);
1568 unset($options['limit']);
1569 unset($options['summary']);
1570 unset($options['coursecontacts']);
1571 $options['idonly'] = true;
1572 $courses = $this->get_courses($options);
1573 $cnt = count($courses);
1579 * Returns true if the user is able to delete this category.
1581 * Note if this category contains any courses this isn't a full check, it will need to be accompanied by a call to either
1582 * {@link coursecat::can_delete_full()} or {@link coursecat::can_move_content_to()} depending upon what the user wished to do.
1586 public function can_delete() {
1587 if (!$this->has_manage_capability()) {
1590 return $this->parent_has_manage_capability();
1594 * Returns true if user can delete current category and all its contents
1596 * To be able to delete course category the user must have permission
1597 * 'moodle/category:manage' in ALL child course categories AND
1598 * be able to delete all courses
1602 public function can_delete_full() {
1609 $context = $this->get_context();
1610 if (!$this->is_uservisible() ||
1611 !has_capability('moodle/category:manage', $context)) {
1615 // Check all child categories (not only direct children).
1616 $sql = context_helper::get_preload_record_columns_sql('ctx');
1617 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1618 ' FROM {context} ctx '.
1619 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1620 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1621 array($context->path. '/%', CONTEXT_COURSECAT));
1622 foreach ($childcategories as $childcat) {
1623 context_helper::preload_from_record($childcat);
1624 $childcontext = context_coursecat::instance($childcat->id);
1625 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1626 !has_capability('moodle/category:manage', $childcontext)) {
1632 $sql = context_helper::get_preload_record_columns_sql('ctx');
1633 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1634 $sql. ' FROM {context} ctx '.
1635 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1636 array('pathmask' => $context->path. '/%',
1637 'courselevel' => CONTEXT_COURSE));
1638 foreach ($coursescontexts as $ctxrecord) {
1639 context_helper::preload_from_record($ctxrecord);
1640 if (!can_delete_course($ctxrecord->courseid)) {
1649 * Recursively delete category including all subcategories and courses
1651 * Function {@link coursecat::can_delete_full()} MUST be called prior
1652 * to calling this function because there is no capability check
1653 * inside this function
1655 * @param boolean $showfeedback display some notices
1656 * @return array return deleted courses
1657 * @throws moodle_exception
1659 public function delete_full($showfeedback = true) {
1662 require_once($CFG->libdir.'/gradelib.php');
1663 require_once($CFG->libdir.'/questionlib.php');
1664 require_once($CFG->dirroot.'/cohort/lib.php');
1666 // Make sure we won't timeout when deleting a lot of courses.
1667 $settimeout = core_php_time_limit::raise();
1669 // Allow plugins to use this category before we completely delete it.
1670 if ($pluginsfunction = get_plugins_with_function('pre_course_category_delete')) {
1671 $category = $this->get_db_record();
1672 foreach ($pluginsfunction as $plugintype => $plugins) {
1673 foreach ($plugins as $pluginfunction) {
1674 $pluginfunction($category);
1679 $deletedcourses = array();
1681 // Get children. Note, we don't want to use cache here because it would be rebuilt too often.
1682 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1683 foreach ($children as $record) {
1684 $coursecat = new coursecat($record);
1685 $deletedcourses += $coursecat->delete_full($showfeedback);
1688 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1689 foreach ($courses as $course) {
1690 if (!delete_course($course, false)) {
1691 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1693 $deletedcourses[] = $course;
1697 // Move or delete cohorts in this context.
1698 cohort_delete_category($this);
1700 // Now delete anything that may depend on course category context.
1701 grade_course_category_delete($this->id, 0, $showfeedback);
1702 if (!question_delete_course_category($this, 0, $showfeedback)) {
1703 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1706 // Finally delete the category and it's context.
1707 $DB->delete_records('course_categories', array('id' => $this->id));
1709 $coursecatcontext = context_coursecat::instance($this->id);
1710 $coursecatcontext->delete();
1712 cache_helper::purge_by_event('changesincoursecat');
1714 // Trigger a course category deleted event.
1715 /* @var \core\event\course_category_deleted $event */
1716 $event = \core\event\course_category_deleted::create(array(
1717 'objectid' => $this->id,
1718 'context' => $coursecatcontext,
1719 'other' => array('name' => $this->name)
1721 $event->set_coursecat($this);
1724 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1725 if ($this->id == $CFG->defaultrequestcategory) {
1726 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1728 return $deletedcourses;
1732 * Checks if user can delete this category and move content (courses, subcategories and questions)
1733 * to another category. If yes returns the array of possible target categories names
1735 * If user can not manage this category or it is completely empty - empty array will be returned
1739 public function move_content_targets_list() {
1741 require_once($CFG->libdir . '/questionlib.php');
1742 $context = $this->get_context();
1743 if (!$this->is_uservisible() ||
1744 !has_capability('moodle/category:manage', $context)) {
1745 // User is not able to manage current category, he is not able to delete it.
1746 // No possible target categories.
1750 $testcaps = array();
1751 // If this category has courses in it, user must have 'course:create' capability in target category.
1752 if ($this->has_courses()) {
1753 $testcaps[] = 'moodle/course:create';
1755 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1756 if ($this->has_children() || question_context_has_any_questions($context)) {
1757 $testcaps[] = 'moodle/category:manage';
1759 if (!empty($testcaps)) {
1760 // Return list of categories excluding this one and it's children.
1761 return self::make_categories_list($testcaps, $this->id);
1764 // Category is completely empty, no need in target for contents.
1769 * Checks if user has capability to move all category content to the new parent before
1770 * removing this category
1772 * @param int $newcatid
1775 public function can_move_content_to($newcatid) {
1777 require_once($CFG->libdir . '/questionlib.php');
1778 $context = $this->get_context();
1779 if (!$this->is_uservisible() ||
1780 !has_capability('moodle/category:manage', $context)) {
1783 $testcaps = array();
1784 // If this category has courses in it, user must have 'course:create' capability in target category.
1785 if ($this->has_courses()) {
1786 $testcaps[] = 'moodle/course:create';
1788 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1789 if ($this->has_children() || question_context_has_any_questions($context)) {
1790 $testcaps[] = 'moodle/category:manage';
1792 if (!empty($testcaps)) {
1793 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1796 // There is no content but still return true.
1801 * Deletes a category and moves all content (children, courses and questions) to the new parent
1803 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1804 * must be called prior
1806 * @param int $newparentid
1807 * @param bool $showfeedback
1810 public function delete_move($newparentid, $showfeedback = false) {
1811 global $CFG, $DB, $OUTPUT;
1813 require_once($CFG->libdir.'/gradelib.php');
1814 require_once($CFG->libdir.'/questionlib.php');
1815 require_once($CFG->dirroot.'/cohort/lib.php');
1817 // Get all objects and lists because later the caches will be reset so.
1818 // We don't need to make extra queries.
1819 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1820 $catname = $this->get_formatted_name();
1821 $children = $this->get_children();
1822 $params = array('category' => $this->id);
1823 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', $params);
1824 $context = $this->get_context();
1827 foreach ($children as $childcat) {
1828 $childcat->change_parent_raw($newparentcat);
1830 $event = \core\event\course_category_updated::create(array(
1831 'objectid' => $childcat->id,
1832 'context' => $childcat->get_context()
1834 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $childcat->id,
1838 fix_course_sortorder();
1842 require_once($CFG->dirroot.'/course/lib.php');
1843 if (!move_courses($coursesids, $newparentid)) {
1844 if ($showfeedback) {
1845 echo $OUTPUT->notification("Error moving courses");
1849 if ($showfeedback) {
1850 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1854 // Move or delete cohorts in this context.
1855 cohort_delete_category($this);
1857 // Now delete anything that may depend on course category context.
1858 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1859 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1860 if ($showfeedback) {
1861 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1866 // Finally delete the category and it's context.
1867 $DB->delete_records('course_categories', array('id' => $this->id));
1870 // Trigger a course category deleted event.
1871 /* @var \core\event\course_category_deleted $event */
1872 $event = \core\event\course_category_deleted::create(array(
1873 'objectid' => $this->id,
1874 'context' => $context,
1875 'other' => array('name' => $this->name)
1877 $event->set_coursecat($this);
1880 cache_helper::purge_by_event('changesincoursecat');
1882 if ($showfeedback) {
1883 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1886 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1887 if ($this->id == $CFG->defaultrequestcategory) {
1888 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1894 * Checks if user can move current category to the new parent
1896 * This checks if new parent category exists, user has manage cap there
1897 * and new parent is not a child of this category
1899 * @param int|stdClass|coursecat $newparentcat
1902 public function can_change_parent($newparentcat) {
1903 if (!has_capability('moodle/category:manage', $this->get_context())) {
1906 if (is_object($newparentcat)) {
1907 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1909 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1911 if (!$newparentcat) {
1914 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1915 // Can not move to itself or it's own child.
1918 if ($newparentcat->id) {
1919 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
1921 return has_capability('moodle/category:manage', context_system::instance());
1926 * Moves the category under another parent category. All associated contexts are moved as well
1928 * This is protected function, use change_parent() or update() from outside of this class
1930 * @see coursecat::change_parent()
1931 * @see coursecat::update()
1933 * @param coursecat $newparentcat
1934 * @throws moodle_exception
1936 protected function change_parent_raw(coursecat $newparentcat) {
1939 $context = $this->get_context();
1942 if (empty($newparentcat->id)) {
1943 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1944 $newparent = context_system::instance();
1946 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1947 // Can not move to itself or it's own child.
1948 throw new moodle_exception('cannotmovecategory');
1950 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
1951 $newparent = context_coursecat::instance($newparentcat->id);
1953 if (!$newparentcat->visible and $this->visible) {
1954 // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children
1955 // will be restored properly.
1959 $this->parent = $newparentcat->id;
1961 $context->update_moved($newparent);
1963 // Now make it last in new category.
1964 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
1967 fix_course_sortorder();
1969 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must
1970 // become visible again.
1976 * Efficiently moves a category - NOTE that this can have
1977 * a huge impact access-control-wise...
1979 * Note that this function does not check capabilities.
1982 * $coursecat = coursecat::get($categoryid);
1983 * if ($coursecat->can_change_parent($newparentcatid)) {
1984 * $coursecat->change_parent($newparentcatid);
1987 * This function does not update field course_categories.timemodified
1988 * If you want to update timemodified, use
1989 * $coursecat->update(array('parent' => $newparentcat));
1991 * @param int|stdClass|coursecat $newparentcat
1993 public function change_parent($newparentcat) {
1994 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1995 if (is_object($newparentcat)) {
1996 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
1998 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
2000 if ($newparentcat->id != $this->parent) {
2001 $this->change_parent_raw($newparentcat);
2002 fix_course_sortorder();
2003 cache_helper::purge_by_event('changesincoursecat');
2006 $event = \core\event\course_category_updated::create(array(
2007 'objectid' => $this->id,
2008 'context' => $this->get_context()
2010 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $this->id, $this->id));
2016 * Hide course category and child course and subcategories
2018 * If this category has changed the parent and is moved under hidden
2019 * category we will want to store it's current visibility state in
2020 * the field 'visibleold'. If admin clicked 'hide' for this particular
2021 * category, the field 'visibleold' should become 0.
2023 * All subcategories and courses will have their current visibility in the field visibleold
2025 * This is protected function, use hide() or update() from outside of this class
2027 * @see coursecat::hide()
2028 * @see coursecat::update()
2030 * @param int $visibleold value to set in field $visibleold for this category
2031 * @return bool whether changes have been made and caches need to be purged afterwards
2033 protected function hide_raw($visibleold = 0) {
2037 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing.
2038 if ($this->id && $this->__get('visibleold') != $visibleold) {
2039 $this->visibleold = $visibleold;
2040 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
2043 if (!$this->visible || !$this->id) {
2044 // Already hidden or can not be hidden.
2049 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
2050 // Store visible flag so that we can return to it if we immediately unhide.
2051 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id));
2052 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
2053 // Get all child categories and hide too.
2054 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
2055 foreach ($subcats as $cat) {
2056 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
2057 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
2058 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
2059 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
2066 * Hide course category and child course and subcategories
2068 * Note that there is no capability check inside this function
2070 * This function does not update field course_categories.timemodified
2071 * If you want to update timemodified, use
2072 * $coursecat->update(array('visible' => 0));
2074 public function hide() {
2075 if ($this->hide_raw(0)) {
2076 cache_helper::purge_by_event('changesincoursecat');
2078 $event = \core\event\course_category_updated::create(array(
2079 'objectid' => $this->id,
2080 'context' => $this->get_context()
2082 $event->set_legacy_logdata(array(SITEID, 'category', 'hide', 'editcategory.php?id=' . $this->id, $this->id));
2088 * Show course category and restores visibility for child course and subcategories
2090 * Note that there is no capability check inside this function
2092 * This is protected function, use show() or update() from outside of this class
2094 * @see coursecat::show()
2095 * @see coursecat::update()
2097 * @return bool whether changes have been made and caches need to be purged afterwards
2099 protected function show_raw() {
2102 if ($this->visible) {
2108 $this->visibleold = 1;
2109 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
2110 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
2111 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
2112 // Get all child categories and unhide too.
2113 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
2114 foreach ($subcats as $cat) {
2115 if ($cat->visibleold) {
2116 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
2118 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
2125 * Show course category and restores visibility for child course and subcategories
2127 * Note that there is no capability check inside this function
2129 * This function does not update field course_categories.timemodified
2130 * If you want to update timemodified, use
2131 * $coursecat->update(array('visible' => 1));
2133 public function show() {
2134 if ($this->show_raw()) {
2135 cache_helper::purge_by_event('changesincoursecat');
2137 $event = \core\event\course_category_updated::create(array(
2138 'objectid' => $this->id,
2139 'context' => $this->get_context()
2141 $event->set_legacy_logdata(array(SITEID, 'category', 'show', 'editcategory.php?id=' . $this->id, $this->id));
2147 * Returns name of the category formatted as a string
2149 * @param array $options formatting options other than context
2152 public function get_formatted_name($options = array()) {
2154 $context = $this->get_context();
2155 return format_string($this->name, true, array('context' => $context) + $options);
2157 return get_string('top');
2162 * Returns ids of all parents of the category. Last element in the return array is the direct parent
2164 * For example, if you have a tree of categories like:
2165 * Miscellaneous (id = 1)
2166 * Subcategory (id = 2)
2167 * Sub-subcategory (id = 4)
2168 * Other category (id = 3)
2170 * coursecat::get(1)->get_parents() == array()
2171 * coursecat::get(2)->get_parents() == array(1)
2172 * coursecat::get(4)->get_parents() == array(1, 2);
2174 * Note that this method does not check if all parents are accessible by current user
2176 * @return array of category ids
2178 public function get_parents() {
2179 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
2180 array_pop($parents);
2185 * This function returns a nice list representing category tree
2186 * for display or to use in a form <select> element
2188 * List is cached for 10 minutes
2190 * For example, if you have a tree of categories like:
2191 * Miscellaneous (id = 1)
2192 * Subcategory (id = 2)
2193 * Sub-subcategory (id = 4)
2194 * Other category (id = 3)
2195 * Then after calling this function you will have
2196 * array(1 => 'Miscellaneous',
2197 * 2 => 'Miscellaneous / Subcategory',
2198 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2199 * 3 => 'Other category');
2201 * If you specify $requiredcapability, then only categories where the current
2202 * user has that capability will be added to $list.
2203 * If you only have $requiredcapability in a child category, not the parent,
2204 * then the child catgegory will still be included.
2206 * If you specify the option $excludeid, then that category, and all its children,
2207 * are omitted from the tree. This is useful when you are doing something like
2208 * moving categories, where you do not want to allow people to move a category
2209 * to be the child of itself.
2211 * See also {@link make_categories_options()}
2213 * @param string/array $requiredcapability if given, only categories where the current
2214 * user has this capability will be returned. Can also be an array of capabilities,
2215 * in which case they are all required.
2216 * @param integer $excludeid Exclude this category and its children from the lists built.
2217 * @param string $separator string to use as a separator between parent and child category. Default ' / '
2218 * @return array of strings
2220 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
2222 $coursecatcache = cache::make('core', 'coursecat');
2224 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids
2225 // with requried cap ($thislist).
2226 $currentlang = current_language();
2227 $basecachekey = $currentlang . '_catlist';
2228 $baselist = $coursecatcache->get($basecachekey);
2230 $thiscachekey = null;
2231 if (!empty($requiredcapability)) {
2232 $requiredcapability = (array)$requiredcapability;
2233 $thiscachekey = 'catlist:'. serialize($requiredcapability);
2234 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
2235 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
2237 } else if ($baselist !== false) {
2238 $thislist = array_keys($baselist);
2241 if ($baselist === false) {
2242 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
2243 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2244 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
2245 FROM {course_categories} cc
2246 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
2247 ORDER BY cc.sortorder";
2248 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2249 $baselist = array();
2250 $thislist = array();
2251 foreach ($rs as $record) {
2252 // If the category's parent is not visible to the user, it is not visible as well.
2253 if (!$record->parent || isset($baselist[$record->parent])) {
2254 context_helper::preload_from_record($record);
2255 $context = context_coursecat::instance($record->id);
2256 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
2257 // No cap to view category, added to neither $baselist nor $thislist.
2260 $baselist[$record->id] = array(
2261 'name' => format_string($record->name, true, array('context' => $context)),
2262 'path' => $record->path
2264 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
2265 // No required capability, added to $baselist but not to $thislist.
2268 $thislist[] = $record->id;
2272 $coursecatcache->set($basecachekey, $baselist);
2273 if (!empty($requiredcapability)) {
2274 $coursecatcache->set($thiscachekey, join(',', $thislist));
2276 } else if ($thislist === false) {
2277 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
2278 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2279 $sql = "SELECT ctx.instanceid AS id, $ctxselect
2280 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
2281 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2282 $thislist = array();
2283 foreach (array_keys($baselist) as $id) {
2284 context_helper::preload_from_record($contexts[$id]);
2285 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
2289 $coursecatcache->set($thiscachekey, join(',', $thislist));
2292 // Now build the array of strings to return, mind $separator and $excludeid.
2294 foreach ($thislist as $id) {
2295 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
2296 if (!$excludeid || !in_array($excludeid, $path)) {
2297 $namechunks = array();
2298 foreach ($path as $parentid) {
2299 $namechunks[] = $baselist[$parentid]['name'];
2301 $names[$id] = join($separator, $namechunks);
2308 * Prepares the object for caching. Works like the __sleep method.
2310 * implementing method from interface cacheable_object
2312 * @return array ready to be cached
2314 public function prepare_to_cache() {
2316 foreach (self::$coursecatfields as $property => $cachedirectives) {
2317 if ($cachedirectives !== null) {
2318 list($shortname, $defaultvalue) = $cachedirectives;
2319 if ($this->$property !== $defaultvalue) {
2320 $a[$shortname] = $this->$property;
2324 $context = $this->get_context();
2325 $a['xi'] = $context->id;
2326 $a['xp'] = $context->path;
2331 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2333 * implementing method from interface cacheable_object
2338 public static function wake_from_cache($a) {
2339 $record = new stdClass;
2340 foreach (self::$coursecatfields as $property => $cachedirectives) {
2341 if ($cachedirectives !== null) {
2342 list($shortname, $defaultvalue) = $cachedirectives;
2343 if (array_key_exists($shortname, $a)) {
2344 $record->$property = $a[$shortname];
2346 $record->$property = $defaultvalue;
2350 $record->ctxid = $a['xi'];
2351 $record->ctxpath = $a['xp'];
2352 $record->ctxdepth = $record->depth + 1;
2353 $record->ctxlevel = CONTEXT_COURSECAT;
2354 $record->ctxinstance = $record->id;
2355 return new coursecat($record, true);
2359 * Returns true if the user is able to create a top level category.
2362 public static function can_create_top_level_category() {
2363 return has_capability('moodle/category:manage', context_system::instance());
2367 * Returns the category context.
2368 * @return context_coursecat
2370 public function get_context() {
2371 if ($this->id === 0) {
2372 // This is the special top level category object.
2373 return context_system::instance();
2375 return context_coursecat::instance($this->id);
2380 * Returns true if the user is able to manage this category.
2383 public function has_manage_capability() {
2384 if ($this->hasmanagecapability === null) {
2385 $this->hasmanagecapability = has_capability('moodle/category:manage', $this->get_context());
2387 return $this->hasmanagecapability;
2391 * Returns true if the user has the manage capability on the parent category.
2394 public function parent_has_manage_capability() {
2395 return has_capability('moodle/category:manage', get_category_or_system_context($this->parent));
2399 * Returns true if the current user can create subcategories of this category.
2402 public function can_create_subcategory() {
2403 return $this->has_manage_capability();
2407 * Returns true if the user can resort this categories sub categories and courses.
2408 * Must have manage capability and be able to see all subcategories.
2411 public function can_resort_subcategories() {
2412 return $this->has_manage_capability() && !$this->get_not_visible_children_ids();
2416 * Returns true if the user can resort the courses within this category.
2417 * Must have manage capability and be able to see all courses.
2420 public function can_resort_courses() {
2421 return $this->has_manage_capability() && $this->coursecount == $this->get_courses_count();
2425 * Returns true of the user can change the sortorder of this category (resort in the parent category)
2428 public function can_change_sortorder() {
2429 return $this->id && $this->get_parent_coursecat()->can_resort_subcategories();
2433 * Returns true if the current user can create a course within this category.
2436 public function can_create_course() {
2437 return has_capability('moodle/course:create', $this->get_context());
2441 * Returns true if the current user can edit this categories settings.
2444 public function can_edit() {
2445 return $this->has_manage_capability();
2449 * Returns true if the current user can review role assignments for this category.
2452 public function can_review_roles() {
2453 return has_capability('moodle/role:assign', $this->get_context());
2457 * Returns true if the current user can review permissions for this category.
2460 public function can_review_permissions() {
2461 return has_any_capability(array(
2462 'moodle/role:assign',
2463 'moodle/role:safeoverride',
2464 'moodle/role:override',
2465 'moodle/role:assign'
2466 ), $this->get_context());
2470 * Returns true if the current user can review cohorts for this category.
2473 public function can_review_cohorts() {
2474 return has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->get_context());
2478 * Returns true if the current user can review filter settings for this category.
2481 public function can_review_filters() {
2482 return has_capability('moodle/filter:manage', $this->get_context()) &&
2483 count(filter_get_available_in_context($this->get_context()))>0;
2487 * Returns true if the current user is able to change the visbility of this category.
2490 public function can_change_visibility() {
2491 return $this->parent_has_manage_capability();
2495 * Returns true if the user can move courses out of this category.
2498 public function can_move_courses_out_of() {
2499 return $this->has_manage_capability();
2503 * Returns true if the user can move courses into this category.
2506 public function can_move_courses_into() {
2507 return $this->has_manage_capability();
2511 * Returns true if the user is able to restore a course into this category as a new course.
2514 public function can_restore_courses_into() {
2515 return has_capability('moodle/restore:restorecourse', $this->get_context());
2519 * Resorts the sub categories of this category by the given field.
2521 * @param string $field One of name, idnumber or descending values of each (appended desc)
2522 * @param bool $cleanup If true cleanup will be done, if false you will need to do it manually later.
2523 * @return bool True on success.
2524 * @throws coding_exception
2526 public function resort_subcategories($field, $cleanup = true) {
2529 if (substr($field, -4) === "desc") {
2531 $field = substr($field, 0, -4); // Remove "desc" from field name.
2533 if ($field !== 'name' && $field !== 'idnumber') {
2534 throw new coding_exception('Invalid field requested');
2536 $children = $this->get_children();
2537 core_collator::asort_objects_by_property($children, $field, core_collator::SORT_NATURAL);
2538 if (!empty($desc)) {
2539 $children = array_reverse($children);
2542 foreach ($children as $cat) {
2544 $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id));
2545 $i += $cat->coursecount;
2548 self::resort_categories_cleanup();
2554 * Cleans things up after categories have been resorted.
2555 * @param bool $includecourses If set to true we know courses have been resorted as well.
2557 public static function resort_categories_cleanup($includecourses = false) {
2558 // This should not be needed but we do it just to be safe.
2559 fix_course_sortorder();
2560 cache_helper::purge_by_event('changesincoursecat');
2561 if ($includecourses) {
2562 cache_helper::purge_by_event('changesincourse');
2567 * Resort the courses within this category by the given field.
2569 * @param string $field One of fullname, shortname, idnumber or descending values of each (appended desc)
2570 * @param bool $cleanup
2571 * @return bool True for success.
2572 * @throws coding_exception
2574 public function resort_courses($field, $cleanup = true) {
2577 if (substr($field, -4) === "desc") {
2579 $field = substr($field, 0, -4); // Remove "desc" from field name.
2581 if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber' && $field !== 'timecreated') {
2582 // This is ultra important as we use $field in an SQL statement below this.
2583 throw new coding_exception('Invalid field requested');
2585 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
2586 $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields
2588 LEFT JOIN {context} ctx ON ctx.instanceid = c.id
2589 WHERE ctx.contextlevel = :ctxlevel AND
2590 c.category = :categoryid";
2592 'ctxlevel' => CONTEXT_COURSE,
2593 'categoryid' => $this->id
2595 $courses = $DB->get_records_sql($sql, $params);
2596 if (count($courses) > 0) {
2597 foreach ($courses as $courseid => $course) {
2598 context_helper::preload_from_record($course);
2599 if ($field === 'idnumber') {
2600 $course->sortby = $course->idnumber;
2602 // It'll require formatting.
2604 'context' => context_course::instance($course->id)
2606 // We format the string first so that it appears as the user would see it.
2607 // This ensures the sorting makes sense to them. However it won't necessarily make
2608 // sense to everyone if things like multilang filters are enabled.
2609 // We then strip any tags as we don't want things such as image tags skewing the
2611 $course->sortby = strip_tags(format_string($course->$field, true, $options));
2613 // We set it back here rather than using references as there is a bug with using
2614 // references in a foreach before passing as an arg by reference.
2615 $courses[$courseid] = $course;
2617 // Sort the courses.
2618 core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL);
2619 if (!empty($desc)) {
2620 $courses = array_reverse($courses);
2623 foreach ($courses as $course) {
2624 $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id));
2628 // This should not be needed but we do it just to be safe.
2629 fix_course_sortorder();
2630 cache_helper::purge_by_event('changesincourse');
2637 * Changes the sort order of this categories parent shifting this category up or down one.
2639 * @global \moodle_database $DB
2640 * @param bool $up If set to true the category is shifted up one spot, else its moved down.
2641 * @return bool True on success, false otherwise.
2643 public function change_sortorder_by_one($up) {
2645 $params = array($this->sortorder, $this->parent);
2647 $select = 'sortorder < ? AND parent = ?';
2648 $sort = 'sortorder DESC';
2650 $select = 'sortorder > ? AND parent = ?';
2651 $sort = 'sortorder ASC';
2653 fix_course_sortorder();
2654 $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1);
2655 $swapcategory = reset($swapcategory);
2656 if ($swapcategory) {
2657 $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id));
2658 $DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id));
2659 $this->sortorder = $swapcategory->sortorder;
2661 $event = \core\event\course_category_updated::create(array(
2662 'objectid' => $this->id,
2663 'context' => $this->get_context()
2665 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'management.php?categoryid=' . $this->id,
2669 // Finally reorder courses.
2670 fix_course_sortorder();
2671 cache_helper::purge_by_event('changesincoursecat');
2678 * Returns the parent coursecat object for this category.
2682 public function get_parent_coursecat() {
2683 return self::get($this->parent);
2688 * Returns true if the user is able to request a new course be created.
2691 public function can_request_course() {
2693 if (empty($CFG->enablecourserequests) || $this->id != $CFG->defaultrequestcategory) {
2696 return !$this->can_create_course() && has_capability('moodle/course:request', $this->get_context());
2700 * Returns true if the user can approve course requests.
2703 public static function can_approve_course_requests() {
2705 if (empty($CFG->enablecourserequests)) {
2708 $context = context_system::instance();
2709 if (!has_capability('moodle/site:approvecourse', $context)) {
2712 if (!$DB->record_exists('course_request', array())) {
2720 * Class to store information about one course in a list of courses
2722 * Not all information may be retrieved when object is created but
2723 * it will be retrieved on demand when appropriate property or method is
2726 * Instances of this class are usually returned by functions
2727 * {@link coursecat::search_courses()}
2729 * {@link coursecat::get_courses()}
2731 * @property-read int $id
2732 * @property-read int $category Category ID
2733 * @property-read int $sortorder
2734 * @property-read string $fullname
2735 * @property-read string $shortname
2736 * @property-read string $idnumber
2737 * @property-read string $summary Course summary. Field is present if coursecat::get_courses()
2738 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2739 * @property-read int $summaryformat Summary format. Field is present if coursecat::get_courses()
2740 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2741 * @property-read string $format Course format. Retrieved from DB on first request
2742 * @property-read int $showgrades Retrieved from DB on first request
2743 * @property-read int $newsitems Retrieved from DB on first request
2744 * @property-read int $startdate
2745 * @property-read int $enddate
2746 * @property-read int $marker Retrieved from DB on first request
2747 * @property-read int $maxbytes Retrieved from DB on first request
2748 * @property-read int $legacyfiles Retrieved from DB on first request
2749 * @property-read int $showreports Retrieved from DB on first request
2750 * @property-read int $visible
2751 * @property-read int $visibleold Retrieved from DB on first request
2752 * @property-read int $groupmode Retrieved from DB on first request
2753 * @property-read int $groupmodeforce Retrieved from DB on first request
2754 * @property-read int $defaultgroupingid Retrieved from DB on first request
2755 * @property-read string $lang Retrieved from DB on first request
2756 * @property-read string $theme Retrieved from DB on first request
2757 * @property-read int $timecreated Retrieved from DB on first request
2758 * @property-read int $timemodified Retrieved from DB on first request
2759 * @property-read int $requested Retrieved from DB on first request
2760 * @property-read int $enablecompletion Retrieved from DB on first request
2761 * @property-read int $completionnotify Retrieved from DB on first request
2762 * @property-read int $cacherev
2765 * @subpackage course
2766 * @copyright 2013 Marina Glancy
2767 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2769 class course_in_list implements IteratorAggregate {
2771 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2774 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2775 protected $coursecontacts;
2777 /** @var bool true if the current user can access the course, false otherwise. */
2778 protected $canaccess = null;
2781 * Creates an instance of the class from record
2783 * @param stdClass $record except fields from course table it may contain
2784 * field hassummary indicating that summary field is not empty.
2785 * Also it is recommended to have context fields here ready for
2786 * context preloading
2788 public function __construct(stdClass $record) {
2789 context_helper::preload_from_record($record);
2790 $this->record = new stdClass();
2791 foreach ($record as $key => $value) {
2792 $this->record->$key = $value;
2797 * Indicates if the course has non-empty summary field
2801 public function has_summary() {
2802 if (isset($this->record->hassummary)) {
2803 return !empty($this->record->hassummary);
2805 if (!isset($this->record->summary)) {
2806 // We need to retrieve summary.
2807 $this->__get('summary');
2809 return !empty($this->record->summary);
2813 * Indicates if the course have course contacts to display
2817 public function has_course_contacts() {
2818 if (!isset($this->record->managers)) {
2819 $courses = array($this->id => &$this->record);
2820 coursecat::preload_course_contacts($courses);
2822 return !empty($this->record->managers);
2826 * Returns list of course contacts (usually teachers) to display in course link
2828 * Roles to display are set up in $CFG->coursecontact
2830 * The result is the list of users where user id is the key and the value
2831 * is an array with elements:
2832 * - 'user' - object containing basic user information
2833 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2834 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2835 * - 'username' => fullname($user, $canviewfullnames)
2839 public function get_course_contacts() {
2841 if (empty($CFG->coursecontact)) {
2842 // No roles are configured to be displayed as course contacts.
2845 if ($this->coursecontacts === null) {
2846 $this->coursecontacts = array();
2847 $context = context_course::instance($this->id);
2849 if (!isset($this->record->managers)) {
2850 // Preload course contacts from DB.
2851 $courses = array($this->id => &$this->record);
2852 coursecat::preload_course_contacts($courses);
2855 // Build return array with full roles names (for this course context) and users names.
2856 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2857 foreach ($this->record->managers as $ruser) {
2858 if (isset($this->coursecontacts[$ruser->id])) {
2859 // Only display a user once with the highest sortorder role.
2862 $user = new stdClass();
2863 $user = username_load_fields_from_object($user, $ruser, null, array('id', 'username'));
2864 $role = new stdClass();
2865 $role->id = $ruser->roleid;
2866 $role->name = $ruser->rolename;
2867 $role->shortname = $ruser->roleshortname;
2868 $role->coursealias = $ruser->rolecoursealias;
2870 $this->coursecontacts[$user->id] = array(
2873 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2874 'username' => fullname($user, $canviewfullnames)
2878 return $this->coursecontacts;
2882 * Checks if course has any associated overview files
2886 public function has_course_overviewfiles() {
2888 if (empty($CFG->courseoverviewfileslimit)) {
2891 $fs = get_file_storage();
2892 $context = context_course::instance($this->id);
2893 return !$fs->is_area_empty($context->id, 'course', 'overviewfiles');
2897 * Returns all course overview files
2899 * @return array array of stored_file objects
2901 public function get_course_overviewfiles() {
2903 if (empty($CFG->courseoverviewfileslimit)) {
2906 require_once($CFG->libdir. '/filestorage/file_storage.php');
2907 require_once($CFG->dirroot. '/course/lib.php');
2908 $fs = get_file_storage();
2909 $context = context_course::instance($this->id);
2910 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2911 if (count($files)) {
2912 $overviewfilesoptions = course_overviewfiles_options($this->id);
2913 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2914 if ($acceptedtypes !== '*') {
2915 // Filter only files with allowed extensions.
2916 require_once($CFG->libdir. '/filelib.php');
2917 foreach ($files as $key => $file) {
2918 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2919 unset($files[$key]);
2923 if (count($files) > $CFG->courseoverviewfileslimit) {
2924 // Return no more than $CFG->courseoverviewfileslimit files.
2925 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
2932 * Magic method to check if property is set
2934 * @param string $name
2937 public function __isset($name) {
2938 return isset($this->record->$name);
2942 * Magic method to get a course property
2944 * Returns any field from table course (retrieves it from DB if it was not retrieved before)
2946 * @param string $name
2949 public function __get($name) {
2951 if (property_exists($this->record, $name)) {
2952 return $this->record->$name;
2953 } else if ($name === 'summary' || $name === 'summaryformat') {
2954 // Retrieve fields summary and summaryformat together because they are most likely to be used together.
2955 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
2956 $this->record->summary = $record->summary;
2957 $this->record->summaryformat = $record->summaryformat;
2958 return $this->record->$name;
2959 } else if (array_key_exists($name, $DB->get_columns('course'))) {
2960 // Another field from table 'course' that was not retrieved.
2961 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
2962 return $this->record->$name;
2964 debugging('Invalid course property accessed! '.$name);
2969 * All properties are read only, sorry.
2971 * @param string $name
2973 public function __unset($name) {
2974 debugging('Can not unset '.get_class($this).' instance properties!');
2978 * Magic setter method, we do not want anybody to modify properties from the outside
2980 * @param string $name
2981 * @param mixed $value
2983 public function __set($name, $value) {
2984 debugging('Can not change '.get_class($this).' instance properties!');
2988 * Create an iterator because magic vars can't be seen by 'foreach'.
2989 * Exclude context fields
2991 * Implementing method from interface IteratorAggregate
2993 * @return ArrayIterator
2995 public function getIterator() {
2996 $ret = array('id' => $this->record->id);
2997 foreach ($this->record as $property => $value) {
2998 $ret[$property] = $value;
3000 return new ArrayIterator($ret);
3004 * Returns the name of this course as it should be displayed within a list.
3007 public function get_formatted_name() {
3008 return format_string(get_course_display_name_for_list($this), true, $this->get_context());
3012 * Returns the formatted fullname for this course.
3015 public function get_formatted_fullname() {
3016 return format_string($this->__get('fullname'), true, $this->get_context());
3020 * Returns the formatted shortname for this course.
3023 public function get_formatted_shortname() {
3024 return format_string($this->__get('shortname'), true, $this->get_context());
3028 * Returns true if the current user can access this course.
3031 public function can_access() {
3032 if ($this->canaccess === null) {
3033 $this->canaccess = can_access_course($this->record);
3035 return $this->canaccess;
3039 * Returns true if the user can edit this courses settings.
3041 * Note: this function does not check that the current user can access the course.
3042 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3046 public function can_edit() {
3047 return has_capability('moodle/course:update', $this->get_context());
3051 * Returns true if the user can change the visibility of this course.
3053 * Note: this function does not check that the current user can access the course.
3054 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3058 public function can_change_visibility() {
3059 // You must be able to both hide a course and view the hidden course.
3060 return has_all_capabilities(array('moodle/course:visibility', 'moodle/course:viewhiddencourses'), $this->get_context());
3064 * Returns the context for this course.
3065 * @return context_course
3067 public function get_context() {
3068 return context_course::instance($this->__get('id'));
3072 * Returns true if this course is visible to the current user.
3075 public function is_uservisible() {
3076 return $this->visible || has_capability('moodle/course:viewhiddencourses', $this->get_context());
3080 * Returns true if the current user can review enrolments for this course.
3082 * Note: this function does not check that the current user can access the course.
3083 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3087 public function can_review_enrolments() {
3088 return has_capability('moodle/course:enrolreview', $this->get_context());
3092 * Returns true if the current user can delete this course.
3094 * Note: this function does not check that the current user can access the course.
3095 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3099 public function can_delete() {
3100 return can_delete_course($this->id);
3104 * Returns true if the current user can backup this course.
3106 * Note: this function does not check that the current user can access the course.
3107 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3111 public function can_backup() {
3112 return has_capability('moodle/backup:backupcourse', $this->get_context());
3116 * Returns true if the current user can restore this course.
3118 * Note: this function does not check that the current user can access the course.
3119 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3123 public function can_restore() {
3124 return has_capability('moodle/restore:restorecourse', $this->get_context());
3129 * An array of records that is sortable by many fields.
3131 * For more info on the ArrayObject class have a look at php.net.
3134 * @subpackage course
3135 * @copyright 2013 Sam Hemelryk
3136 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3138 class coursecat_sortable_records extends ArrayObject {
3141 * An array of sortable fields.
3142 * Gets set temporarily when sort is called.
3145 protected $sortfields = array();
3148 * Sorts this array using the given fields.
3150 * @param array $records
3151 * @param array $fields
3154 public static function sort(array $records, array $fields) {
3155 $records = new coursecat_sortable_records($records);
3156 $records->sortfields = $fields;
3157 $records->uasort(array($records, 'sort_by_many_fields'));
3158 return $records->getArrayCopy();
3162 * Sorts the two records based upon many fields.
3164 * This method should not be called itself, please call $sort instead.
3165 * It has been marked as access private as such.
3168 * @param stdClass $a
3169 * @param stdClass $b
3172 public function sort_by_many_fields($a, $b) {
3173 foreach ($this->sortfields as $field => $mult) {
3175 if (is_null($a->$field) && !is_null($b->$field)) {
3178 if (is_null($b->$field) && !is_null($a->$field)) {
3182 if (is_string($a->$field) || is_string($b->$field)) {
3184 if ($cmp = strcoll($a->$field, $b->$field)) {
3185 return $mult * $cmp;
3189 if ($a->$field > $b->$field) {
3192 if ($a->$field < $b->$field) {