MDL-49684 timezones: rewrite timezone support
[moodle.git] / lib / coursecatlib.php
blobd9609b4d65b348266ab51f8abd9cf10713a8e109
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 // Make sure we won't timeout when deleting a lot of courses.
1566 $settimeout = core_php_time_limit::raise();
1568 $deletedcourses = array();
1570 // Get children. Note, we don't want to use cache here because it would be rebuilt too often.
1571 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1572 foreach ($children as $record) {
1573 $coursecat = new coursecat($record);
1574 $deletedcourses += $coursecat->delete_full($showfeedback);
1577 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1578 foreach ($courses as $course) {
1579 if (!delete_course($course, false)) {
1580 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1582 $deletedcourses[] = $course;
1586 // Move or delete cohorts in this context.
1587 cohort_delete_category($this);
1589 // Now delete anything that may depend on course category context.
1590 grade_course_category_delete($this->id, 0, $showfeedback);
1591 if (!question_delete_course_category($this, 0, $showfeedback)) {
1592 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1595 // Finally delete the category and it's context.
1596 $DB->delete_records('course_categories', array('id' => $this->id));
1598 $coursecatcontext = context_coursecat::instance($this->id);
1599 $coursecatcontext->delete();
1601 cache_helper::purge_by_event('changesincoursecat');
1603 // Trigger a course category deleted event.
1604 /* @var \core\event\course_category_deleted $event */
1605 $event = \core\event\course_category_deleted::create(array(
1606 'objectid' => $this->id,
1607 'context' => $coursecatcontext,
1608 'other' => array('name' => $this->name)
1610 $event->set_coursecat($this);
1611 $event->trigger();
1613 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1614 if ($this->id == $CFG->defaultrequestcategory) {
1615 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1617 return $deletedcourses;
1621 * Checks if user can delete this category and move content (courses, subcategories and questions)
1622 * to another category. If yes returns the array of possible target categories names
1624 * If user can not manage this category or it is completely empty - empty array will be returned
1626 * @return array
1628 public function move_content_targets_list() {
1629 global $CFG;
1630 require_once($CFG->libdir . '/questionlib.php');
1631 $context = $this->get_context();
1632 if (!$this->is_uservisible() ||
1633 !has_capability('moodle/category:manage', $context)) {
1634 // User is not able to manage current category, he is not able to delete it.
1635 // No possible target categories.
1636 return array();
1639 $testcaps = array();
1640 // If this category has courses in it, user must have 'course:create' capability in target category.
1641 if ($this->has_courses()) {
1642 $testcaps[] = 'moodle/course:create';
1644 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1645 if ($this->has_children() || question_context_has_any_questions($context)) {
1646 $testcaps[] = 'moodle/category:manage';
1648 if (!empty($testcaps)) {
1649 // Return list of categories excluding this one and it's children.
1650 return self::make_categories_list($testcaps, $this->id);
1653 // Category is completely empty, no need in target for contents.
1654 return array();
1658 * Checks if user has capability to move all category content to the new parent before
1659 * removing this category
1661 * @param int $newcatid
1662 * @return bool
1664 public function can_move_content_to($newcatid) {
1665 global $CFG;
1666 require_once($CFG->libdir . '/questionlib.php');
1667 $context = $this->get_context();
1668 if (!$this->is_uservisible() ||
1669 !has_capability('moodle/category:manage', $context)) {
1670 return false;
1672 $testcaps = array();
1673 // If this category has courses in it, user must have 'course:create' capability in target category.
1674 if ($this->has_courses()) {
1675 $testcaps[] = 'moodle/course:create';
1677 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1678 if ($this->has_children() || question_context_has_any_questions($context)) {
1679 $testcaps[] = 'moodle/category:manage';
1681 if (!empty($testcaps)) {
1682 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1685 // There is no content but still return true.
1686 return true;
1690 * Deletes a category and moves all content (children, courses and questions) to the new parent
1692 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1693 * must be called prior
1695 * @param int $newparentid
1696 * @param bool $showfeedback
1697 * @return bool
1699 public function delete_move($newparentid, $showfeedback = false) {
1700 global $CFG, $DB, $OUTPUT;
1702 require_once($CFG->libdir.'/gradelib.php');
1703 require_once($CFG->libdir.'/questionlib.php');
1704 require_once($CFG->dirroot.'/cohort/lib.php');
1706 // Get all objects and lists because later the caches will be reset so.
1707 // We don't need to make extra queries.
1708 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1709 $catname = $this->get_formatted_name();
1710 $children = $this->get_children();
1711 $params = array('category' => $this->id);
1712 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', $params);
1713 $context = $this->get_context();
1715 if ($children) {
1716 foreach ($children as $childcat) {
1717 $childcat->change_parent_raw($newparentcat);
1718 // Log action.
1719 $event = \core\event\course_category_updated::create(array(
1720 'objectid' => $childcat->id,
1721 'context' => $childcat->get_context()
1723 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $childcat->id,
1724 $childcat->id));
1725 $event->trigger();
1727 fix_course_sortorder();
1730 if ($coursesids) {
1731 if (!move_courses($coursesids, $newparentid)) {
1732 if ($showfeedback) {
1733 echo $OUTPUT->notification("Error moving courses");
1735 return false;
1737 if ($showfeedback) {
1738 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1742 // Move or delete cohorts in this context.
1743 cohort_delete_category($this);
1745 // Now delete anything that may depend on course category context.
1746 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1747 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1748 if ($showfeedback) {
1749 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1751 return false;
1754 // Finally delete the category and it's context.
1755 $DB->delete_records('course_categories', array('id' => $this->id));
1756 $context->delete();
1758 // Trigger a course category deleted event.
1759 /* @var \core\event\course_category_deleted $event */
1760 $event = \core\event\course_category_deleted::create(array(
1761 'objectid' => $this->id,
1762 'context' => $context,
1763 'other' => array('name' => $this->name)
1765 $event->set_coursecat($this);
1766 $event->trigger();
1768 cache_helper::purge_by_event('changesincoursecat');
1770 if ($showfeedback) {
1771 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1774 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1775 if ($this->id == $CFG->defaultrequestcategory) {
1776 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1778 return true;
1782 * Checks if user can move current category to the new parent
1784 * This checks if new parent category exists, user has manage cap there
1785 * and new parent is not a child of this category
1787 * @param int|stdClass|coursecat $newparentcat
1788 * @return bool
1790 public function can_change_parent($newparentcat) {
1791 if (!has_capability('moodle/category:manage', $this->get_context())) {
1792 return false;
1794 if (is_object($newparentcat)) {
1795 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1796 } else {
1797 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1799 if (!$newparentcat) {
1800 return false;
1802 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1803 // Can not move to itself or it's own child.
1804 return false;
1806 if ($newparentcat->id) {
1807 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
1808 } else {
1809 return has_capability('moodle/category:manage', context_system::instance());
1814 * Moves the category under another parent category. All associated contexts are moved as well
1816 * This is protected function, use change_parent() or update() from outside of this class
1818 * @see coursecat::change_parent()
1819 * @see coursecat::update()
1821 * @param coursecat $newparentcat
1822 * @throws moodle_exception
1824 protected function change_parent_raw(coursecat $newparentcat) {
1825 global $DB;
1827 $context = $this->get_context();
1829 $hidecat = false;
1830 if (empty($newparentcat->id)) {
1831 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1832 $newparent = context_system::instance();
1833 } else {
1834 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1835 // Can not move to itself or it's own child.
1836 throw new moodle_exception('cannotmovecategory');
1838 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
1839 $newparent = context_coursecat::instance($newparentcat->id);
1841 if (!$newparentcat->visible and $this->visible) {
1842 // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children
1843 // will be restored properly.
1844 $hidecat = true;
1847 $this->parent = $newparentcat->id;
1849 $context->update_moved($newparent);
1851 // Now make it last in new category.
1852 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
1854 if ($hidecat) {
1855 fix_course_sortorder();
1856 $this->restore();
1857 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must
1858 // become visible again.
1859 $this->hide_raw(1);
1864 * Efficiently moves a category - NOTE that this can have
1865 * a huge impact access-control-wise...
1867 * Note that this function does not check capabilities.
1869 * Example of usage:
1870 * $coursecat = coursecat::get($categoryid);
1871 * if ($coursecat->can_change_parent($newparentcatid)) {
1872 * $coursecat->change_parent($newparentcatid);
1875 * This function does not update field course_categories.timemodified
1876 * If you want to update timemodified, use
1877 * $coursecat->update(array('parent' => $newparentcat));
1879 * @param int|stdClass|coursecat $newparentcat
1881 public function change_parent($newparentcat) {
1882 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1883 if (is_object($newparentcat)) {
1884 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
1885 } else {
1886 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
1888 if ($newparentcat->id != $this->parent) {
1889 $this->change_parent_raw($newparentcat);
1890 fix_course_sortorder();
1891 cache_helper::purge_by_event('changesincoursecat');
1892 $this->restore();
1894 $event = \core\event\course_category_updated::create(array(
1895 'objectid' => $this->id,
1896 'context' => $this->get_context()
1898 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $this->id, $this->id));
1899 $event->trigger();
1904 * Hide course category and child course and subcategories
1906 * If this category has changed the parent and is moved under hidden
1907 * category we will want to store it's current visibility state in
1908 * the field 'visibleold'. If admin clicked 'hide' for this particular
1909 * category, the field 'visibleold' should become 0.
1911 * All subcategories and courses will have their current visibility in the field visibleold
1913 * This is protected function, use hide() or update() from outside of this class
1915 * @see coursecat::hide()
1916 * @see coursecat::update()
1918 * @param int $visibleold value to set in field $visibleold for this category
1919 * @return bool whether changes have been made and caches need to be purged afterwards
1921 protected function hide_raw($visibleold = 0) {
1922 global $DB;
1923 $changes = false;
1925 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing.
1926 if ($this->id && $this->__get('visibleold') != $visibleold) {
1927 $this->visibleold = $visibleold;
1928 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
1929 $changes = true;
1931 if (!$this->visible || !$this->id) {
1932 // Already hidden or can not be hidden.
1933 return $changes;
1936 $this->visible = 0;
1937 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
1938 // Store visible flag so that we can return to it if we immediately unhide.
1939 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id));
1940 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
1941 // Get all child categories and hide too.
1942 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
1943 foreach ($subcats as $cat) {
1944 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
1945 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
1946 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
1947 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
1950 return true;
1954 * Hide course category and child course and subcategories
1956 * Note that there is no capability check inside this function
1958 * This function does not update field course_categories.timemodified
1959 * If you want to update timemodified, use
1960 * $coursecat->update(array('visible' => 0));
1962 public function hide() {
1963 if ($this->hide_raw(0)) {
1964 cache_helper::purge_by_event('changesincoursecat');
1966 $event = \core\event\course_category_updated::create(array(
1967 'objectid' => $this->id,
1968 'context' => $this->get_context()
1970 $event->set_legacy_logdata(array(SITEID, 'category', 'hide', 'editcategory.php?id=' . $this->id, $this->id));
1971 $event->trigger();
1976 * Show course category and restores visibility for child course and subcategories
1978 * Note that there is no capability check inside this function
1980 * This is protected function, use show() or update() from outside of this class
1982 * @see coursecat::show()
1983 * @see coursecat::update()
1985 * @return bool whether changes have been made and caches need to be purged afterwards
1987 protected function show_raw() {
1988 global $DB;
1990 if ($this->visible) {
1991 // Already visible.
1992 return false;
1995 $this->visible = 1;
1996 $this->visibleold = 1;
1997 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
1998 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
1999 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
2000 // Get all child categories and unhide too.
2001 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
2002 foreach ($subcats as $cat) {
2003 if ($cat->visibleold) {
2004 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
2006 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
2009 return true;
2013 * Show course category and restores visibility for child course and subcategories
2015 * Note that there is no capability check inside this function
2017 * This function does not update field course_categories.timemodified
2018 * If you want to update timemodified, use
2019 * $coursecat->update(array('visible' => 1));
2021 public function show() {
2022 if ($this->show_raw()) {
2023 cache_helper::purge_by_event('changesincoursecat');
2025 $event = \core\event\course_category_updated::create(array(
2026 'objectid' => $this->id,
2027 'context' => $this->get_context()
2029 $event->set_legacy_logdata(array(SITEID, 'category', 'show', 'editcategory.php?id=' . $this->id, $this->id));
2030 $event->trigger();
2035 * Returns name of the category formatted as a string
2037 * @param array $options formatting options other than context
2038 * @return string
2040 public function get_formatted_name($options = array()) {
2041 if ($this->id) {
2042 $context = $this->get_context();
2043 return format_string($this->name, true, array('context' => $context) + $options);
2044 } else {
2045 return get_string('top');
2050 * Returns ids of all parents of the category. Last element in the return array is the direct parent
2052 * For example, if you have a tree of categories like:
2053 * Miscellaneous (id = 1)
2054 * Subcategory (id = 2)
2055 * Sub-subcategory (id = 4)
2056 * Other category (id = 3)
2058 * coursecat::get(1)->get_parents() == array()
2059 * coursecat::get(2)->get_parents() == array(1)
2060 * coursecat::get(4)->get_parents() == array(1, 2);
2062 * Note that this method does not check if all parents are accessible by current user
2064 * @return array of category ids
2066 public function get_parents() {
2067 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
2068 array_pop($parents);
2069 return $parents;
2073 * This function returns a nice list representing category tree
2074 * for display or to use in a form <select> element
2076 * List is cached for 10 minutes
2078 * For example, if you have a tree of categories like:
2079 * Miscellaneous (id = 1)
2080 * Subcategory (id = 2)
2081 * Sub-subcategory (id = 4)
2082 * Other category (id = 3)
2083 * Then after calling this function you will have
2084 * array(1 => 'Miscellaneous',
2085 * 2 => 'Miscellaneous / Subcategory',
2086 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2087 * 3 => 'Other category');
2089 * If you specify $requiredcapability, then only categories where the current
2090 * user has that capability will be added to $list.
2091 * If you only have $requiredcapability in a child category, not the parent,
2092 * then the child catgegory will still be included.
2094 * If you specify the option $excludeid, then that category, and all its children,
2095 * are omitted from the tree. This is useful when you are doing something like
2096 * moving categories, where you do not want to allow people to move a category
2097 * to be the child of itself.
2099 * See also {@link make_categories_options()}
2101 * @param string/array $requiredcapability if given, only categories where the current
2102 * user has this capability will be returned. Can also be an array of capabilities,
2103 * in which case they are all required.
2104 * @param integer $excludeid Exclude this category and its children from the lists built.
2105 * @param string $separator string to use as a separator between parent and child category. Default ' / '
2106 * @return array of strings
2108 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
2109 global $DB;
2110 $coursecatcache = cache::make('core', 'coursecat');
2112 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids
2113 // with requried cap ($thislist).
2114 $currentlang = current_language();
2115 $basecachekey = $currentlang . '_catlist';
2116 $baselist = $coursecatcache->get($basecachekey);
2117 $thislist = false;
2118 $thiscachekey = null;
2119 if (!empty($requiredcapability)) {
2120 $requiredcapability = (array)$requiredcapability;
2121 $thiscachekey = 'catlist:'. serialize($requiredcapability);
2122 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
2123 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
2125 } else if ($baselist !== false) {
2126 $thislist = array_keys($baselist);
2129 if ($baselist === false) {
2130 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
2131 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2132 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
2133 FROM {course_categories} cc
2134 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
2135 ORDER BY cc.sortorder";
2136 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2137 $baselist = array();
2138 $thislist = array();
2139 foreach ($rs as $record) {
2140 // If the category's parent is not visible to the user, it is not visible as well.
2141 if (!$record->parent || isset($baselist[$record->parent])) {
2142 context_helper::preload_from_record($record);
2143 $context = context_coursecat::instance($record->id);
2144 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
2145 // No cap to view category, added to neither $baselist nor $thislist.
2146 continue;
2148 $baselist[$record->id] = array(
2149 'name' => format_string($record->name, true, array('context' => $context)),
2150 'path' => $record->path
2152 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
2153 // No required capability, added to $baselist but not to $thislist.
2154 continue;
2156 $thislist[] = $record->id;
2159 $rs->close();
2160 $coursecatcache->set($basecachekey, $baselist);
2161 if (!empty($requiredcapability)) {
2162 $coursecatcache->set($thiscachekey, join(',', $thislist));
2164 } else if ($thislist === false) {
2165 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
2166 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2167 $sql = "SELECT ctx.instanceid AS id, $ctxselect
2168 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
2169 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2170 $thislist = array();
2171 foreach (array_keys($baselist) as $id) {
2172 context_helper::preload_from_record($contexts[$id]);
2173 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
2174 $thislist[] = $id;
2177 $coursecatcache->set($thiscachekey, join(',', $thislist));
2180 // Now build the array of strings to return, mind $separator and $excludeid.
2181 $names = array();
2182 foreach ($thislist as $id) {
2183 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
2184 if (!$excludeid || !in_array($excludeid, $path)) {
2185 $namechunks = array();
2186 foreach ($path as $parentid) {
2187 $namechunks[] = $baselist[$parentid]['name'];
2189 $names[$id] = join($separator, $namechunks);
2192 return $names;
2196 * Prepares the object for caching. Works like the __sleep method.
2198 * implementing method from interface cacheable_object
2200 * @return array ready to be cached
2202 public function prepare_to_cache() {
2203 $a = array();
2204 foreach (self::$coursecatfields as $property => $cachedirectives) {
2205 if ($cachedirectives !== null) {
2206 list($shortname, $defaultvalue) = $cachedirectives;
2207 if ($this->$property !== $defaultvalue) {
2208 $a[$shortname] = $this->$property;
2212 $context = $this->get_context();
2213 $a['xi'] = $context->id;
2214 $a['xp'] = $context->path;
2215 return $a;
2219 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2221 * implementing method from interface cacheable_object
2223 * @param array $a
2224 * @return coursecat
2226 public static function wake_from_cache($a) {
2227 $record = new stdClass;
2228 foreach (self::$coursecatfields as $property => $cachedirectives) {
2229 if ($cachedirectives !== null) {
2230 list($shortname, $defaultvalue) = $cachedirectives;
2231 if (array_key_exists($shortname, $a)) {
2232 $record->$property = $a[$shortname];
2233 } else {
2234 $record->$property = $defaultvalue;
2238 $record->ctxid = $a['xi'];
2239 $record->ctxpath = $a['xp'];
2240 $record->ctxdepth = $record->depth + 1;
2241 $record->ctxlevel = CONTEXT_COURSECAT;
2242 $record->ctxinstance = $record->id;
2243 return new coursecat($record, true);
2247 * Returns true if the user is able to create a top level category.
2248 * @return bool
2250 public static function can_create_top_level_category() {
2251 return has_capability('moodle/category:manage', context_system::instance());
2255 * Returns the category context.
2256 * @return context_coursecat
2258 public function get_context() {
2259 if ($this->id === 0) {
2260 // This is the special top level category object.
2261 return context_system::instance();
2262 } else {
2263 return context_coursecat::instance($this->id);
2268 * Returns true if the user is able to manage this category.
2269 * @return bool
2271 public function has_manage_capability() {
2272 if ($this->hasmanagecapability === null) {
2273 $this->hasmanagecapability = has_capability('moodle/category:manage', $this->get_context());
2275 return $this->hasmanagecapability;
2279 * Returns true if the user has the manage capability on the parent category.
2280 * @return bool
2282 public function parent_has_manage_capability() {
2283 return has_capability('moodle/category:manage', get_category_or_system_context($this->parent));
2287 * Returns true if the current user can create subcategories of this category.
2288 * @return bool
2290 public function can_create_subcategory() {
2291 return $this->has_manage_capability();
2295 * Returns true if the user can resort this categories sub categories and courses.
2296 * Must have manage capability and be able to see all subcategories.
2297 * @return bool
2299 public function can_resort_subcategories() {
2300 return $this->has_manage_capability() && !$this->get_not_visible_children_ids();
2304 * Returns true if the user can resort the courses within this category.
2305 * Must have manage capability and be able to see all courses.
2306 * @return bool
2308 public function can_resort_courses() {
2309 return $this->has_manage_capability() && $this->coursecount == $this->get_courses_count();
2313 * Returns true of the user can change the sortorder of this category (resort in the parent category)
2314 * @return bool
2316 public function can_change_sortorder() {
2317 return $this->id && $this->get_parent_coursecat()->can_resort_subcategories();
2321 * Returns true if the current user can create a course within this category.
2322 * @return bool
2324 public function can_create_course() {
2325 return has_capability('moodle/course:create', $this->get_context());
2329 * Returns true if the current user can edit this categories settings.
2330 * @return bool
2332 public function can_edit() {
2333 return $this->has_manage_capability();
2337 * Returns true if the current user can review role assignments for this category.
2338 * @return bool
2340 public function can_review_roles() {
2341 return has_capability('moodle/role:assign', $this->get_context());
2345 * Returns true if the current user can review permissions for this category.
2346 * @return bool
2348 public function can_review_permissions() {
2349 return has_any_capability(array(
2350 'moodle/role:assign',
2351 'moodle/role:safeoverride',
2352 'moodle/role:override',
2353 'moodle/role:assign'
2354 ), $this->get_context());
2358 * Returns true if the current user can review cohorts for this category.
2359 * @return bool
2361 public function can_review_cohorts() {
2362 return has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->get_context());
2366 * Returns true if the current user can review filter settings for this category.
2367 * @return bool
2369 public function can_review_filters() {
2370 return has_capability('moodle/filter:manage', $this->get_context()) &&
2371 count(filter_get_available_in_context($this->get_context()))>0;
2375 * Returns true if the current user is able to change the visbility of this category.
2376 * @return bool
2378 public function can_change_visibility() {
2379 return $this->parent_has_manage_capability();
2383 * Returns true if the user can move courses out of this category.
2384 * @return bool
2386 public function can_move_courses_out_of() {
2387 return $this->has_manage_capability();
2391 * Returns true if the user can move courses into this category.
2392 * @return bool
2394 public function can_move_courses_into() {
2395 return $this->has_manage_capability();
2399 * Returns true if the user is able to restore a course into this category as a new course.
2400 * @return bool
2402 public function can_restore_courses_into() {
2403 return has_capability('moodle/course:create', $this->get_context());
2407 * Resorts the sub categories of this category by the given field.
2409 * @param string $field One of name, idnumber or descending values of each (appended desc)
2410 * @param bool $cleanup If true cleanup will be done, if false you will need to do it manually later.
2411 * @return bool True on success.
2412 * @throws coding_exception
2414 public function resort_subcategories($field, $cleanup = true) {
2415 global $DB;
2416 $desc = false;
2417 if (substr($field, -4) === "desc") {
2418 $desc = true;
2419 $field = substr($field, 0, -4); // Remove "desc" from field name.
2421 if ($field !== 'name' && $field !== 'idnumber') {
2422 throw new coding_exception('Invalid field requested');
2424 $children = $this->get_children();
2425 core_collator::asort_objects_by_property($children, $field, core_collator::SORT_NATURAL);
2426 if (!empty($desc)) {
2427 $children = array_reverse($children);
2429 $i = 1;
2430 foreach ($children as $cat) {
2431 $i++;
2432 $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id));
2433 $i += $cat->coursecount;
2435 if ($cleanup) {
2436 self::resort_categories_cleanup();
2438 return true;
2442 * Cleans things up after categories have been resorted.
2443 * @param bool $includecourses If set to true we know courses have been resorted as well.
2445 public static function resort_categories_cleanup($includecourses = false) {
2446 // This should not be needed but we do it just to be safe.
2447 fix_course_sortorder();
2448 cache_helper::purge_by_event('changesincoursecat');
2449 if ($includecourses) {
2450 cache_helper::purge_by_event('changesincourse');
2455 * Resort the courses within this category by the given field.
2457 * @param string $field One of fullname, shortname, idnumber or descending values of each (appended desc)
2458 * @param bool $cleanup
2459 * @return bool True for success.
2460 * @throws coding_exception
2462 public function resort_courses($field, $cleanup = true) {
2463 global $DB;
2464 $desc = false;
2465 if (substr($field, -4) === "desc") {
2466 $desc = true;
2467 $field = substr($field, 0, -4); // Remove "desc" from field name.
2469 if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber' && $field !== 'timecreated') {
2470 // This is ultra important as we use $field in an SQL statement below this.
2471 throw new coding_exception('Invalid field requested');
2473 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
2474 $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields
2475 FROM {course} c
2476 LEFT JOIN {context} ctx ON ctx.instanceid = c.id
2477 WHERE ctx.contextlevel = :ctxlevel AND
2478 c.category = :categoryid";
2479 $params = array(
2480 'ctxlevel' => CONTEXT_COURSE,
2481 'categoryid' => $this->id
2483 $courses = $DB->get_records_sql($sql, $params);
2484 if (count($courses) > 0) {
2485 foreach ($courses as $courseid => $course) {
2486 context_helper::preload_from_record($course);
2487 if ($field === 'idnumber') {
2488 $course->sortby = $course->idnumber;
2489 } else {
2490 // It'll require formatting.
2491 $options = array(
2492 'context' => context_course::instance($course->id)
2494 // We format the string first so that it appears as the user would see it.
2495 // This ensures the sorting makes sense to them. However it won't necessarily make
2496 // sense to everyone if things like multilang filters are enabled.
2497 // We then strip any tags as we don't want things such as image tags skewing the
2498 // sort results.
2499 $course->sortby = strip_tags(format_string($course->$field, true, $options));
2501 // We set it back here rather than using references as there is a bug with using
2502 // references in a foreach before passing as an arg by reference.
2503 $courses[$courseid] = $course;
2505 // Sort the courses.
2506 core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL);
2507 if (!empty($desc)) {
2508 $courses = array_reverse($courses);
2510 $i = 1;
2511 foreach ($courses as $course) {
2512 $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id));
2513 $i++;
2515 if ($cleanup) {
2516 // This should not be needed but we do it just to be safe.
2517 fix_course_sortorder();
2518 cache_helper::purge_by_event('changesincourse');
2521 return true;
2525 * Changes the sort order of this categories parent shifting this category up or down one.
2527 * @global \moodle_database $DB
2528 * @param bool $up If set to true the category is shifted up one spot, else its moved down.
2529 * @return bool True on success, false otherwise.
2531 public function change_sortorder_by_one($up) {
2532 global $DB;
2533 $params = array($this->sortorder, $this->parent);
2534 if ($up) {
2535 $select = 'sortorder < ? AND parent = ?';
2536 $sort = 'sortorder DESC';
2537 } else {
2538 $select = 'sortorder > ? AND parent = ?';
2539 $sort = 'sortorder ASC';
2541 fix_course_sortorder();
2542 $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1);
2543 $swapcategory = reset($swapcategory);
2544 if ($swapcategory) {
2545 $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id));
2546 $DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id));
2547 $this->sortorder = $swapcategory->sortorder;
2549 $event = \core\event\course_category_updated::create(array(
2550 'objectid' => $this->id,
2551 'context' => $this->get_context()
2553 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'management.php?categoryid=' . $this->id,
2554 $this->id));
2555 $event->trigger();
2557 // Finally reorder courses.
2558 fix_course_sortorder();
2559 cache_helper::purge_by_event('changesincoursecat');
2560 return true;
2562 return false;
2566 * Returns the parent coursecat object for this category.
2568 * @return coursecat
2570 public function get_parent_coursecat() {
2571 return self::get($this->parent);
2576 * Returns true if the user is able to request a new course be created.
2577 * @return bool
2579 public function can_request_course() {
2580 global $CFG;
2581 if (empty($CFG->enablecourserequests) || $this->id != $CFG->defaultrequestcategory) {
2582 return false;
2584 return !$this->can_create_course() && has_capability('moodle/course:request', $this->get_context());
2588 * Returns true if the user can approve course requests.
2589 * @return bool
2591 public static function can_approve_course_requests() {
2592 global $CFG, $DB;
2593 if (empty($CFG->enablecourserequests)) {
2594 return false;
2596 $context = context_system::instance();
2597 if (!has_capability('moodle/site:approvecourse', $context)) {
2598 return false;
2600 if (!$DB->record_exists('course_request', array())) {
2601 return false;
2603 return true;
2608 * Class to store information about one course in a list of courses
2610 * Not all information may be retrieved when object is created but
2611 * it will be retrieved on demand when appropriate property or method is
2612 * called.
2614 * Instances of this class are usually returned by functions
2615 * {@link coursecat::search_courses()}
2616 * and
2617 * {@link coursecat::get_courses()}
2619 * @property-read int $id
2620 * @property-read int $category Category ID
2621 * @property-read int $sortorder
2622 * @property-read string $fullname
2623 * @property-read string $shortname
2624 * @property-read string $idnumber
2625 * @property-read string $summary Course summary. Field is present if coursecat::get_courses()
2626 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2627 * @property-read int $summaryformat Summary format. Field is present if coursecat::get_courses()
2628 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2629 * @property-read string $format Course format. Retrieved from DB on first request
2630 * @property-read int $showgrades Retrieved from DB on first request
2631 * @property-read int $newsitems Retrieved from DB on first request
2632 * @property-read int $startdate
2633 * @property-read int $marker Retrieved from DB on first request
2634 * @property-read int $maxbytes Retrieved from DB on first request
2635 * @property-read int $legacyfiles Retrieved from DB on first request
2636 * @property-read int $showreports Retrieved from DB on first request
2637 * @property-read int $visible
2638 * @property-read int $visibleold Retrieved from DB on first request
2639 * @property-read int $groupmode Retrieved from DB on first request
2640 * @property-read int $groupmodeforce Retrieved from DB on first request
2641 * @property-read int $defaultgroupingid Retrieved from DB on first request
2642 * @property-read string $lang Retrieved from DB on first request
2643 * @property-read string $theme Retrieved from DB on first request
2644 * @property-read int $timecreated Retrieved from DB on first request
2645 * @property-read int $timemodified Retrieved from DB on first request
2646 * @property-read int $requested Retrieved from DB on first request
2647 * @property-read int $enablecompletion Retrieved from DB on first request
2648 * @property-read int $completionnotify Retrieved from DB on first request
2649 * @property-read int $cacherev
2651 * @package core
2652 * @subpackage course
2653 * @copyright 2013 Marina Glancy
2654 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2656 class course_in_list implements IteratorAggregate {
2658 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2659 protected $record;
2661 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2662 protected $coursecontacts;
2664 /** @var bool true if the current user can access the course, false otherwise. */
2665 protected $canaccess = null;
2668 * Creates an instance of the class from record
2670 * @param stdClass $record except fields from course table it may contain
2671 * field hassummary indicating that summary field is not empty.
2672 * Also it is recommended to have context fields here ready for
2673 * context preloading
2675 public function __construct(stdClass $record) {
2676 context_helper::preload_from_record($record);
2677 $this->record = new stdClass();
2678 foreach ($record as $key => $value) {
2679 $this->record->$key = $value;
2684 * Indicates if the course has non-empty summary field
2686 * @return bool
2688 public function has_summary() {
2689 if (isset($this->record->hassummary)) {
2690 return !empty($this->record->hassummary);
2692 if (!isset($this->record->summary)) {
2693 // We need to retrieve summary.
2694 $this->__get('summary');
2696 return !empty($this->record->summary);
2700 * Indicates if the course have course contacts to display
2702 * @return bool
2704 public function has_course_contacts() {
2705 if (!isset($this->record->managers)) {
2706 $courses = array($this->id => &$this->record);
2707 coursecat::preload_course_contacts($courses);
2709 return !empty($this->record->managers);
2713 * Returns list of course contacts (usually teachers) to display in course link
2715 * Roles to display are set up in $CFG->coursecontact
2717 * The result is the list of users where user id is the key and the value
2718 * is an array with elements:
2719 * - 'user' - object containing basic user information
2720 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2721 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2722 * - 'username' => fullname($user, $canviewfullnames)
2724 * @return array
2726 public function get_course_contacts() {
2727 global $CFG;
2728 if (empty($CFG->coursecontact)) {
2729 // No roles are configured to be displayed as course contacts.
2730 return array();
2732 if ($this->coursecontacts === null) {
2733 $this->coursecontacts = array();
2734 $context = context_course::instance($this->id);
2736 if (!isset($this->record->managers)) {
2737 // Preload course contacts from DB.
2738 $courses = array($this->id => &$this->record);
2739 coursecat::preload_course_contacts($courses);
2742 // Build return array with full roles names (for this course context) and users names.
2743 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2744 foreach ($this->record->managers as $ruser) {
2745 if (isset($this->coursecontacts[$ruser->id])) {
2746 // Only display a user once with the highest sortorder role.
2747 continue;
2749 $user = new stdClass();
2750 $user = username_load_fields_from_object($user, $ruser, null, array('id', 'username'));
2751 $role = new stdClass();
2752 $role->id = $ruser->roleid;
2753 $role->name = $ruser->rolename;
2754 $role->shortname = $ruser->roleshortname;
2755 $role->coursealias = $ruser->rolecoursealias;
2757 $this->coursecontacts[$user->id] = array(
2758 'user' => $user,
2759 'role' => $role,
2760 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2761 'username' => fullname($user, $canviewfullnames)
2765 return $this->coursecontacts;
2769 * Checks if course has any associated overview files
2771 * @return bool
2773 public function has_course_overviewfiles() {
2774 global $CFG;
2775 if (empty($CFG->courseoverviewfileslimit)) {
2776 return false;
2778 $fs = get_file_storage();
2779 $context = context_course::instance($this->id);
2780 return !$fs->is_area_empty($context->id, 'course', 'overviewfiles');
2784 * Returns all course overview files
2786 * @return array array of stored_file objects
2788 public function get_course_overviewfiles() {
2789 global $CFG;
2790 if (empty($CFG->courseoverviewfileslimit)) {
2791 return array();
2793 require_once($CFG->libdir. '/filestorage/file_storage.php');
2794 require_once($CFG->dirroot. '/course/lib.php');
2795 $fs = get_file_storage();
2796 $context = context_course::instance($this->id);
2797 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2798 if (count($files)) {
2799 $overviewfilesoptions = course_overviewfiles_options($this->id);
2800 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2801 if ($acceptedtypes !== '*') {
2802 // Filter only files with allowed extensions.
2803 require_once($CFG->libdir. '/filelib.php');
2804 foreach ($files as $key => $file) {
2805 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2806 unset($files[$key]);
2810 if (count($files) > $CFG->courseoverviewfileslimit) {
2811 // Return no more than $CFG->courseoverviewfileslimit files.
2812 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
2815 return $files;
2819 * Magic method to check if property is set
2821 * @param string $name
2822 * @return bool
2824 public function __isset($name) {
2825 return isset($this->record->$name);
2829 * Magic method to get a course property
2831 * Returns any field from table course (retrieves it from DB if it was not retrieved before)
2833 * @param string $name
2834 * @return mixed
2836 public function __get($name) {
2837 global $DB;
2838 if (property_exists($this->record, $name)) {
2839 return $this->record->$name;
2840 } else if ($name === 'summary' || $name === 'summaryformat') {
2841 // Retrieve fields summary and summaryformat together because they are most likely to be used together.
2842 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
2843 $this->record->summary = $record->summary;
2844 $this->record->summaryformat = $record->summaryformat;
2845 return $this->record->$name;
2846 } else if (array_key_exists($name, $DB->get_columns('course'))) {
2847 // Another field from table 'course' that was not retrieved.
2848 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
2849 return $this->record->$name;
2851 debugging('Invalid course property accessed! '.$name);
2852 return null;
2856 * All properties are read only, sorry.
2858 * @param string $name
2860 public function __unset($name) {
2861 debugging('Can not unset '.get_class($this).' instance properties!');
2865 * Magic setter method, we do not want anybody to modify properties from the outside
2867 * @param string $name
2868 * @param mixed $value
2870 public function __set($name, $value) {
2871 debugging('Can not change '.get_class($this).' instance properties!');
2875 * Create an iterator because magic vars can't be seen by 'foreach'.
2876 * Exclude context fields
2878 * Implementing method from interface IteratorAggregate
2880 * @return ArrayIterator
2882 public function getIterator() {
2883 $ret = array('id' => $this->record->id);
2884 foreach ($this->record as $property => $value) {
2885 $ret[$property] = $value;
2887 return new ArrayIterator($ret);
2891 * Returns the name of this course as it should be displayed within a list.
2892 * @return string
2894 public function get_formatted_name() {
2895 return format_string(get_course_display_name_for_list($this), true, $this->get_context());
2899 * Returns the formatted fullname for this course.
2900 * @return string
2902 public function get_formatted_fullname() {
2903 return format_string($this->__get('fullname'), true, $this->get_context());
2907 * Returns the formatted shortname for this course.
2908 * @return string
2910 public function get_formatted_shortname() {
2911 return format_string($this->__get('shortname'), true, $this->get_context());
2915 * Returns true if the current user can access this course.
2916 * @return bool
2918 public function can_access() {
2919 if ($this->canaccess === null) {
2920 $this->canaccess = can_access_course($this->record);
2922 return $this->canaccess;
2926 * Returns true if the user can edit this courses settings.
2928 * Note: this function does not check that the current user can access the course.
2929 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2931 * @return bool
2933 public function can_edit() {
2934 return has_capability('moodle/course:update', $this->get_context());
2938 * Returns true if the user can change the visibility of this course.
2940 * Note: this function does not check that the current user can access the course.
2941 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2943 * @return bool
2945 public function can_change_visibility() {
2946 // You must be able to both hide a course and view the hidden course.
2947 return has_all_capabilities(array('moodle/course:visibility', 'moodle/course:viewhiddencourses'), $this->get_context());
2951 * Returns the context for this course.
2952 * @return context_course
2954 public function get_context() {
2955 return context_course::instance($this->__get('id'));
2959 * Returns true if this course is visible to the current user.
2960 * @return bool
2962 public function is_uservisible() {
2963 return $this->visible || has_capability('moodle/course:viewhiddencourses', $this->get_context());
2967 * Returns true if the current user can review enrolments for this course.
2969 * Note: this function does not check that the current user can access the course.
2970 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2972 * @return bool
2974 public function can_review_enrolments() {
2975 return has_capability('moodle/course:enrolreview', $this->get_context());
2979 * Returns true if the current user can delete this course.
2981 * Note: this function does not check that the current user can access the course.
2982 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2984 * @return bool
2986 public function can_delete() {
2987 return can_delete_course($this->id);
2991 * Returns true if the current user can backup this course.
2993 * Note: this function does not check that the current user can access the course.
2994 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2996 * @return bool
2998 public function can_backup() {
2999 return has_capability('moodle/backup:backupcourse', $this->get_context());
3003 * Returns true if the current user can restore this course.
3005 * Note: this function does not check that the current user can access the course.
3006 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3008 * @return bool
3010 public function can_restore() {
3011 return has_capability('moodle/restore:restorecourse', $this->get_context());
3016 * An array of records that is sortable by many fields.
3018 * For more info on the ArrayObject class have a look at php.net.
3020 * @package core
3021 * @subpackage course
3022 * @copyright 2013 Sam Hemelryk
3023 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3025 class coursecat_sortable_records extends ArrayObject {
3028 * An array of sortable fields.
3029 * Gets set temporarily when sort is called.
3030 * @var array
3032 protected $sortfields = array();
3035 * Sorts this array using the given fields.
3037 * @param array $records
3038 * @param array $fields
3039 * @return array
3041 public static function sort(array $records, array $fields) {
3042 $records = new coursecat_sortable_records($records);
3043 $records->sortfields = $fields;
3044 $records->uasort(array($records, 'sort_by_many_fields'));
3045 return $records->getArrayCopy();
3049 * Sorts the two records based upon many fields.
3051 * This method should not be called itself, please call $sort instead.
3052 * It has been marked as access private as such.
3054 * @access private
3055 * @param stdClass $a
3056 * @param stdClass $b
3057 * @return int
3059 public function sort_by_many_fields($a, $b) {
3060 foreach ($this->sortfields as $field => $mult) {
3061 // Nulls first.
3062 if (is_null($a->$field) && !is_null($b->$field)) {
3063 return -$mult;
3065 if (is_null($b->$field) && !is_null($a->$field)) {
3066 return $mult;
3069 if (is_string($a->$field) || is_string($b->$field)) {
3070 // String fields.
3071 if ($cmp = strcoll($a->$field, $b->$field)) {
3072 return $mult * $cmp;
3074 } else {
3075 // Int fields.
3076 if ($a->$field > $b->$field) {
3077 return $mult;
3079 if ($a->$field < $b->$field) {
3080 return -$mult;
3084 return 0;