MDL-48750 Lesson: Behat test for lesson attempt info
[moodle.git] / lib / coursecatlib.php
bloba027c557cb8900df81b6f4062c57c2b9e52dbcb3
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Contains class coursecat reponsible for course category operations
20 * @package core
21 * @subpackage course
22 * @copyright 2013 Marina Glancy
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /**
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
46 * @package core
47 * @subpackage course
48 * @copyright 2013 Marina Glancy
49 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
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 /** Do not fetch course contacts more often than once per hour. */
56 const CACHE_COURSE_CONTACTS_TTL = 3600;
58 /** @var array list of all fields and their short name and default value for caching */
59 protected static $coursecatfields = array(
60 'id' => array('id', 0),
61 'name' => array('na', ''),
62 'idnumber' => array('in', null),
63 'description' => null, // Not cached.
64 'descriptionformat' => null, // Not cached.
65 'parent' => array('pa', 0),
66 'sortorder' => array('so', 0),
67 'coursecount' => array('cc', 0),
68 'visible' => array('vi', 1),
69 'visibleold' => null, // Not cached.
70 'timemodified' => null, // Not cached.
71 'depth' => array('dh', 1),
72 'path' => array('ph', null),
73 'theme' => null, // Not cached.
76 /** @var int */
77 protected $id;
79 /** @var string */
80 protected $name = '';
82 /** @var string */
83 protected $idnumber = null;
85 /** @var string */
86 protected $description = false;
88 /** @var int */
89 protected $descriptionformat = false;
91 /** @var int */
92 protected $parent = 0;
94 /** @var int */
95 protected $sortorder = 0;
97 /** @var int */
98 protected $coursecount = false;
100 /** @var int */
101 protected $visible = 1;
103 /** @var int */
104 protected $visibleold = false;
106 /** @var int */
107 protected $timemodified = false;
109 /** @var int */
110 protected $depth = 0;
112 /** @var string */
113 protected $path = '';
115 /** @var string */
116 protected $theme = false;
118 /** @var bool */
119 protected $fromcache;
121 /** @var bool */
122 protected $hasmanagecapability = null;
125 * Magic setter method, we do not want anybody to modify properties from the outside
127 * @param string $name
128 * @param mixed $value
130 public function __set($name, $value) {
131 debugging('Can not change coursecat instance properties!', DEBUG_DEVELOPER);
135 * Magic method getter, redirects to read only values. Queries from DB the fields that were not cached
137 * @param string $name
138 * @return mixed
140 public function __get($name) {
141 global $DB;
142 if (array_key_exists($name, self::$coursecatfields)) {
143 if ($this->$name === false) {
144 // Property was not retrieved from DB, retrieve all not retrieved fields.
145 $notretrievedfields = array_diff_key(self::$coursecatfields, array_filter(self::$coursecatfields));
146 $record = $DB->get_record('course_categories', array('id' => $this->id),
147 join(',', array_keys($notretrievedfields)), MUST_EXIST);
148 foreach ($record as $key => $value) {
149 $this->$key = $value;
152 return $this->$name;
154 debugging('Invalid coursecat property accessed! '.$name, DEBUG_DEVELOPER);
155 return null;
159 * Full support for isset on our magic read only properties.
161 * @param string $name
162 * @return bool
164 public function __isset($name) {
165 if (array_key_exists($name, self::$coursecatfields)) {
166 return isset($this->$name);
168 return false;
172 * All properties are read only, sorry.
174 * @param string $name
176 public function __unset($name) {
177 debugging('Can not unset coursecat instance properties!', DEBUG_DEVELOPER);
181 * Create an iterator because magic vars can't be seen by 'foreach'.
183 * implementing method from interface IteratorAggregate
185 * @return ArrayIterator
187 public function getIterator() {
188 $ret = array();
189 foreach (self::$coursecatfields as $property => $unused) {
190 if ($this->$property !== false) {
191 $ret[$property] = $this->$property;
194 return new ArrayIterator($ret);
198 * Constructor
200 * Constructor is protected, use coursecat::get($id) to retrieve category
202 * @param stdClass $record record from DB (may not contain all fields)
203 * @param bool $fromcache whether it is being restored from cache
205 protected function __construct(stdClass $record, $fromcache = false) {
206 context_helper::preload_from_record($record);
207 foreach ($record as $key => $val) {
208 if (array_key_exists($key, self::$coursecatfields)) {
209 $this->$key = $val;
212 $this->fromcache = $fromcache;
216 * Returns coursecat object for requested category
218 * If category is not visible to user it is treated as non existing
219 * unless $alwaysreturnhidden is set to true
221 * If id is 0, the pseudo object for root category is returned (convenient
222 * for calling other functions such as get_children())
224 * @param int $id category id
225 * @param int $strictness whether to throw an exception (MUST_EXIST) or
226 * return null (IGNORE_MISSING) in case the category is not found or
227 * not visible to current user
228 * @param bool $alwaysreturnhidden set to true if you want an object to be
229 * returned even if this category is not visible to the current user
230 * (category is hidden and user does not have
231 * 'moodle/category:viewhiddencategories' capability). Use with care!
232 * @return null|coursecat
233 * @throws moodle_exception
235 public static function get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false) {
236 if (!$id) {
237 if (!isset(self::$coursecat0)) {
238 $record = new stdClass();
239 $record->id = 0;
240 $record->visible = 1;
241 $record->depth = 0;
242 $record->path = '';
243 self::$coursecat0 = new coursecat($record);
245 return self::$coursecat0;
247 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
248 $coursecat = $coursecatrecordcache->get($id);
249 if ($coursecat === false) {
250 if ($records = self::get_records('cc.id = :id', array('id' => $id))) {
251 $record = reset($records);
252 $coursecat = new coursecat($record);
253 // Store in cache.
254 $coursecatrecordcache->set($id, $coursecat);
257 if ($coursecat && ($alwaysreturnhidden || $coursecat->is_uservisible())) {
258 return $coursecat;
259 } else {
260 if ($strictness == MUST_EXIST) {
261 throw new moodle_exception('unknowncategory');
264 return null;
268 * Load many coursecat objects.
270 * @global moodle_database $DB
271 * @param array $ids An array of category ID's to load.
272 * @return coursecat[]
274 public static function get_many(array $ids) {
275 global $DB;
276 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
277 $categories = $coursecatrecordcache->get_many($ids);
278 $toload = array();
279 foreach ($categories as $id => $result) {
280 if ($result === false) {
281 $toload[] = $id;
284 if (!empty($toload)) {
285 list($where, $params) = $DB->get_in_or_equal($toload, SQL_PARAMS_NAMED);
286 $records = self::get_records('cc.id '.$where, $params);
287 $toset = array();
288 foreach ($records as $record) {
289 $categories[$record->id] = new coursecat($record);
290 $toset[$record->id] = $categories[$record->id];
292 $coursecatrecordcache->set_many($toset);
294 return $categories;
298 * Returns the first found category
300 * Note that if there are no categories visible to the current user on the first level,
301 * the invisible category may be returned
303 * @return coursecat
305 public static function get_default() {
306 if ($visiblechildren = self::get(0)->get_children()) {
307 $defcategory = reset($visiblechildren);
308 } else {
309 $toplevelcategories = self::get_tree(0);
310 $defcategoryid = $toplevelcategories[0];
311 $defcategory = self::get($defcategoryid, MUST_EXIST, true);
313 return $defcategory;
317 * Restores the object after it has been externally modified in DB for example
318 * during {@link fix_course_sortorder()}
320 protected function restore() {
321 // Update all fields in the current object.
322 $newrecord = self::get($this->id, MUST_EXIST, true);
323 foreach (self::$coursecatfields as $key => $unused) {
324 $this->$key = $newrecord->$key;
329 * Creates a new category either from form data or from raw data
331 * Please note that this function does not verify access control.
333 * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
335 * Category visibility is inherited from parent unless $data->visible = 0 is specified
337 * @param array|stdClass $data
338 * @param array $editoroptions if specified, the data is considered to be
339 * form data and file_postupdate_standard_editor() is being called to
340 * process images in description.
341 * @return coursecat
342 * @throws moodle_exception
344 public static function create($data, $editoroptions = null) {
345 global $DB, $CFG;
346 $data = (object)$data;
347 $newcategory = new stdClass();
349 $newcategory->descriptionformat = FORMAT_MOODLE;
350 $newcategory->description = '';
351 // Copy all description* fields regardless of whether this is form data or direct field update.
352 foreach ($data as $key => $value) {
353 if (preg_match("/^description/", $key)) {
354 $newcategory->$key = $value;
358 if (empty($data->name)) {
359 throw new moodle_exception('categorynamerequired');
361 if (core_text::strlen($data->name) > 255) {
362 throw new moodle_exception('categorytoolong');
364 $newcategory->name = $data->name;
366 // Validate and set idnumber.
367 if (!empty($data->idnumber)) {
368 if (core_text::strlen($data->idnumber) > 100) {
369 throw new moodle_exception('idnumbertoolong');
371 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
372 throw new moodle_exception('categoryidnumbertaken');
375 if (isset($data->idnumber)) {
376 $newcategory->idnumber = $data->idnumber;
379 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
380 $newcategory->theme = $data->theme;
383 if (empty($data->parent)) {
384 $parent = self::get(0);
385 } else {
386 $parent = self::get($data->parent, MUST_EXIST, true);
388 $newcategory->parent = $parent->id;
389 $newcategory->depth = $parent->depth + 1;
391 // By default category is visible, unless visible = 0 is specified or parent category is hidden.
392 if (isset($data->visible) && !$data->visible) {
393 // Create a hidden category.
394 $newcategory->visible = $newcategory->visibleold = 0;
395 } else {
396 // Create a category that inherits visibility from parent.
397 $newcategory->visible = $parent->visible;
398 // In case parent is hidden, when it changes visibility this new subcategory will automatically become visible too.
399 $newcategory->visibleold = 1;
402 $newcategory->sortorder = 0;
403 $newcategory->timemodified = time();
405 $newcategory->id = $DB->insert_record('course_categories', $newcategory);
407 // Update path (only possible after we know the category id.
408 $path = $parent->path . '/' . $newcategory->id;
409 $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));
411 // We should mark the context as dirty.
412 context_coursecat::instance($newcategory->id)->mark_dirty();
414 fix_course_sortorder();
416 // If this is data from form results, save embedded files and update description.
417 $categorycontext = context_coursecat::instance($newcategory->id);
418 if ($editoroptions) {
419 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
420 'coursecat', 'description', 0);
422 // Update only fields description and descriptionformat.
423 $updatedata = new stdClass();
424 $updatedata->id = $newcategory->id;
425 $updatedata->description = $newcategory->description;
426 $updatedata->descriptionformat = $newcategory->descriptionformat;
427 $DB->update_record('course_categories', $updatedata);
430 $event = \core\event\course_category_created::create(array(
431 'objectid' => $newcategory->id,
432 'context' => $categorycontext
434 $event->trigger();
436 cache_helper::purge_by_event('changesincoursecat');
438 return self::get($newcategory->id, MUST_EXIST, true);
442 * Updates the record with either form data or raw data
444 * Please note that this function does not verify access control.
446 * This function calls coursecat::change_parent_raw if field 'parent' is updated.
447 * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
448 * Visibility is changed first and then parent is changed. This means that
449 * if parent category is hidden, the current category will become hidden
450 * too and it may overwrite whatever was set in field 'visible'.
452 * Note that fields 'path' and 'depth' can not be updated manually
453 * Also coursecat::update() can not directly update the field 'sortoder'
455 * @param array|stdClass $data
456 * @param array $editoroptions if specified, the data is considered to be
457 * form data and file_postupdate_standard_editor() is being called to
458 * process images in description.
459 * @throws moodle_exception
461 public function update($data, $editoroptions = null) {
462 global $DB, $CFG;
463 if (!$this->id) {
464 // There is no actual DB record associated with root category.
465 return;
468 $data = (object)$data;
469 $newcategory = new stdClass();
470 $newcategory->id = $this->id;
472 // Copy all description* fields regardless of whether this is form data or direct field update.
473 foreach ($data as $key => $value) {
474 if (preg_match("/^description/", $key)) {
475 $newcategory->$key = $value;
479 if (isset($data->name) && empty($data->name)) {
480 throw new moodle_exception('categorynamerequired');
483 if (!empty($data->name) && $data->name !== $this->name) {
484 if (core_text::strlen($data->name) > 255) {
485 throw new moodle_exception('categorytoolong');
487 $newcategory->name = $data->name;
490 if (isset($data->idnumber) && $data->idnumber != $this->idnumber) {
491 if (core_text::strlen($data->idnumber) > 100) {
492 throw new moodle_exception('idnumbertoolong');
494 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
495 throw new moodle_exception('categoryidnumbertaken');
497 $newcategory->idnumber = $data->idnumber;
500 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
501 $newcategory->theme = $data->theme;
504 $changes = false;
505 if (isset($data->visible)) {
506 if ($data->visible) {
507 $changes = $this->show_raw();
508 } else {
509 $changes = $this->hide_raw(0);
513 if (isset($data->parent) && $data->parent != $this->parent) {
514 if ($changes) {
515 cache_helper::purge_by_event('changesincoursecat');
517 $parentcat = self::get($data->parent, MUST_EXIST, true);
518 $this->change_parent_raw($parentcat);
519 fix_course_sortorder();
522 $newcategory->timemodified = time();
524 $categorycontext = $this->get_context();
525 if ($editoroptions) {
526 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
527 'coursecat', 'description', 0);
529 $DB->update_record('course_categories', $newcategory);
531 $event = \core\event\course_category_updated::create(array(
532 'objectid' => $newcategory->id,
533 'context' => $categorycontext
535 $event->trigger();
537 fix_course_sortorder();
538 // Purge cache even if fix_course_sortorder() did not do it.
539 cache_helper::purge_by_event('changesincoursecat');
541 // Update all fields in the current object.
542 $this->restore();
546 * Checks if this course category is visible to current user
548 * Please note that methods coursecat::get (without 3rd argumet),
549 * coursecat::get_children(), etc. return only visible categories so it is
550 * usually not needed to call this function outside of this class
552 * @return bool
554 public function is_uservisible() {
555 return !$this->id || $this->visible ||
556 has_capability('moodle/category:viewhiddencategories', $this->get_context());
560 * Returns the complete corresponding record from DB table course_categories
562 * Mostly used in deprecated functions
564 * @return stdClass
566 public function get_db_record() {
567 global $DB;
568 if ($record = $DB->get_record('course_categories', array('id' => $this->id))) {
569 return $record;
570 } else {
571 return (object)convert_to_array($this);
576 * Returns the entry from categories tree and makes sure the application-level tree cache is built
578 * The following keys can be requested:
580 * 'countall' - total number of categories in the system (always present)
581 * 0 - array of ids of top-level categories (always present)
582 * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
583 * $id (int) - array of ids of categories that are direct children of category with id $id. If
584 * category with id $id does not exist returns false. If category has no children returns empty array
585 * $id.'i' - array of ids of children categories that have visible=0
587 * @param int|string $id
588 * @return mixed
590 protected static function get_tree($id) {
591 global $DB;
592 $coursecattreecache = cache::make('core', 'coursecattree');
593 $rv = $coursecattreecache->get($id);
594 if ($rv !== false) {
595 return $rv;
597 // Re-build the tree.
598 $sql = "SELECT cc.id, cc.parent, cc.visible
599 FROM {course_categories} cc
600 ORDER BY cc.sortorder";
601 $rs = $DB->get_recordset_sql($sql, array());
602 $all = array(0 => array(), '0i' => array());
603 $count = 0;
604 foreach ($rs as $record) {
605 $all[$record->id] = array();
606 $all[$record->id. 'i'] = array();
607 if (array_key_exists($record->parent, $all)) {
608 $all[$record->parent][] = $record->id;
609 if (!$record->visible) {
610 $all[$record->parent. 'i'][] = $record->id;
612 } else {
613 // Parent not found. This is data consistency error but next fix_course_sortorder() should fix it.
614 $all[0][] = $record->id;
615 if (!$record->visible) {
616 $all['0i'][] = $record->id;
619 $count++;
621 $rs->close();
622 if (!$count) {
623 // No categories found.
624 // This may happen after upgrade of a very old moodle version.
625 // In new versions the default category is created on install.
626 $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
627 set_config('defaultrequestcategory', $defcoursecat->id);
628 $all[0] = array($defcoursecat->id);
629 $all[$defcoursecat->id] = array();
630 $count++;
632 // We must add countall to all in case it was the requested ID.
633 $all['countall'] = $count;
634 foreach ($all as $key => $children) {
635 $coursecattreecache->set($key, $children);
637 if (array_key_exists($id, $all)) {
638 return $all[$id];
640 // Requested non-existing category.
641 return array();
645 * Returns number of ALL categories in the system regardless if
646 * they are visible to current user or not
648 * @return int
650 public static function count_all() {
651 return self::get_tree('countall');
655 * Retrieves number of records from course_categories table
657 * Only cached fields are retrieved. Records are ready for preloading context
659 * @param string $whereclause
660 * @param array $params
661 * @return array array of stdClass objects
663 protected static function get_records($whereclause, $params) {
664 global $DB;
665 // Retrieve from DB only the fields that need to be stored in cache.
666 $fields = array_keys(array_filter(self::$coursecatfields));
667 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
668 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
669 FROM {course_categories} cc
670 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
671 WHERE ". $whereclause." ORDER BY cc.sortorder";
672 return $DB->get_records_sql($sql,
673 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
677 * Given list of DB records from table course populates each record with list of users with course contact roles
679 * This function fills the courses with raw information as {@link get_role_users()} would do.
680 * See also {@link course_in_list::get_course_contacts()} for more readable return
682 * $courses[$i]->managers = array(
683 * $roleassignmentid => $roleuser,
684 * ...
685 * );
687 * where $roleuser is an stdClass with the following properties:
689 * $roleuser->raid - role assignment id
690 * $roleuser->id - user id
691 * $roleuser->username
692 * $roleuser->firstname
693 * $roleuser->lastname
694 * $roleuser->rolecoursealias
695 * $roleuser->rolename
696 * $roleuser->sortorder - role sortorder
697 * $roleuser->roleid
698 * $roleuser->roleshortname
700 * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
702 * @param array $courses
704 public static function preload_course_contacts(&$courses) {
705 global $CFG, $DB;
706 if (empty($courses) || empty($CFG->coursecontact)) {
707 return;
709 $managerroles = explode(',', $CFG->coursecontact);
710 $cache = cache::make('core', 'coursecontacts');
711 $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
712 // Check if cache was set for the current course contacts and it is not yet expired.
713 if (empty($cacheddata['basic']) || $cacheddata['basic']['roles'] !== $CFG->coursecontact ||
714 $cacheddata['basic']['lastreset'] < time() - self::CACHE_COURSE_CONTACTS_TTL) {
715 // Reset cache.
716 $cache->purge();
717 $cache->set('basic', array('roles' => $CFG->coursecontact, 'lastreset' => time()));
718 $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
720 $courseids = array();
721 foreach (array_keys($courses) as $id) {
722 if ($cacheddata[$id] !== false) {
723 $courses[$id]->managers = $cacheddata[$id];
724 } else {
725 $courseids[] = $id;
729 // Array $courseids now stores list of ids of courses for which we still need to retrieve contacts.
730 if (empty($courseids)) {
731 return;
734 // First build the array of all context ids of the courses and their categories.
735 $allcontexts = array();
736 foreach ($courseids as $id) {
737 $context = context_course::instance($id);
738 $courses[$id]->managers = array();
739 foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
740 if (!isset($allcontexts[$ctxid])) {
741 $allcontexts[$ctxid] = array();
743 $allcontexts[$ctxid][] = $id;
747 // Fetch list of all users with course contact roles in any of the courses contexts or parent contexts.
748 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
749 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
750 list($sort, $sortparams) = users_order_by_sql('u');
751 $notdeleted = array('notdeleted'=>0);
752 $allnames = get_all_user_name_fields(true, 'u');
753 $sql = "SELECT ra.contextid, ra.id AS raid,
754 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
755 rn.name AS rolecoursealias, u.id, u.username, $allnames
756 FROM {role_assignments} ra
757 JOIN {user} u ON ra.userid = u.id
758 JOIN {role} r ON ra.roleid = r.id
759 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
760 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
761 ORDER BY r.sortorder, $sort";
762 $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
763 $checkenrolments = array();
764 foreach ($rs as $ra) {
765 foreach ($allcontexts[$ra->contextid] as $id) {
766 $courses[$id]->managers[$ra->raid] = $ra;
767 if (!isset($checkenrolments[$id])) {
768 $checkenrolments[$id] = array();
770 $checkenrolments[$id][] = $ra->id;
773 $rs->close();
775 // Remove from course contacts users who are not enrolled in the course.
776 $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
777 foreach ($checkenrolments as $id => $userids) {
778 if (empty($enrolleduserids[$id])) {
779 $courses[$id]->managers = array();
780 } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
781 foreach ($courses[$id]->managers as $raid => $ra) {
782 if (in_array($ra->id, $notenrolled)) {
783 unset($courses[$id]->managers[$raid]);
789 // Set the cache.
790 $values = array();
791 foreach ($courseids as $id) {
792 $values[$id] = $courses[$id]->managers;
794 $cache->set_many($values);
798 * Verify user enrollments for multiple course-user combinations
800 * @param array $courseusers array where keys are course ids and values are array
801 * of users in this course whose enrolment we wish to verify
802 * @return array same structure as input array but values list only users from input
803 * who are enrolled in the course
805 protected static function ensure_users_enrolled($courseusers) {
806 global $DB;
807 // If the input array is too big, split it into chunks.
808 $maxcoursesinquery = 20;
809 if (count($courseusers) > $maxcoursesinquery) {
810 $rv = array();
811 for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
812 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
813 $rv = $rv + self::ensure_users_enrolled($chunk);
815 return $rv;
818 // Create a query verifying valid user enrolments for the number of courses.
819 $sql = "SELECT DISTINCT e.courseid, ue.userid
820 FROM {user_enrolments} ue
821 JOIN {enrol} e ON e.id = ue.enrolid
822 WHERE ue.status = :active
823 AND e.status = :enabled
824 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
825 $now = round(time(), -2); // Rounding helps caching in DB.
826 $params = array('enabled' => ENROL_INSTANCE_ENABLED,
827 'active' => ENROL_USER_ACTIVE,
828 'now1' => $now, 'now2' => $now);
829 $cnt = 0;
830 $subsqls = array();
831 $enrolled = array();
832 foreach ($courseusers as $id => $userids) {
833 $enrolled[$id] = array();
834 if (count($userids)) {
835 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
836 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
837 $params = $params + array('courseid'.$cnt => $id) + $params2;
838 $cnt++;
841 if (count($subsqls)) {
842 $sql .= "AND (". join(' OR ', $subsqls).")";
843 $rs = $DB->get_recordset_sql($sql, $params);
844 foreach ($rs as $record) {
845 $enrolled[$record->courseid][] = $record->userid;
847 $rs->close();
849 return $enrolled;
853 * Retrieves number of records from course table
855 * Not all fields are retrieved. Records are ready for preloading context
857 * @param string $whereclause
858 * @param array $params
859 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
860 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
861 * on not visible courses
862 * @return array array of stdClass objects
864 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
865 global $DB;
866 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
867 $fields = array('c.id', 'c.category', 'c.sortorder',
868 'c.shortname', 'c.fullname', 'c.idnumber',
869 'c.startdate', 'c.visible', 'c.cacherev');
870 if (!empty($options['summary'])) {
871 $fields[] = 'c.summary';
872 $fields[] = 'c.summaryformat';
873 } else {
874 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
876 $sql = "SELECT ". join(',', $fields). ", $ctxselect
877 FROM {course} c
878 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
879 WHERE ". $whereclause." ORDER BY c.sortorder";
880 $list = $DB->get_records_sql($sql,
881 array('contextcourse' => CONTEXT_COURSE) + $params);
883 if ($checkvisibility) {
884 // Loop through all records and make sure we only return the courses accessible by user.
885 foreach ($list as $course) {
886 if (isset($list[$course->id]->hassummary)) {
887 $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
889 if (empty($course->visible)) {
890 // Load context only if we need to check capability.
891 context_helper::preload_from_record($course);
892 if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
893 unset($list[$course->id]);
899 // Preload course contacts if necessary.
900 if (!empty($options['coursecontacts'])) {
901 self::preload_course_contacts($list);
903 return $list;
907 * Returns array of ids of children categories that current user can not see
909 * This data is cached in user session cache
911 * @return array
913 protected function get_not_visible_children_ids() {
914 global $DB;
915 $coursecatcache = cache::make('core', 'coursecat');
916 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
917 // We never checked visible children before.
918 $hidden = self::get_tree($this->id.'i');
919 $invisibleids = array();
920 if ($hidden) {
921 // Preload categories contexts.
922 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
923 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
924 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
925 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
926 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
927 foreach ($contexts as $record) {
928 context_helper::preload_from_record($record);
930 // Check that user has 'viewhiddencategories' capability for each hidden category.
931 foreach ($hidden as $id) {
932 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
933 $invisibleids[] = $id;
937 $coursecatcache->set('ic'. $this->id, $invisibleids);
939 return $invisibleids;
943 * Sorts list of records by several fields
945 * @param array $records array of stdClass objects
946 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
947 * @return int
949 protected static function sort_records(&$records, $sortfields) {
950 if (empty($records)) {
951 return;
953 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname).
954 if (array_key_exists('displayname', $sortfields)) {
955 foreach ($records as $key => $record) {
956 if (!isset($record->displayname)) {
957 $records[$key]->displayname = get_course_display_name_for_list($record);
961 // Sorting by one field - use core_collator.
962 if (count($sortfields) == 1) {
963 $property = key($sortfields);
964 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
965 $sortflag = core_collator::SORT_NUMERIC;
966 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
967 $sortflag = core_collator::SORT_STRING;
968 } else {
969 $sortflag = core_collator::SORT_REGULAR;
971 core_collator::asort_objects_by_property($records, $property, $sortflag);
972 if ($sortfields[$property] < 0) {
973 $records = array_reverse($records, true);
975 return;
977 $records = coursecat_sortable_records::sort($records, $sortfields);
981 * Returns array of children categories visible to the current user
983 * @param array $options options for retrieving children
984 * - sort - list of fields to sort. Example
985 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
986 * will sort by idnumber asc, name asc and id desc.
987 * Default: array('sortorder' => 1)
988 * Only cached fields may be used for sorting!
989 * - offset
990 * - limit - maximum number of children to return, 0 or null for no limit
991 * @return coursecat[] Array of coursecat objects indexed by category id
993 public function get_children($options = array()) {
994 global $DB;
995 $coursecatcache = cache::make('core', 'coursecat');
997 // Get default values for options.
998 if (!empty($options['sort']) && is_array($options['sort'])) {
999 $sortfields = $options['sort'];
1000 } else {
1001 $sortfields = array('sortorder' => 1);
1003 $limit = null;
1004 if (!empty($options['limit']) && (int)$options['limit']) {
1005 $limit = (int)$options['limit'];
1007 $offset = 0;
1008 if (!empty($options['offset']) && (int)$options['offset']) {
1009 $offset = (int)$options['offset'];
1012 // First retrieve list of user-visible and sorted children ids from cache.
1013 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
1014 if ($sortedids === false) {
1015 $sortfieldskeys = array_keys($sortfields);
1016 if ($sortfieldskeys[0] === 'sortorder') {
1017 // No DB requests required to build the list of ids sorted by sortorder.
1018 // We can easily ignore other sort fields because sortorder is always different.
1019 $sortedids = self::get_tree($this->id);
1020 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
1021 $sortedids = array_diff($sortedids, $invisibleids);
1022 if ($sortfields['sortorder'] == -1) {
1023 $sortedids = array_reverse($sortedids, true);
1026 } else {
1027 // We need to retrieve and sort all children. Good thing that it is done only on first request.
1028 if ($invisibleids = $this->get_not_visible_children_ids()) {
1029 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
1030 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
1031 array('parent' => $this->id) + $params);
1032 } else {
1033 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
1035 self::sort_records($records, $sortfields);
1036 $sortedids = array_keys($records);
1038 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
1041 if (empty($sortedids)) {
1042 return array();
1045 // Now retrieive and return categories.
1046 if ($offset || $limit) {
1047 $sortedids = array_slice($sortedids, $offset, $limit);
1049 if (isset($records)) {
1050 // Easy, we have already retrieved records.
1051 if ($offset || $limit) {
1052 $records = array_slice($records, $offset, $limit, true);
1054 } else {
1055 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
1056 $records = self::get_records('cc.id '. $sql, array('parent' => $this->id) + $params);
1059 $rv = array();
1060 foreach ($sortedids as $id) {
1061 if (isset($records[$id])) {
1062 $rv[$id] = new coursecat($records[$id]);
1065 return $rv;
1069 * Returns true if the user has the manage capability on any category.
1071 * This method uses the coursecat cache and an entry `has_manage_capability` to speed up
1072 * calls to this method.
1074 * @return bool
1076 public static function has_manage_capability_on_any() {
1077 return self::has_capability_on_any('moodle/category:manage');
1081 * Checks if the user has at least one of the given capabilities on any category.
1083 * @param array|string $capabilities One or more capabilities to check. Check made is an OR.
1084 * @return bool
1086 public static function has_capability_on_any($capabilities) {
1087 global $DB;
1088 if (!isloggedin() || isguestuser()) {
1089 return false;
1092 if (!is_array($capabilities)) {
1093 $capabilities = array($capabilities);
1095 $keys = array();
1096 foreach ($capabilities as $capability) {
1097 $keys[$capability] = sha1($capability);
1100 /* @var cache_session $cache */
1101 $cache = cache::make('core', 'coursecat');
1102 $hascapability = $cache->get_many($keys);
1103 $needtoload = false;
1104 foreach ($hascapability as $capability) {
1105 if ($capability === '1') {
1106 return true;
1107 } else if ($capability === false) {
1108 $needtoload = true;
1111 if ($needtoload === false) {
1112 // All capabilities were retrieved and the user didn't have any.
1113 return false;
1116 $haskey = null;
1117 $fields = context_helper::get_preload_record_columns_sql('ctx');
1118 $sql = "SELECT ctx.instanceid AS categoryid, $fields
1119 FROM {context} ctx
1120 WHERE contextlevel = :contextlevel
1121 ORDER BY depth ASC";
1122 $params = array('contextlevel' => CONTEXT_COURSECAT);
1123 $recordset = $DB->get_recordset_sql($sql, $params);
1124 foreach ($recordset as $context) {
1125 context_helper::preload_from_record($context);
1126 $context = context_coursecat::instance($context->categoryid);
1127 foreach ($capabilities as $capability) {
1128 if (has_capability($capability, $context)) {
1129 $haskey = $capability;
1130 break 2;
1134 $recordset->close();
1135 if ($haskey === null) {
1136 $data = array();
1137 foreach ($keys as $key) {
1138 $data[$key] = '0';
1140 $cache->set_many($data);
1141 return false;
1142 } else {
1143 $cache->set($haskey, '1');
1144 return true;
1149 * Returns true if the user can resort any category.
1150 * @return bool
1152 public static function can_resort_any() {
1153 return self::has_manage_capability_on_any();
1157 * Returns true if the user can change the parent of any category.
1158 * @return bool
1160 public static function can_change_parent_any() {
1161 return self::has_manage_capability_on_any();
1165 * Returns number of subcategories visible to the current user
1167 * @return int
1169 public function get_children_count() {
1170 $sortedids = self::get_tree($this->id);
1171 $invisibleids = $this->get_not_visible_children_ids();
1172 return count($sortedids) - count($invisibleids);
1176 * Returns true if the category has ANY children, including those not visible to the user
1178 * @return boolean
1180 public function has_children() {
1181 $allchildren = self::get_tree($this->id);
1182 return !empty($allchildren);
1186 * Returns true if the category has courses in it (count does not include courses
1187 * in child categories)
1189 * @return bool
1191 public function has_courses() {
1192 global $DB;
1193 return $DB->record_exists_sql("select 1 from {course} where category = ?",
1194 array($this->id));
1198 * Searches courses
1200 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1201 * to this when somebody edits courses or categories, however it is very
1202 * difficult to keep track of all possible changes that may affect list of courses.
1204 * @param array $search contains search criterias, such as:
1205 * - search - search string
1206 * - blocklist - id of block (if we are searching for courses containing specific block0
1207 * - modulelist - name of module (if we are searching for courses containing specific module
1208 * - tagid - id of tag
1209 * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
1210 * search is always category-independent
1211 * @return course_in_list[]
1213 public static function search_courses($search, $options = array()) {
1214 global $DB;
1215 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1216 $limit = !empty($options['limit']) ? $options['limit'] : null;
1217 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1219 $coursecatcache = cache::make('core', 'coursecat');
1220 $cachekey = 's-'. serialize($search + array('sort' => $sortfields));
1221 $cntcachekey = 'scnt-'. serialize($search);
1223 $ids = $coursecatcache->get($cachekey);
1224 if ($ids !== false) {
1225 // We already cached last search result.
1226 $ids = array_slice($ids, $offset, $limit);
1227 $courses = array();
1228 if (!empty($ids)) {
1229 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1230 $records = self::get_course_records("c.id ". $sql, $params, $options);
1231 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1232 if (!empty($options['coursecontacts'])) {
1233 self::preload_course_contacts($records);
1235 // If option 'idonly' is specified no further action is needed, just return list of ids.
1236 if (!empty($options['idonly'])) {
1237 return array_keys($records);
1239 // Prepare the list of course_in_list objects.
1240 foreach ($ids as $id) {
1241 $courses[$id] = new course_in_list($records[$id]);
1244 return $courses;
1247 $preloadcoursecontacts = !empty($options['coursecontacts']);
1248 unset($options['coursecontacts']);
1250 if (!empty($search['search'])) {
1251 // Search courses that have specified words in their names/summaries.
1252 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1253 $searchterms = array_filter($searchterms, create_function('$v', 'return strlen($v) > 1;'));
1254 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount);
1255 self::sort_records($courselist, $sortfields);
1256 $coursecatcache->set($cachekey, array_keys($courselist));
1257 $coursecatcache->set($cntcachekey, $totalcount);
1258 $records = array_slice($courselist, $offset, $limit, true);
1259 } else {
1260 if (!empty($search['blocklist'])) {
1261 // Search courses that have block with specified id.
1262 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1263 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1264 WHERE bi.blockname = :blockname)';
1265 $params = array('blockname' => $blockname);
1266 } else if (!empty($search['modulelist'])) {
1267 // Search courses that have module with specified name.
1268 $where = "c.id IN (SELECT DISTINCT module.course ".
1269 "FROM {".$search['modulelist']."} module)";
1270 $params = array();
1271 } else if (!empty($search['tagid'])) {
1272 // Search courses that are tagged with the specified tag.
1273 $where = "c.id IN (SELECT t.itemid ".
1274 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype)";
1275 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course');
1276 } else {
1277 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1278 return array();
1280 $courselist = self::get_course_records($where, $params, $options, true);
1281 self::sort_records($courselist, $sortfields);
1282 $coursecatcache->set($cachekey, array_keys($courselist));
1283 $coursecatcache->set($cntcachekey, count($courselist));
1284 $records = array_slice($courselist, $offset, $limit, true);
1287 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1288 if (!empty($preloadcoursecontacts)) {
1289 self::preload_course_contacts($records);
1291 // If option 'idonly' is specified no further action is needed, just return list of ids.
1292 if (!empty($options['idonly'])) {
1293 return array_keys($records);
1295 // Prepare the list of course_in_list objects.
1296 $courses = array();
1297 foreach ($records as $record) {
1298 $courses[$record->id] = new course_in_list($record);
1300 return $courses;
1304 * Returns number of courses in the search results
1306 * It is recommended to call this function after {@link coursecat::search_courses()}
1307 * and not before because only course ids are cached. Otherwise search_courses() may
1308 * perform extra DB queries.
1310 * @param array $search search criteria, see method search_courses() for more details
1311 * @param array $options display options. They do not affect the result but
1312 * the 'sort' property is used in cache key for storing list of course ids
1313 * @return int
1315 public static function search_courses_count($search, $options = array()) {
1316 $coursecatcache = cache::make('core', 'coursecat');
1317 $cntcachekey = 'scnt-'. serialize($search);
1318 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1319 // Cached value not found. Retrieve ALL courses and return their count.
1320 unset($options['offset']);
1321 unset($options['limit']);
1322 unset($options['summary']);
1323 unset($options['coursecontacts']);
1324 $options['idonly'] = true;
1325 $courses = self::search_courses($search, $options);
1326 $cnt = count($courses);
1328 return $cnt;
1332 * Retrieves the list of courses accessible by user
1334 * Not all information is cached, try to avoid calling this method
1335 * twice in the same request.
1337 * The following fields are always retrieved:
1338 * - id, visible, fullname, shortname, idnumber, category, sortorder
1340 * If you plan to use properties/methods course_in_list::$summary and/or
1341 * course_in_list::get_course_contacts()
1342 * you can preload this information using appropriate 'options'. Otherwise
1343 * they will be retrieved from DB on demand and it may end with bigger DB load.
1345 * Note that method course_in_list::has_summary() will not perform additional
1346 * DB queries even if $options['summary'] is not specified
1348 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1349 * to this when somebody edits courses or categories, however it is very
1350 * difficult to keep track of all possible changes that may affect list of courses.
1352 * @param array $options options for retrieving children
1353 * - recursive - return courses from subcategories as well. Use with care,
1354 * this may be a huge list!
1355 * - summary - preloads fields 'summary' and 'summaryformat'
1356 * - coursecontacts - preloads course contacts
1357 * - sort - list of fields to sort. Example
1358 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1359 * will sort by idnumber asc, shortname asc and id desc.
1360 * Default: array('sortorder' => 1)
1361 * Only cached fields may be used for sorting!
1362 * - offset
1363 * - limit - maximum number of children to return, 0 or null for no limit
1364 * - idonly - returns the array or course ids instead of array of objects
1365 * used only in get_courses_count()
1366 * @return course_in_list[]
1368 public function get_courses($options = array()) {
1369 global $DB;
1370 $recursive = !empty($options['recursive']);
1371 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1372 $limit = !empty($options['limit']) ? $options['limit'] : null;
1373 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1375 // Check if this category is hidden.
1376 // Also 0-category never has courses unless this is recursive call.
1377 if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1378 return array();
1381 $coursecatcache = cache::make('core', 'coursecat');
1382 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1383 '-'. serialize($sortfields);
1384 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1386 // Check if we have already cached results.
1387 $ids = $coursecatcache->get($cachekey);
1388 if ($ids !== false) {
1389 // We already cached last search result and it did not expire yet.
1390 $ids = array_slice($ids, $offset, $limit);
1391 $courses = array();
1392 if (!empty($ids)) {
1393 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1394 $records = self::get_course_records("c.id ". $sql, $params, $options);
1395 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1396 if (!empty($options['coursecontacts'])) {
1397 self::preload_course_contacts($records);
1399 // If option 'idonly' is specified no further action is needed, just return list of ids.
1400 if (!empty($options['idonly'])) {
1401 return array_keys($records);
1403 // Prepare the list of course_in_list objects.
1404 foreach ($ids as $id) {
1405 $courses[$id] = new course_in_list($records[$id]);
1408 return $courses;
1411 // Retrieve list of courses in category.
1412 $where = 'c.id <> :siteid';
1413 $params = array('siteid' => SITEID);
1414 if ($recursive) {
1415 if ($this->id) {
1416 $context = context_coursecat::instance($this->id);
1417 $where .= ' AND ctx.path like :path';
1418 $params['path'] = $context->path. '/%';
1420 } else {
1421 $where .= ' AND c.category = :categoryid';
1422 $params['categoryid'] = $this->id;
1424 // Get list of courses without preloaded coursecontacts because we don't need them for every course.
1425 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1427 // Sort and cache list.
1428 self::sort_records($list, $sortfields);
1429 $coursecatcache->set($cachekey, array_keys($list));
1430 $coursecatcache->set($cntcachekey, count($list));
1432 // Apply offset/limit, convert to course_in_list and return.
1433 $courses = array();
1434 if (isset($list)) {
1435 if ($offset || $limit) {
1436 $list = array_slice($list, $offset, $limit, true);
1438 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1439 if (!empty($options['coursecontacts'])) {
1440 self::preload_course_contacts($list);
1442 // If option 'idonly' is specified no further action is needed, just return list of ids.
1443 if (!empty($options['idonly'])) {
1444 return array_keys($list);
1446 // Prepare the list of course_in_list objects.
1447 foreach ($list as $record) {
1448 $courses[$record->id] = new course_in_list($record);
1451 return $courses;
1455 * Returns number of courses visible to the user
1457 * @param array $options similar to get_courses() except some options do not affect
1458 * number of courses (i.e. sort, summary, offset, limit etc.)
1459 * @return int
1461 public function get_courses_count($options = array()) {
1462 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1463 $coursecatcache = cache::make('core', 'coursecat');
1464 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1465 // Cached value not found. Retrieve ALL courses and return their count.
1466 unset($options['offset']);
1467 unset($options['limit']);
1468 unset($options['summary']);
1469 unset($options['coursecontacts']);
1470 $options['idonly'] = true;
1471 $courses = $this->get_courses($options);
1472 $cnt = count($courses);
1474 return $cnt;
1478 * Returns true if the user is able to delete this category.
1480 * Note if this category contains any courses this isn't a full check, it will need to be accompanied by a call to either
1481 * {@link coursecat::can_delete_full()} or {@link coursecat::can_move_content_to()} depending upon what the user wished to do.
1483 * @return boolean
1485 public function can_delete() {
1486 if (!$this->has_manage_capability()) {
1487 return false;
1489 return $this->parent_has_manage_capability();
1493 * Returns true if user can delete current category and all its contents
1495 * To be able to delete course category the user must have permission
1496 * 'moodle/category:manage' in ALL child course categories AND
1497 * be able to delete all courses
1499 * @return bool
1501 public function can_delete_full() {
1502 global $DB;
1503 if (!$this->id) {
1504 // Fool-proof.
1505 return false;
1508 $context = $this->get_context();
1509 if (!$this->is_uservisible() ||
1510 !has_capability('moodle/category:manage', $context)) {
1511 return false;
1514 // Check all child categories (not only direct children).
1515 $sql = context_helper::get_preload_record_columns_sql('ctx');
1516 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1517 ' FROM {context} ctx '.
1518 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1519 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1520 array($context->path. '/%', CONTEXT_COURSECAT));
1521 foreach ($childcategories as $childcat) {
1522 context_helper::preload_from_record($childcat);
1523 $childcontext = context_coursecat::instance($childcat->id);
1524 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1525 !has_capability('moodle/category:manage', $childcontext)) {
1526 return false;
1530 // Check courses.
1531 $sql = context_helper::get_preload_record_columns_sql('ctx');
1532 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1533 $sql. ' FROM {context} ctx '.
1534 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1535 array('pathmask' => $context->path. '/%',
1536 'courselevel' => CONTEXT_COURSE));
1537 foreach ($coursescontexts as $ctxrecord) {
1538 context_helper::preload_from_record($ctxrecord);
1539 if (!can_delete_course($ctxrecord->courseid)) {
1540 return false;
1544 return true;
1548 * Recursively delete category including all subcategories and courses
1550 * Function {@link coursecat::can_delete_full()} MUST be called prior
1551 * to calling this function because there is no capability check
1552 * inside this function
1554 * @param boolean $showfeedback display some notices
1555 * @return array return deleted courses
1556 * @throws moodle_exception
1558 public function delete_full($showfeedback = true) {
1559 global $CFG, $DB;
1561 require_once($CFG->libdir.'/gradelib.php');
1562 require_once($CFG->libdir.'/questionlib.php');
1563 require_once($CFG->dirroot.'/cohort/lib.php');
1565 $deletedcourses = array();
1567 // Get children. Note, we don't want to use cache here because it would be rebuilt too often.
1568 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1569 foreach ($children as $record) {
1570 $coursecat = new coursecat($record);
1571 $deletedcourses += $coursecat->delete_full($showfeedback);
1574 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1575 foreach ($courses as $course) {
1576 if (!delete_course($course, false)) {
1577 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1579 $deletedcourses[] = $course;
1583 // Move or delete cohorts in this context.
1584 cohort_delete_category($this);
1586 // Now delete anything that may depend on course category context.
1587 grade_course_category_delete($this->id, 0, $showfeedback);
1588 if (!question_delete_course_category($this, 0, $showfeedback)) {
1589 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1592 // Finally delete the category and it's context.
1593 $DB->delete_records('course_categories', array('id' => $this->id));
1595 $coursecatcontext = context_coursecat::instance($this->id);
1596 $coursecatcontext->delete();
1598 cache_helper::purge_by_event('changesincoursecat');
1600 // Trigger a course category deleted event.
1601 /* @var \core\event\course_category_deleted $event */
1602 $event = \core\event\course_category_deleted::create(array(
1603 'objectid' => $this->id,
1604 'context' => $coursecatcontext,
1605 'other' => array('name' => $this->name)
1607 $event->set_coursecat($this);
1608 $event->trigger();
1610 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1611 if ($this->id == $CFG->defaultrequestcategory) {
1612 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1614 return $deletedcourses;
1618 * Checks if user can delete this category and move content (courses, subcategories and questions)
1619 * to another category. If yes returns the array of possible target categories names
1621 * If user can not manage this category or it is completely empty - empty array will be returned
1623 * @return array
1625 public function move_content_targets_list() {
1626 global $CFG;
1627 require_once($CFG->libdir . '/questionlib.php');
1628 $context = $this->get_context();
1629 if (!$this->is_uservisible() ||
1630 !has_capability('moodle/category:manage', $context)) {
1631 // User is not able to manage current category, he is not able to delete it.
1632 // No possible target categories.
1633 return array();
1636 $testcaps = array();
1637 // If this category has courses in it, user must have 'course:create' capability in target category.
1638 if ($this->has_courses()) {
1639 $testcaps[] = 'moodle/course:create';
1641 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1642 if ($this->has_children() || question_context_has_any_questions($context)) {
1643 $testcaps[] = 'moodle/category:manage';
1645 if (!empty($testcaps)) {
1646 // Return list of categories excluding this one and it's children.
1647 return self::make_categories_list($testcaps, $this->id);
1650 // Category is completely empty, no need in target for contents.
1651 return array();
1655 * Checks if user has capability to move all category content to the new parent before
1656 * removing this category
1658 * @param int $newcatid
1659 * @return bool
1661 public function can_move_content_to($newcatid) {
1662 global $CFG;
1663 require_once($CFG->libdir . '/questionlib.php');
1664 $context = $this->get_context();
1665 if (!$this->is_uservisible() ||
1666 !has_capability('moodle/category:manage', $context)) {
1667 return false;
1669 $testcaps = array();
1670 // If this category has courses in it, user must have 'course:create' capability in target category.
1671 if ($this->has_courses()) {
1672 $testcaps[] = 'moodle/course:create';
1674 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1675 if ($this->has_children() || question_context_has_any_questions($context)) {
1676 $testcaps[] = 'moodle/category:manage';
1678 if (!empty($testcaps)) {
1679 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1682 // There is no content but still return true.
1683 return true;
1687 * Deletes a category and moves all content (children, courses and questions) to the new parent
1689 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1690 * must be called prior
1692 * @param int $newparentid
1693 * @param bool $showfeedback
1694 * @return bool
1696 public function delete_move($newparentid, $showfeedback = false) {
1697 global $CFG, $DB, $OUTPUT;
1699 require_once($CFG->libdir.'/gradelib.php');
1700 require_once($CFG->libdir.'/questionlib.php');
1701 require_once($CFG->dirroot.'/cohort/lib.php');
1703 // Get all objects and lists because later the caches will be reset so.
1704 // We don't need to make extra queries.
1705 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1706 $catname = $this->get_formatted_name();
1707 $children = $this->get_children();
1708 $params = array('category' => $this->id);
1709 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', $params);
1710 $context = $this->get_context();
1712 if ($children) {
1713 foreach ($children as $childcat) {
1714 $childcat->change_parent_raw($newparentcat);
1715 // Log action.
1716 $event = \core\event\course_category_updated::create(array(
1717 'objectid' => $childcat->id,
1718 'context' => $childcat->get_context()
1720 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $childcat->id,
1721 $childcat->id));
1722 $event->trigger();
1724 fix_course_sortorder();
1727 if ($coursesids) {
1728 if (!move_courses($coursesids, $newparentid)) {
1729 if ($showfeedback) {
1730 echo $OUTPUT->notification("Error moving courses");
1732 return false;
1734 if ($showfeedback) {
1735 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1739 // Move or delete cohorts in this context.
1740 cohort_delete_category($this);
1742 // Now delete anything that may depend on course category context.
1743 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1744 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1745 if ($showfeedback) {
1746 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1748 return false;
1751 // Finally delete the category and it's context.
1752 $DB->delete_records('course_categories', array('id' => $this->id));
1753 $context->delete();
1755 // Trigger a course category deleted event.
1756 /* @var \core\event\course_category_deleted $event */
1757 $event = \core\event\course_category_deleted::create(array(
1758 'objectid' => $this->id,
1759 'context' => $context,
1760 'other' => array('name' => $this->name)
1762 $event->set_coursecat($this);
1763 $event->trigger();
1765 cache_helper::purge_by_event('changesincoursecat');
1767 if ($showfeedback) {
1768 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1771 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1772 if ($this->id == $CFG->defaultrequestcategory) {
1773 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1775 return true;
1779 * Checks if user can move current category to the new parent
1781 * This checks if new parent category exists, user has manage cap there
1782 * and new parent is not a child of this category
1784 * @param int|stdClass|coursecat $newparentcat
1785 * @return bool
1787 public function can_change_parent($newparentcat) {
1788 if (!has_capability('moodle/category:manage', $this->get_context())) {
1789 return false;
1791 if (is_object($newparentcat)) {
1792 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1793 } else {
1794 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1796 if (!$newparentcat) {
1797 return false;
1799 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1800 // Can not move to itself or it's own child.
1801 return false;
1803 if ($newparentcat->id) {
1804 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
1805 } else {
1806 return has_capability('moodle/category:manage', context_system::instance());
1811 * Moves the category under another parent category. All associated contexts are moved as well
1813 * This is protected function, use change_parent() or update() from outside of this class
1815 * @see coursecat::change_parent()
1816 * @see coursecat::update()
1818 * @param coursecat $newparentcat
1819 * @throws moodle_exception
1821 protected function change_parent_raw(coursecat $newparentcat) {
1822 global $DB;
1824 $context = $this->get_context();
1826 $hidecat = false;
1827 if (empty($newparentcat->id)) {
1828 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1829 $newparent = context_system::instance();
1830 } else {
1831 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1832 // Can not move to itself or it's own child.
1833 throw new moodle_exception('cannotmovecategory');
1835 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
1836 $newparent = context_coursecat::instance($newparentcat->id);
1838 if (!$newparentcat->visible and $this->visible) {
1839 // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children
1840 // will be restored properly.
1841 $hidecat = true;
1844 $this->parent = $newparentcat->id;
1846 $context->update_moved($newparent);
1848 // Now make it last in new category.
1849 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
1851 if ($hidecat) {
1852 fix_course_sortorder();
1853 $this->restore();
1854 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must
1855 // become visible again.
1856 $this->hide_raw(1);
1861 * Efficiently moves a category - NOTE that this can have
1862 * a huge impact access-control-wise...
1864 * Note that this function does not check capabilities.
1866 * Example of usage:
1867 * $coursecat = coursecat::get($categoryid);
1868 * if ($coursecat->can_change_parent($newparentcatid)) {
1869 * $coursecat->change_parent($newparentcatid);
1872 * This function does not update field course_categories.timemodified
1873 * If you want to update timemodified, use
1874 * $coursecat->update(array('parent' => $newparentcat));
1876 * @param int|stdClass|coursecat $newparentcat
1878 public function change_parent($newparentcat) {
1879 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1880 if (is_object($newparentcat)) {
1881 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
1882 } else {
1883 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
1885 if ($newparentcat->id != $this->parent) {
1886 $this->change_parent_raw($newparentcat);
1887 fix_course_sortorder();
1888 cache_helper::purge_by_event('changesincoursecat');
1889 $this->restore();
1891 $event = \core\event\course_category_updated::create(array(
1892 'objectid' => $this->id,
1893 'context' => $this->get_context()
1895 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $this->id, $this->id));
1896 $event->trigger();
1901 * Hide course category and child course and subcategories
1903 * If this category has changed the parent and is moved under hidden
1904 * category we will want to store it's current visibility state in
1905 * the field 'visibleold'. If admin clicked 'hide' for this particular
1906 * category, the field 'visibleold' should become 0.
1908 * All subcategories and courses will have their current visibility in the field visibleold
1910 * This is protected function, use hide() or update() from outside of this class
1912 * @see coursecat::hide()
1913 * @see coursecat::update()
1915 * @param int $visibleold value to set in field $visibleold for this category
1916 * @return bool whether changes have been made and caches need to be purged afterwards
1918 protected function hide_raw($visibleold = 0) {
1919 global $DB;
1920 $changes = false;
1922 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing.
1923 if ($this->id && $this->__get('visibleold') != $visibleold) {
1924 $this->visibleold = $visibleold;
1925 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
1926 $changes = true;
1928 if (!$this->visible || !$this->id) {
1929 // Already hidden or can not be hidden.
1930 return $changes;
1933 $this->visible = 0;
1934 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
1935 // Store visible flag so that we can return to it if we immediately unhide.
1936 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id));
1937 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
1938 // Get all child categories and hide too.
1939 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
1940 foreach ($subcats as $cat) {
1941 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
1942 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
1943 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
1944 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
1947 return true;
1951 * Hide course category and child course and subcategories
1953 * Note that there is no capability check inside this function
1955 * This function does not update field course_categories.timemodified
1956 * If you want to update timemodified, use
1957 * $coursecat->update(array('visible' => 0));
1959 public function hide() {
1960 if ($this->hide_raw(0)) {
1961 cache_helper::purge_by_event('changesincoursecat');
1963 $event = \core\event\course_category_updated::create(array(
1964 'objectid' => $this->id,
1965 'context' => $this->get_context()
1967 $event->set_legacy_logdata(array(SITEID, 'category', 'hide', 'editcategory.php?id=' . $this->id, $this->id));
1968 $event->trigger();
1973 * Show course category and restores visibility for child course and subcategories
1975 * Note that there is no capability check inside this function
1977 * This is protected function, use show() or update() from outside of this class
1979 * @see coursecat::show()
1980 * @see coursecat::update()
1982 * @return bool whether changes have been made and caches need to be purged afterwards
1984 protected function show_raw() {
1985 global $DB;
1987 if ($this->visible) {
1988 // Already visible.
1989 return false;
1992 $this->visible = 1;
1993 $this->visibleold = 1;
1994 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
1995 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
1996 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
1997 // Get all child categories and unhide too.
1998 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
1999 foreach ($subcats as $cat) {
2000 if ($cat->visibleold) {
2001 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
2003 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
2006 return true;
2010 * Show course category and restores visibility for child course and subcategories
2012 * Note that there is no capability check inside this function
2014 * This function does not update field course_categories.timemodified
2015 * If you want to update timemodified, use
2016 * $coursecat->update(array('visible' => 1));
2018 public function show() {
2019 if ($this->show_raw()) {
2020 cache_helper::purge_by_event('changesincoursecat');
2022 $event = \core\event\course_category_updated::create(array(
2023 'objectid' => $this->id,
2024 'context' => $this->get_context()
2026 $event->set_legacy_logdata(array(SITEID, 'category', 'show', 'editcategory.php?id=' . $this->id, $this->id));
2027 $event->trigger();
2032 * Returns name of the category formatted as a string
2034 * @param array $options formatting options other than context
2035 * @return string
2037 public function get_formatted_name($options = array()) {
2038 if ($this->id) {
2039 $context = $this->get_context();
2040 return format_string($this->name, true, array('context' => $context) + $options);
2041 } else {
2042 return get_string('top');
2047 * Returns ids of all parents of the category. Last element in the return array is the direct parent
2049 * For example, if you have a tree of categories like:
2050 * Miscellaneous (id = 1)
2051 * Subcategory (id = 2)
2052 * Sub-subcategory (id = 4)
2053 * Other category (id = 3)
2055 * coursecat::get(1)->get_parents() == array()
2056 * coursecat::get(2)->get_parents() == array(1)
2057 * coursecat::get(4)->get_parents() == array(1, 2);
2059 * Note that this method does not check if all parents are accessible by current user
2061 * @return array of category ids
2063 public function get_parents() {
2064 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
2065 array_pop($parents);
2066 return $parents;
2070 * This function returns a nice list representing category tree
2071 * for display or to use in a form <select> element
2073 * List is cached for 10 minutes
2075 * For example, if you have a tree of categories like:
2076 * Miscellaneous (id = 1)
2077 * Subcategory (id = 2)
2078 * Sub-subcategory (id = 4)
2079 * Other category (id = 3)
2080 * Then after calling this function you will have
2081 * array(1 => 'Miscellaneous',
2082 * 2 => 'Miscellaneous / Subcategory',
2083 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2084 * 3 => 'Other category');
2086 * If you specify $requiredcapability, then only categories where the current
2087 * user has that capability will be added to $list.
2088 * If you only have $requiredcapability in a child category, not the parent,
2089 * then the child catgegory will still be included.
2091 * If you specify the option $excludeid, then that category, and all its children,
2092 * are omitted from the tree. This is useful when you are doing something like
2093 * moving categories, where you do not want to allow people to move a category
2094 * to be the child of itself.
2096 * See also {@link make_categories_options()}
2098 * @param string/array $requiredcapability if given, only categories where the current
2099 * user has this capability will be returned. Can also be an array of capabilities,
2100 * in which case they are all required.
2101 * @param integer $excludeid Exclude this category and its children from the lists built.
2102 * @param string $separator string to use as a separator between parent and child category. Default ' / '
2103 * @return array of strings
2105 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
2106 global $DB;
2107 $coursecatcache = cache::make('core', 'coursecat');
2109 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids
2110 // with requried cap ($thislist).
2111 $currentlang = current_language();
2112 $basecachekey = $currentlang . '_catlist';
2113 $baselist = $coursecatcache->get($basecachekey);
2114 $thislist = false;
2115 $thiscachekey = null;
2116 if (!empty($requiredcapability)) {
2117 $requiredcapability = (array)$requiredcapability;
2118 $thiscachekey = 'catlist:'. serialize($requiredcapability);
2119 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
2120 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
2122 } else if ($baselist !== false) {
2123 $thislist = array_keys($baselist);
2126 if ($baselist === false) {
2127 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
2128 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2129 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
2130 FROM {course_categories} cc
2131 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
2132 ORDER BY cc.sortorder";
2133 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2134 $baselist = array();
2135 $thislist = array();
2136 foreach ($rs as $record) {
2137 // If the category's parent is not visible to the user, it is not visible as well.
2138 if (!$record->parent || isset($baselist[$record->parent])) {
2139 context_helper::preload_from_record($record);
2140 $context = context_coursecat::instance($record->id);
2141 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
2142 // No cap to view category, added to neither $baselist nor $thislist.
2143 continue;
2145 $baselist[$record->id] = array(
2146 'name' => format_string($record->name, true, array('context' => $context)),
2147 'path' => $record->path
2149 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
2150 // No required capability, added to $baselist but not to $thislist.
2151 continue;
2153 $thislist[] = $record->id;
2156 $rs->close();
2157 $coursecatcache->set($basecachekey, $baselist);
2158 if (!empty($requiredcapability)) {
2159 $coursecatcache->set($thiscachekey, join(',', $thislist));
2161 } else if ($thislist === false) {
2162 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
2163 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2164 $sql = "SELECT ctx.instanceid AS id, $ctxselect
2165 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
2166 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2167 $thislist = array();
2168 foreach (array_keys($baselist) as $id) {
2169 context_helper::preload_from_record($contexts[$id]);
2170 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
2171 $thislist[] = $id;
2174 $coursecatcache->set($thiscachekey, join(',', $thislist));
2177 // Now build the array of strings to return, mind $separator and $excludeid.
2178 $names = array();
2179 foreach ($thislist as $id) {
2180 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
2181 if (!$excludeid || !in_array($excludeid, $path)) {
2182 $namechunks = array();
2183 foreach ($path as $parentid) {
2184 $namechunks[] = $baselist[$parentid]['name'];
2186 $names[$id] = join($separator, $namechunks);
2189 return $names;
2193 * Prepares the object for caching. Works like the __sleep method.
2195 * implementing method from interface cacheable_object
2197 * @return array ready to be cached
2199 public function prepare_to_cache() {
2200 $a = array();
2201 foreach (self::$coursecatfields as $property => $cachedirectives) {
2202 if ($cachedirectives !== null) {
2203 list($shortname, $defaultvalue) = $cachedirectives;
2204 if ($this->$property !== $defaultvalue) {
2205 $a[$shortname] = $this->$property;
2209 $context = $this->get_context();
2210 $a['xi'] = $context->id;
2211 $a['xp'] = $context->path;
2212 return $a;
2216 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2218 * implementing method from interface cacheable_object
2220 * @param array $a
2221 * @return coursecat
2223 public static function wake_from_cache($a) {
2224 $record = new stdClass;
2225 foreach (self::$coursecatfields as $property => $cachedirectives) {
2226 if ($cachedirectives !== null) {
2227 list($shortname, $defaultvalue) = $cachedirectives;
2228 if (array_key_exists($shortname, $a)) {
2229 $record->$property = $a[$shortname];
2230 } else {
2231 $record->$property = $defaultvalue;
2235 $record->ctxid = $a['xi'];
2236 $record->ctxpath = $a['xp'];
2237 $record->ctxdepth = $record->depth + 1;
2238 $record->ctxlevel = CONTEXT_COURSECAT;
2239 $record->ctxinstance = $record->id;
2240 return new coursecat($record, true);
2244 * Returns true if the user is able to create a top level category.
2245 * @return bool
2247 public static function can_create_top_level_category() {
2248 return has_capability('moodle/category:manage', context_system::instance());
2252 * Returns the category context.
2253 * @return context_coursecat
2255 public function get_context() {
2256 if ($this->id === 0) {
2257 // This is the special top level category object.
2258 return context_system::instance();
2259 } else {
2260 return context_coursecat::instance($this->id);
2265 * Returns true if the user is able to manage this category.
2266 * @return bool
2268 public function has_manage_capability() {
2269 if ($this->hasmanagecapability === null) {
2270 $this->hasmanagecapability = has_capability('moodle/category:manage', $this->get_context());
2272 return $this->hasmanagecapability;
2276 * Returns true if the user has the manage capability on the parent category.
2277 * @return bool
2279 public function parent_has_manage_capability() {
2280 return has_capability('moodle/category:manage', get_category_or_system_context($this->parent));
2284 * Returns true if the current user can create subcategories of this category.
2285 * @return bool
2287 public function can_create_subcategory() {
2288 return $this->has_manage_capability();
2292 * Returns true if the user can resort this categories sub categories and courses.
2293 * Must have manage capability and be able to see all subcategories.
2294 * @return bool
2296 public function can_resort_subcategories() {
2297 return $this->has_manage_capability() && !$this->get_not_visible_children_ids();
2301 * Returns true if the user can resort the courses within this category.
2302 * Must have manage capability and be able to see all courses.
2303 * @return bool
2305 public function can_resort_courses() {
2306 return $this->has_manage_capability() && $this->coursecount == $this->get_courses_count();
2310 * Returns true of the user can change the sortorder of this category (resort in the parent category)
2311 * @return bool
2313 public function can_change_sortorder() {
2314 return $this->id && $this->get_parent_coursecat()->can_resort_subcategories();
2318 * Returns true if the current user can create a course within this category.
2319 * @return bool
2321 public function can_create_course() {
2322 return has_capability('moodle/course:create', $this->get_context());
2326 * Returns true if the current user can edit this categories settings.
2327 * @return bool
2329 public function can_edit() {
2330 return $this->has_manage_capability();
2334 * Returns true if the current user can review role assignments for this category.
2335 * @return bool
2337 public function can_review_roles() {
2338 return has_capability('moodle/role:assign', $this->get_context());
2342 * Returns true if the current user can review permissions for this category.
2343 * @return bool
2345 public function can_review_permissions() {
2346 return has_any_capability(array(
2347 'moodle/role:assign',
2348 'moodle/role:safeoverride',
2349 'moodle/role:override',
2350 'moodle/role:assign'
2351 ), $this->get_context());
2355 * Returns true if the current user can review cohorts for this category.
2356 * @return bool
2358 public function can_review_cohorts() {
2359 return has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->get_context());
2363 * Returns true if the current user can review filter settings for this category.
2364 * @return bool
2366 public function can_review_filters() {
2367 return has_capability('moodle/filter:manage', $this->get_context()) &&
2368 count(filter_get_available_in_context($this->get_context()))>0;
2372 * Returns true if the current user is able to change the visbility of this category.
2373 * @return bool
2375 public function can_change_visibility() {
2376 return $this->parent_has_manage_capability();
2380 * Returns true if the user can move courses out of this category.
2381 * @return bool
2383 public function can_move_courses_out_of() {
2384 return $this->has_manage_capability();
2388 * Returns true if the user can move courses into this category.
2389 * @return bool
2391 public function can_move_courses_into() {
2392 return $this->has_manage_capability();
2396 * Returns true if the user is able to restore a course into this category as a new course.
2397 * @return bool
2399 public function can_restore_courses_into() {
2400 return has_capability('moodle/course:create', $this->get_context());
2404 * Resorts the sub categories of this category by the given field.
2406 * @param string $field One of name, idnumber or descending values of each (appended desc)
2407 * @param bool $cleanup If true cleanup will be done, if false you will need to do it manually later.
2408 * @return bool True on success.
2409 * @throws coding_exception
2411 public function resort_subcategories($field, $cleanup = true) {
2412 global $DB;
2413 $desc = false;
2414 if (substr($field, -4) === "desc") {
2415 $desc = true;
2416 $field = substr($field, 0, -4); // Remove "desc" from field name.
2418 if ($field !== 'name' && $field !== 'idnumber') {
2419 throw new coding_exception('Invalid field requested');
2421 $children = $this->get_children();
2422 core_collator::asort_objects_by_property($children, $field, core_collator::SORT_NATURAL);
2423 if (!empty($desc)) {
2424 $children = array_reverse($children);
2426 $i = 1;
2427 foreach ($children as $cat) {
2428 $i++;
2429 $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id));
2430 $i += $cat->coursecount;
2432 if ($cleanup) {
2433 self::resort_categories_cleanup();
2435 return true;
2439 * Cleans things up after categories have been resorted.
2440 * @param bool $includecourses If set to true we know courses have been resorted as well.
2442 public static function resort_categories_cleanup($includecourses = false) {
2443 // This should not be needed but we do it just to be safe.
2444 fix_course_sortorder();
2445 cache_helper::purge_by_event('changesincoursecat');
2446 if ($includecourses) {
2447 cache_helper::purge_by_event('changesincourse');
2452 * Resort the courses within this category by the given field.
2454 * @param string $field One of fullname, shortname, idnumber or descending values of each (appended desc)
2455 * @param bool $cleanup
2456 * @return bool True for success.
2457 * @throws coding_exception
2459 public function resort_courses($field, $cleanup = true) {
2460 global $DB;
2461 $desc = false;
2462 if (substr($field, -4) === "desc") {
2463 $desc = true;
2464 $field = substr($field, 0, -4); // Remove "desc" from field name.
2466 if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber' && $field !== 'timecreated') {
2467 // This is ultra important as we use $field in an SQL statement below this.
2468 throw new coding_exception('Invalid field requested');
2470 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
2471 $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields
2472 FROM {course} c
2473 LEFT JOIN {context} ctx ON ctx.instanceid = c.id
2474 WHERE ctx.contextlevel = :ctxlevel AND
2475 c.category = :categoryid";
2476 $params = array(
2477 'ctxlevel' => CONTEXT_COURSE,
2478 'categoryid' => $this->id
2480 $courses = $DB->get_records_sql($sql, $params);
2481 if (count($courses) > 0) {
2482 foreach ($courses as $courseid => $course) {
2483 context_helper::preload_from_record($course);
2484 if ($field === 'idnumber') {
2485 $course->sortby = $course->idnumber;
2486 } else {
2487 // It'll require formatting.
2488 $options = array(
2489 'context' => context_course::instance($course->id)
2491 // We format the string first so that it appears as the user would see it.
2492 // This ensures the sorting makes sense to them. However it won't necessarily make
2493 // sense to everyone if things like multilang filters are enabled.
2494 // We then strip any tags as we don't want things such as image tags skewing the
2495 // sort results.
2496 $course->sortby = strip_tags(format_string($course->$field, true, $options));
2498 // We set it back here rather than using references as there is a bug with using
2499 // references in a foreach before passing as an arg by reference.
2500 $courses[$courseid] = $course;
2502 // Sort the courses.
2503 core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL);
2504 if (!empty($desc)) {
2505 $courses = array_reverse($courses);
2507 $i = 1;
2508 foreach ($courses as $course) {
2509 $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id));
2510 $i++;
2512 if ($cleanup) {
2513 // This should not be needed but we do it just to be safe.
2514 fix_course_sortorder();
2515 cache_helper::purge_by_event('changesincourse');
2518 return true;
2522 * Changes the sort order of this categories parent shifting this category up or down one.
2524 * @global \moodle_database $DB
2525 * @param bool $up If set to true the category is shifted up one spot, else its moved down.
2526 * @return bool True on success, false otherwise.
2528 public function change_sortorder_by_one($up) {
2529 global $DB;
2530 $params = array($this->sortorder, $this->parent);
2531 if ($up) {
2532 $select = 'sortorder < ? AND parent = ?';
2533 $sort = 'sortorder DESC';
2534 } else {
2535 $select = 'sortorder > ? AND parent = ?';
2536 $sort = 'sortorder ASC';
2538 fix_course_sortorder();
2539 $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1);
2540 $swapcategory = reset($swapcategory);
2541 if ($swapcategory) {
2542 $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id));
2543 $DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id));
2544 $this->sortorder = $swapcategory->sortorder;
2546 $event = \core\event\course_category_updated::create(array(
2547 'objectid' => $this->id,
2548 'context' => $this->get_context()
2550 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'management.php?categoryid=' . $this->id,
2551 $this->id));
2552 $event->trigger();
2554 // Finally reorder courses.
2555 fix_course_sortorder();
2556 cache_helper::purge_by_event('changesincoursecat');
2557 return true;
2559 return false;
2563 * Returns the parent coursecat object for this category.
2565 * @return coursecat
2567 public function get_parent_coursecat() {
2568 return self::get($this->parent);
2573 * Returns true if the user is able to request a new course be created.
2574 * @return bool
2576 public function can_request_course() {
2577 global $CFG;
2578 if (empty($CFG->enablecourserequests) || $this->id != $CFG->defaultrequestcategory) {
2579 return false;
2581 return !$this->can_create_course() && has_capability('moodle/course:request', $this->get_context());
2585 * Returns true if the user can approve course requests.
2586 * @return bool
2588 public static function can_approve_course_requests() {
2589 global $CFG, $DB;
2590 if (empty($CFG->enablecourserequests)) {
2591 return false;
2593 $context = context_system::instance();
2594 if (!has_capability('moodle/site:approvecourse', $context)) {
2595 return false;
2597 if (!$DB->record_exists('course_request', array())) {
2598 return false;
2600 return true;
2605 * Class to store information about one course in a list of courses
2607 * Not all information may be retrieved when object is created but
2608 * it will be retrieved on demand when appropriate property or method is
2609 * called.
2611 * Instances of this class are usually returned by functions
2612 * {@link coursecat::search_courses()}
2613 * and
2614 * {@link coursecat::get_courses()}
2616 * @property-read int $id
2617 * @property-read int $category Category ID
2618 * @property-read int $sortorder
2619 * @property-read string $fullname
2620 * @property-read string $shortname
2621 * @property-read string $idnumber
2622 * @property-read string $summary Course summary. Field is present if coursecat::get_courses()
2623 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2624 * @property-read int $summaryformat Summary format. Field is present if coursecat::get_courses()
2625 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2626 * @property-read string $format Course format. Retrieved from DB on first request
2627 * @property-read int $showgrades Retrieved from DB on first request
2628 * @property-read int $newsitems Retrieved from DB on first request
2629 * @property-read int $startdate
2630 * @property-read int $marker Retrieved from DB on first request
2631 * @property-read int $maxbytes Retrieved from DB on first request
2632 * @property-read int $legacyfiles Retrieved from DB on first request
2633 * @property-read int $showreports Retrieved from DB on first request
2634 * @property-read int $visible
2635 * @property-read int $visibleold Retrieved from DB on first request
2636 * @property-read int $groupmode Retrieved from DB on first request
2637 * @property-read int $groupmodeforce Retrieved from DB on first request
2638 * @property-read int $defaultgroupingid Retrieved from DB on first request
2639 * @property-read string $lang Retrieved from DB on first request
2640 * @property-read string $theme Retrieved from DB on first request
2641 * @property-read int $timecreated Retrieved from DB on first request
2642 * @property-read int $timemodified Retrieved from DB on first request
2643 * @property-read int $requested Retrieved from DB on first request
2644 * @property-read int $enablecompletion Retrieved from DB on first request
2645 * @property-read int $completionnotify Retrieved from DB on first request
2646 * @property-read int $cacherev
2648 * @package core
2649 * @subpackage course
2650 * @copyright 2013 Marina Glancy
2651 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2653 class course_in_list implements IteratorAggregate {
2655 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2656 protected $record;
2658 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2659 protected $coursecontacts;
2661 /** @var bool true if the current user can access the course, false otherwise. */
2662 protected $canaccess = null;
2665 * Creates an instance of the class from record
2667 * @param stdClass $record except fields from course table it may contain
2668 * field hassummary indicating that summary field is not empty.
2669 * Also it is recommended to have context fields here ready for
2670 * context preloading
2672 public function __construct(stdClass $record) {
2673 context_helper::preload_from_record($record);
2674 $this->record = new stdClass();
2675 foreach ($record as $key => $value) {
2676 $this->record->$key = $value;
2681 * Indicates if the course has non-empty summary field
2683 * @return bool
2685 public function has_summary() {
2686 if (isset($this->record->hassummary)) {
2687 return !empty($this->record->hassummary);
2689 if (!isset($this->record->summary)) {
2690 // We need to retrieve summary.
2691 $this->__get('summary');
2693 return !empty($this->record->summary);
2697 * Indicates if the course have course contacts to display
2699 * @return bool
2701 public function has_course_contacts() {
2702 if (!isset($this->record->managers)) {
2703 $courses = array($this->id => &$this->record);
2704 coursecat::preload_course_contacts($courses);
2706 return !empty($this->record->managers);
2710 * Returns list of course contacts (usually teachers) to display in course link
2712 * Roles to display are set up in $CFG->coursecontact
2714 * The result is the list of users where user id is the key and the value
2715 * is an array with elements:
2716 * - 'user' - object containing basic user information
2717 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2718 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2719 * - 'username' => fullname($user, $canviewfullnames)
2721 * @return array
2723 public function get_course_contacts() {
2724 global $CFG;
2725 if (empty($CFG->coursecontact)) {
2726 // No roles are configured to be displayed as course contacts.
2727 return array();
2729 if ($this->coursecontacts === null) {
2730 $this->coursecontacts = array();
2731 $context = context_course::instance($this->id);
2733 if (!isset($this->record->managers)) {
2734 // Preload course contacts from DB.
2735 $courses = array($this->id => &$this->record);
2736 coursecat::preload_course_contacts($courses);
2739 // Build return array with full roles names (for this course context) and users names.
2740 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2741 foreach ($this->record->managers as $ruser) {
2742 if (isset($this->coursecontacts[$ruser->id])) {
2743 // Only display a user once with the highest sortorder role.
2744 continue;
2746 $user = new stdClass();
2747 $user = username_load_fields_from_object($user, $ruser, null, array('id', 'username'));
2748 $role = new stdClass();
2749 $role->id = $ruser->roleid;
2750 $role->name = $ruser->rolename;
2751 $role->shortname = $ruser->roleshortname;
2752 $role->coursealias = $ruser->rolecoursealias;
2754 $this->coursecontacts[$user->id] = array(
2755 'user' => $user,
2756 'role' => $role,
2757 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2758 'username' => fullname($user, $canviewfullnames)
2762 return $this->coursecontacts;
2766 * Checks if course has any associated overview files
2768 * @return bool
2770 public function has_course_overviewfiles() {
2771 global $CFG;
2772 if (empty($CFG->courseoverviewfileslimit)) {
2773 return false;
2775 $fs = get_file_storage();
2776 $context = context_course::instance($this->id);
2777 return !$fs->is_area_empty($context->id, 'course', 'overviewfiles');
2781 * Returns all course overview files
2783 * @return array array of stored_file objects
2785 public function get_course_overviewfiles() {
2786 global $CFG;
2787 if (empty($CFG->courseoverviewfileslimit)) {
2788 return array();
2790 require_once($CFG->libdir. '/filestorage/file_storage.php');
2791 require_once($CFG->dirroot. '/course/lib.php');
2792 $fs = get_file_storage();
2793 $context = context_course::instance($this->id);
2794 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2795 if (count($files)) {
2796 $overviewfilesoptions = course_overviewfiles_options($this->id);
2797 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2798 if ($acceptedtypes !== '*') {
2799 // Filter only files with allowed extensions.
2800 require_once($CFG->libdir. '/filelib.php');
2801 foreach ($files as $key => $file) {
2802 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2803 unset($files[$key]);
2807 if (count($files) > $CFG->courseoverviewfileslimit) {
2808 // Return no more than $CFG->courseoverviewfileslimit files.
2809 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
2812 return $files;
2816 * Magic method to check if property is set
2818 * @param string $name
2819 * @return bool
2821 public function __isset($name) {
2822 return isset($this->record->$name);
2826 * Magic method to get a course property
2828 * Returns any field from table course (retrieves it from DB if it was not retrieved before)
2830 * @param string $name
2831 * @return mixed
2833 public function __get($name) {
2834 global $DB;
2835 if (property_exists($this->record, $name)) {
2836 return $this->record->$name;
2837 } else if ($name === 'summary' || $name === 'summaryformat') {
2838 // Retrieve fields summary and summaryformat together because they are most likely to be used together.
2839 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
2840 $this->record->summary = $record->summary;
2841 $this->record->summaryformat = $record->summaryformat;
2842 return $this->record->$name;
2843 } else if (array_key_exists($name, $DB->get_columns('course'))) {
2844 // Another field from table 'course' that was not retrieved.
2845 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
2846 return $this->record->$name;
2848 debugging('Invalid course property accessed! '.$name);
2849 return null;
2853 * All properties are read only, sorry.
2855 * @param string $name
2857 public function __unset($name) {
2858 debugging('Can not unset '.get_class($this).' instance properties!');
2862 * Magic setter method, we do not want anybody to modify properties from the outside
2864 * @param string $name
2865 * @param mixed $value
2867 public function __set($name, $value) {
2868 debugging('Can not change '.get_class($this).' instance properties!');
2872 * Create an iterator because magic vars can't be seen by 'foreach'.
2873 * Exclude context fields
2875 * Implementing method from interface IteratorAggregate
2877 * @return ArrayIterator
2879 public function getIterator() {
2880 $ret = array('id' => $this->record->id);
2881 foreach ($this->record as $property => $value) {
2882 $ret[$property] = $value;
2884 return new ArrayIterator($ret);
2888 * Returns the name of this course as it should be displayed within a list.
2889 * @return string
2891 public function get_formatted_name() {
2892 return format_string(get_course_display_name_for_list($this), true, $this->get_context());
2896 * Returns the formatted fullname for this course.
2897 * @return string
2899 public function get_formatted_fullname() {
2900 return format_string($this->__get('fullname'), true, $this->get_context());
2904 * Returns the formatted shortname for this course.
2905 * @return string
2907 public function get_formatted_shortname() {
2908 return format_string($this->__get('shortname'), true, $this->get_context());
2912 * Returns true if the current user can access this course.
2913 * @return bool
2915 public function can_access() {
2916 if ($this->canaccess === null) {
2917 $this->canaccess = can_access_course($this->record);
2919 return $this->canaccess;
2923 * Returns true if the user can edit this courses settings.
2925 * Note: this function does not check that the current user can access the course.
2926 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2928 * @return bool
2930 public function can_edit() {
2931 return has_capability('moodle/course:update', $this->get_context());
2935 * Returns true if the user can change the visibility of this course.
2937 * Note: this function does not check that the current user can access the course.
2938 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2940 * @return bool
2942 public function can_change_visibility() {
2943 // You must be able to both hide a course and view the hidden course.
2944 return has_all_capabilities(array('moodle/course:visibility', 'moodle/course:viewhiddencourses'), $this->get_context());
2948 * Returns the context for this course.
2949 * @return context_course
2951 public function get_context() {
2952 return context_course::instance($this->__get('id'));
2956 * Returns true if this course is visible to the current user.
2957 * @return bool
2959 public function is_uservisible() {
2960 return $this->visible || has_capability('moodle/course:viewhiddencourses', $this->get_context());
2964 * Returns true if the current user can review enrolments for this course.
2966 * Note: this function does not check that the current user can access the course.
2967 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2969 * @return bool
2971 public function can_review_enrolments() {
2972 return has_capability('moodle/course:enrolreview', $this->get_context());
2976 * Returns true if the current user can delete this course.
2978 * Note: this function does not check that the current user can access the course.
2979 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2981 * @return bool
2983 public function can_delete() {
2984 return can_delete_course($this->id);
2988 * Returns true if the current user can backup this course.
2990 * Note: this function does not check that the current user can access the course.
2991 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2993 * @return bool
2995 public function can_backup() {
2996 return has_capability('moodle/backup:backupcourse', $this->get_context());
3000 * Returns true if the current user can restore this course.
3002 * Note: this function does not check that the current user can access the course.
3003 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3005 * @return bool
3007 public function can_restore() {
3008 return has_capability('moodle/restore:restorecourse', $this->get_context());
3013 * An array of records that is sortable by many fields.
3015 * For more info on the ArrayObject class have a look at php.net.
3017 * @package core
3018 * @subpackage course
3019 * @copyright 2013 Sam Hemelryk
3020 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3022 class coursecat_sortable_records extends ArrayObject {
3025 * An array of sortable fields.
3026 * Gets set temporarily when sort is called.
3027 * @var array
3029 protected $sortfields = array();
3032 * Sorts this array using the given fields.
3034 * @param array $records
3035 * @param array $fields
3036 * @return array
3038 public static function sort(array $records, array $fields) {
3039 $records = new coursecat_sortable_records($records);
3040 $records->sortfields = $fields;
3041 $records->uasort(array($records, 'sort_by_many_fields'));
3042 return $records->getArrayCopy();
3046 * Sorts the two records based upon many fields.
3048 * This method should not be called itself, please call $sort instead.
3049 * It has been marked as access private as such.
3051 * @access private
3052 * @param stdClass $a
3053 * @param stdClass $b
3054 * @return int
3056 public function sort_by_many_fields($a, $b) {
3057 foreach ($this->sortfields as $field => $mult) {
3058 // Nulls first.
3059 if (is_null($a->$field) && !is_null($b->$field)) {
3060 return -$mult;
3062 if (is_null($b->$field) && !is_null($a->$field)) {
3063 return $mult;
3066 if (is_string($a->$field) || is_string($b->$field)) {
3067 // String fields.
3068 if ($cmp = strcoll($a->$field, $b->$field)) {
3069 return $mult * $cmp;
3071 } else {
3072 // Int fields.
3073 if ($a->$field > $b->$field) {
3074 return $mult;
3076 if ($a->$field < $b->$field) {
3077 return -$mult;
3081 return 0;