Merge branch 'MDL-49360-28' of git://github.com/lameze/moodle into MOODLE_28_STABLE
[moodle.git] / lib / coursecatlib.php
blobee93258afea2ed227814cfcf1c3dbc2a68759591
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 $keys = $DB->get_fieldset_select('course', 'id', '');
717 $cache->delete_many($keys);
718 $cache->set('basic', array('roles' => $CFG->coursecontact, 'lastreset' => time()));
719 $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
721 $courseids = array();
722 foreach (array_keys($courses) as $id) {
723 if ($cacheddata[$id] !== false) {
724 $courses[$id]->managers = $cacheddata[$id];
725 } else {
726 $courseids[] = $id;
730 // Array $courseids now stores list of ids of courses for which we still need to retrieve contacts.
731 if (empty($courseids)) {
732 return;
735 // First build the array of all context ids of the courses and their categories.
736 $allcontexts = array();
737 foreach ($courseids as $id) {
738 $context = context_course::instance($id);
739 $courses[$id]->managers = array();
740 foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
741 if (!isset($allcontexts[$ctxid])) {
742 $allcontexts[$ctxid] = array();
744 $allcontexts[$ctxid][] = $id;
748 // Fetch list of all users with course contact roles in any of the courses contexts or parent contexts.
749 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
750 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
751 list($sort, $sortparams) = users_order_by_sql('u');
752 $notdeleted = array('notdeleted'=>0);
753 $allnames = get_all_user_name_fields(true, 'u');
754 $sql = "SELECT ra.contextid, ra.id AS raid,
755 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
756 rn.name AS rolecoursealias, u.id, u.username, $allnames
757 FROM {role_assignments} ra
758 JOIN {user} u ON ra.userid = u.id
759 JOIN {role} r ON ra.roleid = r.id
760 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
761 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
762 ORDER BY r.sortorder, $sort";
763 $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
764 $checkenrolments = array();
765 foreach ($rs as $ra) {
766 foreach ($allcontexts[$ra->contextid] as $id) {
767 $courses[$id]->managers[$ra->raid] = $ra;
768 if (!isset($checkenrolments[$id])) {
769 $checkenrolments[$id] = array();
771 $checkenrolments[$id][] = $ra->id;
774 $rs->close();
776 // Remove from course contacts users who are not enrolled in the course.
777 $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
778 foreach ($checkenrolments as $id => $userids) {
779 if (empty($enrolleduserids[$id])) {
780 $courses[$id]->managers = array();
781 } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
782 foreach ($courses[$id]->managers as $raid => $ra) {
783 if (in_array($ra->id, $notenrolled)) {
784 unset($courses[$id]->managers[$raid]);
790 // Set the cache.
791 $values = array();
792 foreach ($courseids as $id) {
793 $values[$id] = $courses[$id]->managers;
795 $cache->set_many($values);
799 * Verify user enrollments for multiple course-user combinations
801 * @param array $courseusers array where keys are course ids and values are array
802 * of users in this course whose enrolment we wish to verify
803 * @return array same structure as input array but values list only users from input
804 * who are enrolled in the course
806 protected static function ensure_users_enrolled($courseusers) {
807 global $DB;
808 // If the input array is too big, split it into chunks.
809 $maxcoursesinquery = 20;
810 if (count($courseusers) > $maxcoursesinquery) {
811 $rv = array();
812 for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
813 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
814 $rv = $rv + self::ensure_users_enrolled($chunk);
816 return $rv;
819 // Create a query verifying valid user enrolments for the number of courses.
820 $sql = "SELECT DISTINCT e.courseid, ue.userid
821 FROM {user_enrolments} ue
822 JOIN {enrol} e ON e.id = ue.enrolid
823 WHERE ue.status = :active
824 AND e.status = :enabled
825 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
826 $now = round(time(), -2); // Rounding helps caching in DB.
827 $params = array('enabled' => ENROL_INSTANCE_ENABLED,
828 'active' => ENROL_USER_ACTIVE,
829 'now1' => $now, 'now2' => $now);
830 $cnt = 0;
831 $subsqls = array();
832 $enrolled = array();
833 foreach ($courseusers as $id => $userids) {
834 $enrolled[$id] = array();
835 if (count($userids)) {
836 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
837 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
838 $params = $params + array('courseid'.$cnt => $id) + $params2;
839 $cnt++;
842 if (count($subsqls)) {
843 $sql .= "AND (". join(' OR ', $subsqls).")";
844 $rs = $DB->get_recordset_sql($sql, $params);
845 foreach ($rs as $record) {
846 $enrolled[$record->courseid][] = $record->userid;
848 $rs->close();
850 return $enrolled;
854 * Retrieves number of records from course table
856 * Not all fields are retrieved. Records are ready for preloading context
858 * @param string $whereclause
859 * @param array $params
860 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
861 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
862 * on not visible courses
863 * @return array array of stdClass objects
865 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
866 global $DB;
867 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
868 $fields = array('c.id', 'c.category', 'c.sortorder',
869 'c.shortname', 'c.fullname', 'c.idnumber',
870 'c.startdate', 'c.visible', 'c.cacherev');
871 if (!empty($options['summary'])) {
872 $fields[] = 'c.summary';
873 $fields[] = 'c.summaryformat';
874 } else {
875 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
877 $sql = "SELECT ". join(',', $fields). ", $ctxselect
878 FROM {course} c
879 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
880 WHERE ". $whereclause." ORDER BY c.sortorder";
881 $list = $DB->get_records_sql($sql,
882 array('contextcourse' => CONTEXT_COURSE) + $params);
884 if ($checkvisibility) {
885 // Loop through all records and make sure we only return the courses accessible by user.
886 foreach ($list as $course) {
887 if (isset($list[$course->id]->hassummary)) {
888 $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
890 if (empty($course->visible)) {
891 // Load context only if we need to check capability.
892 context_helper::preload_from_record($course);
893 if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
894 unset($list[$course->id]);
900 // Preload course contacts if necessary.
901 if (!empty($options['coursecontacts'])) {
902 self::preload_course_contacts($list);
904 return $list;
908 * Returns array of ids of children categories that current user can not see
910 * This data is cached in user session cache
912 * @return array
914 protected function get_not_visible_children_ids() {
915 global $DB;
916 $coursecatcache = cache::make('core', 'coursecat');
917 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
918 // We never checked visible children before.
919 $hidden = self::get_tree($this->id.'i');
920 $invisibleids = array();
921 if ($hidden) {
922 // Preload categories contexts.
923 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
924 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
925 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
926 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
927 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
928 foreach ($contexts as $record) {
929 context_helper::preload_from_record($record);
931 // Check that user has 'viewhiddencategories' capability for each hidden category.
932 foreach ($hidden as $id) {
933 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
934 $invisibleids[] = $id;
938 $coursecatcache->set('ic'. $this->id, $invisibleids);
940 return $invisibleids;
944 * Sorts list of records by several fields
946 * @param array $records array of stdClass objects
947 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
948 * @return int
950 protected static function sort_records(&$records, $sortfields) {
951 if (empty($records)) {
952 return;
954 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname).
955 if (array_key_exists('displayname', $sortfields)) {
956 foreach ($records as $key => $record) {
957 if (!isset($record->displayname)) {
958 $records[$key]->displayname = get_course_display_name_for_list($record);
962 // Sorting by one field - use core_collator.
963 if (count($sortfields) == 1) {
964 $property = key($sortfields);
965 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
966 $sortflag = core_collator::SORT_NUMERIC;
967 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
968 $sortflag = core_collator::SORT_STRING;
969 } else {
970 $sortflag = core_collator::SORT_REGULAR;
972 core_collator::asort_objects_by_property($records, $property, $sortflag);
973 if ($sortfields[$property] < 0) {
974 $records = array_reverse($records, true);
976 return;
978 $records = coursecat_sortable_records::sort($records, $sortfields);
982 * Returns array of children categories visible to the current user
984 * @param array $options options for retrieving children
985 * - sort - list of fields to sort. Example
986 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
987 * will sort by idnumber asc, name asc and id desc.
988 * Default: array('sortorder' => 1)
989 * Only cached fields may be used for sorting!
990 * - offset
991 * - limit - maximum number of children to return, 0 or null for no limit
992 * @return coursecat[] Array of coursecat objects indexed by category id
994 public function get_children($options = array()) {
995 global $DB;
996 $coursecatcache = cache::make('core', 'coursecat');
998 // Get default values for options.
999 if (!empty($options['sort']) && is_array($options['sort'])) {
1000 $sortfields = $options['sort'];
1001 } else {
1002 $sortfields = array('sortorder' => 1);
1004 $limit = null;
1005 if (!empty($options['limit']) && (int)$options['limit']) {
1006 $limit = (int)$options['limit'];
1008 $offset = 0;
1009 if (!empty($options['offset']) && (int)$options['offset']) {
1010 $offset = (int)$options['offset'];
1013 // First retrieve list of user-visible and sorted children ids from cache.
1014 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
1015 if ($sortedids === false) {
1016 $sortfieldskeys = array_keys($sortfields);
1017 if ($sortfieldskeys[0] === 'sortorder') {
1018 // No DB requests required to build the list of ids sorted by sortorder.
1019 // We can easily ignore other sort fields because sortorder is always different.
1020 $sortedids = self::get_tree($this->id);
1021 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
1022 $sortedids = array_diff($sortedids, $invisibleids);
1023 if ($sortfields['sortorder'] == -1) {
1024 $sortedids = array_reverse($sortedids, true);
1027 } else {
1028 // We need to retrieve and sort all children. Good thing that it is done only on first request.
1029 if ($invisibleids = $this->get_not_visible_children_ids()) {
1030 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
1031 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
1032 array('parent' => $this->id) + $params);
1033 } else {
1034 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
1036 self::sort_records($records, $sortfields);
1037 $sortedids = array_keys($records);
1039 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
1042 if (empty($sortedids)) {
1043 return array();
1046 // Now retrieive and return categories.
1047 if ($offset || $limit) {
1048 $sortedids = array_slice($sortedids, $offset, $limit);
1050 if (isset($records)) {
1051 // Easy, we have already retrieved records.
1052 if ($offset || $limit) {
1053 $records = array_slice($records, $offset, $limit, true);
1055 } else {
1056 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
1057 $records = self::get_records('cc.id '. $sql, array('parent' => $this->id) + $params);
1060 $rv = array();
1061 foreach ($sortedids as $id) {
1062 if (isset($records[$id])) {
1063 $rv[$id] = new coursecat($records[$id]);
1066 return $rv;
1070 * Returns true if the user has the manage capability on any category.
1072 * This method uses the coursecat cache and an entry `has_manage_capability` to speed up
1073 * calls to this method.
1075 * @return bool
1077 public static function has_manage_capability_on_any() {
1078 return self::has_capability_on_any('moodle/category:manage');
1082 * Checks if the user has at least one of the given capabilities on any category.
1084 * @param array|string $capabilities One or more capabilities to check. Check made is an OR.
1085 * @return bool
1087 public static function has_capability_on_any($capabilities) {
1088 global $DB;
1089 if (!isloggedin() || isguestuser()) {
1090 return false;
1093 if (!is_array($capabilities)) {
1094 $capabilities = array($capabilities);
1096 $keys = array();
1097 foreach ($capabilities as $capability) {
1098 $keys[$capability] = sha1($capability);
1101 /* @var cache_session $cache */
1102 $cache = cache::make('core', 'coursecat');
1103 $hascapability = $cache->get_many($keys);
1104 $needtoload = false;
1105 foreach ($hascapability as $capability) {
1106 if ($capability === '1') {
1107 return true;
1108 } else if ($capability === false) {
1109 $needtoload = true;
1112 if ($needtoload === false) {
1113 // All capabilities were retrieved and the user didn't have any.
1114 return false;
1117 $haskey = null;
1118 $fields = context_helper::get_preload_record_columns_sql('ctx');
1119 $sql = "SELECT ctx.instanceid AS categoryid, $fields
1120 FROM {context} ctx
1121 WHERE contextlevel = :contextlevel
1122 ORDER BY depth ASC";
1123 $params = array('contextlevel' => CONTEXT_COURSECAT);
1124 $recordset = $DB->get_recordset_sql($sql, $params);
1125 foreach ($recordset as $context) {
1126 context_helper::preload_from_record($context);
1127 $context = context_coursecat::instance($context->categoryid);
1128 foreach ($capabilities as $capability) {
1129 if (has_capability($capability, $context)) {
1130 $haskey = $capability;
1131 break 2;
1135 $recordset->close();
1136 if ($haskey === null) {
1137 $data = array();
1138 foreach ($keys as $key) {
1139 $data[$key] = '0';
1141 $cache->set_many($data);
1142 return false;
1143 } else {
1144 $cache->set($haskey, '1');
1145 return true;
1150 * Returns true if the user can resort any category.
1151 * @return bool
1153 public static function can_resort_any() {
1154 return self::has_manage_capability_on_any();
1158 * Returns true if the user can change the parent of any category.
1159 * @return bool
1161 public static function can_change_parent_any() {
1162 return self::has_manage_capability_on_any();
1166 * Returns number of subcategories visible to the current user
1168 * @return int
1170 public function get_children_count() {
1171 $sortedids = self::get_tree($this->id);
1172 $invisibleids = $this->get_not_visible_children_ids();
1173 return count($sortedids) - count($invisibleids);
1177 * Returns true if the category has ANY children, including those not visible to the user
1179 * @return boolean
1181 public function has_children() {
1182 $allchildren = self::get_tree($this->id);
1183 return !empty($allchildren);
1187 * Returns true if the category has courses in it (count does not include courses
1188 * in child categories)
1190 * @return bool
1192 public function has_courses() {
1193 global $DB;
1194 return $DB->record_exists_sql("select 1 from {course} where category = ?",
1195 array($this->id));
1199 * Searches courses
1201 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1202 * to this when somebody edits courses or categories, however it is very
1203 * difficult to keep track of all possible changes that may affect list of courses.
1205 * @param array $search contains search criterias, such as:
1206 * - search - search string
1207 * - blocklist - id of block (if we are searching for courses containing specific block0
1208 * - modulelist - name of module (if we are searching for courses containing specific module
1209 * - tagid - id of tag
1210 * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
1211 * search is always category-independent
1212 * @return course_in_list[]
1214 public static function search_courses($search, $options = array()) {
1215 global $DB;
1216 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1217 $limit = !empty($options['limit']) ? $options['limit'] : null;
1218 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1220 $coursecatcache = cache::make('core', 'coursecat');
1221 $cachekey = 's-'. serialize($search + array('sort' => $sortfields));
1222 $cntcachekey = 'scnt-'. serialize($search);
1224 $ids = $coursecatcache->get($cachekey);
1225 if ($ids !== false) {
1226 // We already cached last search result.
1227 $ids = array_slice($ids, $offset, $limit);
1228 $courses = array();
1229 if (!empty($ids)) {
1230 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1231 $records = self::get_course_records("c.id ". $sql, $params, $options);
1232 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1233 if (!empty($options['coursecontacts'])) {
1234 self::preload_course_contacts($records);
1236 // If option 'idonly' is specified no further action is needed, just return list of ids.
1237 if (!empty($options['idonly'])) {
1238 return array_keys($records);
1240 // Prepare the list of course_in_list objects.
1241 foreach ($ids as $id) {
1242 $courses[$id] = new course_in_list($records[$id]);
1245 return $courses;
1248 $preloadcoursecontacts = !empty($options['coursecontacts']);
1249 unset($options['coursecontacts']);
1251 if (!empty($search['search'])) {
1252 // Search courses that have specified words in their names/summaries.
1253 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1254 $searchterms = array_filter($searchterms, create_function('$v', 'return strlen($v) > 1;'));
1255 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount);
1256 self::sort_records($courselist, $sortfields);
1257 $coursecatcache->set($cachekey, array_keys($courselist));
1258 $coursecatcache->set($cntcachekey, $totalcount);
1259 $records = array_slice($courselist, $offset, $limit, true);
1260 } else {
1261 if (!empty($search['blocklist'])) {
1262 // Search courses that have block with specified id.
1263 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1264 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1265 WHERE bi.blockname = :blockname)';
1266 $params = array('blockname' => $blockname);
1267 } else if (!empty($search['modulelist'])) {
1268 // Search courses that have module with specified name.
1269 $where = "c.id IN (SELECT DISTINCT module.course ".
1270 "FROM {".$search['modulelist']."} module)";
1271 $params = array();
1272 } else if (!empty($search['tagid'])) {
1273 // Search courses that are tagged with the specified tag.
1274 $where = "c.id IN (SELECT t.itemid ".
1275 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype)";
1276 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course');
1277 } else {
1278 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1279 return array();
1281 $courselist = self::get_course_records($where, $params, $options, true);
1282 self::sort_records($courselist, $sortfields);
1283 $coursecatcache->set($cachekey, array_keys($courselist));
1284 $coursecatcache->set($cntcachekey, count($courselist));
1285 $records = array_slice($courselist, $offset, $limit, true);
1288 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1289 if (!empty($preloadcoursecontacts)) {
1290 self::preload_course_contacts($records);
1292 // If option 'idonly' is specified no further action is needed, just return list of ids.
1293 if (!empty($options['idonly'])) {
1294 return array_keys($records);
1296 // Prepare the list of course_in_list objects.
1297 $courses = array();
1298 foreach ($records as $record) {
1299 $courses[$record->id] = new course_in_list($record);
1301 return $courses;
1305 * Returns number of courses in the search results
1307 * It is recommended to call this function after {@link coursecat::search_courses()}
1308 * and not before because only course ids are cached. Otherwise search_courses() may
1309 * perform extra DB queries.
1311 * @param array $search search criteria, see method search_courses() for more details
1312 * @param array $options display options. They do not affect the result but
1313 * the 'sort' property is used in cache key for storing list of course ids
1314 * @return int
1316 public static function search_courses_count($search, $options = array()) {
1317 $coursecatcache = cache::make('core', 'coursecat');
1318 $cntcachekey = 'scnt-'. serialize($search);
1319 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1320 // Cached value not found. Retrieve ALL courses and return their count.
1321 unset($options['offset']);
1322 unset($options['limit']);
1323 unset($options['summary']);
1324 unset($options['coursecontacts']);
1325 $options['idonly'] = true;
1326 $courses = self::search_courses($search, $options);
1327 $cnt = count($courses);
1329 return $cnt;
1333 * Retrieves the list of courses accessible by user
1335 * Not all information is cached, try to avoid calling this method
1336 * twice in the same request.
1338 * The following fields are always retrieved:
1339 * - id, visible, fullname, shortname, idnumber, category, sortorder
1341 * If you plan to use properties/methods course_in_list::$summary and/or
1342 * course_in_list::get_course_contacts()
1343 * you can preload this information using appropriate 'options'. Otherwise
1344 * they will be retrieved from DB on demand and it may end with bigger DB load.
1346 * Note that method course_in_list::has_summary() will not perform additional
1347 * DB queries even if $options['summary'] is not specified
1349 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1350 * to this when somebody edits courses or categories, however it is very
1351 * difficult to keep track of all possible changes that may affect list of courses.
1353 * @param array $options options for retrieving children
1354 * - recursive - return courses from subcategories as well. Use with care,
1355 * this may be a huge list!
1356 * - summary - preloads fields 'summary' and 'summaryformat'
1357 * - coursecontacts - preloads course contacts
1358 * - sort - list of fields to sort. Example
1359 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1360 * will sort by idnumber asc, shortname asc and id desc.
1361 * Default: array('sortorder' => 1)
1362 * Only cached fields may be used for sorting!
1363 * - offset
1364 * - limit - maximum number of children to return, 0 or null for no limit
1365 * - idonly - returns the array or course ids instead of array of objects
1366 * used only in get_courses_count()
1367 * @return course_in_list[]
1369 public function get_courses($options = array()) {
1370 global $DB;
1371 $recursive = !empty($options['recursive']);
1372 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1373 $limit = !empty($options['limit']) ? $options['limit'] : null;
1374 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1376 // Check if this category is hidden.
1377 // Also 0-category never has courses unless this is recursive call.
1378 if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1379 return array();
1382 $coursecatcache = cache::make('core', 'coursecat');
1383 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1384 '-'. serialize($sortfields);
1385 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1387 // Check if we have already cached results.
1388 $ids = $coursecatcache->get($cachekey);
1389 if ($ids !== false) {
1390 // We already cached last search result and it did not expire yet.
1391 $ids = array_slice($ids, $offset, $limit);
1392 $courses = array();
1393 if (!empty($ids)) {
1394 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1395 $records = self::get_course_records("c.id ". $sql, $params, $options);
1396 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1397 if (!empty($options['coursecontacts'])) {
1398 self::preload_course_contacts($records);
1400 // If option 'idonly' is specified no further action is needed, just return list of ids.
1401 if (!empty($options['idonly'])) {
1402 return array_keys($records);
1404 // Prepare the list of course_in_list objects.
1405 foreach ($ids as $id) {
1406 $courses[$id] = new course_in_list($records[$id]);
1409 return $courses;
1412 // Retrieve list of courses in category.
1413 $where = 'c.id <> :siteid';
1414 $params = array('siteid' => SITEID);
1415 if ($recursive) {
1416 if ($this->id) {
1417 $context = context_coursecat::instance($this->id);
1418 $where .= ' AND ctx.path like :path';
1419 $params['path'] = $context->path. '/%';
1421 } else {
1422 $where .= ' AND c.category = :categoryid';
1423 $params['categoryid'] = $this->id;
1425 // Get list of courses without preloaded coursecontacts because we don't need them for every course.
1426 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1428 // Sort and cache list.
1429 self::sort_records($list, $sortfields);
1430 $coursecatcache->set($cachekey, array_keys($list));
1431 $coursecatcache->set($cntcachekey, count($list));
1433 // Apply offset/limit, convert to course_in_list and return.
1434 $courses = array();
1435 if (isset($list)) {
1436 if ($offset || $limit) {
1437 $list = array_slice($list, $offset, $limit, true);
1439 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1440 if (!empty($options['coursecontacts'])) {
1441 self::preload_course_contacts($list);
1443 // If option 'idonly' is specified no further action is needed, just return list of ids.
1444 if (!empty($options['idonly'])) {
1445 return array_keys($list);
1447 // Prepare the list of course_in_list objects.
1448 foreach ($list as $record) {
1449 $courses[$record->id] = new course_in_list($record);
1452 return $courses;
1456 * Returns number of courses visible to the user
1458 * @param array $options similar to get_courses() except some options do not affect
1459 * number of courses (i.e. sort, summary, offset, limit etc.)
1460 * @return int
1462 public function get_courses_count($options = array()) {
1463 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1464 $coursecatcache = cache::make('core', 'coursecat');
1465 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1466 // Cached value not found. Retrieve ALL courses and return their count.
1467 unset($options['offset']);
1468 unset($options['limit']);
1469 unset($options['summary']);
1470 unset($options['coursecontacts']);
1471 $options['idonly'] = true;
1472 $courses = $this->get_courses($options);
1473 $cnt = count($courses);
1475 return $cnt;
1479 * Returns true if the user is able to delete this category.
1481 * Note if this category contains any courses this isn't a full check, it will need to be accompanied by a call to either
1482 * {@link coursecat::can_delete_full()} or {@link coursecat::can_move_content_to()} depending upon what the user wished to do.
1484 * @return boolean
1486 public function can_delete() {
1487 if (!$this->has_manage_capability()) {
1488 return false;
1490 return $this->parent_has_manage_capability();
1494 * Returns true if user can delete current category and all its contents
1496 * To be able to delete course category the user must have permission
1497 * 'moodle/category:manage' in ALL child course categories AND
1498 * be able to delete all courses
1500 * @return bool
1502 public function can_delete_full() {
1503 global $DB;
1504 if (!$this->id) {
1505 // Fool-proof.
1506 return false;
1509 $context = $this->get_context();
1510 if (!$this->is_uservisible() ||
1511 !has_capability('moodle/category:manage', $context)) {
1512 return false;
1515 // Check all child categories (not only direct children).
1516 $sql = context_helper::get_preload_record_columns_sql('ctx');
1517 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1518 ' FROM {context} ctx '.
1519 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1520 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1521 array($context->path. '/%', CONTEXT_COURSECAT));
1522 foreach ($childcategories as $childcat) {
1523 context_helper::preload_from_record($childcat);
1524 $childcontext = context_coursecat::instance($childcat->id);
1525 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1526 !has_capability('moodle/category:manage', $childcontext)) {
1527 return false;
1531 // Check courses.
1532 $sql = context_helper::get_preload_record_columns_sql('ctx');
1533 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1534 $sql. ' FROM {context} ctx '.
1535 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1536 array('pathmask' => $context->path. '/%',
1537 'courselevel' => CONTEXT_COURSE));
1538 foreach ($coursescontexts as $ctxrecord) {
1539 context_helper::preload_from_record($ctxrecord);
1540 if (!can_delete_course($ctxrecord->courseid)) {
1541 return false;
1545 return true;
1549 * Recursively delete category including all subcategories and courses
1551 * Function {@link coursecat::can_delete_full()} MUST be called prior
1552 * to calling this function because there is no capability check
1553 * inside this function
1555 * @param boolean $showfeedback display some notices
1556 * @return array return deleted courses
1557 * @throws moodle_exception
1559 public function delete_full($showfeedback = true) {
1560 global $CFG, $DB;
1562 require_once($CFG->libdir.'/gradelib.php');
1563 require_once($CFG->libdir.'/questionlib.php');
1564 require_once($CFG->dirroot.'/cohort/lib.php');
1566 // Make sure we won't timeout when deleting a lot of courses.
1567 $settimeout = core_php_time_limit::raise();
1569 $deletedcourses = array();
1571 // Get children. Note, we don't want to use cache here because it would be rebuilt too often.
1572 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1573 foreach ($children as $record) {
1574 $coursecat = new coursecat($record);
1575 $deletedcourses += $coursecat->delete_full($showfeedback);
1578 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1579 foreach ($courses as $course) {
1580 if (!delete_course($course, false)) {
1581 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1583 $deletedcourses[] = $course;
1587 // Move or delete cohorts in this context.
1588 cohort_delete_category($this);
1590 // Now delete anything that may depend on course category context.
1591 grade_course_category_delete($this->id, 0, $showfeedback);
1592 if (!question_delete_course_category($this, 0, $showfeedback)) {
1593 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1596 // Finally delete the category and it's context.
1597 $DB->delete_records('course_categories', array('id' => $this->id));
1599 $coursecatcontext = context_coursecat::instance($this->id);
1600 $coursecatcontext->delete();
1602 cache_helper::purge_by_event('changesincoursecat');
1604 // Trigger a course category deleted event.
1605 /* @var \core\event\course_category_deleted $event */
1606 $event = \core\event\course_category_deleted::create(array(
1607 'objectid' => $this->id,
1608 'context' => $coursecatcontext,
1609 'other' => array('name' => $this->name)
1611 $event->set_coursecat($this);
1612 $event->trigger();
1614 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1615 if ($this->id == $CFG->defaultrequestcategory) {
1616 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1618 return $deletedcourses;
1622 * Checks if user can delete this category and move content (courses, subcategories and questions)
1623 * to another category. If yes returns the array of possible target categories names
1625 * If user can not manage this category or it is completely empty - empty array will be returned
1627 * @return array
1629 public function move_content_targets_list() {
1630 global $CFG;
1631 require_once($CFG->libdir . '/questionlib.php');
1632 $context = $this->get_context();
1633 if (!$this->is_uservisible() ||
1634 !has_capability('moodle/category:manage', $context)) {
1635 // User is not able to manage current category, he is not able to delete it.
1636 // No possible target categories.
1637 return array();
1640 $testcaps = array();
1641 // If this category has courses in it, user must have 'course:create' capability in target category.
1642 if ($this->has_courses()) {
1643 $testcaps[] = 'moodle/course:create';
1645 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1646 if ($this->has_children() || question_context_has_any_questions($context)) {
1647 $testcaps[] = 'moodle/category:manage';
1649 if (!empty($testcaps)) {
1650 // Return list of categories excluding this one and it's children.
1651 return self::make_categories_list($testcaps, $this->id);
1654 // Category is completely empty, no need in target for contents.
1655 return array();
1659 * Checks if user has capability to move all category content to the new parent before
1660 * removing this category
1662 * @param int $newcatid
1663 * @return bool
1665 public function can_move_content_to($newcatid) {
1666 global $CFG;
1667 require_once($CFG->libdir . '/questionlib.php');
1668 $context = $this->get_context();
1669 if (!$this->is_uservisible() ||
1670 !has_capability('moodle/category:manage', $context)) {
1671 return false;
1673 $testcaps = array();
1674 // If this category has courses in it, user must have 'course:create' capability in target category.
1675 if ($this->has_courses()) {
1676 $testcaps[] = 'moodle/course:create';
1678 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1679 if ($this->has_children() || question_context_has_any_questions($context)) {
1680 $testcaps[] = 'moodle/category:manage';
1682 if (!empty($testcaps)) {
1683 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1686 // There is no content but still return true.
1687 return true;
1691 * Deletes a category and moves all content (children, courses and questions) to the new parent
1693 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1694 * must be called prior
1696 * @param int $newparentid
1697 * @param bool $showfeedback
1698 * @return bool
1700 public function delete_move($newparentid, $showfeedback = false) {
1701 global $CFG, $DB, $OUTPUT;
1703 require_once($CFG->libdir.'/gradelib.php');
1704 require_once($CFG->libdir.'/questionlib.php');
1705 require_once($CFG->dirroot.'/cohort/lib.php');
1707 // Get all objects and lists because later the caches will be reset so.
1708 // We don't need to make extra queries.
1709 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1710 $catname = $this->get_formatted_name();
1711 $children = $this->get_children();
1712 $params = array('category' => $this->id);
1713 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', $params);
1714 $context = $this->get_context();
1716 if ($children) {
1717 foreach ($children as $childcat) {
1718 $childcat->change_parent_raw($newparentcat);
1719 // Log action.
1720 $event = \core\event\course_category_updated::create(array(
1721 'objectid' => $childcat->id,
1722 'context' => $childcat->get_context()
1724 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $childcat->id,
1725 $childcat->id));
1726 $event->trigger();
1728 fix_course_sortorder();
1731 if ($coursesids) {
1732 if (!move_courses($coursesids, $newparentid)) {
1733 if ($showfeedback) {
1734 echo $OUTPUT->notification("Error moving courses");
1736 return false;
1738 if ($showfeedback) {
1739 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1743 // Move or delete cohorts in this context.
1744 cohort_delete_category($this);
1746 // Now delete anything that may depend on course category context.
1747 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1748 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1749 if ($showfeedback) {
1750 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1752 return false;
1755 // Finally delete the category and it's context.
1756 $DB->delete_records('course_categories', array('id' => $this->id));
1757 $context->delete();
1759 // Trigger a course category deleted event.
1760 /* @var \core\event\course_category_deleted $event */
1761 $event = \core\event\course_category_deleted::create(array(
1762 'objectid' => $this->id,
1763 'context' => $context,
1764 'other' => array('name' => $this->name)
1766 $event->set_coursecat($this);
1767 $event->trigger();
1769 cache_helper::purge_by_event('changesincoursecat');
1771 if ($showfeedback) {
1772 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1775 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1776 if ($this->id == $CFG->defaultrequestcategory) {
1777 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1779 return true;
1783 * Checks if user can move current category to the new parent
1785 * This checks if new parent category exists, user has manage cap there
1786 * and new parent is not a child of this category
1788 * @param int|stdClass|coursecat $newparentcat
1789 * @return bool
1791 public function can_change_parent($newparentcat) {
1792 if (!has_capability('moodle/category:manage', $this->get_context())) {
1793 return false;
1795 if (is_object($newparentcat)) {
1796 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1797 } else {
1798 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1800 if (!$newparentcat) {
1801 return false;
1803 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1804 // Can not move to itself or it's own child.
1805 return false;
1807 if ($newparentcat->id) {
1808 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
1809 } else {
1810 return has_capability('moodle/category:manage', context_system::instance());
1815 * Moves the category under another parent category. All associated contexts are moved as well
1817 * This is protected function, use change_parent() or update() from outside of this class
1819 * @see coursecat::change_parent()
1820 * @see coursecat::update()
1822 * @param coursecat $newparentcat
1823 * @throws moodle_exception
1825 protected function change_parent_raw(coursecat $newparentcat) {
1826 global $DB;
1828 $context = $this->get_context();
1830 $hidecat = false;
1831 if (empty($newparentcat->id)) {
1832 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1833 $newparent = context_system::instance();
1834 } else {
1835 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1836 // Can not move to itself or it's own child.
1837 throw new moodle_exception('cannotmovecategory');
1839 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
1840 $newparent = context_coursecat::instance($newparentcat->id);
1842 if (!$newparentcat->visible and $this->visible) {
1843 // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children
1844 // will be restored properly.
1845 $hidecat = true;
1848 $this->parent = $newparentcat->id;
1850 $context->update_moved($newparent);
1852 // Now make it last in new category.
1853 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
1855 if ($hidecat) {
1856 fix_course_sortorder();
1857 $this->restore();
1858 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must
1859 // become visible again.
1860 $this->hide_raw(1);
1865 * Efficiently moves a category - NOTE that this can have
1866 * a huge impact access-control-wise...
1868 * Note that this function does not check capabilities.
1870 * Example of usage:
1871 * $coursecat = coursecat::get($categoryid);
1872 * if ($coursecat->can_change_parent($newparentcatid)) {
1873 * $coursecat->change_parent($newparentcatid);
1876 * This function does not update field course_categories.timemodified
1877 * If you want to update timemodified, use
1878 * $coursecat->update(array('parent' => $newparentcat));
1880 * @param int|stdClass|coursecat $newparentcat
1882 public function change_parent($newparentcat) {
1883 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1884 if (is_object($newparentcat)) {
1885 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
1886 } else {
1887 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
1889 if ($newparentcat->id != $this->parent) {
1890 $this->change_parent_raw($newparentcat);
1891 fix_course_sortorder();
1892 cache_helper::purge_by_event('changesincoursecat');
1893 $this->restore();
1895 $event = \core\event\course_category_updated::create(array(
1896 'objectid' => $this->id,
1897 'context' => $this->get_context()
1899 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $this->id, $this->id));
1900 $event->trigger();
1905 * Hide course category and child course and subcategories
1907 * If this category has changed the parent and is moved under hidden
1908 * category we will want to store it's current visibility state in
1909 * the field 'visibleold'. If admin clicked 'hide' for this particular
1910 * category, the field 'visibleold' should become 0.
1912 * All subcategories and courses will have their current visibility in the field visibleold
1914 * This is protected function, use hide() or update() from outside of this class
1916 * @see coursecat::hide()
1917 * @see coursecat::update()
1919 * @param int $visibleold value to set in field $visibleold for this category
1920 * @return bool whether changes have been made and caches need to be purged afterwards
1922 protected function hide_raw($visibleold = 0) {
1923 global $DB;
1924 $changes = false;
1926 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing.
1927 if ($this->id && $this->__get('visibleold') != $visibleold) {
1928 $this->visibleold = $visibleold;
1929 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
1930 $changes = true;
1932 if (!$this->visible || !$this->id) {
1933 // Already hidden or can not be hidden.
1934 return $changes;
1937 $this->visible = 0;
1938 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
1939 // Store visible flag so that we can return to it if we immediately unhide.
1940 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id));
1941 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
1942 // Get all child categories and hide too.
1943 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
1944 foreach ($subcats as $cat) {
1945 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
1946 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
1947 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
1948 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
1951 return true;
1955 * Hide course category and child course and subcategories
1957 * Note that there is no capability check inside this function
1959 * This function does not update field course_categories.timemodified
1960 * If you want to update timemodified, use
1961 * $coursecat->update(array('visible' => 0));
1963 public function hide() {
1964 if ($this->hide_raw(0)) {
1965 cache_helper::purge_by_event('changesincoursecat');
1967 $event = \core\event\course_category_updated::create(array(
1968 'objectid' => $this->id,
1969 'context' => $this->get_context()
1971 $event->set_legacy_logdata(array(SITEID, 'category', 'hide', 'editcategory.php?id=' . $this->id, $this->id));
1972 $event->trigger();
1977 * Show course category and restores visibility for child course and subcategories
1979 * Note that there is no capability check inside this function
1981 * This is protected function, use show() or update() from outside of this class
1983 * @see coursecat::show()
1984 * @see coursecat::update()
1986 * @return bool whether changes have been made and caches need to be purged afterwards
1988 protected function show_raw() {
1989 global $DB;
1991 if ($this->visible) {
1992 // Already visible.
1993 return false;
1996 $this->visible = 1;
1997 $this->visibleold = 1;
1998 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
1999 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
2000 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
2001 // Get all child categories and unhide too.
2002 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
2003 foreach ($subcats as $cat) {
2004 if ($cat->visibleold) {
2005 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
2007 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
2010 return true;
2014 * Show course category and restores visibility for child course and subcategories
2016 * Note that there is no capability check inside this function
2018 * This function does not update field course_categories.timemodified
2019 * If you want to update timemodified, use
2020 * $coursecat->update(array('visible' => 1));
2022 public function show() {
2023 if ($this->show_raw()) {
2024 cache_helper::purge_by_event('changesincoursecat');
2026 $event = \core\event\course_category_updated::create(array(
2027 'objectid' => $this->id,
2028 'context' => $this->get_context()
2030 $event->set_legacy_logdata(array(SITEID, 'category', 'show', 'editcategory.php?id=' . $this->id, $this->id));
2031 $event->trigger();
2036 * Returns name of the category formatted as a string
2038 * @param array $options formatting options other than context
2039 * @return string
2041 public function get_formatted_name($options = array()) {
2042 if ($this->id) {
2043 $context = $this->get_context();
2044 return format_string($this->name, true, array('context' => $context) + $options);
2045 } else {
2046 return get_string('top');
2051 * Returns ids of all parents of the category. Last element in the return array is the direct parent
2053 * For example, if you have a tree of categories like:
2054 * Miscellaneous (id = 1)
2055 * Subcategory (id = 2)
2056 * Sub-subcategory (id = 4)
2057 * Other category (id = 3)
2059 * coursecat::get(1)->get_parents() == array()
2060 * coursecat::get(2)->get_parents() == array(1)
2061 * coursecat::get(4)->get_parents() == array(1, 2);
2063 * Note that this method does not check if all parents are accessible by current user
2065 * @return array of category ids
2067 public function get_parents() {
2068 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
2069 array_pop($parents);
2070 return $parents;
2074 * This function returns a nice list representing category tree
2075 * for display or to use in a form <select> element
2077 * List is cached for 10 minutes
2079 * For example, if you have a tree of categories like:
2080 * Miscellaneous (id = 1)
2081 * Subcategory (id = 2)
2082 * Sub-subcategory (id = 4)
2083 * Other category (id = 3)
2084 * Then after calling this function you will have
2085 * array(1 => 'Miscellaneous',
2086 * 2 => 'Miscellaneous / Subcategory',
2087 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2088 * 3 => 'Other category');
2090 * If you specify $requiredcapability, then only categories where the current
2091 * user has that capability will be added to $list.
2092 * If you only have $requiredcapability in a child category, not the parent,
2093 * then the child catgegory will still be included.
2095 * If you specify the option $excludeid, then that category, and all its children,
2096 * are omitted from the tree. This is useful when you are doing something like
2097 * moving categories, where you do not want to allow people to move a category
2098 * to be the child of itself.
2100 * See also {@link make_categories_options()}
2102 * @param string/array $requiredcapability if given, only categories where the current
2103 * user has this capability will be returned. Can also be an array of capabilities,
2104 * in which case they are all required.
2105 * @param integer $excludeid Exclude this category and its children from the lists built.
2106 * @param string $separator string to use as a separator between parent and child category. Default ' / '
2107 * @return array of strings
2109 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
2110 global $DB;
2111 $coursecatcache = cache::make('core', 'coursecat');
2113 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids
2114 // with requried cap ($thislist).
2115 $currentlang = current_language();
2116 $basecachekey = $currentlang . '_catlist';
2117 $baselist = $coursecatcache->get($basecachekey);
2118 $thislist = false;
2119 $thiscachekey = null;
2120 if (!empty($requiredcapability)) {
2121 $requiredcapability = (array)$requiredcapability;
2122 $thiscachekey = 'catlist:'. serialize($requiredcapability);
2123 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
2124 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
2126 } else if ($baselist !== false) {
2127 $thislist = array_keys($baselist);
2130 if ($baselist === false) {
2131 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
2132 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2133 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
2134 FROM {course_categories} cc
2135 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
2136 ORDER BY cc.sortorder";
2137 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2138 $baselist = array();
2139 $thislist = array();
2140 foreach ($rs as $record) {
2141 // If the category's parent is not visible to the user, it is not visible as well.
2142 if (!$record->parent || isset($baselist[$record->parent])) {
2143 context_helper::preload_from_record($record);
2144 $context = context_coursecat::instance($record->id);
2145 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
2146 // No cap to view category, added to neither $baselist nor $thislist.
2147 continue;
2149 $baselist[$record->id] = array(
2150 'name' => format_string($record->name, true, array('context' => $context)),
2151 'path' => $record->path
2153 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
2154 // No required capability, added to $baselist but not to $thislist.
2155 continue;
2157 $thislist[] = $record->id;
2160 $rs->close();
2161 $coursecatcache->set($basecachekey, $baselist);
2162 if (!empty($requiredcapability)) {
2163 $coursecatcache->set($thiscachekey, join(',', $thislist));
2165 } else if ($thislist === false) {
2166 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
2167 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2168 $sql = "SELECT ctx.instanceid AS id, $ctxselect
2169 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
2170 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2171 $thislist = array();
2172 foreach (array_keys($baselist) as $id) {
2173 context_helper::preload_from_record($contexts[$id]);
2174 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
2175 $thislist[] = $id;
2178 $coursecatcache->set($thiscachekey, join(',', $thislist));
2181 // Now build the array of strings to return, mind $separator and $excludeid.
2182 $names = array();
2183 foreach ($thislist as $id) {
2184 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
2185 if (!$excludeid || !in_array($excludeid, $path)) {
2186 $namechunks = array();
2187 foreach ($path as $parentid) {
2188 $namechunks[] = $baselist[$parentid]['name'];
2190 $names[$id] = join($separator, $namechunks);
2193 return $names;
2197 * Prepares the object for caching. Works like the __sleep method.
2199 * implementing method from interface cacheable_object
2201 * @return array ready to be cached
2203 public function prepare_to_cache() {
2204 $a = array();
2205 foreach (self::$coursecatfields as $property => $cachedirectives) {
2206 if ($cachedirectives !== null) {
2207 list($shortname, $defaultvalue) = $cachedirectives;
2208 if ($this->$property !== $defaultvalue) {
2209 $a[$shortname] = $this->$property;
2213 $context = $this->get_context();
2214 $a['xi'] = $context->id;
2215 $a['xp'] = $context->path;
2216 return $a;
2220 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2222 * implementing method from interface cacheable_object
2224 * @param array $a
2225 * @return coursecat
2227 public static function wake_from_cache($a) {
2228 $record = new stdClass;
2229 foreach (self::$coursecatfields as $property => $cachedirectives) {
2230 if ($cachedirectives !== null) {
2231 list($shortname, $defaultvalue) = $cachedirectives;
2232 if (array_key_exists($shortname, $a)) {
2233 $record->$property = $a[$shortname];
2234 } else {
2235 $record->$property = $defaultvalue;
2239 $record->ctxid = $a['xi'];
2240 $record->ctxpath = $a['xp'];
2241 $record->ctxdepth = $record->depth + 1;
2242 $record->ctxlevel = CONTEXT_COURSECAT;
2243 $record->ctxinstance = $record->id;
2244 return new coursecat($record, true);
2248 * Returns true if the user is able to create a top level category.
2249 * @return bool
2251 public static function can_create_top_level_category() {
2252 return has_capability('moodle/category:manage', context_system::instance());
2256 * Returns the category context.
2257 * @return context_coursecat
2259 public function get_context() {
2260 if ($this->id === 0) {
2261 // This is the special top level category object.
2262 return context_system::instance();
2263 } else {
2264 return context_coursecat::instance($this->id);
2269 * Returns true if the user is able to manage this category.
2270 * @return bool
2272 public function has_manage_capability() {
2273 if ($this->hasmanagecapability === null) {
2274 $this->hasmanagecapability = has_capability('moodle/category:manage', $this->get_context());
2276 return $this->hasmanagecapability;
2280 * Returns true if the user has the manage capability on the parent category.
2281 * @return bool
2283 public function parent_has_manage_capability() {
2284 return has_capability('moodle/category:manage', get_category_or_system_context($this->parent));
2288 * Returns true if the current user can create subcategories of this category.
2289 * @return bool
2291 public function can_create_subcategory() {
2292 return $this->has_manage_capability();
2296 * Returns true if the user can resort this categories sub categories and courses.
2297 * Must have manage capability and be able to see all subcategories.
2298 * @return bool
2300 public function can_resort_subcategories() {
2301 return $this->has_manage_capability() && !$this->get_not_visible_children_ids();
2305 * Returns true if the user can resort the courses within this category.
2306 * Must have manage capability and be able to see all courses.
2307 * @return bool
2309 public function can_resort_courses() {
2310 return $this->has_manage_capability() && $this->coursecount == $this->get_courses_count();
2314 * Returns true of the user can change the sortorder of this category (resort in the parent category)
2315 * @return bool
2317 public function can_change_sortorder() {
2318 return $this->id && $this->get_parent_coursecat()->can_resort_subcategories();
2322 * Returns true if the current user can create a course within this category.
2323 * @return bool
2325 public function can_create_course() {
2326 return has_capability('moodle/course:create', $this->get_context());
2330 * Returns true if the current user can edit this categories settings.
2331 * @return bool
2333 public function can_edit() {
2334 return $this->has_manage_capability();
2338 * Returns true if the current user can review role assignments for this category.
2339 * @return bool
2341 public function can_review_roles() {
2342 return has_capability('moodle/role:assign', $this->get_context());
2346 * Returns true if the current user can review permissions for this category.
2347 * @return bool
2349 public function can_review_permissions() {
2350 return has_any_capability(array(
2351 'moodle/role:assign',
2352 'moodle/role:safeoverride',
2353 'moodle/role:override',
2354 'moodle/role:assign'
2355 ), $this->get_context());
2359 * Returns true if the current user can review cohorts for this category.
2360 * @return bool
2362 public function can_review_cohorts() {
2363 return has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->get_context());
2367 * Returns true if the current user can review filter settings for this category.
2368 * @return bool
2370 public function can_review_filters() {
2371 return has_capability('moodle/filter:manage', $this->get_context()) &&
2372 count(filter_get_available_in_context($this->get_context()))>0;
2376 * Returns true if the current user is able to change the visbility of this category.
2377 * @return bool
2379 public function can_change_visibility() {
2380 return $this->parent_has_manage_capability();
2384 * Returns true if the user can move courses out of this category.
2385 * @return bool
2387 public function can_move_courses_out_of() {
2388 return $this->has_manage_capability();
2392 * Returns true if the user can move courses into this category.
2393 * @return bool
2395 public function can_move_courses_into() {
2396 return $this->has_manage_capability();
2400 * Returns true if the user is able to restore a course into this category as a new course.
2401 * @return bool
2403 public function can_restore_courses_into() {
2404 return has_capability('moodle/restore:restorecourse', $this->get_context());
2408 * Resorts the sub categories of this category by the given field.
2410 * @param string $field One of name, idnumber or descending values of each (appended desc)
2411 * @param bool $cleanup If true cleanup will be done, if false you will need to do it manually later.
2412 * @return bool True on success.
2413 * @throws coding_exception
2415 public function resort_subcategories($field, $cleanup = true) {
2416 global $DB;
2417 $desc = false;
2418 if (substr($field, -4) === "desc") {
2419 $desc = true;
2420 $field = substr($field, 0, -4); // Remove "desc" from field name.
2422 if ($field !== 'name' && $field !== 'idnumber') {
2423 throw new coding_exception('Invalid field requested');
2425 $children = $this->get_children();
2426 core_collator::asort_objects_by_property($children, $field, core_collator::SORT_NATURAL);
2427 if (!empty($desc)) {
2428 $children = array_reverse($children);
2430 $i = 1;
2431 foreach ($children as $cat) {
2432 $i++;
2433 $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id));
2434 $i += $cat->coursecount;
2436 if ($cleanup) {
2437 self::resort_categories_cleanup();
2439 return true;
2443 * Cleans things up after categories have been resorted.
2444 * @param bool $includecourses If set to true we know courses have been resorted as well.
2446 public static function resort_categories_cleanup($includecourses = false) {
2447 // This should not be needed but we do it just to be safe.
2448 fix_course_sortorder();
2449 cache_helper::purge_by_event('changesincoursecat');
2450 if ($includecourses) {
2451 cache_helper::purge_by_event('changesincourse');
2456 * Resort the courses within this category by the given field.
2458 * @param string $field One of fullname, shortname, idnumber or descending values of each (appended desc)
2459 * @param bool $cleanup
2460 * @return bool True for success.
2461 * @throws coding_exception
2463 public function resort_courses($field, $cleanup = true) {
2464 global $DB;
2465 $desc = false;
2466 if (substr($field, -4) === "desc") {
2467 $desc = true;
2468 $field = substr($field, 0, -4); // Remove "desc" from field name.
2470 if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber' && $field !== 'timecreated') {
2471 // This is ultra important as we use $field in an SQL statement below this.
2472 throw new coding_exception('Invalid field requested');
2474 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
2475 $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields
2476 FROM {course} c
2477 LEFT JOIN {context} ctx ON ctx.instanceid = c.id
2478 WHERE ctx.contextlevel = :ctxlevel AND
2479 c.category = :categoryid";
2480 $params = array(
2481 'ctxlevel' => CONTEXT_COURSE,
2482 'categoryid' => $this->id
2484 $courses = $DB->get_records_sql($sql, $params);
2485 if (count($courses) > 0) {
2486 foreach ($courses as $courseid => $course) {
2487 context_helper::preload_from_record($course);
2488 if ($field === 'idnumber') {
2489 $course->sortby = $course->idnumber;
2490 } else {
2491 // It'll require formatting.
2492 $options = array(
2493 'context' => context_course::instance($course->id)
2495 // We format the string first so that it appears as the user would see it.
2496 // This ensures the sorting makes sense to them. However it won't necessarily make
2497 // sense to everyone if things like multilang filters are enabled.
2498 // We then strip any tags as we don't want things such as image tags skewing the
2499 // sort results.
2500 $course->sortby = strip_tags(format_string($course->$field, true, $options));
2502 // We set it back here rather than using references as there is a bug with using
2503 // references in a foreach before passing as an arg by reference.
2504 $courses[$courseid] = $course;
2506 // Sort the courses.
2507 core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL);
2508 if (!empty($desc)) {
2509 $courses = array_reverse($courses);
2511 $i = 1;
2512 foreach ($courses as $course) {
2513 $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id));
2514 $i++;
2516 if ($cleanup) {
2517 // This should not be needed but we do it just to be safe.
2518 fix_course_sortorder();
2519 cache_helper::purge_by_event('changesincourse');
2522 return true;
2526 * Changes the sort order of this categories parent shifting this category up or down one.
2528 * @global \moodle_database $DB
2529 * @param bool $up If set to true the category is shifted up one spot, else its moved down.
2530 * @return bool True on success, false otherwise.
2532 public function change_sortorder_by_one($up) {
2533 global $DB;
2534 $params = array($this->sortorder, $this->parent);
2535 if ($up) {
2536 $select = 'sortorder < ? AND parent = ?';
2537 $sort = 'sortorder DESC';
2538 } else {
2539 $select = 'sortorder > ? AND parent = ?';
2540 $sort = 'sortorder ASC';
2542 fix_course_sortorder();
2543 $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1);
2544 $swapcategory = reset($swapcategory);
2545 if ($swapcategory) {
2546 $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id));
2547 $DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id));
2548 $this->sortorder = $swapcategory->sortorder;
2550 $event = \core\event\course_category_updated::create(array(
2551 'objectid' => $this->id,
2552 'context' => $this->get_context()
2554 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'management.php?categoryid=' . $this->id,
2555 $this->id));
2556 $event->trigger();
2558 // Finally reorder courses.
2559 fix_course_sortorder();
2560 cache_helper::purge_by_event('changesincoursecat');
2561 return true;
2563 return false;
2567 * Returns the parent coursecat object for this category.
2569 * @return coursecat
2571 public function get_parent_coursecat() {
2572 return self::get($this->parent);
2577 * Returns true if the user is able to request a new course be created.
2578 * @return bool
2580 public function can_request_course() {
2581 global $CFG;
2582 if (empty($CFG->enablecourserequests) || $this->id != $CFG->defaultrequestcategory) {
2583 return false;
2585 return !$this->can_create_course() && has_capability('moodle/course:request', $this->get_context());
2589 * Returns true if the user can approve course requests.
2590 * @return bool
2592 public static function can_approve_course_requests() {
2593 global $CFG, $DB;
2594 if (empty($CFG->enablecourserequests)) {
2595 return false;
2597 $context = context_system::instance();
2598 if (!has_capability('moodle/site:approvecourse', $context)) {
2599 return false;
2601 if (!$DB->record_exists('course_request', array())) {
2602 return false;
2604 return true;
2609 * Class to store information about one course in a list of courses
2611 * Not all information may be retrieved when object is created but
2612 * it will be retrieved on demand when appropriate property or method is
2613 * called.
2615 * Instances of this class are usually returned by functions
2616 * {@link coursecat::search_courses()}
2617 * and
2618 * {@link coursecat::get_courses()}
2620 * @property-read int $id
2621 * @property-read int $category Category ID
2622 * @property-read int $sortorder
2623 * @property-read string $fullname
2624 * @property-read string $shortname
2625 * @property-read string $idnumber
2626 * @property-read string $summary Course summary. Field is present if coursecat::get_courses()
2627 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2628 * @property-read int $summaryformat Summary format. Field is present if coursecat::get_courses()
2629 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2630 * @property-read string $format Course format. Retrieved from DB on first request
2631 * @property-read int $showgrades Retrieved from DB on first request
2632 * @property-read int $newsitems Retrieved from DB on first request
2633 * @property-read int $startdate
2634 * @property-read int $marker Retrieved from DB on first request
2635 * @property-read int $maxbytes Retrieved from DB on first request
2636 * @property-read int $legacyfiles Retrieved from DB on first request
2637 * @property-read int $showreports Retrieved from DB on first request
2638 * @property-read int $visible
2639 * @property-read int $visibleold Retrieved from DB on first request
2640 * @property-read int $groupmode Retrieved from DB on first request
2641 * @property-read int $groupmodeforce Retrieved from DB on first request
2642 * @property-read int $defaultgroupingid Retrieved from DB on first request
2643 * @property-read string $lang Retrieved from DB on first request
2644 * @property-read string $theme Retrieved from DB on first request
2645 * @property-read int $timecreated Retrieved from DB on first request
2646 * @property-read int $timemodified Retrieved from DB on first request
2647 * @property-read int $requested Retrieved from DB on first request
2648 * @property-read int $enablecompletion Retrieved from DB on first request
2649 * @property-read int $completionnotify Retrieved from DB on first request
2650 * @property-read int $cacherev
2652 * @package core
2653 * @subpackage course
2654 * @copyright 2013 Marina Glancy
2655 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2657 class course_in_list implements IteratorAggregate {
2659 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2660 protected $record;
2662 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2663 protected $coursecontacts;
2665 /** @var bool true if the current user can access the course, false otherwise. */
2666 protected $canaccess = null;
2669 * Creates an instance of the class from record
2671 * @param stdClass $record except fields from course table it may contain
2672 * field hassummary indicating that summary field is not empty.
2673 * Also it is recommended to have context fields here ready for
2674 * context preloading
2676 public function __construct(stdClass $record) {
2677 context_helper::preload_from_record($record);
2678 $this->record = new stdClass();
2679 foreach ($record as $key => $value) {
2680 $this->record->$key = $value;
2685 * Indicates if the course has non-empty summary field
2687 * @return bool
2689 public function has_summary() {
2690 if (isset($this->record->hassummary)) {
2691 return !empty($this->record->hassummary);
2693 if (!isset($this->record->summary)) {
2694 // We need to retrieve summary.
2695 $this->__get('summary');
2697 return !empty($this->record->summary);
2701 * Indicates if the course have course contacts to display
2703 * @return bool
2705 public function has_course_contacts() {
2706 if (!isset($this->record->managers)) {
2707 $courses = array($this->id => &$this->record);
2708 coursecat::preload_course_contacts($courses);
2710 return !empty($this->record->managers);
2714 * Returns list of course contacts (usually teachers) to display in course link
2716 * Roles to display are set up in $CFG->coursecontact
2718 * The result is the list of users where user id is the key and the value
2719 * is an array with elements:
2720 * - 'user' - object containing basic user information
2721 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2722 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2723 * - 'username' => fullname($user, $canviewfullnames)
2725 * @return array
2727 public function get_course_contacts() {
2728 global $CFG;
2729 if (empty($CFG->coursecontact)) {
2730 // No roles are configured to be displayed as course contacts.
2731 return array();
2733 if ($this->coursecontacts === null) {
2734 $this->coursecontacts = array();
2735 $context = context_course::instance($this->id);
2737 if (!isset($this->record->managers)) {
2738 // Preload course contacts from DB.
2739 $courses = array($this->id => &$this->record);
2740 coursecat::preload_course_contacts($courses);
2743 // Build return array with full roles names (for this course context) and users names.
2744 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2745 foreach ($this->record->managers as $ruser) {
2746 if (isset($this->coursecontacts[$ruser->id])) {
2747 // Only display a user once with the highest sortorder role.
2748 continue;
2750 $user = new stdClass();
2751 $user = username_load_fields_from_object($user, $ruser, null, array('id', 'username'));
2752 $role = new stdClass();
2753 $role->id = $ruser->roleid;
2754 $role->name = $ruser->rolename;
2755 $role->shortname = $ruser->roleshortname;
2756 $role->coursealias = $ruser->rolecoursealias;
2758 $this->coursecontacts[$user->id] = array(
2759 'user' => $user,
2760 'role' => $role,
2761 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2762 'username' => fullname($user, $canviewfullnames)
2766 return $this->coursecontacts;
2770 * Checks if course has any associated overview files
2772 * @return bool
2774 public function has_course_overviewfiles() {
2775 global $CFG;
2776 if (empty($CFG->courseoverviewfileslimit)) {
2777 return false;
2779 $fs = get_file_storage();
2780 $context = context_course::instance($this->id);
2781 return !$fs->is_area_empty($context->id, 'course', 'overviewfiles');
2785 * Returns all course overview files
2787 * @return array array of stored_file objects
2789 public function get_course_overviewfiles() {
2790 global $CFG;
2791 if (empty($CFG->courseoverviewfileslimit)) {
2792 return array();
2794 require_once($CFG->libdir. '/filestorage/file_storage.php');
2795 require_once($CFG->dirroot. '/course/lib.php');
2796 $fs = get_file_storage();
2797 $context = context_course::instance($this->id);
2798 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2799 if (count($files)) {
2800 $overviewfilesoptions = course_overviewfiles_options($this->id);
2801 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2802 if ($acceptedtypes !== '*') {
2803 // Filter only files with allowed extensions.
2804 require_once($CFG->libdir. '/filelib.php');
2805 foreach ($files as $key => $file) {
2806 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2807 unset($files[$key]);
2811 if (count($files) > $CFG->courseoverviewfileslimit) {
2812 // Return no more than $CFG->courseoverviewfileslimit files.
2813 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
2816 return $files;
2820 * Magic method to check if property is set
2822 * @param string $name
2823 * @return bool
2825 public function __isset($name) {
2826 return isset($this->record->$name);
2830 * Magic method to get a course property
2832 * Returns any field from table course (retrieves it from DB if it was not retrieved before)
2834 * @param string $name
2835 * @return mixed
2837 public function __get($name) {
2838 global $DB;
2839 if (property_exists($this->record, $name)) {
2840 return $this->record->$name;
2841 } else if ($name === 'summary' || $name === 'summaryformat') {
2842 // Retrieve fields summary and summaryformat together because they are most likely to be used together.
2843 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
2844 $this->record->summary = $record->summary;
2845 $this->record->summaryformat = $record->summaryformat;
2846 return $this->record->$name;
2847 } else if (array_key_exists($name, $DB->get_columns('course'))) {
2848 // Another field from table 'course' that was not retrieved.
2849 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
2850 return $this->record->$name;
2852 debugging('Invalid course property accessed! '.$name);
2853 return null;
2857 * All properties are read only, sorry.
2859 * @param string $name
2861 public function __unset($name) {
2862 debugging('Can not unset '.get_class($this).' instance properties!');
2866 * Magic setter method, we do not want anybody to modify properties from the outside
2868 * @param string $name
2869 * @param mixed $value
2871 public function __set($name, $value) {
2872 debugging('Can not change '.get_class($this).' instance properties!');
2876 * Create an iterator because magic vars can't be seen by 'foreach'.
2877 * Exclude context fields
2879 * Implementing method from interface IteratorAggregate
2881 * @return ArrayIterator
2883 public function getIterator() {
2884 $ret = array('id' => $this->record->id);
2885 foreach ($this->record as $property => $value) {
2886 $ret[$property] = $value;
2888 return new ArrayIterator($ret);
2892 * Returns the name of this course as it should be displayed within a list.
2893 * @return string
2895 public function get_formatted_name() {
2896 return format_string(get_course_display_name_for_list($this), true, $this->get_context());
2900 * Returns the formatted fullname for this course.
2901 * @return string
2903 public function get_formatted_fullname() {
2904 return format_string($this->__get('fullname'), true, $this->get_context());
2908 * Returns the formatted shortname for this course.
2909 * @return string
2911 public function get_formatted_shortname() {
2912 return format_string($this->__get('shortname'), true, $this->get_context());
2916 * Returns true if the current user can access this course.
2917 * @return bool
2919 public function can_access() {
2920 if ($this->canaccess === null) {
2921 $this->canaccess = can_access_course($this->record);
2923 return $this->canaccess;
2927 * Returns true if the user can edit this courses settings.
2929 * Note: this function does not check that the current user can access the course.
2930 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2932 * @return bool
2934 public function can_edit() {
2935 return has_capability('moodle/course:update', $this->get_context());
2939 * Returns true if the user can change the visibility of this course.
2941 * Note: this function does not check that the current user can access the course.
2942 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2944 * @return bool
2946 public function can_change_visibility() {
2947 // You must be able to both hide a course and view the hidden course.
2948 return has_all_capabilities(array('moodle/course:visibility', 'moodle/course:viewhiddencourses'), $this->get_context());
2952 * Returns the context for this course.
2953 * @return context_course
2955 public function get_context() {
2956 return context_course::instance($this->__get('id'));
2960 * Returns true if this course is visible to the current user.
2961 * @return bool
2963 public function is_uservisible() {
2964 return $this->visible || has_capability('moodle/course:viewhiddencourses', $this->get_context());
2968 * Returns true if the current user can review enrolments for this course.
2970 * Note: this function does not check that the current user can access the course.
2971 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2973 * @return bool
2975 public function can_review_enrolments() {
2976 return has_capability('moodle/course:enrolreview', $this->get_context());
2980 * Returns true if the current user can delete this course.
2982 * Note: this function does not check that the current user can access the course.
2983 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2985 * @return bool
2987 public function can_delete() {
2988 return can_delete_course($this->id);
2992 * Returns true if the current user can backup this course.
2994 * Note: this function does not check that the current user can access the course.
2995 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2997 * @return bool
2999 public function can_backup() {
3000 return has_capability('moodle/backup:backupcourse', $this->get_context());
3004 * Returns true if the current user can restore this course.
3006 * Note: this function does not check that the current user can access the course.
3007 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3009 * @return bool
3011 public function can_restore() {
3012 return has_capability('moodle/restore:restorecourse', $this->get_context());
3017 * An array of records that is sortable by many fields.
3019 * For more info on the ArrayObject class have a look at php.net.
3021 * @package core
3022 * @subpackage course
3023 * @copyright 2013 Sam Hemelryk
3024 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3026 class coursecat_sortable_records extends ArrayObject {
3029 * An array of sortable fields.
3030 * Gets set temporarily when sort is called.
3031 * @var array
3033 protected $sortfields = array();
3036 * Sorts this array using the given fields.
3038 * @param array $records
3039 * @param array $fields
3040 * @return array
3042 public static function sort(array $records, array $fields) {
3043 $records = new coursecat_sortable_records($records);
3044 $records->sortfields = $fields;
3045 $records->uasort(array($records, 'sort_by_many_fields'));
3046 return $records->getArrayCopy();
3050 * Sorts the two records based upon many fields.
3052 * This method should not be called itself, please call $sort instead.
3053 * It has been marked as access private as such.
3055 * @access private
3056 * @param stdClass $a
3057 * @param stdClass $b
3058 * @return int
3060 public function sort_by_many_fields($a, $b) {
3061 foreach ($this->sortfields as $field => $mult) {
3062 // Nulls first.
3063 if (is_null($a->$field) && !is_null($b->$field)) {
3064 return -$mult;
3066 if (is_null($b->$field) && !is_null($a->$field)) {
3067 return $mult;
3070 if (is_string($a->$field) || is_string($b->$field)) {
3071 // String fields.
3072 if ($cmp = strcoll($a->$field, $b->$field)) {
3073 return $mult * $cmp;
3075 } else {
3076 // Int fields.
3077 if ($a->$field > $b->$field) {
3078 return $mult;
3080 if ($a->$field < $b->$field) {
3081 return -$mult;
3085 return 0;