Merge branch 'wip-mdl-31405-new' of git://github.com/rajeshtaneja/moodle
[moodle.git] / lib / coursecatlib.php
blob8f941eab3a982e361897de43824dc4f3e7128f8b
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('unknowcategory');
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 add_to_log(SITEID, "category", 'add', "editcategory.php?id=$newcategory->id", $newcategory->id);
431 cache_helper::purge_by_event('changesincoursecat');
433 return self::get($newcategory->id, MUST_EXIST, true);
437 * Updates the record with either form data or raw data
439 * Please note that this function does not verify access control.
441 * This function calls coursecat::change_parent_raw if field 'parent' is updated.
442 * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
443 * Visibility is changed first and then parent is changed. This means that
444 * if parent category is hidden, the current category will become hidden
445 * too and it may overwrite whatever was set in field 'visible'.
447 * Note that fields 'path' and 'depth' can not be updated manually
448 * Also coursecat::update() can not directly update the field 'sortoder'
450 * @param array|stdClass $data
451 * @param array $editoroptions if specified, the data is considered to be
452 * form data and file_postupdate_standard_editor() is being called to
453 * process images in description.
454 * @throws moodle_exception
456 public function update($data, $editoroptions = null) {
457 global $DB, $CFG;
458 if (!$this->id) {
459 // There is no actual DB record associated with root category.
460 return;
463 $data = (object)$data;
464 $newcategory = new stdClass();
465 $newcategory->id = $this->id;
467 // Copy all description* fields regardless of whether this is form data or direct field update.
468 foreach ($data as $key => $value) {
469 if (preg_match("/^description/", $key)) {
470 $newcategory->$key = $value;
474 if (isset($data->name) && empty($data->name)) {
475 throw new moodle_exception('categorynamerequired');
478 if (!empty($data->name) && $data->name !== $this->name) {
479 if (core_text::strlen($data->name) > 255) {
480 throw new moodle_exception('categorytoolong');
482 $newcategory->name = $data->name;
485 if (isset($data->idnumber) && $data->idnumber != $this->idnumber) {
486 if (core_text::strlen($data->idnumber) > 100) {
487 throw new moodle_exception('idnumbertoolong');
489 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
490 throw new moodle_exception('categoryidnumbertaken');
492 $newcategory->idnumber = $data->idnumber;
495 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
496 $newcategory->theme = $data->theme;
499 $changes = false;
500 if (isset($data->visible)) {
501 if ($data->visible) {
502 $changes = $this->show_raw();
503 } else {
504 $changes = $this->hide_raw(0);
508 if (isset($data->parent) && $data->parent != $this->parent) {
509 if ($changes) {
510 cache_helper::purge_by_event('changesincoursecat');
512 $parentcat = self::get($data->parent, MUST_EXIST, true);
513 $this->change_parent_raw($parentcat);
514 fix_course_sortorder();
517 $newcategory->timemodified = time();
519 if ($editoroptions) {
520 $categorycontext = $this->get_context();
521 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
522 'coursecat', 'description', 0);
524 $DB->update_record('course_categories', $newcategory);
525 add_to_log(SITEID, "category", 'update', "editcategory.php?id=$this->id", $this->id);
526 fix_course_sortorder();
527 // Purge cache even if fix_course_sortorder() did not do it.
528 cache_helper::purge_by_event('changesincoursecat');
530 // Update all fields in the current object.
531 $this->restore();
535 * Checks if this course category is visible to current user
537 * Please note that methods coursecat::get (without 3rd argumet),
538 * coursecat::get_children(), etc. return only visible categories so it is
539 * usually not needed to call this function outside of this class
541 * @return bool
543 public function is_uservisible() {
544 return !$this->id || $this->visible ||
545 has_capability('moodle/category:viewhiddencategories', $this->get_context());
549 * Returns all categories visible to the current user
551 * This is a generic function that returns an array of
552 * (category id => coursecat object) sorted by sortorder
554 * @see coursecat::get_children()
555 * @see coursecat::get_all_parents()
557 * @return cacheable_object_array array of coursecat objects
559 public static function get_all_visible() {
560 global $USER;
561 $coursecatcache = cache::make('core', 'coursecat');
562 $ids = $coursecatcache->get('user'. $USER->id);
563 if ($ids === false) {
564 $all = self::get_all_ids();
565 $parentvisible = $all[0];
566 $rv = array();
567 foreach ($all as $id => $children) {
568 if ($id && in_array($id, $parentvisible) &&
569 ($coursecat = self::get($id, IGNORE_MISSING)) &&
570 (!$coursecat->parent || isset($rv[$coursecat->parent]))) {
571 $rv[$id] = $coursecat;
572 $parentvisible += $children;
575 $coursecatcache->set('user'. $USER->id, array_keys($rv));
576 } else {
577 $rv = array();
578 foreach ($ids as $id) {
579 if ($coursecat = self::get($id, IGNORE_MISSING)) {
580 $rv[$id] = $coursecat;
584 return $rv;
588 * Returns the complete corresponding record from DB table course_categories
590 * Mostly used in deprecated functions
592 * @return stdClass
594 public function get_db_record() {
595 global $DB;
596 if ($record = $DB->get_record('course_categories', array('id' => $this->id))) {
597 return $record;
598 } else {
599 return (object)convert_to_array($this);
604 * Returns the entry from categories tree and makes sure the application-level tree cache is built
606 * The following keys can be requested:
608 * 'countall' - total number of categories in the system (always present)
609 * 0 - array of ids of top-level categories (always present)
610 * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
611 * $id (int) - array of ids of categories that are direct children of category with id $id. If
612 * category with id $id does not exist returns false. If category has no children returns empty array
613 * $id.'i' - array of ids of children categories that have visible=0
615 * @param int|string $id
616 * @return mixed
618 protected static function get_tree($id) {
619 global $DB;
620 $coursecattreecache = cache::make('core', 'coursecattree');
621 $rv = $coursecattreecache->get($id);
622 if ($rv !== false) {
623 return $rv;
625 // Re-build the tree.
626 $sql = "SELECT cc.id, cc.parent, cc.visible
627 FROM {course_categories} cc
628 ORDER BY cc.sortorder";
629 $rs = $DB->get_recordset_sql($sql, array());
630 $all = array(0 => array(), '0i' => array());
631 $count = 0;
632 foreach ($rs as $record) {
633 $all[$record->id] = array();
634 $all[$record->id. 'i'] = array();
635 if (array_key_exists($record->parent, $all)) {
636 $all[$record->parent][] = $record->id;
637 if (!$record->visible) {
638 $all[$record->parent. 'i'][] = $record->id;
640 } else {
641 // Parent not found. This is data consistency error but next fix_course_sortorder() should fix it.
642 $all[0][] = $record->id;
643 if (!$record->visible) {
644 $all['0i'][] = $record->id;
647 $count++;
649 $rs->close();
650 if (!$count) {
651 // No categories found.
652 // This may happen after upgrade of a very old moodle version.
653 // In new versions the default category is created on install.
654 $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
655 set_config('defaultrequestcategory', $defcoursecat->id);
656 $all[0] = array($defcoursecat->id);
657 $all[$defcoursecat->id] = array();
658 $count++;
660 // We must add countall to all in case it was the requested ID.
661 $all['countall'] = $count;
662 foreach ($all as $key => $children) {
663 $coursecattreecache->set($key, $children);
665 if (array_key_exists($id, $all)) {
666 return $all[$id];
668 // Requested non-existing category.
669 return array();
673 * Returns number of ALL categories in the system regardless if
674 * they are visible to current user or not
676 * @return int
678 public static function count_all() {
679 return self::get_tree('countall');
683 * Retrieves number of records from course_categories table
685 * Only cached fields are retrieved. Records are ready for preloading context
687 * @param string $whereclause
688 * @param array $params
689 * @return array array of stdClass objects
691 protected static function get_records($whereclause, $params) {
692 global $DB;
693 // Retrieve from DB only the fields that need to be stored in cache.
694 $fields = array_keys(array_filter(self::$coursecatfields));
695 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
696 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
697 FROM {course_categories} cc
698 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
699 WHERE ". $whereclause." ORDER BY cc.sortorder";
700 return $DB->get_records_sql($sql,
701 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
705 * Given list of DB records from table course populates each record with list of users with course contact roles
707 * This function fills the courses with raw information as {@link get_role_users()} would do.
708 * See also {@link course_in_list::get_course_contacts()} for more readable return
710 * $courses[$i]->managers = array(
711 * $roleassignmentid => $roleuser,
712 * ...
713 * );
715 * where $roleuser is an stdClass with the following properties:
717 * $roleuser->raid - role assignment id
718 * $roleuser->id - user id
719 * $roleuser->username
720 * $roleuser->firstname
721 * $roleuser->lastname
722 * $roleuser->rolecoursealias
723 * $roleuser->rolename
724 * $roleuser->sortorder - role sortorder
725 * $roleuser->roleid
726 * $roleuser->roleshortname
728 * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
730 * @param array $courses
732 public static function preload_course_contacts(&$courses) {
733 global $CFG, $DB;
734 if (empty($courses) || empty($CFG->coursecontact)) {
735 return;
737 $managerroles = explode(',', $CFG->coursecontact);
738 $cache = cache::make('core', 'coursecontacts');
739 $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
740 // Check if cache was set for the current course contacts and it is not yet expired.
741 if (empty($cacheddata['basic']) || $cacheddata['basic']['roles'] !== $CFG->coursecontact ||
742 $cacheddata['basic']['lastreset'] < time() - self::CACHE_COURSE_CONTACTS_TTL) {
743 // Reset cache.
744 $cache->purge();
745 $cache->set('basic', array('roles' => $CFG->coursecontact, 'lastreset' => time()));
746 $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
748 $courseids = array();
749 foreach (array_keys($courses) as $id) {
750 if ($cacheddata[$id] !== false) {
751 $courses[$id]->managers = $cacheddata[$id];
752 } else {
753 $courseids[] = $id;
757 // Array $courseids now stores list of ids of courses for which we still need to retrieve contacts.
758 if (empty($courseids)) {
759 return;
762 // First build the array of all context ids of the courses and their categories.
763 $allcontexts = array();
764 foreach ($courseids as $id) {
765 $context = context_course::instance($id);
766 $courses[$id]->managers = array();
767 foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
768 if (!isset($allcontexts[$ctxid])) {
769 $allcontexts[$ctxid] = array();
771 $allcontexts[$ctxid][] = $id;
775 // Fetch list of all users with course contact roles in any of the courses contexts or parent contexts.
776 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
777 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
778 list($sort, $sortparams) = users_order_by_sql('u');
779 $notdeleted = array('notdeleted'=>0);
780 $allnames = get_all_user_name_fields(true, 'u');
781 $sql = "SELECT ra.contextid, ra.id AS raid,
782 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
783 rn.name AS rolecoursealias, u.id, u.username, $allnames
784 FROM {role_assignments} ra
785 JOIN {user} u ON ra.userid = u.id
786 JOIN {role} r ON ra.roleid = r.id
787 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
788 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
789 ORDER BY r.sortorder, $sort";
790 $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
791 $checkenrolments = array();
792 foreach ($rs as $ra) {
793 foreach ($allcontexts[$ra->contextid] as $id) {
794 $courses[$id]->managers[$ra->raid] = $ra;
795 if (!isset($checkenrolments[$id])) {
796 $checkenrolments[$id] = array();
798 $checkenrolments[$id][] = $ra->id;
801 $rs->close();
803 // Remove from course contacts users who are not enrolled in the course.
804 $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
805 foreach ($checkenrolments as $id => $userids) {
806 if (empty($enrolleduserids[$id])) {
807 $courses[$id]->managers = array();
808 } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
809 foreach ($courses[$id]->managers as $raid => $ra) {
810 if (in_array($ra->id, $notenrolled)) {
811 unset($courses[$id]->managers[$raid]);
817 // Set the cache.
818 $values = array();
819 foreach ($courseids as $id) {
820 $values[$id] = $courses[$id]->managers;
822 $cache->set_many($values);
826 * Verify user enrollments for multiple course-user combinations
828 * @param array $courseusers array where keys are course ids and values are array
829 * of users in this course whose enrolment we wish to verify
830 * @return array same structure as input array but values list only users from input
831 * who are enrolled in the course
833 protected static function ensure_users_enrolled($courseusers) {
834 global $DB;
835 // If the input array is too big, split it into chunks.
836 $maxcoursesinquery = 20;
837 if (count($courseusers) > $maxcoursesinquery) {
838 $rv = array();
839 for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
840 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
841 $rv = $rv + self::ensure_users_enrolled($chunk);
843 return $rv;
846 // Create a query verifying valid user enrolments for the number of courses.
847 $sql = "SELECT DISTINCT e.courseid, ue.userid
848 FROM {user_enrolments} ue
849 JOIN {enrol} e ON e.id = ue.enrolid
850 WHERE ue.status = :active
851 AND e.status = :enabled
852 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
853 $now = round(time(), -2); // Rounding helps caching in DB.
854 $params = array('enabled' => ENROL_INSTANCE_ENABLED,
855 'active' => ENROL_USER_ACTIVE,
856 'now1' => $now, 'now2' => $now);
857 $cnt = 0;
858 $subsqls = array();
859 $enrolled = array();
860 foreach ($courseusers as $id => $userids) {
861 $enrolled[$id] = array();
862 if (count($userids)) {
863 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
864 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
865 $params = $params + array('courseid'.$cnt => $id) + $params2;
866 $cnt++;
869 if (count($subsqls)) {
870 $sql .= "AND (". join(' OR ', $subsqls).")";
871 $rs = $DB->get_recordset_sql($sql, $params);
872 foreach ($rs as $record) {
873 $enrolled[$record->courseid][] = $record->userid;
875 $rs->close();
877 return $enrolled;
881 * Retrieves number of records from course table
883 * Not all fields are retrieved. Records are ready for preloading context
885 * @param string $whereclause
886 * @param array $params
887 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
888 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
889 * on not visible courses
890 * @return array array of stdClass objects
892 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
893 global $DB;
894 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
895 $fields = array('c.id', 'c.category', 'c.sortorder',
896 'c.shortname', 'c.fullname', 'c.idnumber',
897 'c.startdate', 'c.visible', 'c.cacherev');
898 if (!empty($options['summary'])) {
899 $fields[] = 'c.summary';
900 $fields[] = 'c.summaryformat';
901 } else {
902 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
904 $sql = "SELECT ". join(',', $fields). ", $ctxselect
905 FROM {course} c
906 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
907 WHERE ". $whereclause." ORDER BY c.sortorder";
908 $list = $DB->get_records_sql($sql,
909 array('contextcourse' => CONTEXT_COURSE) + $params);
911 if ($checkvisibility) {
912 // Loop through all records and make sure we only return the courses accessible by user.
913 foreach ($list as $course) {
914 if (isset($list[$course->id]->hassummary)) {
915 $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
917 if (empty($course->visible)) {
918 // Load context only if we need to check capability.
919 context_helper::preload_from_record($course);
920 if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
921 unset($list[$course->id]);
927 // Preload course contacts if necessary.
928 if (!empty($options['coursecontacts'])) {
929 self::preload_course_contacts($list);
931 return $list;
935 * Returns array of ids of children categories that current user can not see
937 * This data is cached in user session cache
939 * @return array
941 protected function get_not_visible_children_ids() {
942 global $DB;
943 $coursecatcache = cache::make('core', 'coursecat');
944 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
945 // We never checked visible children before.
946 $hidden = self::get_tree($this->id.'i');
947 $invisibleids = array();
948 if ($hidden) {
949 // Preload categories contexts.
950 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
951 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
952 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
953 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
954 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
955 foreach ($contexts as $record) {
956 context_helper::preload_from_record($record);
958 // Check that user has 'viewhiddencategories' capability for each hidden category.
959 foreach ($hidden as $id) {
960 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
961 $invisibleids[] = $id;
965 $coursecatcache->set('ic'. $this->id, $invisibleids);
967 return $invisibleids;
971 * Sorts list of records by several fields
973 * @param array $records array of stdClass objects
974 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
975 * @return int
977 protected static function sort_records(&$records, $sortfields) {
978 if (empty($records)) {
979 return;
981 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname).
982 if (array_key_exists('displayname', $sortfields)) {
983 foreach ($records as $key => $record) {
984 if (!isset($record->displayname)) {
985 $records[$key]->displayname = get_course_display_name_for_list($record);
989 // Sorting by one field - use core_collator.
990 if (count($sortfields) == 1) {
991 $property = key($sortfields);
992 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
993 $sortflag = core_collator::SORT_NUMERIC;
994 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
995 $sortflag = core_collator::SORT_STRING;
996 } else {
997 $sortflag = core_collator::SORT_REGULAR;
999 core_collator::asort_objects_by_property($records, $property, $sortflag);
1000 if ($sortfields[$property] < 0) {
1001 $records = array_reverse($records, true);
1003 return;
1005 $records = coursecat_sortable_records::sort($records, $sortfields);
1009 * Returns array of children categories visible to the current user
1011 * @param array $options options for retrieving children
1012 * - sort - list of fields to sort. Example
1013 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
1014 * will sort by idnumber asc, name asc and id desc.
1015 * Default: array('sortorder' => 1)
1016 * Only cached fields may be used for sorting!
1017 * - offset
1018 * - limit - maximum number of children to return, 0 or null for no limit
1019 * @return coursecat[] Array of coursecat objects indexed by category id
1021 public function get_children($options = array()) {
1022 global $DB;
1023 $coursecatcache = cache::make('core', 'coursecat');
1025 // Get default values for options.
1026 if (!empty($options['sort']) && is_array($options['sort'])) {
1027 $sortfields = $options['sort'];
1028 } else {
1029 $sortfields = array('sortorder' => 1);
1031 $limit = null;
1032 if (!empty($options['limit']) && (int)$options['limit']) {
1033 $limit = (int)$options['limit'];
1035 $offset = 0;
1036 if (!empty($options['offset']) && (int)$options['offset']) {
1037 $offset = (int)$options['offset'];
1040 // First retrieve list of user-visible and sorted children ids from cache.
1041 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
1042 if ($sortedids === false) {
1043 $sortfieldskeys = array_keys($sortfields);
1044 if ($sortfieldskeys[0] === 'sortorder') {
1045 // No DB requests required to build the list of ids sorted by sortorder.
1046 // We can easily ignore other sort fields because sortorder is always different.
1047 $sortedids = self::get_tree($this->id);
1048 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
1049 $sortedids = array_diff($sortedids, $invisibleids);
1050 if ($sortfields['sortorder'] == -1) {
1051 $sortedids = array_reverse($sortedids, true);
1054 } else {
1055 // We need to retrieve and sort all children. Good thing that it is done only on first request.
1056 if ($invisibleids = $this->get_not_visible_children_ids()) {
1057 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
1058 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
1059 array('parent' => $this->id) + $params);
1060 } else {
1061 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
1063 self::sort_records($records, $sortfields);
1064 $sortedids = array_keys($records);
1066 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
1069 if (empty($sortedids)) {
1070 return array();
1073 // Now retrieive and return categories.
1074 if ($offset || $limit) {
1075 $sortedids = array_slice($sortedids, $offset, $limit);
1077 if (isset($records)) {
1078 // Easy, we have already retrieved records.
1079 if ($offset || $limit) {
1080 $records = array_slice($records, $offset, $limit, true);
1082 } else {
1083 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
1084 $records = self::get_records('cc.id '. $sql, array('parent' => $this->id) + $params);
1087 $rv = array();
1088 foreach ($sortedids as $id) {
1089 if (isset($records[$id])) {
1090 $rv[$id] = new coursecat($records[$id]);
1093 return $rv;
1097 * Returns true if the user has the manage capability on any category.
1099 * This method uses the coursecat cache and an entry `has_manage_capability` to speed up
1100 * calls to this method.
1102 * @return bool
1104 public static function has_manage_capability_on_any() {
1105 return self::has_capability_on_any('moodle/category:manage');
1109 * Checks if the user has at least one of the given capabilities on any category.
1111 * @param array|string $capabilities One or more capabilities to check. Check made is an OR.
1112 * @return bool
1114 public static function has_capability_on_any($capabilities) {
1115 global $DB;
1116 if (!isloggedin() || isguestuser()) {
1117 return false;
1120 if (!is_array($capabilities)) {
1121 $capabilities = array($capabilities);
1123 $keys = array();
1124 foreach ($capabilities as $capability) {
1125 $keys[$capability] = sha1($capability);
1128 /* @var cache_session $cache */
1129 $cache = cache::make('core', 'coursecat');
1130 $hascapability = $cache->get_many($keys);
1131 $needtoload = false;
1132 foreach ($hascapability as $capability) {
1133 if ($capability === '1') {
1134 return true;
1135 } else if ($capability === false) {
1136 $needtoload = true;
1139 if ($needtoload === false) {
1140 // All capabilities were retrieved and the user didn't have any.
1141 return false;
1144 $haskey = null;
1145 $fields = context_helper::get_preload_record_columns_sql('ctx');
1146 $sql = "SELECT ctx.instanceid AS categoryid, $fields
1147 FROM {context} ctx
1148 WHERE contextlevel = :contextlevel
1149 ORDER BY depth ASC";
1150 $params = array('contextlevel' => CONTEXT_COURSECAT);
1151 $recordset = $DB->get_recordset_sql($sql, $params);
1152 foreach ($recordset as $context) {
1153 context_helper::preload_from_record($context);
1154 $context = context_coursecat::instance($context->categoryid);
1155 foreach ($capabilities as $capability) {
1156 if (has_capability($capability, $context)) {
1157 $haskey = $capability;
1158 break 2;
1162 $recordset->close();
1163 if ($haskey === null) {
1164 $data = array();
1165 foreach ($keys as $key) {
1166 $data[$key] = '0';
1168 $cache->set_many($data);
1169 return false;
1170 } else {
1171 $cache->set($haskey, '1');
1172 return true;
1177 * Returns true if the user can resort any category.
1178 * @return bool
1180 public static function can_resort_any() {
1181 return self::has_manage_capability_on_any();
1185 * Returns true if the user can change the parent of any category.
1186 * @return bool
1188 public static function can_change_parent_any() {
1189 return self::has_manage_capability_on_any();
1193 * Returns number of subcategories visible to the current user
1195 * @return int
1197 public function get_children_count() {
1198 $sortedids = self::get_tree($this->id);
1199 $invisibleids = $this->get_not_visible_children_ids();
1200 return count($sortedids) - count($invisibleids);
1204 * Returns true if the category has ANY children, including those not visible to the user
1206 * @return boolean
1208 public function has_children() {
1209 $allchildren = self::get_tree($this->id);
1210 return !empty($allchildren);
1214 * Returns true if the category has courses in it (count does not include courses
1215 * in child categories)
1217 * @return bool
1219 public function has_courses() {
1220 global $DB;
1221 return $DB->record_exists_sql("select 1 from {course} where category = ?",
1222 array($this->id));
1226 * Searches courses
1228 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1229 * to this when somebody edits courses or categories, however it is very
1230 * difficult to keep track of all possible changes that may affect list of courses.
1232 * @param array $search contains search criterias, such as:
1233 * - search - search string
1234 * - blocklist - id of block (if we are searching for courses containing specific block0
1235 * - modulelist - name of module (if we are searching for courses containing specific module
1236 * - tagid - id of tag
1237 * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
1238 * search is always category-independent
1239 * @return course_in_list[]
1241 public static function search_courses($search, $options = array()) {
1242 global $DB;
1243 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1244 $limit = !empty($options['limit']) ? $options['limit'] : null;
1245 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1247 $coursecatcache = cache::make('core', 'coursecat');
1248 $cachekey = 's-'. serialize($search + array('sort' => $sortfields));
1249 $cntcachekey = 'scnt-'. serialize($search);
1251 $ids = $coursecatcache->get($cachekey);
1252 if ($ids !== false) {
1253 // We already cached last search result.
1254 $ids = array_slice($ids, $offset, $limit);
1255 $courses = array();
1256 if (!empty($ids)) {
1257 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1258 $records = self::get_course_records("c.id ". $sql, $params, $options);
1259 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1260 if (!empty($options['coursecontacts'])) {
1261 self::preload_course_contacts($records);
1263 // If option 'idonly' is specified no further action is needed, just return list of ids.
1264 if (!empty($options['idonly'])) {
1265 return array_keys($records);
1267 // Prepare the list of course_in_list objects.
1268 foreach ($ids as $id) {
1269 $courses[$id] = new course_in_list($records[$id]);
1272 return $courses;
1275 $preloadcoursecontacts = !empty($options['coursecontacts']);
1276 unset($options['coursecontacts']);
1278 if (!empty($search['search'])) {
1279 // Search courses that have specified words in their names/summaries.
1280 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1281 $searchterms = array_filter($searchterms, create_function('$v', 'return strlen($v) > 1;'));
1282 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount);
1283 self::sort_records($courselist, $sortfields);
1284 $coursecatcache->set($cachekey, array_keys($courselist));
1285 $coursecatcache->set($cntcachekey, $totalcount);
1286 $records = array_slice($courselist, $offset, $limit, true);
1287 } else {
1288 if (!empty($search['blocklist'])) {
1289 // Search courses that have block with specified id.
1290 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1291 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1292 WHERE bi.blockname = :blockname)';
1293 $params = array('blockname' => $blockname);
1294 } else if (!empty($search['modulelist'])) {
1295 // Search courses that have module with specified name.
1296 $where = "c.id IN (SELECT DISTINCT module.course ".
1297 "FROM {".$search['modulelist']."} module)";
1298 $params = array();
1299 } else if (!empty($search['tagid'])) {
1300 // Search courses that are tagged with the specified tag.
1301 $where = "c.id IN (SELECT t.itemid ".
1302 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype)";
1303 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course');
1304 } else {
1305 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1306 return array();
1308 $courselist = self::get_course_records($where, $params, $options, true);
1309 self::sort_records($courselist, $sortfields);
1310 $coursecatcache->set($cachekey, array_keys($courselist));
1311 $coursecatcache->set($cntcachekey, count($courselist));
1312 $records = array_slice($courselist, $offset, $limit, true);
1315 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1316 if (!empty($preloadcoursecontacts)) {
1317 self::preload_course_contacts($records);
1319 // If option 'idonly' is specified no further action is needed, just return list of ids.
1320 if (!empty($options['idonly'])) {
1321 return array_keys($records);
1323 // Prepare the list of course_in_list objects.
1324 $courses = array();
1325 foreach ($records as $record) {
1326 $courses[$record->id] = new course_in_list($record);
1328 return $courses;
1332 * Returns number of courses in the search results
1334 * It is recommended to call this function after {@link coursecat::search_courses()}
1335 * and not before because only course ids are cached. Otherwise search_courses() may
1336 * perform extra DB queries.
1338 * @param array $search search criteria, see method search_courses() for more details
1339 * @param array $options display options. They do not affect the result but
1340 * the 'sort' property is used in cache key for storing list of course ids
1341 * @return int
1343 public static function search_courses_count($search, $options = array()) {
1344 $coursecatcache = cache::make('core', 'coursecat');
1345 $cntcachekey = 'scnt-'. serialize($search);
1346 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1347 // Cached value not found. Retrieve ALL courses and return their count.
1348 unset($options['offset']);
1349 unset($options['limit']);
1350 unset($options['summary']);
1351 unset($options['coursecontacts']);
1352 $options['idonly'] = true;
1353 $courses = self::search_courses($search, $options);
1354 $cnt = count($courses);
1356 return $cnt;
1360 * Retrieves the list of courses accessible by user
1362 * Not all information is cached, try to avoid calling this method
1363 * twice in the same request.
1365 * The following fields are always retrieved:
1366 * - id, visible, fullname, shortname, idnumber, category, sortorder
1368 * If you plan to use properties/methods course_in_list::$summary and/or
1369 * course_in_list::get_course_contacts()
1370 * you can preload this information using appropriate 'options'. Otherwise
1371 * they will be retrieved from DB on demand and it may end with bigger DB load.
1373 * Note that method course_in_list::has_summary() will not perform additional
1374 * DB queries even if $options['summary'] is not specified
1376 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1377 * to this when somebody edits courses or categories, however it is very
1378 * difficult to keep track of all possible changes that may affect list of courses.
1380 * @param array $options options for retrieving children
1381 * - recursive - return courses from subcategories as well. Use with care,
1382 * this may be a huge list!
1383 * - summary - preloads fields 'summary' and 'summaryformat'
1384 * - coursecontacts - preloads course contacts
1385 * - sort - list of fields to sort. Example
1386 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1387 * will sort by idnumber asc, shortname asc and id desc.
1388 * Default: array('sortorder' => 1)
1389 * Only cached fields may be used for sorting!
1390 * - offset
1391 * - limit - maximum number of children to return, 0 or null for no limit
1392 * - idonly - returns the array or course ids instead of array of objects
1393 * used only in get_courses_count()
1394 * @return course_in_list[]
1396 public function get_courses($options = array()) {
1397 global $DB;
1398 $recursive = !empty($options['recursive']);
1399 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1400 $limit = !empty($options['limit']) ? $options['limit'] : null;
1401 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1403 // Check if this category is hidden.
1404 // Also 0-category never has courses unless this is recursive call.
1405 if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1406 return array();
1409 $coursecatcache = cache::make('core', 'coursecat');
1410 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1411 '-'. serialize($sortfields);
1412 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1414 // Check if we have already cached results.
1415 $ids = $coursecatcache->get($cachekey);
1416 if ($ids !== false) {
1417 // We already cached last search result and it did not expire yet.
1418 $ids = array_slice($ids, $offset, $limit);
1419 $courses = array();
1420 if (!empty($ids)) {
1421 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1422 $records = self::get_course_records("c.id ". $sql, $params, $options);
1423 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1424 if (!empty($options['coursecontacts'])) {
1425 self::preload_course_contacts($records);
1427 // If option 'idonly' is specified no further action is needed, just return list of ids.
1428 if (!empty($options['idonly'])) {
1429 return array_keys($records);
1431 // Prepare the list of course_in_list objects.
1432 foreach ($ids as $id) {
1433 $courses[$id] = new course_in_list($records[$id]);
1436 return $courses;
1439 // Retrieve list of courses in category.
1440 $where = 'c.id <> :siteid';
1441 $params = array('siteid' => SITEID);
1442 if ($recursive) {
1443 if ($this->id) {
1444 $context = context_coursecat::instance($this->id);
1445 $where .= ' AND ctx.path like :path';
1446 $params['path'] = $context->path. '/%';
1448 } else {
1449 $where .= ' AND c.category = :categoryid';
1450 $params['categoryid'] = $this->id;
1452 // Get list of courses without preloaded coursecontacts because we don't need them for every course.
1453 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1455 // Sort and cache list.
1456 self::sort_records($list, $sortfields);
1457 $coursecatcache->set($cachekey, array_keys($list));
1458 $coursecatcache->set($cntcachekey, count($list));
1460 // Apply offset/limit, convert to course_in_list and return.
1461 $courses = array();
1462 if (isset($list)) {
1463 if ($offset || $limit) {
1464 $list = array_slice($list, $offset, $limit, true);
1466 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1467 if (!empty($options['coursecontacts'])) {
1468 self::preload_course_contacts($list);
1470 // If option 'idonly' is specified no further action is needed, just return list of ids.
1471 if (!empty($options['idonly'])) {
1472 return array_keys($list);
1474 // Prepare the list of course_in_list objects.
1475 foreach ($list as $record) {
1476 $courses[$record->id] = new course_in_list($record);
1479 return $courses;
1483 * Returns number of courses visible to the user
1485 * @param array $options similar to get_courses() except some options do not affect
1486 * number of courses (i.e. sort, summary, offset, limit etc.)
1487 * @return int
1489 public function get_courses_count($options = array()) {
1490 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1491 $coursecatcache = cache::make('core', 'coursecat');
1492 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1493 // Cached value not found. Retrieve ALL courses and return their count.
1494 unset($options['offset']);
1495 unset($options['limit']);
1496 unset($options['summary']);
1497 unset($options['coursecontacts']);
1498 $options['idonly'] = true;
1499 $courses = $this->get_courses($options);
1500 $cnt = count($courses);
1502 return $cnt;
1506 * Returns true if the user is able to delete this category.
1508 * Note if this category contains any courses this isn't a full check, it will need to be accompanied by a call to either
1509 * {@link coursecat::can_delete_full()} or {@link coursecat::can_move_content_to()} depending upon what the user wished to do.
1511 * @return boolean
1513 public function can_delete() {
1514 if (!$this->has_manage_capability()) {
1515 return false;
1517 return $this->parent_has_manage_capability();
1521 * Returns true if user can delete current category and all its contents
1523 * To be able to delete course category the user must have permission
1524 * 'moodle/category:manage' in ALL child course categories AND
1525 * be able to delete all courses
1527 * @return bool
1529 public function can_delete_full() {
1530 global $DB;
1531 if (!$this->id) {
1532 // Fool-proof.
1533 return false;
1536 $context = $this->get_context();
1537 if (!$this->is_uservisible() ||
1538 !has_capability('moodle/category:manage', $context)) {
1539 return false;
1542 // Check all child categories (not only direct children).
1543 $sql = context_helper::get_preload_record_columns_sql('ctx');
1544 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1545 ' FROM {context} ctx '.
1546 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1547 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1548 array($context->path. '/%', CONTEXT_COURSECAT));
1549 foreach ($childcategories as $childcat) {
1550 context_helper::preload_from_record($childcat);
1551 $childcontext = context_coursecat::instance($childcat->id);
1552 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1553 !has_capability('moodle/category:manage', $childcontext)) {
1554 return false;
1558 // Check courses.
1559 $sql = context_helper::get_preload_record_columns_sql('ctx');
1560 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1561 $sql. ' FROM {context} ctx '.
1562 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1563 array('pathmask' => $context->path. '/%',
1564 'courselevel' => CONTEXT_COURSE));
1565 foreach ($coursescontexts as $ctxrecord) {
1566 context_helper::preload_from_record($ctxrecord);
1567 if (!can_delete_course($ctxrecord->courseid)) {
1568 return false;
1572 return true;
1576 * Recursively delete category including all subcategories and courses
1578 * Function {@link coursecat::can_delete_full()} MUST be called prior
1579 * to calling this function because there is no capability check
1580 * inside this function
1582 * @param boolean $showfeedback display some notices
1583 * @return array return deleted courses
1584 * @throws moodle_exception
1586 public function delete_full($showfeedback = true) {
1587 global $CFG, $DB;
1589 require_once($CFG->libdir.'/gradelib.php');
1590 require_once($CFG->libdir.'/questionlib.php');
1591 require_once($CFG->dirroot.'/cohort/lib.php');
1593 $deletedcourses = array();
1595 // Get children. Note, we don't want to use cache here because it would be rebuilt too often.
1596 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1597 foreach ($children as $record) {
1598 $coursecat = new coursecat($record);
1599 $deletedcourses += $coursecat->delete_full($showfeedback);
1602 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1603 foreach ($courses as $course) {
1604 if (!delete_course($course, false)) {
1605 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1607 $deletedcourses[] = $course;
1611 // Move or delete cohorts in this context.
1612 cohort_delete_category($this);
1614 // Now delete anything that may depend on course category context.
1615 grade_course_category_delete($this->id, 0, $showfeedback);
1616 if (!question_delete_course_category($this, 0, $showfeedback)) {
1617 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1620 // Finally delete the category and it's context.
1621 $DB->delete_records('course_categories', array('id' => $this->id));
1623 $coursecatcontext = context_coursecat::instance($this->id);
1624 $coursecatcontext->delete();
1626 cache_helper::purge_by_event('changesincoursecat');
1628 // Trigger a course category deleted event.
1629 /* @var \core\event\course_category_deleted $event */
1630 $event = \core\event\course_category_deleted::create(array(
1631 'objectid' => $this->id,
1632 'context' => $coursecatcontext,
1633 'other' => array('name' => $this->name)
1635 $event->set_legacy_eventdata($this);
1636 $event->trigger();
1638 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1639 if ($this->id == $CFG->defaultrequestcategory) {
1640 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1642 return $deletedcourses;
1646 * Checks if user can delete this category and move content (courses, subcategories and questions)
1647 * to another category. If yes returns the array of possible target categories names
1649 * If user can not manage this category or it is completely empty - empty array will be returned
1651 * @return array
1653 public function move_content_targets_list() {
1654 global $CFG;
1655 require_once($CFG->libdir . '/questionlib.php');
1656 $context = $this->get_context();
1657 if (!$this->is_uservisible() ||
1658 !has_capability('moodle/category:manage', $context)) {
1659 // User is not able to manage current category, he is not able to delete it.
1660 // No possible target categories.
1661 return array();
1664 $testcaps = array();
1665 // If this category has courses in it, user must have 'course:create' capability in target category.
1666 if ($this->has_courses()) {
1667 $testcaps[] = 'moodle/course:create';
1669 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1670 if ($this->has_children() || question_context_has_any_questions($context)) {
1671 $testcaps[] = 'moodle/category:manage';
1673 if (!empty($testcaps)) {
1674 // Return list of categories excluding this one and it's children.
1675 return self::make_categories_list($testcaps, $this->id);
1678 // Category is completely empty, no need in target for contents.
1679 return array();
1683 * Checks if user has capability to move all category content to the new parent before
1684 * removing this category
1686 * @param int $newcatid
1687 * @return bool
1689 public function can_move_content_to($newcatid) {
1690 global $CFG;
1691 require_once($CFG->libdir . '/questionlib.php');
1692 $context = $this->get_context();
1693 if (!$this->is_uservisible() ||
1694 !has_capability('moodle/category:manage', $context)) {
1695 return false;
1697 $testcaps = array();
1698 // If this category has courses in it, user must have 'course:create' capability in target category.
1699 if ($this->has_courses()) {
1700 $testcaps[] = 'moodle/course:create';
1702 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1703 if ($this->has_children() || question_context_has_any_questions($context)) {
1704 $testcaps[] = 'moodle/category:manage';
1706 if (!empty($testcaps)) {
1707 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1710 // There is no content but still return true.
1711 return true;
1715 * Deletes a category and moves all content (children, courses and questions) to the new parent
1717 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1718 * must be called prior
1720 * @param int $newparentid
1721 * @param bool $showfeedback
1722 * @return bool
1724 public function delete_move($newparentid, $showfeedback = false) {
1725 global $CFG, $DB, $OUTPUT;
1727 require_once($CFG->libdir.'/gradelib.php');
1728 require_once($CFG->libdir.'/questionlib.php');
1729 require_once($CFG->dirroot.'/cohort/lib.php');
1731 // Get all objects and lists because later the caches will be reset so.
1732 // We don't need to make extra queries.
1733 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1734 $catname = $this->get_formatted_name();
1735 $children = $this->get_children();
1736 $params = array('category' => $this->id);
1737 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', $params);
1738 $context = $this->get_context();
1740 if ($children) {
1741 foreach ($children as $childcat) {
1742 $childcat->change_parent_raw($newparentcat);
1743 // Log action.
1744 add_to_log(SITEID, "category", "move", "editcategory.php?id=$childcat->id", $childcat->id);
1746 fix_course_sortorder();
1749 if ($coursesids) {
1750 if (!move_courses($coursesids, $newparentid)) {
1751 if ($showfeedback) {
1752 echo $OUTPUT->notification("Error moving courses");
1754 return false;
1756 if ($showfeedback) {
1757 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1761 // Move or delete cohorts in this context.
1762 cohort_delete_category($this);
1764 // Now delete anything that may depend on course category context.
1765 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1766 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1767 if ($showfeedback) {
1768 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1770 return false;
1773 // Finally delete the category and it's context.
1774 $DB->delete_records('course_categories', array('id' => $this->id));
1775 $context->delete();
1777 // Trigger a course category deleted event.
1778 /* @var \core\event\course_category_deleted $event */
1779 $event = \core\event\course_category_deleted::create(array(
1780 'objectid' => $this->id,
1781 'context' => $context,
1782 'other' => array('name' => $this->name)
1784 $event->set_legacy_eventdata($this);
1785 $event->trigger();
1787 cache_helper::purge_by_event('changesincoursecat');
1789 if ($showfeedback) {
1790 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1793 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1794 if ($this->id == $CFG->defaultrequestcategory) {
1795 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1797 return true;
1801 * Checks if user can move current category to the new parent
1803 * This checks if new parent category exists, user has manage cap there
1804 * and new parent is not a child of this category
1806 * @param int|stdClass|coursecat $newparentcat
1807 * @return bool
1809 public function can_change_parent($newparentcat) {
1810 if (!has_capability('moodle/category:manage', $this->get_context())) {
1811 return false;
1813 if (is_object($newparentcat)) {
1814 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1815 } else {
1816 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1818 if (!$newparentcat) {
1819 return false;
1821 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1822 // Can not move to itself or it's own child.
1823 return false;
1825 if ($newparentcat->id) {
1826 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
1827 } else {
1828 return has_capability('moodle/category:manage', context_system::instance());
1833 * Moves the category under another parent category. All associated contexts are moved as well
1835 * This is protected function, use change_parent() or update() from outside of this class
1837 * @see coursecat::change_parent()
1838 * @see coursecat::update()
1840 * @param coursecat $newparentcat
1841 * @throws moodle_exception
1843 protected function change_parent_raw(coursecat $newparentcat) {
1844 global $DB;
1846 $context = $this->get_context();
1848 $hidecat = false;
1849 if (empty($newparentcat->id)) {
1850 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1851 $newparent = context_system::instance();
1852 } else {
1853 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1854 // Can not move to itself or it's own child.
1855 throw new moodle_exception('cannotmovecategory');
1857 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
1858 $newparent = context_coursecat::instance($newparentcat->id);
1860 if (!$newparentcat->visible and $this->visible) {
1861 // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children
1862 // will be restored properly.
1863 $hidecat = true;
1866 $this->parent = $newparentcat->id;
1868 $context->update_moved($newparent);
1870 // Now make it last in new category.
1871 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
1873 if ($hidecat) {
1874 fix_course_sortorder();
1875 $this->restore();
1876 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must
1877 // become visible again.
1878 $this->hide_raw(1);
1883 * Efficiently moves a category - NOTE that this can have
1884 * a huge impact access-control-wise...
1886 * Note that this function does not check capabilities.
1888 * Example of usage:
1889 * $coursecat = coursecat::get($categoryid);
1890 * if ($coursecat->can_change_parent($newparentcatid)) {
1891 * $coursecat->change_parent($newparentcatid);
1894 * This function does not update field course_categories.timemodified
1895 * If you want to update timemodified, use
1896 * $coursecat->update(array('parent' => $newparentcat));
1898 * @param int|stdClass|coursecat $newparentcat
1900 public function change_parent($newparentcat) {
1901 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1902 if (is_object($newparentcat)) {
1903 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
1904 } else {
1905 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
1907 if ($newparentcat->id != $this->parent) {
1908 $this->change_parent_raw($newparentcat);
1909 fix_course_sortorder();
1910 cache_helper::purge_by_event('changesincoursecat');
1911 $this->restore();
1912 add_to_log(SITEID, "category", "move", "editcategory.php?id=$this->id", $this->id);
1917 * Hide course category and child course and subcategories
1919 * If this category has changed the parent and is moved under hidden
1920 * category we will want to store it's current visibility state in
1921 * the field 'visibleold'. If admin clicked 'hide' for this particular
1922 * category, the field 'visibleold' should become 0.
1924 * All subcategories and courses will have their current visibility in the field visibleold
1926 * This is protected function, use hide() or update() from outside of this class
1928 * @see coursecat::hide()
1929 * @see coursecat::update()
1931 * @param int $visibleold value to set in field $visibleold for this category
1932 * @return bool whether changes have been made and caches need to be purged afterwards
1934 protected function hide_raw($visibleold = 0) {
1935 global $DB;
1936 $changes = false;
1938 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing.
1939 if ($this->id && $this->__get('visibleold') != $visibleold) {
1940 $this->visibleold = $visibleold;
1941 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
1942 $changes = true;
1944 if (!$this->visible || !$this->id) {
1945 // Already hidden or can not be hidden.
1946 return $changes;
1949 $this->visible = 0;
1950 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
1951 // Store visible flag so that we can return to it if we immediately unhide.
1952 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id));
1953 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
1954 // Get all child categories and hide too.
1955 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
1956 foreach ($subcats as $cat) {
1957 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
1958 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
1959 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
1960 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
1963 return true;
1967 * Hide course category and child course and subcategories
1969 * Note that there is no capability check inside this function
1971 * This function does not update field course_categories.timemodified
1972 * If you want to update timemodified, use
1973 * $coursecat->update(array('visible' => 0));
1975 public function hide() {
1976 if ($this->hide_raw(0)) {
1977 cache_helper::purge_by_event('changesincoursecat');
1978 add_to_log(SITEID, "category", "hide", "editcategory.php?id=$this->id", $this->id);
1983 * Show course category and restores visibility for child course and subcategories
1985 * Note that there is no capability check inside this function
1987 * This is protected function, use show() or update() from outside of this class
1989 * @see coursecat::show()
1990 * @see coursecat::update()
1992 * @return bool whether changes have been made and caches need to be purged afterwards
1994 protected function show_raw() {
1995 global $DB;
1997 if ($this->visible) {
1998 // Already visible.
1999 return false;
2002 $this->visible = 1;
2003 $this->visibleold = 1;
2004 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
2005 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
2006 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
2007 // Get all child categories and unhide too.
2008 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
2009 foreach ($subcats as $cat) {
2010 if ($cat->visibleold) {
2011 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
2013 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
2016 return true;
2020 * Show course category and restores visibility for child course and subcategories
2022 * Note that there is no capability check inside this function
2024 * This function does not update field course_categories.timemodified
2025 * If you want to update timemodified, use
2026 * $coursecat->update(array('visible' => 1));
2028 public function show() {
2029 if ($this->show_raw()) {
2030 cache_helper::purge_by_event('changesincoursecat');
2031 add_to_log(SITEID, "category", "show", "editcategory.php?id=$this->id", $this->id);
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 ''; // TODO '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 $basecachekey = 'catlist';
2116 $baselist = $coursecatcache->get($basecachekey);
2117 $thislist = false;
2118 $thiscachekey = null;
2119 if (!empty($requiredcapability)) {
2120 $requiredcapability = (array)$requiredcapability;
2121 $thiscachekey = 'catlist:'. serialize($requiredcapability);
2122 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
2123 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
2125 } else if ($baselist !== false) {
2126 $thislist = array_keys($baselist);
2129 if ($baselist === false) {
2130 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
2131 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2132 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
2133 FROM {course_categories} cc
2134 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
2135 ORDER BY cc.sortorder";
2136 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2137 $baselist = array();
2138 $thislist = array();
2139 foreach ($rs as $record) {
2140 // If the category's parent is not visible to the user, it is not visible as well.
2141 if (!$record->parent || isset($baselist[$record->parent])) {
2142 context_helper::preload_from_record($record);
2143 $context = context_coursecat::instance($record->id);
2144 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
2145 // No cap to view category, added to neither $baselist nor $thislist.
2146 continue;
2148 $baselist[$record->id] = array(
2149 'name' => format_string($record->name, true, array('context' => $context)),
2150 'path' => $record->path
2152 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
2153 // No required capability, added to $baselist but not to $thislist.
2154 continue;
2156 $thislist[] = $record->id;
2159 $rs->close();
2160 $coursecatcache->set($basecachekey, $baselist);
2161 if (!empty($requiredcapability)) {
2162 $coursecatcache->set($thiscachekey, join(',', $thislist));
2164 } else if ($thislist === false) {
2165 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
2166 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2167 $sql = "SELECT ctx.instanceid AS id, $ctxselect
2168 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
2169 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2170 $thislist = array();
2171 foreach (array_keys($baselist) as $id) {
2172 context_helper::preload_from_record($contexts[$id]);
2173 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
2174 $thislist[] = $id;
2177 $coursecatcache->set($thiscachekey, join(',', $thislist));
2180 // Now build the array of strings to return, mind $separator and $excludeid.
2181 $names = array();
2182 foreach ($thislist as $id) {
2183 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
2184 if (!$excludeid || !in_array($excludeid, $path)) {
2185 $namechunks = array();
2186 foreach ($path as $parentid) {
2187 $namechunks[] = $baselist[$parentid]['name'];
2189 $names[$id] = join($separator, $namechunks);
2192 return $names;
2196 * Prepares the object for caching. Works like the __sleep method.
2198 * implementing method from interface cacheable_object
2200 * @return array ready to be cached
2202 public function prepare_to_cache() {
2203 $a = array();
2204 foreach (self::$coursecatfields as $property => $cachedirectives) {
2205 if ($cachedirectives !== null) {
2206 list($shortname, $defaultvalue) = $cachedirectives;
2207 if ($this->$property !== $defaultvalue) {
2208 $a[$shortname] = $this->$property;
2212 $context = $this->get_context();
2213 $a['xi'] = $context->id;
2214 $a['xp'] = $context->path;
2215 return $a;
2219 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2221 * implementing method from interface cacheable_object
2223 * @param array $a
2224 * @return coursecat
2226 public static function wake_from_cache($a) {
2227 $record = new stdClass;
2228 foreach (self::$coursecatfields as $property => $cachedirectives) {
2229 if ($cachedirectives !== null) {
2230 list($shortname, $defaultvalue) = $cachedirectives;
2231 if (array_key_exists($shortname, $a)) {
2232 $record->$property = $a[$shortname];
2233 } else {
2234 $record->$property = $defaultvalue;
2238 $record->ctxid = $a['xi'];
2239 $record->ctxpath = $a['xp'];
2240 $record->ctxdepth = $record->depth + 1;
2241 $record->ctxlevel = CONTEXT_COURSECAT;
2242 $record->ctxinstance = $record->id;
2243 return new coursecat($record, true);
2247 * Returns true if the user is able to create a top level category.
2248 * @return bool
2250 public static function can_create_top_level_category() {
2251 return has_capability('moodle/category:manage', context_system::instance());
2255 * Returns the category context.
2256 * @return context_coursecat
2258 public function get_context() {
2259 if ($this->id === 0) {
2260 // This is the special top level category object.
2261 return context_system::instance();
2262 } else {
2263 return context_coursecat::instance($this->id);
2268 * Returns true if the user is able to manage this category.
2269 * @return bool
2271 public function has_manage_capability() {
2272 if ($this->hasmanagecapability === null) {
2273 $this->hasmanagecapability = has_capability('moodle/category:manage', $this->get_context());
2275 return $this->hasmanagecapability;
2279 * Returns true if the user has the manage capability on the parent category.
2280 * @return bool
2282 public function parent_has_manage_capability() {
2283 return has_capability('moodle/category:manage', get_category_or_system_context($this->parent));
2287 * Returns true if the current user can create subcategories of this category.
2288 * @return bool
2290 public function can_create_subcategory() {
2291 return $this->has_manage_capability();
2295 * Returns true if the user can resort this categories sub categories and courses.
2296 * @return bool
2298 public function can_resort_subcategories() {
2299 return $this->has_manage_capability();
2303 * Returns true if the user can resort the courses within this category.
2304 * @return bool
2306 public function can_resort_courses() {
2307 return $this->has_manage_capability();
2311 * Returns true of the user can change the sortorder of this category (resort the parent category)
2312 * @return bool
2314 public function can_change_sortorder() {
2315 return $this->parent_has_manage_capability();
2319 * Returns true if the current user can create a course within this category.
2320 * @return bool
2322 public function can_create_course() {
2323 return has_capability('moodle/course:create', $this->get_context());
2327 * Returns true if the current user can edit this categories settings.
2328 * @return bool
2330 public function can_edit() {
2331 return $this->has_manage_capability();
2335 * Returns true if the current user can review role assignments for this category.
2336 * @return bool
2338 public function can_review_roles() {
2339 return has_capability('moodle/role:assign', $this->get_context());
2343 * Returns true if the current user can review permissions for this category.
2344 * @return bool
2346 public function can_review_permissions() {
2347 return has_any_capability(array(
2348 'moodle/role:assign',
2349 'moodle/role:safeoverride',
2350 'moodle/role:override',
2351 'moodle/role:assign'
2352 ), $this->get_context());
2356 * Returns true if the current user can review cohorts for this category.
2357 * @return bool
2359 public function can_review_cohorts() {
2360 return has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->get_context());
2364 * Returns true if the current user can review filter settings for this category.
2365 * @return bool
2367 public function can_review_filters() {
2368 return has_capability('moodle/filter:manage', $this->get_context()) &&
2369 count(filter_get_available_in_context($this->get_context()))>0;
2373 * Returns true if the current user is able to change the visbility of this category.
2374 * @return bool
2376 public function can_change_visibility() {
2377 return $this->parent_has_manage_capability();
2381 * Returns true if the user can move courses out of this category.
2382 * @return bool
2384 public function can_move_courses_out_of() {
2385 return $this->has_manage_capability();
2389 * Returns true if the user can move courses into this category.
2390 * @return bool
2392 public function can_move_courses_into() {
2393 return $this->has_manage_capability();
2397 * Resorts the sub categories of this category by the given field.
2399 * @param string $field
2400 * @param bool $cleanup If true cleanup will be done, if false you will need to do it manually later.
2401 * @return bool True on success.
2402 * @throws coding_exception
2404 public function resort_subcategories($field, $cleanup = true) {
2405 global $DB;
2406 if ($field !== 'name' && $field !== 'idnumber') {
2407 throw new coding_exception('Invalid field requested');
2409 $children = $this->get_children();
2410 core_collator::asort_objects_by_property($children, $field, core_collator::SORT_NATURAL);
2411 $i = 1;
2412 foreach ($children as $cat) {
2413 $i++;
2414 $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id));
2415 $i += $cat->coursecount;
2417 if ($cleanup) {
2418 self::resort_categories_cleanup();
2420 return true;
2424 * Cleans things up after categories have been resorted.
2426 public static function resort_categories_cleanup() {
2427 // This should not be needed but we do it just to be safe.
2428 fix_course_sortorder();
2429 cache_helper::purge_by_event('changesincoursecat');
2433 * Resort the courses within this category by the given field.
2435 * @param string $field One of fullname, shortname or idnumber
2436 * @param bool $cleanup
2437 * @return bool True for success.
2438 * @throws coding_exception
2440 public function resort_courses($field, $cleanup = true) {
2441 global $DB;
2442 if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber') {
2443 // This is ultra important as we use $field in an SQL statement below this.
2444 throw new coding_exception('Invalid field requested');
2446 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
2447 $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields
2448 FROM {course} c
2449 LEFT JOIN {context} ctx ON ctx.instanceid = c.id
2450 WHERE ctx.contextlevel = :ctxlevel AND
2451 c.category = :categoryid
2452 ORDER BY c.{$field}, c.sortorder";
2453 $params = array(
2454 'ctxlevel' => CONTEXT_COURSE,
2455 'categoryid' => $this->id
2457 $courses = $DB->get_records_sql($sql, $params);
2458 if (count($courses) > 0) {
2459 foreach ($courses as $courseid => $course) {
2460 context_helper::preload_from_record($course);
2461 if ($field === 'idnumber') {
2462 $course->sortby = $course->idnumber;
2463 } else {
2464 // It'll require formatting.
2465 $options = array(
2466 'context' => context_course::instance($course->id)
2468 // We format the string first so that it appears as the user would see it.
2469 // This ensures the sorting makes sense to them. However it won't necessarily make
2470 // sense to everyone if things like multilang filters are enabled.
2471 // We then strip any tags as we don't want things such as image tags skewing the
2472 // sort results.
2473 $course->sortby = strip_tags(format_string($course->$field, true, $options));
2475 // We set it back here rather than using references as there is a bug with using
2476 // references in a foreach before passing as an arg by reference.
2477 $courses[$courseid] = $course;
2479 // Sort the courses.
2480 core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL);
2481 $i = 1;
2482 foreach ($courses as $course) {
2483 $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id));
2484 $i++;
2486 if ($cleanup) {
2487 // This should not be needed but we do it just to be safe.
2488 fix_course_sortorder();
2489 cache_helper::purge_by_event('changesincourse');
2492 return true;
2496 * Changes the sort order of this categories parent shifting this category up or down one.
2498 * @global \moodle_database $DB
2499 * @param bool $up If set to true the category is shifted up one spot, else its moved down.
2500 * @return bool True on success, false otherwise.
2502 public function change_sortorder_by_one($up) {
2503 global $DB;
2504 $params = array($this->sortorder, $this->parent);
2505 if ($up) {
2506 $select = 'sortorder < ? AND parent = ?';
2507 $sort = 'sortorder DESC';
2508 } else {
2509 $select = 'sortorder > ? AND parent = ?';
2510 $sort = 'sortorder ASC';
2512 fix_course_sortorder();
2513 $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1);
2514 $swapcategory = reset($swapcategory);
2515 if ($swapcategory) {
2516 $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id));
2517 $DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id));
2518 $this->sortorder = $swapcategory->sortorder;
2519 add_to_log(SITEID, "category", "move", "management.php?categoryid={$this->id}", $this->id);
2520 // Finally reorder courses.
2521 fix_course_sortorder();
2522 cache_helper::purge_by_event('changesincoursecat');
2523 return true;
2525 return false;
2529 * Returns the parent coursecat object for this category.
2531 * @return coursecat
2533 public function get_parent_coursecat() {
2534 return self::get($this->parent);
2539 * Returns true if the user is able to request a new course be created.
2540 * @return bool
2542 public function can_request_course() {
2543 global $CFG;
2544 if (empty($CFG->enablecourserequests) || $this->id != $CFG->defaultrequestcategory) {
2545 return false;
2547 return !$this->can_create_course() && has_capability('moodle/course:request', $this->get_context());
2551 * Returns true if the user can approve course requests.
2552 * @return bool
2554 public static function can_approve_course_requests() {
2555 global $CFG, $DB;
2556 if (empty($CFG->enablecourserequests)) {
2557 return false;
2559 $context = context_system::instance();
2560 if (!has_capability('moodle/site:approvecourse', $context)) {
2561 return false;
2563 if (!$DB->record_exists('course_request', array())) {
2564 return false;
2566 return true;
2571 * Class to store information about one course in a list of courses
2573 * Not all information may be retrieved when object is created but
2574 * it will be retrieved on demand when appropriate property or method is
2575 * called.
2577 * Instances of this class are usually returned by functions
2578 * {@link coursecat::search_courses()}
2579 * and
2580 * {@link coursecat::get_courses()}
2582 * @property-read int $id
2583 * @property-read int $category Category ID
2584 * @property-read int $sortorder
2585 * @property-read string $fullname
2586 * @property-read string $shortname
2587 * @property-read string $idnumber
2588 * @property-read string $summary Course summary. Field is present if coursecat::get_courses()
2589 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2590 * @property-read int $summaryformat Summary format. Field is present if coursecat::get_courses()
2591 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2592 * @property-read string $format Course format. Retrieved from DB on first request
2593 * @property-read int $showgrades Retrieved from DB on first request
2594 * @property-read int $newsitems Retrieved from DB on first request
2595 * @property-read int $startdate
2596 * @property-read int $marker Retrieved from DB on first request
2597 * @property-read int $maxbytes Retrieved from DB on first request
2598 * @property-read int $legacyfiles Retrieved from DB on first request
2599 * @property-read int $showreports Retrieved from DB on first request
2600 * @property-read int $visible
2601 * @property-read int $visibleold Retrieved from DB on first request
2602 * @property-read int $groupmode Retrieved from DB on first request
2603 * @property-read int $groupmodeforce Retrieved from DB on first request
2604 * @property-read int $defaultgroupingid Retrieved from DB on first request
2605 * @property-read string $lang Retrieved from DB on first request
2606 * @property-read string $theme Retrieved from DB on first request
2607 * @property-read int $timecreated Retrieved from DB on first request
2608 * @property-read int $timemodified Retrieved from DB on first request
2609 * @property-read int $requested Retrieved from DB on first request
2610 * @property-read int $enablecompletion Retrieved from DB on first request
2611 * @property-read int $completionnotify Retrieved from DB on first request
2612 * @property-read int $cacherev
2614 * @package core
2615 * @subpackage course
2616 * @copyright 2013 Marina Glancy
2617 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2619 class course_in_list implements IteratorAggregate {
2621 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2622 protected $record;
2624 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2625 protected $coursecontacts;
2627 /** @var bool true if the current user can access the course, false otherwise. */
2628 protected $canaccess = null;
2631 * Creates an instance of the class from record
2633 * @param stdClass $record except fields from course table it may contain
2634 * field hassummary indicating that summary field is not empty.
2635 * Also it is recommended to have context fields here ready for
2636 * context preloading
2638 public function __construct(stdClass $record) {
2639 context_helper::preload_from_record($record);
2640 $this->record = new stdClass();
2641 foreach ($record as $key => $value) {
2642 $this->record->$key = $value;
2647 * Indicates if the course has non-empty summary field
2649 * @return bool
2651 public function has_summary() {
2652 if (isset($this->record->hassummary)) {
2653 return !empty($this->record->hassummary);
2655 if (!isset($this->record->summary)) {
2656 // We need to retrieve summary.
2657 $this->__get('summary');
2659 return !empty($this->record->summary);
2663 * Indicates if the course have course contacts to display
2665 * @return bool
2667 public function has_course_contacts() {
2668 if (!isset($this->record->managers)) {
2669 $courses = array($this->id => &$this->record);
2670 coursecat::preload_course_contacts($courses);
2672 return !empty($this->record->managers);
2676 * Returns list of course contacts (usually teachers) to display in course link
2678 * Roles to display are set up in $CFG->coursecontact
2680 * The result is the list of users where user id is the key and the value
2681 * is an array with elements:
2682 * - 'user' - object containing basic user information
2683 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2684 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2685 * - 'username' => fullname($user, $canviewfullnames)
2687 * @return array
2689 public function get_course_contacts() {
2690 global $CFG;
2691 if (empty($CFG->coursecontact)) {
2692 // No roles are configured to be displayed as course contacts.
2693 return array();
2695 if ($this->coursecontacts === null) {
2696 $this->coursecontacts = array();
2697 $context = context_course::instance($this->id);
2699 if (!isset($this->record->managers)) {
2700 // Preload course contacts from DB.
2701 $courses = array($this->id => &$this->record);
2702 coursecat::preload_course_contacts($courses);
2705 // Build return array with full roles names (for this course context) and users names.
2706 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2707 foreach ($this->record->managers as $ruser) {
2708 if (isset($this->coursecontacts[$ruser->id])) {
2709 // Only display a user once with the highest sortorder role.
2710 continue;
2712 $user = new stdClass();
2713 $user->id = $ruser->id;
2714 $user->username = $ruser->username;
2715 foreach (get_all_user_name_fields() as $addname) {
2716 $user->$addname = $ruser->$addname;
2718 $role = new stdClass();
2719 $role->id = $ruser->roleid;
2720 $role->name = $ruser->rolename;
2721 $role->shortname = $ruser->roleshortname;
2722 $role->coursealias = $ruser->rolecoursealias;
2724 $this->coursecontacts[$user->id] = array(
2725 'user' => $user,
2726 'role' => $role,
2727 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2728 'username' => fullname($user, $canviewfullnames)
2732 return $this->coursecontacts;
2736 * Checks if course has any associated overview files
2738 * @return bool
2740 public function has_course_overviewfiles() {
2741 global $CFG;
2742 if (empty($CFG->courseoverviewfileslimit)) {
2743 return false;
2745 $fs = get_file_storage();
2746 $context = context_course::instance($this->id);
2747 return !$fs->is_area_empty($context->id, 'course', 'overviewfiles');
2751 * Returns all course overview files
2753 * @return array array of stored_file objects
2755 public function get_course_overviewfiles() {
2756 global $CFG;
2757 if (empty($CFG->courseoverviewfileslimit)) {
2758 return array();
2760 require_once($CFG->libdir. '/filestorage/file_storage.php');
2761 require_once($CFG->dirroot. '/course/lib.php');
2762 $fs = get_file_storage();
2763 $context = context_course::instance($this->id);
2764 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2765 if (count($files)) {
2766 $overviewfilesoptions = course_overviewfiles_options($this->id);
2767 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2768 if ($acceptedtypes !== '*') {
2769 // Filter only files with allowed extensions.
2770 require_once($CFG->libdir. '/filelib.php');
2771 foreach ($files as $key => $file) {
2772 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2773 unset($files[$key]);
2777 if (count($files) > $CFG->courseoverviewfileslimit) {
2778 // Return no more than $CFG->courseoverviewfileslimit files.
2779 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
2782 return $files;
2786 * Magic method to check if property is set
2788 * @param string $name
2789 * @return bool
2791 public function __isset($name) {
2792 return isset($this->record->$name);
2796 * Magic method to get a course property
2798 * Returns any field from table course (retrieves it from DB if it was not retrieved before)
2800 * @param string $name
2801 * @return mixed
2803 public function __get($name) {
2804 global $DB;
2805 if (property_exists($this->record, $name)) {
2806 return $this->record->$name;
2807 } else if ($name === 'summary' || $name === 'summaryformat') {
2808 // Retrieve fields summary and summaryformat together because they are most likely to be used together.
2809 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
2810 $this->record->summary = $record->summary;
2811 $this->record->summaryformat = $record->summaryformat;
2812 return $this->record->$name;
2813 } else if (array_key_exists($name, $DB->get_columns('course'))) {
2814 // Another field from table 'course' that was not retrieved.
2815 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
2816 return $this->record->$name;
2818 debugging('Invalid course property accessed! '.$name);
2819 return null;
2823 * All properties are read only, sorry.
2825 * @param string $name
2827 public function __unset($name) {
2828 debugging('Can not unset '.get_class($this).' instance properties!');
2832 * Magic setter method, we do not want anybody to modify properties from the outside
2834 * @param string $name
2835 * @param mixed $value
2837 public function __set($name, $value) {
2838 debugging('Can not change '.get_class($this).' instance properties!');
2842 * Create an iterator because magic vars can't be seen by 'foreach'.
2843 * Exclude context fields
2845 * Implementing method from interface IteratorAggregate
2847 * @return ArrayIterator
2849 public function getIterator() {
2850 $ret = array('id' => $this->record->id);
2851 foreach ($this->record as $property => $value) {
2852 $ret[$property] = $value;
2854 return new ArrayIterator($ret);
2858 * Returns the name of this course as it should be displayed within a list.
2859 * @return string
2861 public function get_formatted_name() {
2862 return format_string(get_course_display_name_for_list($this), true, $this->get_context());
2866 * Returns the formatted fullname for this course.
2867 * @return string
2869 public function get_formatted_fullname() {
2870 return format_string($this->__get('fullname'), true, $this->get_context());
2874 * Returns the formatted shortname for this course.
2875 * @return string
2877 public function get_formatted_shortname() {
2878 return format_string($this->__get('shortname'), true, $this->get_context());
2882 * Returns true if the current user can access this course.
2883 * @return bool
2885 public function can_access() {
2886 if ($this->canaccess === null) {
2887 $this->canaccess = can_access_course($this->record);
2889 return $this->canaccess;
2893 * Returns true if the user can edit this courses settings.
2895 * Note: this function does not check that the current user can access the course.
2896 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2898 * @return bool
2900 public function can_edit() {
2901 return has_capability('moodle/course:update', $this->get_context());
2905 * Returns true if the user can change the visibility of this course.
2907 * Note: this function does not check that the current user can access the course.
2908 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2910 * @return bool
2912 public function can_change_visibility() {
2913 // You must be able to both hide a course and view the hidden course.
2914 return has_all_capabilities(array('moodle/course:visibility', 'moodle/course:viewhiddencourses'), $this->get_context());
2918 * Returns the context for this course.
2919 * @return context_course
2921 public function get_context() {
2922 return context_course::instance($this->__get('id'));
2926 * Returns true if this course is visible to the current user.
2927 * @return bool
2929 public function is_uservisible() {
2930 return $this->visible || has_capability('moodle/course:viewhiddencourses', $this->get_context());
2934 * Returns true if the current user can review enrolments for this course.
2936 * Note: this function does not check that the current user can access the course.
2937 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2939 * @return bool
2941 public function can_review_enrolments() {
2942 return has_capability('moodle/course:enrolreview', $this->get_context());
2946 * Returns true if the current user can delete this course.
2948 * Note: this function does not check that the current user can access the course.
2949 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2951 * @return bool
2953 public function can_delete() {
2954 return can_delete_course($this->id);
2958 * Returns true if the current user can backup this course.
2960 * Note: this function does not check that the current user can access the course.
2961 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2963 * @return bool
2965 public function can_backup() {
2966 return has_capability('moodle/backup:backupcourse', $this->get_context());
2970 * Returns true if the current user can restore this course.
2972 * Note: this function does not check that the current user can access the course.
2973 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2975 * @return bool
2977 public function can_restore() {
2978 return has_capability('moodle/restore:restorecourse', $this->get_context());
2983 * An array of records that is sortable by many fields.
2985 * For more info on the ArrayObject class have a look at php.net.
2987 * @package core
2988 * @subpackage course
2989 * @copyright 2013 Sam Hemelryk
2990 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2992 class coursecat_sortable_records extends ArrayObject {
2995 * An array of sortable fields.
2996 * Gets set temporarily when sort is called.
2997 * @var array
2999 protected $sortfields = array();
3002 * Sorts this array using the given fields.
3004 * @param array $records
3005 * @param array $fields
3006 * @return array
3008 public static function sort(array $records, array $fields) {
3009 $records = new coursecat_sortable_records($records);
3010 $records->sortfields = $fields;
3011 $records->uasort(array($records, 'sort_by_many_fields'));
3012 return $records->getArrayCopy();
3016 * Sorts the two records based upon many fields.
3018 * This method should not be called itself, please call $sort instead.
3019 * It has been marked as access private as such.
3021 * @access private
3022 * @param stdClass $a
3023 * @param stdClass $b
3024 * @return int
3026 public function sort_by_many_fields($a, $b) {
3027 foreach ($this->sortfields as $field => $mult) {
3028 // Nulls first.
3029 if (is_null($a->$field) && !is_null($b->$field)) {
3030 return -$mult;
3032 if (is_null($b->$field) && !is_null($a->$field)) {
3033 return $mult;
3036 if (is_string($a->$field) || is_string($b->$field)) {
3037 // String fields.
3038 if ($cmp = strcoll($a->$field, $b->$field)) {
3039 return $mult * $cmp;
3041 } else {
3042 // Int fields.
3043 if ($a->$field > $b->$field) {
3044 return $mult;
3046 if ($a->$field < $b->$field) {
3047 return -$mult;
3051 return 0;