Merge branch 'MDL-61960-master' of git://github.com/farhan6318/moodle
[moodle.git] / lib / coursecatlib.php
blob5ad20b73ac582a20b1ccd32fbdcef8691ef23e8f
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 /** @var array list of all fields and their short name and default value for caching */
56 protected static $coursecatfields = array(
57 'id' => array('id', 0),
58 'name' => array('na', ''),
59 'idnumber' => array('in', null),
60 'description' => null, // Not cached.
61 'descriptionformat' => null, // Not cached.
62 'parent' => array('pa', 0),
63 'sortorder' => array('so', 0),
64 'coursecount' => array('cc', 0),
65 'visible' => array('vi', 1),
66 'visibleold' => null, // Not cached.
67 'timemodified' => null, // Not cached.
68 'depth' => array('dh', 1),
69 'path' => array('ph', null),
70 'theme' => null, // Not cached.
73 /** @var int */
74 protected $id;
76 /** @var string */
77 protected $name = '';
79 /** @var string */
80 protected $idnumber = null;
82 /** @var string */
83 protected $description = false;
85 /** @var int */
86 protected $descriptionformat = false;
88 /** @var int */
89 protected $parent = 0;
91 /** @var int */
92 protected $sortorder = 0;
94 /** @var int */
95 protected $coursecount = false;
97 /** @var int */
98 protected $visible = 1;
100 /** @var int */
101 protected $visibleold = false;
103 /** @var int */
104 protected $timemodified = false;
106 /** @var int */
107 protected $depth = 0;
109 /** @var string */
110 protected $path = '';
112 /** @var string */
113 protected $theme = false;
115 /** @var bool */
116 protected $fromcache;
118 /** @var bool */
119 protected $hasmanagecapability = null;
122 * Magic setter method, we do not want anybody to modify properties from the outside
124 * @param string $name
125 * @param mixed $value
127 public function __set($name, $value) {
128 debugging('Can not change coursecat instance properties!', DEBUG_DEVELOPER);
132 * Magic method getter, redirects to read only values. Queries from DB the fields that were not cached
134 * @param string $name
135 * @return mixed
137 public function __get($name) {
138 global $DB;
139 if (array_key_exists($name, self::$coursecatfields)) {
140 if ($this->$name === false) {
141 // Property was not retrieved from DB, retrieve all not retrieved fields.
142 $notretrievedfields = array_diff_key(self::$coursecatfields, array_filter(self::$coursecatfields));
143 $record = $DB->get_record('course_categories', array('id' => $this->id),
144 join(',', array_keys($notretrievedfields)), MUST_EXIST);
145 foreach ($record as $key => $value) {
146 $this->$key = $value;
149 return $this->$name;
151 debugging('Invalid coursecat property accessed! '.$name, DEBUG_DEVELOPER);
152 return null;
156 * Full support for isset on our magic read only properties.
158 * @param string $name
159 * @return bool
161 public function __isset($name) {
162 if (array_key_exists($name, self::$coursecatfields)) {
163 return isset($this->$name);
165 return false;
169 * All properties are read only, sorry.
171 * @param string $name
173 public function __unset($name) {
174 debugging('Can not unset coursecat instance properties!', DEBUG_DEVELOPER);
178 * Create an iterator because magic vars can't be seen by 'foreach'.
180 * implementing method from interface IteratorAggregate
182 * @return ArrayIterator
184 public function getIterator() {
185 $ret = array();
186 foreach (self::$coursecatfields as $property => $unused) {
187 if ($this->$property !== false) {
188 $ret[$property] = $this->$property;
191 return new ArrayIterator($ret);
195 * Constructor
197 * Constructor is protected, use coursecat::get($id) to retrieve category
199 * @param stdClass $record record from DB (may not contain all fields)
200 * @param bool $fromcache whether it is being restored from cache
202 protected function __construct(stdClass $record, $fromcache = false) {
203 context_helper::preload_from_record($record);
204 foreach ($record as $key => $val) {
205 if (array_key_exists($key, self::$coursecatfields)) {
206 $this->$key = $val;
209 $this->fromcache = $fromcache;
213 * Returns coursecat object for requested category
215 * If category is not visible to user it is treated as non existing
216 * unless $alwaysreturnhidden is set to true
218 * If id is 0, the pseudo object for root category is returned (convenient
219 * for calling other functions such as get_children())
221 * @param int $id category id
222 * @param int $strictness whether to throw an exception (MUST_EXIST) or
223 * return null (IGNORE_MISSING) in case the category is not found or
224 * not visible to current user
225 * @param bool $alwaysreturnhidden set to true if you want an object to be
226 * returned even if this category is not visible to the current user
227 * (category is hidden and user does not have
228 * 'moodle/category:viewhiddencategories' capability). Use with care!
229 * @return null|coursecat
230 * @throws moodle_exception
232 public static function get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false) {
233 if (!$id) {
234 if (!isset(self::$coursecat0)) {
235 $record = new stdClass();
236 $record->id = 0;
237 $record->visible = 1;
238 $record->depth = 0;
239 $record->path = '';
240 self::$coursecat0 = new coursecat($record);
242 return self::$coursecat0;
244 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
245 $coursecat = $coursecatrecordcache->get($id);
246 if ($coursecat === false) {
247 if ($records = self::get_records('cc.id = :id', array('id' => $id))) {
248 $record = reset($records);
249 $coursecat = new coursecat($record);
250 // Store in cache.
251 $coursecatrecordcache->set($id, $coursecat);
254 if ($coursecat && ($alwaysreturnhidden || $coursecat->is_uservisible())) {
255 return $coursecat;
256 } else {
257 if ($strictness == MUST_EXIST) {
258 throw new moodle_exception('unknowncategory');
261 return null;
265 * Load many coursecat objects.
267 * @global moodle_database $DB
268 * @param array $ids An array of category ID's to load.
269 * @return coursecat[]
271 public static function get_many(array $ids) {
272 global $DB;
273 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
274 $categories = $coursecatrecordcache->get_many($ids);
275 $toload = array();
276 foreach ($categories as $id => $result) {
277 if ($result === false) {
278 $toload[] = $id;
281 if (!empty($toload)) {
282 list($where, $params) = $DB->get_in_or_equal($toload, SQL_PARAMS_NAMED);
283 $records = self::get_records('cc.id '.$where, $params);
284 $toset = array();
285 foreach ($records as $record) {
286 $categories[$record->id] = new coursecat($record);
287 $toset[$record->id] = $categories[$record->id];
289 $coursecatrecordcache->set_many($toset);
291 return $categories;
295 * Load all coursecat objects.
297 * @param array $options Options:
298 * @param bool $options.returnhidden Return categories even if they are hidden
299 * @return coursecat[]
301 public static function get_all($options = []) {
302 global $DB;
304 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
306 $catcontextsql = \context_helper::get_preload_record_columns_sql('ctx');
307 $catsql = "SELECT cc.*, {$catcontextsql}
308 FROM {course_categories} cc
309 JOIN {context} ctx ON cc.id = ctx.instanceid";
310 $catsqlwhere = "WHERE ctx.contextlevel = :contextlevel";
311 $catsqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC";
313 $catrs = $DB->get_recordset_sql("{$catsql} {$catsqlwhere} {$catsqlorder}", [
314 'contextlevel' => CONTEXT_COURSECAT,
317 $types['categories'] = [];
318 $categories = [];
319 $toset = [];
320 foreach ($catrs as $record) {
321 $category = new coursecat($record);
322 $toset[$category->id] = $category;
324 if (!empty($options['returnhidden']) || $category->is_uservisible()) {
325 $categories[$record->id] = $category;
328 $catrs->close();
330 $coursecatrecordcache->set_many($toset);
332 return $categories;
337 * Returns the first found category
339 * Note that if there are no categories visible to the current user on the first level,
340 * the invisible category may be returned
342 * @return coursecat
344 public static function get_default() {
345 if ($visiblechildren = self::get(0)->get_children()) {
346 $defcategory = reset($visiblechildren);
347 } else {
348 $toplevelcategories = self::get_tree(0);
349 $defcategoryid = $toplevelcategories[0];
350 $defcategory = self::get($defcategoryid, MUST_EXIST, true);
352 return $defcategory;
356 * Restores the object after it has been externally modified in DB for example
357 * during {@link fix_course_sortorder()}
359 protected function restore() {
360 // Update all fields in the current object.
361 $newrecord = self::get($this->id, MUST_EXIST, true);
362 foreach (self::$coursecatfields as $key => $unused) {
363 $this->$key = $newrecord->$key;
368 * Creates a new category either from form data or from raw data
370 * Please note that this function does not verify access control.
372 * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
374 * Category visibility is inherited from parent unless $data->visible = 0 is specified
376 * @param array|stdClass $data
377 * @param array $editoroptions if specified, the data is considered to be
378 * form data and file_postupdate_standard_editor() is being called to
379 * process images in description.
380 * @return coursecat
381 * @throws moodle_exception
383 public static function create($data, $editoroptions = null) {
384 global $DB, $CFG;
385 $data = (object)$data;
386 $newcategory = new stdClass();
388 $newcategory->descriptionformat = FORMAT_MOODLE;
389 $newcategory->description = '';
390 // Copy all description* fields regardless of whether this is form data or direct field update.
391 foreach ($data as $key => $value) {
392 if (preg_match("/^description/", $key)) {
393 $newcategory->$key = $value;
397 if (empty($data->name)) {
398 throw new moodle_exception('categorynamerequired');
400 if (core_text::strlen($data->name) > 255) {
401 throw new moodle_exception('categorytoolong');
403 $newcategory->name = $data->name;
405 // Validate and set idnumber.
406 if (isset($data->idnumber)) {
407 if (core_text::strlen($data->idnumber) > 100) {
408 throw new moodle_exception('idnumbertoolong');
410 if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
411 throw new moodle_exception('categoryidnumbertaken');
413 $newcategory->idnumber = $data->idnumber;
416 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
417 $newcategory->theme = $data->theme;
420 if (empty($data->parent)) {
421 $parent = self::get(0);
422 } else {
423 $parent = self::get($data->parent, MUST_EXIST, true);
425 $newcategory->parent = $parent->id;
426 $newcategory->depth = $parent->depth + 1;
428 // By default category is visible, unless visible = 0 is specified or parent category is hidden.
429 if (isset($data->visible) && !$data->visible) {
430 // Create a hidden category.
431 $newcategory->visible = $newcategory->visibleold = 0;
432 } else {
433 // Create a category that inherits visibility from parent.
434 $newcategory->visible = $parent->visible;
435 // In case parent is hidden, when it changes visibility this new subcategory will automatically become visible too.
436 $newcategory->visibleold = 1;
439 $newcategory->sortorder = 0;
440 $newcategory->timemodified = time();
442 $newcategory->id = $DB->insert_record('course_categories', $newcategory);
444 // Update path (only possible after we know the category id.
445 $path = $parent->path . '/' . $newcategory->id;
446 $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));
448 // We should mark the context as dirty.
449 context_coursecat::instance($newcategory->id)->mark_dirty();
451 fix_course_sortorder();
453 // If this is data from form results, save embedded files and update description.
454 $categorycontext = context_coursecat::instance($newcategory->id);
455 if ($editoroptions) {
456 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
457 'coursecat', 'description', 0);
459 // Update only fields description and descriptionformat.
460 $updatedata = new stdClass();
461 $updatedata->id = $newcategory->id;
462 $updatedata->description = $newcategory->description;
463 $updatedata->descriptionformat = $newcategory->descriptionformat;
464 $DB->update_record('course_categories', $updatedata);
467 $event = \core\event\course_category_created::create(array(
468 'objectid' => $newcategory->id,
469 'context' => $categorycontext
471 $event->trigger();
473 cache_helper::purge_by_event('changesincoursecat');
475 return self::get($newcategory->id, MUST_EXIST, true);
479 * Updates the record with either form data or raw data
481 * Please note that this function does not verify access control.
483 * This function calls coursecat::change_parent_raw if field 'parent' is updated.
484 * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
485 * Visibility is changed first and then parent is changed. This means that
486 * if parent category is hidden, the current category will become hidden
487 * too and it may overwrite whatever was set in field 'visible'.
489 * Note that fields 'path' and 'depth' can not be updated manually
490 * Also coursecat::update() can not directly update the field 'sortoder'
492 * @param array|stdClass $data
493 * @param array $editoroptions if specified, the data is considered to be
494 * form data and file_postupdate_standard_editor() is being called to
495 * process images in description.
496 * @throws moodle_exception
498 public function update($data, $editoroptions = null) {
499 global $DB, $CFG;
500 if (!$this->id) {
501 // There is no actual DB record associated with root category.
502 return;
505 $data = (object)$data;
506 $newcategory = new stdClass();
507 $newcategory->id = $this->id;
509 // Copy all description* fields regardless of whether this is form data or direct field update.
510 foreach ($data as $key => $value) {
511 if (preg_match("/^description/", $key)) {
512 $newcategory->$key = $value;
516 if (isset($data->name) && empty($data->name)) {
517 throw new moodle_exception('categorynamerequired');
520 if (!empty($data->name) && $data->name !== $this->name) {
521 if (core_text::strlen($data->name) > 255) {
522 throw new moodle_exception('categorytoolong');
524 $newcategory->name = $data->name;
527 if (isset($data->idnumber) && $data->idnumber !== $this->idnumber) {
528 if (core_text::strlen($data->idnumber) > 100) {
529 throw new moodle_exception('idnumbertoolong');
531 if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
532 throw new moodle_exception('categoryidnumbertaken');
534 $newcategory->idnumber = $data->idnumber;
537 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
538 $newcategory->theme = $data->theme;
541 $changes = false;
542 if (isset($data->visible)) {
543 if ($data->visible) {
544 $changes = $this->show_raw();
545 } else {
546 $changes = $this->hide_raw(0);
550 if (isset($data->parent) && $data->parent != $this->parent) {
551 if ($changes) {
552 cache_helper::purge_by_event('changesincoursecat');
554 $parentcat = self::get($data->parent, MUST_EXIST, true);
555 $this->change_parent_raw($parentcat);
556 fix_course_sortorder();
559 $newcategory->timemodified = time();
561 $categorycontext = $this->get_context();
562 if ($editoroptions) {
563 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
564 'coursecat', 'description', 0);
566 $DB->update_record('course_categories', $newcategory);
568 $event = \core\event\course_category_updated::create(array(
569 'objectid' => $newcategory->id,
570 'context' => $categorycontext
572 $event->trigger();
574 fix_course_sortorder();
575 // Purge cache even if fix_course_sortorder() did not do it.
576 cache_helper::purge_by_event('changesincoursecat');
578 // Update all fields in the current object.
579 $this->restore();
583 * Checks if this course category is visible to current user
585 * Please note that methods coursecat::get (without 3rd argumet),
586 * coursecat::get_children(), etc. return only visible categories so it is
587 * usually not needed to call this function outside of this class
589 * @return bool
591 public function is_uservisible() {
592 return !$this->id || $this->visible ||
593 has_capability('moodle/category:viewhiddencategories', $this->get_context());
597 * Returns the complete corresponding record from DB table course_categories
599 * Mostly used in deprecated functions
601 * @return stdClass
603 public function get_db_record() {
604 global $DB;
605 if ($record = $DB->get_record('course_categories', array('id' => $this->id))) {
606 return $record;
607 } else {
608 return (object)convert_to_array($this);
613 * Returns the entry from categories tree and makes sure the application-level tree cache is built
615 * The following keys can be requested:
617 * 'countall' - total number of categories in the system (always present)
618 * 0 - array of ids of top-level categories (always present)
619 * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
620 * $id (int) - array of ids of categories that are direct children of category with id $id. If
621 * category with id $id does not exist returns false. If category has no children returns empty array
622 * $id.'i' - array of ids of children categories that have visible=0
624 * @param int|string $id
625 * @return mixed
627 protected static function get_tree($id) {
628 global $DB;
629 $coursecattreecache = cache::make('core', 'coursecattree');
630 $rv = $coursecattreecache->get($id);
631 if ($rv !== false) {
632 return $rv;
634 // Re-build the tree.
635 $sql = "SELECT cc.id, cc.parent, cc.visible
636 FROM {course_categories} cc
637 ORDER BY cc.sortorder";
638 $rs = $DB->get_recordset_sql($sql, array());
639 $all = array(0 => array(), '0i' => array());
640 $count = 0;
641 foreach ($rs as $record) {
642 $all[$record->id] = array();
643 $all[$record->id. 'i'] = array();
644 if (array_key_exists($record->parent, $all)) {
645 $all[$record->parent][] = $record->id;
646 if (!$record->visible) {
647 $all[$record->parent. 'i'][] = $record->id;
649 } else {
650 // Parent not found. This is data consistency error but next fix_course_sortorder() should fix it.
651 $all[0][] = $record->id;
652 if (!$record->visible) {
653 $all['0i'][] = $record->id;
656 $count++;
658 $rs->close();
659 if (!$count) {
660 // No categories found.
661 // This may happen after upgrade of a very old moodle version.
662 // In new versions the default category is created on install.
663 $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
664 set_config('defaultrequestcategory', $defcoursecat->id);
665 $all[0] = array($defcoursecat->id);
666 $all[$defcoursecat->id] = array();
667 $count++;
669 // We must add countall to all in case it was the requested ID.
670 $all['countall'] = $count;
671 $coursecattreecache->set_many($all);
672 if (array_key_exists($id, $all)) {
673 return $all[$id];
675 // Requested non-existing category.
676 return array();
680 * Returns number of ALL categories in the system regardless if
681 * they are visible to current user or not
683 * @return int
685 public static function count_all() {
686 return self::get_tree('countall');
690 * Retrieves number of records from course_categories table
692 * Only cached fields are retrieved. Records are ready for preloading context
694 * @param string $whereclause
695 * @param array $params
696 * @return array array of stdClass objects
698 protected static function get_records($whereclause, $params) {
699 global $DB;
700 // Retrieve from DB only the fields that need to be stored in cache.
701 $fields = array_keys(array_filter(self::$coursecatfields));
702 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
703 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
704 FROM {course_categories} cc
705 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
706 WHERE ". $whereclause." ORDER BY cc.sortorder";
707 return $DB->get_records_sql($sql,
708 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
712 * Resets course contact caches when role assignments were changed
714 * @param int $roleid role id that was given or taken away
715 * @param context $context context where role assignment has been changed
717 public static function role_assignment_changed($roleid, $context) {
718 global $CFG, $DB;
720 if ($context->contextlevel > CONTEXT_COURSE) {
721 // No changes to course contacts if role was assigned on the module/block level.
722 return;
725 // Trigger a purge for all caches listening for changes to category enrolment.
726 cache_helper::purge_by_event('changesincategoryenrolment');
728 if (!$CFG->coursecontact || !in_array($roleid, explode(',', $CFG->coursecontact))) {
729 // The role is not one of course contact roles.
730 return;
733 // Remove from cache course contacts of all affected courses.
734 $cache = cache::make('core', 'coursecontacts');
735 if ($context->contextlevel == CONTEXT_COURSE) {
736 $cache->delete($context->instanceid);
737 } else if ($context->contextlevel == CONTEXT_SYSTEM) {
738 $cache->purge();
739 } else {
740 $sql = "SELECT ctx.instanceid
741 FROM {context} ctx
742 WHERE ctx.path LIKE ? AND ctx.contextlevel = ?";
743 $params = array($context->path . '/%', CONTEXT_COURSE);
744 if ($courses = $DB->get_fieldset_sql($sql, $params)) {
745 $cache->delete_many($courses);
751 * Executed when user enrolment was changed to check if course
752 * contacts cache needs to be cleared
754 * @param int $courseid course id
755 * @param int $userid user id
756 * @param int $status new enrolment status (0 - active, 1 - suspended)
757 * @param int $timestart new enrolment time start
758 * @param int $timeend new enrolment time end
760 public static function user_enrolment_changed($courseid, $userid,
761 $status, $timestart = null, $timeend = null) {
762 $cache = cache::make('core', 'coursecontacts');
763 $contacts = $cache->get($courseid);
764 if ($contacts === false) {
765 // The contacts for the affected course were not cached anyway.
766 return;
768 $enrolmentactive = ($status == 0) &&
769 (!$timestart || $timestart < time()) &&
770 (!$timeend || $timeend > time());
771 if (!$enrolmentactive) {
772 $isincontacts = false;
773 foreach ($contacts as $contact) {
774 if ($contact->id == $userid) {
775 $isincontacts = true;
778 if (!$isincontacts) {
779 // Changed user's enrolment does not exist or is not active,
780 // and he is not in cached course contacts, no changes to be made.
781 return;
784 // Either enrolment of manager was deleted/suspended
785 // or user enrolment was added or activated.
786 // In order to see if the course contacts for this course need
787 // changing we would need to make additional queries, they will
788 // slow down bulk enrolment changes. It is better just to remove
789 // course contacts cache for this course.
790 $cache->delete($courseid);
794 * Given list of DB records from table course populates each record with list of users with course contact roles
796 * This function fills the courses with raw information as {@link get_role_users()} would do.
797 * See also {@link course_in_list::get_course_contacts()} for more readable return
799 * $courses[$i]->managers = array(
800 * $roleassignmentid => $roleuser,
801 * ...
802 * );
804 * where $roleuser is an stdClass with the following properties:
806 * $roleuser->raid - role assignment id
807 * $roleuser->id - user id
808 * $roleuser->username
809 * $roleuser->firstname
810 * $roleuser->lastname
811 * $roleuser->rolecoursealias
812 * $roleuser->rolename
813 * $roleuser->sortorder - role sortorder
814 * $roleuser->roleid
815 * $roleuser->roleshortname
817 * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
819 * @param array $courses
821 public static function preload_course_contacts(&$courses) {
822 global $CFG, $DB;
823 if (empty($courses) || empty($CFG->coursecontact)) {
824 return;
826 $managerroles = explode(',', $CFG->coursecontact);
827 $cache = cache::make('core', 'coursecontacts');
828 $cacheddata = $cache->get_many(array_keys($courses));
829 $courseids = array();
830 foreach (array_keys($courses) as $id) {
831 if ($cacheddata[$id] !== false) {
832 $courses[$id]->managers = $cacheddata[$id];
833 } else {
834 $courseids[] = $id;
838 // Array $courseids now stores list of ids of courses for which we still need to retrieve contacts.
839 if (empty($courseids)) {
840 return;
843 // First build the array of all context ids of the courses and their categories.
844 $allcontexts = array();
845 foreach ($courseids as $id) {
846 $context = context_course::instance($id);
847 $courses[$id]->managers = array();
848 foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
849 if (!isset($allcontexts[$ctxid])) {
850 $allcontexts[$ctxid] = array();
852 $allcontexts[$ctxid][] = $id;
856 // Fetch list of all users with course contact roles in any of the courses contexts or parent contexts.
857 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
858 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
859 list($sort, $sortparams) = users_order_by_sql('u');
860 $notdeleted = array('notdeleted'=>0);
861 $allnames = get_all_user_name_fields(true, 'u');
862 $sql = "SELECT ra.contextid, ra.id AS raid,
863 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
864 rn.name AS rolecoursealias, u.id, u.username, $allnames
865 FROM {role_assignments} ra
866 JOIN {user} u ON ra.userid = u.id
867 JOIN {role} r ON ra.roleid = r.id
868 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
869 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
870 ORDER BY r.sortorder, $sort";
871 $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
872 $checkenrolments = array();
873 foreach ($rs as $ra) {
874 foreach ($allcontexts[$ra->contextid] as $id) {
875 $courses[$id]->managers[$ra->raid] = $ra;
876 if (!isset($checkenrolments[$id])) {
877 $checkenrolments[$id] = array();
879 $checkenrolments[$id][] = $ra->id;
882 $rs->close();
884 // Remove from course contacts users who are not enrolled in the course.
885 $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
886 foreach ($checkenrolments as $id => $userids) {
887 if (empty($enrolleduserids[$id])) {
888 $courses[$id]->managers = array();
889 } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
890 foreach ($courses[$id]->managers as $raid => $ra) {
891 if (in_array($ra->id, $notenrolled)) {
892 unset($courses[$id]->managers[$raid]);
898 // Set the cache.
899 $values = array();
900 foreach ($courseids as $id) {
901 $values[$id] = $courses[$id]->managers;
903 $cache->set_many($values);
907 * Verify user enrollments for multiple course-user combinations
909 * @param array $courseusers array where keys are course ids and values are array
910 * of users in this course whose enrolment we wish to verify
911 * @return array same structure as input array but values list only users from input
912 * who are enrolled in the course
914 protected static function ensure_users_enrolled($courseusers) {
915 global $DB;
916 // If the input array is too big, split it into chunks.
917 $maxcoursesinquery = 20;
918 if (count($courseusers) > $maxcoursesinquery) {
919 $rv = array();
920 for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
921 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
922 $rv = $rv + self::ensure_users_enrolled($chunk);
924 return $rv;
927 // Create a query verifying valid user enrolments for the number of courses.
928 $sql = "SELECT DISTINCT e.courseid, ue.userid
929 FROM {user_enrolments} ue
930 JOIN {enrol} e ON e.id = ue.enrolid
931 WHERE ue.status = :active
932 AND e.status = :enabled
933 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
934 $now = round(time(), -2); // Rounding helps caching in DB.
935 $params = array('enabled' => ENROL_INSTANCE_ENABLED,
936 'active' => ENROL_USER_ACTIVE,
937 'now1' => $now, 'now2' => $now);
938 $cnt = 0;
939 $subsqls = array();
940 $enrolled = array();
941 foreach ($courseusers as $id => $userids) {
942 $enrolled[$id] = array();
943 if (count($userids)) {
944 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
945 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
946 $params = $params + array('courseid'.$cnt => $id) + $params2;
947 $cnt++;
950 if (count($subsqls)) {
951 $sql .= "AND (". join(' OR ', $subsqls).")";
952 $rs = $DB->get_recordset_sql($sql, $params);
953 foreach ($rs as $record) {
954 $enrolled[$record->courseid][] = $record->userid;
956 $rs->close();
958 return $enrolled;
962 * Retrieves number of records from course table
964 * Not all fields are retrieved. Records are ready for preloading context
966 * @param string $whereclause
967 * @param array $params
968 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
969 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
970 * on not visible courses
971 * @return array array of stdClass objects
973 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
974 global $DB;
975 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
976 $fields = array('c.id', 'c.category', 'c.sortorder',
977 'c.shortname', 'c.fullname', 'c.idnumber',
978 'c.startdate', 'c.enddate', 'c.visible', 'c.cacherev');
979 if (!empty($options['summary'])) {
980 $fields[] = 'c.summary';
981 $fields[] = 'c.summaryformat';
982 } else {
983 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
985 $sql = "SELECT ". join(',', $fields). ", $ctxselect
986 FROM {course} c
987 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
988 WHERE ". $whereclause." ORDER BY c.sortorder";
989 $list = $DB->get_records_sql($sql,
990 array('contextcourse' => CONTEXT_COURSE) + $params);
992 if ($checkvisibility) {
993 // Loop through all records and make sure we only return the courses accessible by user.
994 foreach ($list as $course) {
995 if (isset($list[$course->id]->hassummary)) {
996 $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
998 if (empty($course->visible)) {
999 // Load context only if we need to check capability.
1000 context_helper::preload_from_record($course);
1001 if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1002 unset($list[$course->id]);
1008 // Preload course contacts if necessary.
1009 if (!empty($options['coursecontacts'])) {
1010 self::preload_course_contacts($list);
1012 return $list;
1016 * Returns array of ids of children categories that current user can not see
1018 * This data is cached in user session cache
1020 * @return array
1022 protected function get_not_visible_children_ids() {
1023 global $DB;
1024 $coursecatcache = cache::make('core', 'coursecat');
1025 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
1026 // We never checked visible children before.
1027 $hidden = self::get_tree($this->id.'i');
1028 $invisibleids = array();
1029 if ($hidden) {
1030 // Preload categories contexts.
1031 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
1032 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1033 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
1034 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
1035 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
1036 foreach ($contexts as $record) {
1037 context_helper::preload_from_record($record);
1039 // Check that user has 'viewhiddencategories' capability for each hidden category.
1040 foreach ($hidden as $id) {
1041 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
1042 $invisibleids[] = $id;
1046 $coursecatcache->set('ic'. $this->id, $invisibleids);
1048 return $invisibleids;
1052 * Sorts list of records by several fields
1054 * @param array $records array of stdClass objects
1055 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
1056 * @return int
1058 protected static function sort_records(&$records, $sortfields) {
1059 if (empty($records)) {
1060 return;
1062 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname).
1063 if (array_key_exists('displayname', $sortfields)) {
1064 foreach ($records as $key => $record) {
1065 if (!isset($record->displayname)) {
1066 $records[$key]->displayname = get_course_display_name_for_list($record);
1070 // Sorting by one field - use core_collator.
1071 if (count($sortfields) == 1) {
1072 $property = key($sortfields);
1073 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
1074 $sortflag = core_collator::SORT_NUMERIC;
1075 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
1076 $sortflag = core_collator::SORT_STRING;
1077 } else {
1078 $sortflag = core_collator::SORT_REGULAR;
1080 core_collator::asort_objects_by_property($records, $property, $sortflag);
1081 if ($sortfields[$property] < 0) {
1082 $records = array_reverse($records, true);
1084 return;
1086 $records = coursecat_sortable_records::sort($records, $sortfields);
1090 * Returns array of children categories visible to the current user
1092 * @param array $options options for retrieving children
1093 * - sort - list of fields to sort. Example
1094 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
1095 * will sort by idnumber asc, name asc and id desc.
1096 * Default: array('sortorder' => 1)
1097 * Only cached fields may be used for sorting!
1098 * - offset
1099 * - limit - maximum number of children to return, 0 or null for no limit
1100 * @return coursecat[] Array of coursecat objects indexed by category id
1102 public function get_children($options = array()) {
1103 global $DB;
1104 $coursecatcache = cache::make('core', 'coursecat');
1106 // Get default values for options.
1107 if (!empty($options['sort']) && is_array($options['sort'])) {
1108 $sortfields = $options['sort'];
1109 } else {
1110 $sortfields = array('sortorder' => 1);
1112 $limit = null;
1113 if (!empty($options['limit']) && (int)$options['limit']) {
1114 $limit = (int)$options['limit'];
1116 $offset = 0;
1117 if (!empty($options['offset']) && (int)$options['offset']) {
1118 $offset = (int)$options['offset'];
1121 // First retrieve list of user-visible and sorted children ids from cache.
1122 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
1123 if ($sortedids === false) {
1124 $sortfieldskeys = array_keys($sortfields);
1125 if ($sortfieldskeys[0] === 'sortorder') {
1126 // No DB requests required to build the list of ids sorted by sortorder.
1127 // We can easily ignore other sort fields because sortorder is always different.
1128 $sortedids = self::get_tree($this->id);
1129 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
1130 $sortedids = array_diff($sortedids, $invisibleids);
1131 if ($sortfields['sortorder'] == -1) {
1132 $sortedids = array_reverse($sortedids, true);
1135 } else {
1136 // We need to retrieve and sort all children. Good thing that it is done only on first request.
1137 if ($invisibleids = $this->get_not_visible_children_ids()) {
1138 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
1139 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
1140 array('parent' => $this->id) + $params);
1141 } else {
1142 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
1144 self::sort_records($records, $sortfields);
1145 $sortedids = array_keys($records);
1147 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
1150 if (empty($sortedids)) {
1151 return array();
1154 // Now retrieive and return categories.
1155 if ($offset || $limit) {
1156 $sortedids = array_slice($sortedids, $offset, $limit);
1158 if (isset($records)) {
1159 // Easy, we have already retrieved records.
1160 if ($offset || $limit) {
1161 $records = array_slice($records, $offset, $limit, true);
1163 } else {
1164 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
1165 $records = self::get_records('cc.id '. $sql, array('parent' => $this->id) + $params);
1168 $rv = array();
1169 foreach ($sortedids as $id) {
1170 if (isset($records[$id])) {
1171 $rv[$id] = new coursecat($records[$id]);
1174 return $rv;
1178 * Returns an array of ids of categories that are (direct and indirect) children
1179 * of this category.
1181 * @return int[]
1183 public function get_all_children_ids() {
1184 $children = [];
1185 $walk = [$this->id];
1186 while (count($walk) > 0) {
1187 $catid = array_pop($walk);
1188 $directchildren = self::get_tree($catid);
1189 if ($directchildren !== false && count($directchildren) > 0) {
1190 $walk = array_merge($walk, $directchildren);
1191 $children = array_merge($children, $directchildren);
1195 return $children;
1199 * Returns true if the user has the manage capability on any category.
1201 * This method uses the coursecat cache and an entry `has_manage_capability` to speed up
1202 * calls to this method.
1204 * @return bool
1206 public static function has_manage_capability_on_any() {
1207 return self::has_capability_on_any('moodle/category:manage');
1211 * Checks if the user has at least one of the given capabilities on any category.
1213 * @param array|string $capabilities One or more capabilities to check. Check made is an OR.
1214 * @return bool
1216 public static function has_capability_on_any($capabilities) {
1217 global $DB;
1218 if (!isloggedin() || isguestuser()) {
1219 return false;
1222 if (!is_array($capabilities)) {
1223 $capabilities = array($capabilities);
1225 $keys = array();
1226 foreach ($capabilities as $capability) {
1227 $keys[$capability] = sha1($capability);
1230 /* @var cache_session $cache */
1231 $cache = cache::make('core', 'coursecat');
1232 $hascapability = $cache->get_many($keys);
1233 $needtoload = false;
1234 foreach ($hascapability as $capability) {
1235 if ($capability === '1') {
1236 return true;
1237 } else if ($capability === false) {
1238 $needtoload = true;
1241 if ($needtoload === false) {
1242 // All capabilities were retrieved and the user didn't have any.
1243 return false;
1246 $haskey = null;
1247 $fields = context_helper::get_preload_record_columns_sql('ctx');
1248 $sql = "SELECT ctx.instanceid AS categoryid, $fields
1249 FROM {context} ctx
1250 WHERE contextlevel = :contextlevel
1251 ORDER BY depth ASC";
1252 $params = array('contextlevel' => CONTEXT_COURSECAT);
1253 $recordset = $DB->get_recordset_sql($sql, $params);
1254 foreach ($recordset as $context) {
1255 context_helper::preload_from_record($context);
1256 $context = context_coursecat::instance($context->categoryid);
1257 foreach ($capabilities as $capability) {
1258 if (has_capability($capability, $context)) {
1259 $haskey = $capability;
1260 break 2;
1264 $recordset->close();
1265 if ($haskey === null) {
1266 $data = array();
1267 foreach ($keys as $key) {
1268 $data[$key] = '0';
1270 $cache->set_many($data);
1271 return false;
1272 } else {
1273 $cache->set($haskey, '1');
1274 return true;
1279 * Returns true if the user can resort any category.
1280 * @return bool
1282 public static function can_resort_any() {
1283 return self::has_manage_capability_on_any();
1287 * Returns true if the user can change the parent of any category.
1288 * @return bool
1290 public static function can_change_parent_any() {
1291 return self::has_manage_capability_on_any();
1295 * Returns number of subcategories visible to the current user
1297 * @return int
1299 public function get_children_count() {
1300 $sortedids = self::get_tree($this->id);
1301 $invisibleids = $this->get_not_visible_children_ids();
1302 return count($sortedids) - count($invisibleids);
1306 * Returns true if the category has ANY children, including those not visible to the user
1308 * @return boolean
1310 public function has_children() {
1311 $allchildren = self::get_tree($this->id);
1312 return !empty($allchildren);
1316 * Returns true if the category has courses in it (count does not include courses
1317 * in child categories)
1319 * @return bool
1321 public function has_courses() {
1322 global $DB;
1323 return $DB->record_exists_sql("select 1 from {course} where category = ?",
1324 array($this->id));
1328 * Get the link used to view this course category.
1330 * @return \moodle_url
1332 public function get_view_link() {
1333 return new \moodle_url('/course/index.php', [
1334 'categoryid' => $this->id,
1339 * Searches courses
1341 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1342 * to this when somebody edits courses or categories, however it is very
1343 * difficult to keep track of all possible changes that may affect list of courses.
1345 * @param array $search contains search criterias, such as:
1346 * - search - search string
1347 * - blocklist - id of block (if we are searching for courses containing specific block0
1348 * - modulelist - name of module (if we are searching for courses containing specific module
1349 * - tagid - id of tag
1350 * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
1351 * search is always category-independent
1352 * @param array $requiredcapabilites List of capabilities required to see return course.
1353 * @return course_in_list[]
1355 public static function search_courses($search, $options = array(), $requiredcapabilities = array()) {
1356 global $DB;
1357 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1358 $limit = !empty($options['limit']) ? $options['limit'] : null;
1359 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1361 $coursecatcache = cache::make('core', 'coursecat');
1362 $cachekey = 's-'. serialize(
1363 $search + array('sort' => $sortfields) + array('requiredcapabilities' => $requiredcapabilities)
1365 $cntcachekey = 'scnt-'. serialize($search);
1367 $ids = $coursecatcache->get($cachekey);
1368 if ($ids !== false) {
1369 // We already cached last search result.
1370 $ids = array_slice($ids, $offset, $limit);
1371 $courses = array();
1372 if (!empty($ids)) {
1373 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1374 $records = self::get_course_records("c.id ". $sql, $params, $options);
1375 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1376 if (!empty($options['coursecontacts'])) {
1377 self::preload_course_contacts($records);
1379 // If option 'idonly' is specified no further action is needed, just return list of ids.
1380 if (!empty($options['idonly'])) {
1381 return array_keys($records);
1383 // Prepare the list of course_in_list objects.
1384 foreach ($ids as $id) {
1385 $courses[$id] = new course_in_list($records[$id]);
1388 return $courses;
1391 $preloadcoursecontacts = !empty($options['coursecontacts']);
1392 unset($options['coursecontacts']);
1394 // Empty search string will return all results.
1395 if (!isset($search['search'])) {
1396 $search['search'] = '';
1399 if (empty($search['blocklist']) && empty($search['modulelist']) && empty($search['tagid'])) {
1400 // Search courses that have specified words in their names/summaries.
1401 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1403 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount, $requiredcapabilities);
1404 self::sort_records($courselist, $sortfields);
1405 $coursecatcache->set($cachekey, array_keys($courselist));
1406 $coursecatcache->set($cntcachekey, $totalcount);
1407 $records = array_slice($courselist, $offset, $limit, true);
1408 } else {
1409 if (!empty($search['blocklist'])) {
1410 // Search courses that have block with specified id.
1411 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1412 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1413 WHERE bi.blockname = :blockname)';
1414 $params = array('blockname' => $blockname);
1415 } else if (!empty($search['modulelist'])) {
1416 // Search courses that have module with specified name.
1417 $where = "c.id IN (SELECT DISTINCT module.course ".
1418 "FROM {".$search['modulelist']."} module)";
1419 $params = array();
1420 } else if (!empty($search['tagid'])) {
1421 // Search courses that are tagged with the specified tag.
1422 $where = "c.id IN (SELECT t.itemid ".
1423 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype AND t.component = :component)";
1424 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course', 'component' => 'core');
1425 if (!empty($search['ctx'])) {
1426 $rec = isset($search['rec']) ? $search['rec'] : true;
1427 $parentcontext = context::instance_by_id($search['ctx']);
1428 if ($parentcontext->contextlevel == CONTEXT_SYSTEM && $rec) {
1429 // Parent context is system context and recursive is set to yes.
1430 // Nothing to filter - all courses fall into this condition.
1431 } else if ($rec) {
1432 // Filter all courses in the parent context at any level.
1433 $where .= ' AND ctx.path LIKE :contextpath';
1434 $params['contextpath'] = $parentcontext->path . '%';
1435 } else if ($parentcontext->contextlevel == CONTEXT_COURSECAT) {
1436 // All courses in the given course category.
1437 $where .= ' AND c.category = :category';
1438 $params['category'] = $parentcontext->instanceid;
1439 } else {
1440 // No courses will satisfy the context criterion, do not bother searching.
1441 $where = '1=0';
1444 } else {
1445 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1446 return array();
1448 $courselist = self::get_course_records($where, $params, $options, true);
1449 if (!empty($requiredcapabilities)) {
1450 foreach ($courselist as $key => $course) {
1451 context_helper::preload_from_record($course);
1452 $coursecontext = context_course::instance($course->id);
1453 if (!has_all_capabilities($requiredcapabilities, $coursecontext)) {
1454 unset($courselist[$key]);
1458 self::sort_records($courselist, $sortfields);
1459 $coursecatcache->set($cachekey, array_keys($courselist));
1460 $coursecatcache->set($cntcachekey, count($courselist));
1461 $records = array_slice($courselist, $offset, $limit, true);
1464 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1465 if (!empty($preloadcoursecontacts)) {
1466 self::preload_course_contacts($records);
1468 // If option 'idonly' is specified no further action is needed, just return list of ids.
1469 if (!empty($options['idonly'])) {
1470 return array_keys($records);
1472 // Prepare the list of course_in_list objects.
1473 $courses = array();
1474 foreach ($records as $record) {
1475 $courses[$record->id] = new course_in_list($record);
1477 return $courses;
1481 * Returns number of courses in the search results
1483 * It is recommended to call this function after {@link coursecat::search_courses()}
1484 * and not before because only course ids are cached. Otherwise search_courses() may
1485 * perform extra DB queries.
1487 * @param array $search search criteria, see method search_courses() for more details
1488 * @param array $options display options. They do not affect the result but
1489 * the 'sort' property is used in cache key for storing list of course ids
1490 * @param array $requiredcapabilites List of capabilities required to see return course.
1491 * @return int
1493 public static function search_courses_count($search, $options = array(), $requiredcapabilities = array()) {
1494 $coursecatcache = cache::make('core', 'coursecat');
1495 $cntcachekey = 'scnt-'. serialize($search) . serialize($requiredcapabilities);
1496 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1497 // Cached value not found. Retrieve ALL courses and return their count.
1498 unset($options['offset']);
1499 unset($options['limit']);
1500 unset($options['summary']);
1501 unset($options['coursecontacts']);
1502 $options['idonly'] = true;
1503 $courses = self::search_courses($search, $options, $requiredcapabilities);
1504 $cnt = count($courses);
1506 return $cnt;
1510 * Retrieves the list of courses accessible by user
1512 * Not all information is cached, try to avoid calling this method
1513 * twice in the same request.
1515 * The following fields are always retrieved:
1516 * - id, visible, fullname, shortname, idnumber, category, sortorder
1518 * If you plan to use properties/methods course_in_list::$summary and/or
1519 * course_in_list::get_course_contacts()
1520 * you can preload this information using appropriate 'options'. Otherwise
1521 * they will be retrieved from DB on demand and it may end with bigger DB load.
1523 * Note that method course_in_list::has_summary() will not perform additional
1524 * DB queries even if $options['summary'] is not specified
1526 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1527 * to this when somebody edits courses or categories, however it is very
1528 * difficult to keep track of all possible changes that may affect list of courses.
1530 * @param array $options options for retrieving children
1531 * - recursive - return courses from subcategories as well. Use with care,
1532 * this may be a huge list!
1533 * - summary - preloads fields 'summary' and 'summaryformat'
1534 * - coursecontacts - preloads course contacts
1535 * - sort - list of fields to sort. Example
1536 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1537 * will sort by idnumber asc, shortname asc and id desc.
1538 * Default: array('sortorder' => 1)
1539 * Only cached fields may be used for sorting!
1540 * - offset
1541 * - limit - maximum number of children to return, 0 or null for no limit
1542 * - idonly - returns the array or course ids instead of array of objects
1543 * used only in get_courses_count()
1544 * @return course_in_list[]
1546 public function get_courses($options = array()) {
1547 global $DB;
1548 $recursive = !empty($options['recursive']);
1549 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1550 $limit = !empty($options['limit']) ? $options['limit'] : null;
1551 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1553 // Check if this category is hidden.
1554 // Also 0-category never has courses unless this is recursive call.
1555 if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1556 return array();
1559 $coursecatcache = cache::make('core', 'coursecat');
1560 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1561 '-'. serialize($sortfields);
1562 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1564 // Check if we have already cached results.
1565 $ids = $coursecatcache->get($cachekey);
1566 if ($ids !== false) {
1567 // We already cached last search result and it did not expire yet.
1568 $ids = array_slice($ids, $offset, $limit);
1569 $courses = array();
1570 if (!empty($ids)) {
1571 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1572 $records = self::get_course_records("c.id ". $sql, $params, $options);
1573 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1574 if (!empty($options['coursecontacts'])) {
1575 self::preload_course_contacts($records);
1577 // If option 'idonly' is specified no further action is needed, just return list of ids.
1578 if (!empty($options['idonly'])) {
1579 return array_keys($records);
1581 // Prepare the list of course_in_list objects.
1582 foreach ($ids as $id) {
1583 $courses[$id] = new course_in_list($records[$id]);
1586 return $courses;
1589 // Retrieve list of courses in category.
1590 $where = 'c.id <> :siteid';
1591 $params = array('siteid' => SITEID);
1592 if ($recursive) {
1593 if ($this->id) {
1594 $context = context_coursecat::instance($this->id);
1595 $where .= ' AND ctx.path like :path';
1596 $params['path'] = $context->path. '/%';
1598 } else {
1599 $where .= ' AND c.category = :categoryid';
1600 $params['categoryid'] = $this->id;
1602 // Get list of courses without preloaded coursecontacts because we don't need them for every course.
1603 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1605 // Sort and cache list.
1606 self::sort_records($list, $sortfields);
1607 $coursecatcache->set($cachekey, array_keys($list));
1608 $coursecatcache->set($cntcachekey, count($list));
1610 // Apply offset/limit, convert to course_in_list and return.
1611 $courses = array();
1612 if (isset($list)) {
1613 if ($offset || $limit) {
1614 $list = array_slice($list, $offset, $limit, true);
1616 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1617 if (!empty($options['coursecontacts'])) {
1618 self::preload_course_contacts($list);
1620 // If option 'idonly' is specified no further action is needed, just return list of ids.
1621 if (!empty($options['idonly'])) {
1622 return array_keys($list);
1624 // Prepare the list of course_in_list objects.
1625 foreach ($list as $record) {
1626 $courses[$record->id] = new course_in_list($record);
1629 return $courses;
1633 * Returns number of courses visible to the user
1635 * @param array $options similar to get_courses() except some options do not affect
1636 * number of courses (i.e. sort, summary, offset, limit etc.)
1637 * @return int
1639 public function get_courses_count($options = array()) {
1640 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1641 $coursecatcache = cache::make('core', 'coursecat');
1642 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1643 // Cached value not found. Retrieve ALL courses and return their count.
1644 unset($options['offset']);
1645 unset($options['limit']);
1646 unset($options['summary']);
1647 unset($options['coursecontacts']);
1648 $options['idonly'] = true;
1649 $courses = $this->get_courses($options);
1650 $cnt = count($courses);
1652 return $cnt;
1656 * Returns true if the user is able to delete this category.
1658 * Note if this category contains any courses this isn't a full check, it will need to be accompanied by a call to either
1659 * {@link coursecat::can_delete_full()} or {@link coursecat::can_move_content_to()} depending upon what the user wished to do.
1661 * @return boolean
1663 public function can_delete() {
1664 if (!$this->has_manage_capability()) {
1665 return false;
1667 return $this->parent_has_manage_capability();
1671 * Returns true if user can delete current category and all its contents
1673 * To be able to delete course category the user must have permission
1674 * 'moodle/category:manage' in ALL child course categories AND
1675 * be able to delete all courses
1677 * @return bool
1679 public function can_delete_full() {
1680 global $DB;
1681 if (!$this->id) {
1682 // Fool-proof.
1683 return false;
1686 $context = $this->get_context();
1687 if (!$this->is_uservisible() ||
1688 !has_capability('moodle/category:manage', $context)) {
1689 return false;
1692 // Check all child categories (not only direct children).
1693 $sql = context_helper::get_preload_record_columns_sql('ctx');
1694 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1695 ' FROM {context} ctx '.
1696 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1697 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1698 array($context->path. '/%', CONTEXT_COURSECAT));
1699 foreach ($childcategories as $childcat) {
1700 context_helper::preload_from_record($childcat);
1701 $childcontext = context_coursecat::instance($childcat->id);
1702 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1703 !has_capability('moodle/category:manage', $childcontext)) {
1704 return false;
1708 // Check courses.
1709 $sql = context_helper::get_preload_record_columns_sql('ctx');
1710 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1711 $sql. ' FROM {context} ctx '.
1712 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1713 array('pathmask' => $context->path. '/%',
1714 'courselevel' => CONTEXT_COURSE));
1715 foreach ($coursescontexts as $ctxrecord) {
1716 context_helper::preload_from_record($ctxrecord);
1717 if (!can_delete_course($ctxrecord->courseid)) {
1718 return false;
1722 return true;
1726 * Recursively delete category including all subcategories and courses
1728 * Function {@link coursecat::can_delete_full()} MUST be called prior
1729 * to calling this function because there is no capability check
1730 * inside this function
1732 * @param boolean $showfeedback display some notices
1733 * @return array return deleted courses
1734 * @throws moodle_exception
1736 public function delete_full($showfeedback = true) {
1737 global $CFG, $DB;
1739 require_once($CFG->libdir.'/gradelib.php');
1740 require_once($CFG->libdir.'/questionlib.php');
1741 require_once($CFG->dirroot.'/cohort/lib.php');
1743 // Make sure we won't timeout when deleting a lot of courses.
1744 $settimeout = core_php_time_limit::raise();
1746 // Allow plugins to use this category before we completely delete it.
1747 if ($pluginsfunction = get_plugins_with_function('pre_course_category_delete')) {
1748 $category = $this->get_db_record();
1749 foreach ($pluginsfunction as $plugintype => $plugins) {
1750 foreach ($plugins as $pluginfunction) {
1751 $pluginfunction($category);
1756 $deletedcourses = array();
1758 // Get children. Note, we don't want to use cache here because it would be rebuilt too often.
1759 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1760 foreach ($children as $record) {
1761 $coursecat = new coursecat($record);
1762 $deletedcourses += $coursecat->delete_full($showfeedback);
1765 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1766 foreach ($courses as $course) {
1767 if (!delete_course($course, false)) {
1768 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1770 $deletedcourses[] = $course;
1774 // Move or delete cohorts in this context.
1775 cohort_delete_category($this);
1777 // Now delete anything that may depend on course category context.
1778 grade_course_category_delete($this->id, 0, $showfeedback);
1779 if (!question_delete_course_category($this, 0, $showfeedback)) {
1780 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1783 // Delete all events in the category.
1784 $DB->delete_records('event', array('categoryid' => $this->id));
1786 // Finally delete the category and it's context.
1787 $DB->delete_records('course_categories', array('id' => $this->id));
1789 $coursecatcontext = context_coursecat::instance($this->id);
1790 $coursecatcontext->delete();
1792 cache_helper::purge_by_event('changesincoursecat');
1794 // Trigger a course category deleted event.
1795 /* @var \core\event\course_category_deleted $event */
1796 $event = \core\event\course_category_deleted::create(array(
1797 'objectid' => $this->id,
1798 'context' => $coursecatcontext,
1799 'other' => array('name' => $this->name)
1801 $event->set_coursecat($this);
1802 $event->trigger();
1804 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1805 if ($this->id == $CFG->defaultrequestcategory) {
1806 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1808 return $deletedcourses;
1812 * Checks if user can delete this category and move content (courses, subcategories and questions)
1813 * to another category. If yes returns the array of possible target categories names
1815 * If user can not manage this category or it is completely empty - empty array will be returned
1817 * @return array
1819 public function move_content_targets_list() {
1820 global $CFG;
1821 require_once($CFG->libdir . '/questionlib.php');
1822 $context = $this->get_context();
1823 if (!$this->is_uservisible() ||
1824 !has_capability('moodle/category:manage', $context)) {
1825 // User is not able to manage current category, he is not able to delete it.
1826 // No possible target categories.
1827 return array();
1830 $testcaps = array();
1831 // If this category has courses in it, user must have 'course:create' capability in target category.
1832 if ($this->has_courses()) {
1833 $testcaps[] = 'moodle/course:create';
1835 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1836 if ($this->has_children() || question_context_has_any_questions($context)) {
1837 $testcaps[] = 'moodle/category:manage';
1839 if (!empty($testcaps)) {
1840 // Return list of categories excluding this one and it's children.
1841 return self::make_categories_list($testcaps, $this->id);
1844 // Category is completely empty, no need in target for contents.
1845 return array();
1849 * Checks if user has capability to move all category content to the new parent before
1850 * removing this category
1852 * @param int $newcatid
1853 * @return bool
1855 public function can_move_content_to($newcatid) {
1856 global $CFG;
1857 require_once($CFG->libdir . '/questionlib.php');
1858 $context = $this->get_context();
1859 if (!$this->is_uservisible() ||
1860 !has_capability('moodle/category:manage', $context)) {
1861 return false;
1863 $testcaps = array();
1864 // If this category has courses in it, user must have 'course:create' capability in target category.
1865 if ($this->has_courses()) {
1866 $testcaps[] = 'moodle/course:create';
1868 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1869 if ($this->has_children() || question_context_has_any_questions($context)) {
1870 $testcaps[] = 'moodle/category:manage';
1872 if (!empty($testcaps)) {
1873 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1876 // There is no content but still return true.
1877 return true;
1881 * Deletes a category and moves all content (children, courses and questions) to the new parent
1883 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1884 * must be called prior
1886 * @param int $newparentid
1887 * @param bool $showfeedback
1888 * @return bool
1890 public function delete_move($newparentid, $showfeedback = false) {
1891 global $CFG, $DB, $OUTPUT;
1893 require_once($CFG->libdir.'/gradelib.php');
1894 require_once($CFG->libdir.'/questionlib.php');
1895 require_once($CFG->dirroot.'/cohort/lib.php');
1897 // Get all objects and lists because later the caches will be reset so.
1898 // We don't need to make extra queries.
1899 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1900 $catname = $this->get_formatted_name();
1901 $children = $this->get_children();
1902 $params = array('category' => $this->id);
1903 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', $params);
1904 $context = $this->get_context();
1906 if ($children) {
1907 foreach ($children as $childcat) {
1908 $childcat->change_parent_raw($newparentcat);
1909 // Log action.
1910 $event = \core\event\course_category_updated::create(array(
1911 'objectid' => $childcat->id,
1912 'context' => $childcat->get_context()
1914 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $childcat->id,
1915 $childcat->id));
1916 $event->trigger();
1918 fix_course_sortorder();
1921 if ($coursesids) {
1922 require_once($CFG->dirroot.'/course/lib.php');
1923 if (!move_courses($coursesids, $newparentid)) {
1924 if ($showfeedback) {
1925 echo $OUTPUT->notification("Error moving courses");
1927 return false;
1929 if ($showfeedback) {
1930 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1934 // Move or delete cohorts in this context.
1935 cohort_delete_category($this);
1937 // Now delete anything that may depend on course category context.
1938 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1939 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1940 if ($showfeedback) {
1941 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1943 return false;
1946 // Finally delete the category and it's context.
1947 $DB->delete_records('course_categories', array('id' => $this->id));
1948 $context->delete();
1950 // Trigger a course category deleted event.
1951 /* @var \core\event\course_category_deleted $event */
1952 $event = \core\event\course_category_deleted::create(array(
1953 'objectid' => $this->id,
1954 'context' => $context,
1955 'other' => array('name' => $this->name)
1957 $event->set_coursecat($this);
1958 $event->trigger();
1960 cache_helper::purge_by_event('changesincoursecat');
1962 if ($showfeedback) {
1963 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1966 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1967 if ($this->id == $CFG->defaultrequestcategory) {
1968 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1970 return true;
1974 * Checks if user can move current category to the new parent
1976 * This checks if new parent category exists, user has manage cap there
1977 * and new parent is not a child of this category
1979 * @param int|stdClass|coursecat $newparentcat
1980 * @return bool
1982 public function can_change_parent($newparentcat) {
1983 if (!has_capability('moodle/category:manage', $this->get_context())) {
1984 return false;
1986 if (is_object($newparentcat)) {
1987 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1988 } else {
1989 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1991 if (!$newparentcat) {
1992 return false;
1994 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1995 // Can not move to itself or it's own child.
1996 return false;
1998 if ($newparentcat->id) {
1999 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
2000 } else {
2001 return has_capability('moodle/category:manage', context_system::instance());
2006 * Moves the category under another parent category. All associated contexts are moved as well
2008 * This is protected function, use change_parent() or update() from outside of this class
2010 * @see coursecat::change_parent()
2011 * @see coursecat::update()
2013 * @param coursecat $newparentcat
2014 * @throws moodle_exception
2016 protected function change_parent_raw(coursecat $newparentcat) {
2017 global $DB;
2019 $context = $this->get_context();
2021 $hidecat = false;
2022 if (empty($newparentcat->id)) {
2023 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
2024 $newparent = context_system::instance();
2025 } else {
2026 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
2027 // Can not move to itself or it's own child.
2028 throw new moodle_exception('cannotmovecategory');
2030 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
2031 $newparent = context_coursecat::instance($newparentcat->id);
2033 if (!$newparentcat->visible and $this->visible) {
2034 // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children
2035 // will be restored properly.
2036 $hidecat = true;
2039 $this->parent = $newparentcat->id;
2041 $context->update_moved($newparent);
2043 // Now make it last in new category.
2044 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
2046 if ($hidecat) {
2047 fix_course_sortorder();
2048 $this->restore();
2049 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must
2050 // become visible again.
2051 $this->hide_raw(1);
2056 * Efficiently moves a category - NOTE that this can have
2057 * a huge impact access-control-wise...
2059 * Note that this function does not check capabilities.
2061 * Example of usage:
2062 * $coursecat = coursecat::get($categoryid);
2063 * if ($coursecat->can_change_parent($newparentcatid)) {
2064 * $coursecat->change_parent($newparentcatid);
2067 * This function does not update field course_categories.timemodified
2068 * If you want to update timemodified, use
2069 * $coursecat->update(array('parent' => $newparentcat));
2071 * @param int|stdClass|coursecat $newparentcat
2073 public function change_parent($newparentcat) {
2074 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
2075 if (is_object($newparentcat)) {
2076 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
2077 } else {
2078 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
2080 if ($newparentcat->id != $this->parent) {
2081 $this->change_parent_raw($newparentcat);
2082 fix_course_sortorder();
2083 cache_helper::purge_by_event('changesincoursecat');
2084 $this->restore();
2086 $event = \core\event\course_category_updated::create(array(
2087 'objectid' => $this->id,
2088 'context' => $this->get_context()
2090 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $this->id, $this->id));
2091 $event->trigger();
2096 * Hide course category and child course and subcategories
2098 * If this category has changed the parent and is moved under hidden
2099 * category we will want to store it's current visibility state in
2100 * the field 'visibleold'. If admin clicked 'hide' for this particular
2101 * category, the field 'visibleold' should become 0.
2103 * All subcategories and courses will have their current visibility in the field visibleold
2105 * This is protected function, use hide() or update() from outside of this class
2107 * @see coursecat::hide()
2108 * @see coursecat::update()
2110 * @param int $visibleold value to set in field $visibleold for this category
2111 * @return bool whether changes have been made and caches need to be purged afterwards
2113 protected function hide_raw($visibleold = 0) {
2114 global $DB;
2115 $changes = false;
2117 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing.
2118 if ($this->id && $this->__get('visibleold') != $visibleold) {
2119 $this->visibleold = $visibleold;
2120 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
2121 $changes = true;
2123 if (!$this->visible || !$this->id) {
2124 // Already hidden or can not be hidden.
2125 return $changes;
2128 $this->visible = 0;
2129 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
2130 // Store visible flag so that we can return to it if we immediately unhide.
2131 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id));
2132 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
2133 // Get all child categories and hide too.
2134 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
2135 foreach ($subcats as $cat) {
2136 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
2137 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
2138 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
2139 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
2142 return true;
2146 * Hide course category and child course and subcategories
2148 * Note that there is no capability check inside this function
2150 * This function does not update field course_categories.timemodified
2151 * If you want to update timemodified, use
2152 * $coursecat->update(array('visible' => 0));
2154 public function hide() {
2155 if ($this->hide_raw(0)) {
2156 cache_helper::purge_by_event('changesincoursecat');
2158 $event = \core\event\course_category_updated::create(array(
2159 'objectid' => $this->id,
2160 'context' => $this->get_context()
2162 $event->set_legacy_logdata(array(SITEID, 'category', 'hide', 'editcategory.php?id=' . $this->id, $this->id));
2163 $event->trigger();
2168 * Show course category and restores visibility for child course and subcategories
2170 * Note that there is no capability check inside this function
2172 * This is protected function, use show() or update() from outside of this class
2174 * @see coursecat::show()
2175 * @see coursecat::update()
2177 * @return bool whether changes have been made and caches need to be purged afterwards
2179 protected function show_raw() {
2180 global $DB;
2182 if ($this->visible) {
2183 // Already visible.
2184 return false;
2187 $this->visible = 1;
2188 $this->visibleold = 1;
2189 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
2190 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
2191 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
2192 // Get all child categories and unhide too.
2193 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
2194 foreach ($subcats as $cat) {
2195 if ($cat->visibleold) {
2196 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
2198 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
2201 return true;
2205 * Show course category and restores visibility for child course and subcategories
2207 * Note that there is no capability check inside this function
2209 * This function does not update field course_categories.timemodified
2210 * If you want to update timemodified, use
2211 * $coursecat->update(array('visible' => 1));
2213 public function show() {
2214 if ($this->show_raw()) {
2215 cache_helper::purge_by_event('changesincoursecat');
2217 $event = \core\event\course_category_updated::create(array(
2218 'objectid' => $this->id,
2219 'context' => $this->get_context()
2221 $event->set_legacy_logdata(array(SITEID, 'category', 'show', 'editcategory.php?id=' . $this->id, $this->id));
2222 $event->trigger();
2227 * Returns name of the category formatted as a string
2229 * @param array $options formatting options other than context
2230 * @return string
2232 public function get_formatted_name($options = array()) {
2233 if ($this->id) {
2234 $context = $this->get_context();
2235 return format_string($this->name, true, array('context' => $context) + $options);
2236 } else {
2237 return get_string('top');
2242 * Get the nested name of this category, with all of it's parents.
2244 * @param bool $includelinks Whether to wrap each name in the view link for that category.
2245 * @param string $separator The string between each name.
2246 * @param array $options Formatting options.
2247 * @return string
2249 public function get_nested_name($includelinks = true, $separator = ' / ', $options = []) {
2250 // Get the name of hierarchical name of this category.
2251 $parents = $this->get_parents();
2252 $categories = static::get_many($parents);
2253 $categories[] = $this;
2255 $names = array_map(function($category) use ($options, $includelinks) {
2256 if ($includelinks) {
2257 return html_writer::link($category->get_view_link(), $category->get_formatted_name($options));
2258 } else {
2259 return $category->get_formatted_name($options);
2262 }, $categories);
2264 return implode($separator, $names);
2268 * Returns ids of all parents of the category. Last element in the return array is the direct parent
2270 * For example, if you have a tree of categories like:
2271 * Miscellaneous (id = 1)
2272 * Subcategory (id = 2)
2273 * Sub-subcategory (id = 4)
2274 * Other category (id = 3)
2276 * coursecat::get(1)->get_parents() == array()
2277 * coursecat::get(2)->get_parents() == array(1)
2278 * coursecat::get(4)->get_parents() == array(1, 2);
2280 * Note that this method does not check if all parents are accessible by current user
2282 * @return array of category ids
2284 public function get_parents() {
2285 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
2286 array_pop($parents);
2287 return $parents;
2291 * This function returns a nice list representing category tree
2292 * for display or to use in a form <select> element
2294 * List is cached for 10 minutes
2296 * For example, if you have a tree of categories like:
2297 * Miscellaneous (id = 1)
2298 * Subcategory (id = 2)
2299 * Sub-subcategory (id = 4)
2300 * Other category (id = 3)
2301 * Then after calling this function you will have
2302 * array(1 => 'Miscellaneous',
2303 * 2 => 'Miscellaneous / Subcategory',
2304 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2305 * 3 => 'Other category');
2307 * If you specify $requiredcapability, then only categories where the current
2308 * user has that capability will be added to $list.
2309 * If you only have $requiredcapability in a child category, not the parent,
2310 * then the child catgegory will still be included.
2312 * If you specify the option $excludeid, then that category, and all its children,
2313 * are omitted from the tree. This is useful when you are doing something like
2314 * moving categories, where you do not want to allow people to move a category
2315 * to be the child of itself.
2317 * See also {@link make_categories_options()}
2319 * @param string/array $requiredcapability if given, only categories where the current
2320 * user has this capability will be returned. Can also be an array of capabilities,
2321 * in which case they are all required.
2322 * @param integer $excludeid Exclude this category and its children from the lists built.
2323 * @param string $separator string to use as a separator between parent and child category. Default ' / '
2324 * @return array of strings
2326 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
2327 global $DB;
2328 $coursecatcache = cache::make('core', 'coursecat');
2330 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids
2331 // with requried cap ($thislist).
2332 $currentlang = current_language();
2333 $basecachekey = $currentlang . '_catlist';
2334 $baselist = $coursecatcache->get($basecachekey);
2335 $thislist = false;
2336 $thiscachekey = null;
2337 if (!empty($requiredcapability)) {
2338 $requiredcapability = (array)$requiredcapability;
2339 $thiscachekey = 'catlist:'. serialize($requiredcapability);
2340 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
2341 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
2343 } else if ($baselist !== false) {
2344 $thislist = array_keys($baselist);
2347 if ($baselist === false) {
2348 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
2349 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2350 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
2351 FROM {course_categories} cc
2352 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
2353 ORDER BY cc.sortorder";
2354 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2355 $baselist = array();
2356 $thislist = array();
2357 foreach ($rs as $record) {
2358 // If the category's parent is not visible to the user, it is not visible as well.
2359 if (!$record->parent || isset($baselist[$record->parent])) {
2360 context_helper::preload_from_record($record);
2361 $context = context_coursecat::instance($record->id);
2362 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
2363 // No cap to view category, added to neither $baselist nor $thislist.
2364 continue;
2366 $baselist[$record->id] = array(
2367 'name' => format_string($record->name, true, array('context' => $context)),
2368 'path' => $record->path
2370 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
2371 // No required capability, added to $baselist but not to $thislist.
2372 continue;
2374 $thislist[] = $record->id;
2377 $rs->close();
2378 $coursecatcache->set($basecachekey, $baselist);
2379 if (!empty($requiredcapability)) {
2380 $coursecatcache->set($thiscachekey, join(',', $thislist));
2382 } else if ($thislist === false) {
2383 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
2384 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2385 $sql = "SELECT ctx.instanceid AS id, $ctxselect
2386 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
2387 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2388 $thislist = array();
2389 foreach (array_keys($baselist) as $id) {
2390 context_helper::preload_from_record($contexts[$id]);
2391 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
2392 $thislist[] = $id;
2395 $coursecatcache->set($thiscachekey, join(',', $thislist));
2398 // Now build the array of strings to return, mind $separator and $excludeid.
2399 $names = array();
2400 foreach ($thislist as $id) {
2401 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
2402 if (!$excludeid || !in_array($excludeid, $path)) {
2403 $namechunks = array();
2404 foreach ($path as $parentid) {
2405 $namechunks[] = $baselist[$parentid]['name'];
2407 $names[$id] = join($separator, $namechunks);
2410 return $names;
2414 * Prepares the object for caching. Works like the __sleep method.
2416 * implementing method from interface cacheable_object
2418 * @return array ready to be cached
2420 public function prepare_to_cache() {
2421 $a = array();
2422 foreach (self::$coursecatfields as $property => $cachedirectives) {
2423 if ($cachedirectives !== null) {
2424 list($shortname, $defaultvalue) = $cachedirectives;
2425 if ($this->$property !== $defaultvalue) {
2426 $a[$shortname] = $this->$property;
2430 $context = $this->get_context();
2431 $a['xi'] = $context->id;
2432 $a['xp'] = $context->path;
2433 return $a;
2437 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2439 * implementing method from interface cacheable_object
2441 * @param array $a
2442 * @return coursecat
2444 public static function wake_from_cache($a) {
2445 $record = new stdClass;
2446 foreach (self::$coursecatfields as $property => $cachedirectives) {
2447 if ($cachedirectives !== null) {
2448 list($shortname, $defaultvalue) = $cachedirectives;
2449 if (array_key_exists($shortname, $a)) {
2450 $record->$property = $a[$shortname];
2451 } else {
2452 $record->$property = $defaultvalue;
2456 $record->ctxid = $a['xi'];
2457 $record->ctxpath = $a['xp'];
2458 $record->ctxdepth = $record->depth + 1;
2459 $record->ctxlevel = CONTEXT_COURSECAT;
2460 $record->ctxinstance = $record->id;
2461 return new coursecat($record, true);
2465 * Returns true if the user is able to create a top level category.
2466 * @return bool
2468 public static function can_create_top_level_category() {
2469 return has_capability('moodle/category:manage', context_system::instance());
2473 * Returns the category context.
2474 * @return context_coursecat
2476 public function get_context() {
2477 if ($this->id === 0) {
2478 // This is the special top level category object.
2479 return context_system::instance();
2480 } else {
2481 return context_coursecat::instance($this->id);
2486 * Returns true if the user is able to manage this category.
2487 * @return bool
2489 public function has_manage_capability() {
2490 if ($this->hasmanagecapability === null) {
2491 $this->hasmanagecapability = has_capability('moodle/category:manage', $this->get_context());
2493 return $this->hasmanagecapability;
2497 * Returns true if the user has the manage capability on the parent category.
2498 * @return bool
2500 public function parent_has_manage_capability() {
2501 return has_capability('moodle/category:manage', get_category_or_system_context($this->parent));
2505 * Returns true if the current user can create subcategories of this category.
2506 * @return bool
2508 public function can_create_subcategory() {
2509 return $this->has_manage_capability();
2513 * Returns true if the user can resort this categories sub categories and courses.
2514 * Must have manage capability and be able to see all subcategories.
2515 * @return bool
2517 public function can_resort_subcategories() {
2518 return $this->has_manage_capability() && !$this->get_not_visible_children_ids();
2522 * Returns true if the user can resort the courses within this category.
2523 * Must have manage capability and be able to see all courses.
2524 * @return bool
2526 public function can_resort_courses() {
2527 return $this->has_manage_capability() && $this->coursecount == $this->get_courses_count();
2531 * Returns true of the user can change the sortorder of this category (resort in the parent category)
2532 * @return bool
2534 public function can_change_sortorder() {
2535 return $this->id && $this->get_parent_coursecat()->can_resort_subcategories();
2539 * Returns true if the current user can create a course within this category.
2540 * @return bool
2542 public function can_create_course() {
2543 return has_capability('moodle/course:create', $this->get_context());
2547 * Returns true if the current user can edit this categories settings.
2548 * @return bool
2550 public function can_edit() {
2551 return $this->has_manage_capability();
2555 * Returns true if the current user can review role assignments for this category.
2556 * @return bool
2558 public function can_review_roles() {
2559 return has_capability('moodle/role:assign', $this->get_context());
2563 * Returns true if the current user can review permissions for this category.
2564 * @return bool
2566 public function can_review_permissions() {
2567 return has_any_capability(array(
2568 'moodle/role:assign',
2569 'moodle/role:safeoverride',
2570 'moodle/role:override',
2571 'moodle/role:assign'
2572 ), $this->get_context());
2576 * Returns true if the current user can review cohorts for this category.
2577 * @return bool
2579 public function can_review_cohorts() {
2580 return has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->get_context());
2584 * Returns true if the current user can review filter settings for this category.
2585 * @return bool
2587 public function can_review_filters() {
2588 return has_capability('moodle/filter:manage', $this->get_context()) &&
2589 count(filter_get_available_in_context($this->get_context()))>0;
2593 * Returns true if the current user is able to change the visbility of this category.
2594 * @return bool
2596 public function can_change_visibility() {
2597 return $this->parent_has_manage_capability();
2601 * Returns true if the user can move courses out of this category.
2602 * @return bool
2604 public function can_move_courses_out_of() {
2605 return $this->has_manage_capability();
2609 * Returns true if the user can move courses into this category.
2610 * @return bool
2612 public function can_move_courses_into() {
2613 return $this->has_manage_capability();
2617 * Returns true if the user is able to restore a course into this category as a new course.
2618 * @return bool
2620 public function can_restore_courses_into() {
2621 return has_capability('moodle/restore:restorecourse', $this->get_context());
2625 * Resorts the sub categories of this category by the given field.
2627 * @param string $field One of name, idnumber or descending values of each (appended desc)
2628 * @param bool $cleanup If true cleanup will be done, if false you will need to do it manually later.
2629 * @return bool True on success.
2630 * @throws coding_exception
2632 public function resort_subcategories($field, $cleanup = true) {
2633 global $DB;
2634 $desc = false;
2635 if (substr($field, -4) === "desc") {
2636 $desc = true;
2637 $field = substr($field, 0, -4); // Remove "desc" from field name.
2639 if ($field !== 'name' && $field !== 'idnumber') {
2640 throw new coding_exception('Invalid field requested');
2642 $children = $this->get_children();
2643 core_collator::asort_objects_by_property($children, $field, core_collator::SORT_NATURAL);
2644 if (!empty($desc)) {
2645 $children = array_reverse($children);
2647 $i = 1;
2648 foreach ($children as $cat) {
2649 $i++;
2650 $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id));
2651 $i += $cat->coursecount;
2653 if ($cleanup) {
2654 self::resort_categories_cleanup();
2656 return true;
2660 * Cleans things up after categories have been resorted.
2661 * @param bool $includecourses If set to true we know courses have been resorted as well.
2663 public static function resort_categories_cleanup($includecourses = false) {
2664 // This should not be needed but we do it just to be safe.
2665 fix_course_sortorder();
2666 cache_helper::purge_by_event('changesincoursecat');
2667 if ($includecourses) {
2668 cache_helper::purge_by_event('changesincourse');
2673 * Resort the courses within this category by the given field.
2675 * @param string $field One of fullname, shortname, idnumber or descending values of each (appended desc)
2676 * @param bool $cleanup
2677 * @return bool True for success.
2678 * @throws coding_exception
2680 public function resort_courses($field, $cleanup = true) {
2681 global $DB;
2682 $desc = false;
2683 if (substr($field, -4) === "desc") {
2684 $desc = true;
2685 $field = substr($field, 0, -4); // Remove "desc" from field name.
2687 if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber' && $field !== 'timecreated') {
2688 // This is ultra important as we use $field in an SQL statement below this.
2689 throw new coding_exception('Invalid field requested');
2691 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
2692 $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields
2693 FROM {course} c
2694 LEFT JOIN {context} ctx ON ctx.instanceid = c.id
2695 WHERE ctx.contextlevel = :ctxlevel AND
2696 c.category = :categoryid";
2697 $params = array(
2698 'ctxlevel' => CONTEXT_COURSE,
2699 'categoryid' => $this->id
2701 $courses = $DB->get_records_sql($sql, $params);
2702 if (count($courses) > 0) {
2703 foreach ($courses as $courseid => $course) {
2704 context_helper::preload_from_record($course);
2705 if ($field === 'idnumber') {
2706 $course->sortby = $course->idnumber;
2707 } else {
2708 // It'll require formatting.
2709 $options = array(
2710 'context' => context_course::instance($course->id)
2712 // We format the string first so that it appears as the user would see it.
2713 // This ensures the sorting makes sense to them. However it won't necessarily make
2714 // sense to everyone if things like multilang filters are enabled.
2715 // We then strip any tags as we don't want things such as image tags skewing the
2716 // sort results.
2717 $course->sortby = strip_tags(format_string($course->$field, true, $options));
2719 // We set it back here rather than using references as there is a bug with using
2720 // references in a foreach before passing as an arg by reference.
2721 $courses[$courseid] = $course;
2723 // Sort the courses.
2724 core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL);
2725 if (!empty($desc)) {
2726 $courses = array_reverse($courses);
2728 $i = 1;
2729 foreach ($courses as $course) {
2730 $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id));
2731 $i++;
2733 if ($cleanup) {
2734 // This should not be needed but we do it just to be safe.
2735 fix_course_sortorder();
2736 cache_helper::purge_by_event('changesincourse');
2739 return true;
2743 * Changes the sort order of this categories parent shifting this category up or down one.
2745 * @global \moodle_database $DB
2746 * @param bool $up If set to true the category is shifted up one spot, else its moved down.
2747 * @return bool True on success, false otherwise.
2749 public function change_sortorder_by_one($up) {
2750 global $DB;
2751 $params = array($this->sortorder, $this->parent);
2752 if ($up) {
2753 $select = 'sortorder < ? AND parent = ?';
2754 $sort = 'sortorder DESC';
2755 } else {
2756 $select = 'sortorder > ? AND parent = ?';
2757 $sort = 'sortorder ASC';
2759 fix_course_sortorder();
2760 $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1);
2761 $swapcategory = reset($swapcategory);
2762 if ($swapcategory) {
2763 $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id));
2764 $DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id));
2765 $this->sortorder = $swapcategory->sortorder;
2767 $event = \core\event\course_category_updated::create(array(
2768 'objectid' => $this->id,
2769 'context' => $this->get_context()
2771 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'management.php?categoryid=' . $this->id,
2772 $this->id));
2773 $event->trigger();
2775 // Finally reorder courses.
2776 fix_course_sortorder();
2777 cache_helper::purge_by_event('changesincoursecat');
2778 return true;
2780 return false;
2784 * Returns the parent coursecat object for this category.
2786 * @return coursecat
2788 public function get_parent_coursecat() {
2789 return self::get($this->parent);
2794 * Returns true if the user is able to request a new course be created.
2795 * @return bool
2797 public function can_request_course() {
2798 global $CFG;
2799 if (empty($CFG->enablecourserequests) || $this->id != $CFG->defaultrequestcategory) {
2800 return false;
2802 return !$this->can_create_course() && has_capability('moodle/course:request', $this->get_context());
2806 * Returns true if the user can approve course requests.
2807 * @return bool
2809 public static function can_approve_course_requests() {
2810 global $CFG, $DB;
2811 if (empty($CFG->enablecourserequests)) {
2812 return false;
2814 $context = context_system::instance();
2815 if (!has_capability('moodle/site:approvecourse', $context)) {
2816 return false;
2818 if (!$DB->record_exists('course_request', array())) {
2819 return false;
2821 return true;
2826 * Class to store information about one course in a list of courses
2828 * Not all information may be retrieved when object is created but
2829 * it will be retrieved on demand when appropriate property or method is
2830 * called.
2832 * Instances of this class are usually returned by functions
2833 * {@link coursecat::search_courses()}
2834 * and
2835 * {@link coursecat::get_courses()}
2837 * @property-read int $id
2838 * @property-read int $category Category ID
2839 * @property-read int $sortorder
2840 * @property-read string $fullname
2841 * @property-read string $shortname
2842 * @property-read string $idnumber
2843 * @property-read string $summary Course summary. Field is present if coursecat::get_courses()
2844 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2845 * @property-read int $summaryformat Summary format. Field is present if coursecat::get_courses()
2846 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2847 * @property-read string $format Course format. Retrieved from DB on first request
2848 * @property-read int $showgrades Retrieved from DB on first request
2849 * @property-read int $newsitems Retrieved from DB on first request
2850 * @property-read int $startdate
2851 * @property-read int $enddate
2852 * @property-read int $marker Retrieved from DB on first request
2853 * @property-read int $maxbytes Retrieved from DB on first request
2854 * @property-read int $legacyfiles Retrieved from DB on first request
2855 * @property-read int $showreports Retrieved from DB on first request
2856 * @property-read int $visible
2857 * @property-read int $visibleold Retrieved from DB on first request
2858 * @property-read int $groupmode Retrieved from DB on first request
2859 * @property-read int $groupmodeforce Retrieved from DB on first request
2860 * @property-read int $defaultgroupingid Retrieved from DB on first request
2861 * @property-read string $lang Retrieved from DB on first request
2862 * @property-read string $theme Retrieved from DB on first request
2863 * @property-read int $timecreated Retrieved from DB on first request
2864 * @property-read int $timemodified Retrieved from DB on first request
2865 * @property-read int $requested Retrieved from DB on first request
2866 * @property-read int $enablecompletion Retrieved from DB on first request
2867 * @property-read int $completionnotify Retrieved from DB on first request
2868 * @property-read int $cacherev
2870 * @package core
2871 * @subpackage course
2872 * @copyright 2013 Marina Glancy
2873 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2875 class course_in_list implements IteratorAggregate {
2877 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2878 protected $record;
2880 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2881 protected $coursecontacts;
2883 /** @var bool true if the current user can access the course, false otherwise. */
2884 protected $canaccess = null;
2887 * Creates an instance of the class from record
2889 * @param stdClass $record except fields from course table it may contain
2890 * field hassummary indicating that summary field is not empty.
2891 * Also it is recommended to have context fields here ready for
2892 * context preloading
2894 public function __construct(stdClass $record) {
2895 context_helper::preload_from_record($record);
2896 $this->record = new stdClass();
2897 foreach ($record as $key => $value) {
2898 $this->record->$key = $value;
2903 * Indicates if the course has non-empty summary field
2905 * @return bool
2907 public function has_summary() {
2908 if (isset($this->record->hassummary)) {
2909 return !empty($this->record->hassummary);
2911 if (!isset($this->record->summary)) {
2912 // We need to retrieve summary.
2913 $this->__get('summary');
2915 return !empty($this->record->summary);
2919 * Indicates if the course have course contacts to display
2921 * @return bool
2923 public function has_course_contacts() {
2924 if (!isset($this->record->managers)) {
2925 $courses = array($this->id => &$this->record);
2926 coursecat::preload_course_contacts($courses);
2928 return !empty($this->record->managers);
2932 * Returns list of course contacts (usually teachers) to display in course link
2934 * Roles to display are set up in $CFG->coursecontact
2936 * The result is the list of users where user id is the key and the value
2937 * is an array with elements:
2938 * - 'user' - object containing basic user information
2939 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2940 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2941 * - 'username' => fullname($user, $canviewfullnames)
2943 * @return array
2945 public function get_course_contacts() {
2946 global $CFG;
2947 if (empty($CFG->coursecontact)) {
2948 // No roles are configured to be displayed as course contacts.
2949 return array();
2951 if ($this->coursecontacts === null) {
2952 $this->coursecontacts = array();
2953 $context = context_course::instance($this->id);
2955 if (!isset($this->record->managers)) {
2956 // Preload course contacts from DB.
2957 $courses = array($this->id => &$this->record);
2958 coursecat::preload_course_contacts($courses);
2961 // Build return array with full roles names (for this course context) and users names.
2962 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2963 foreach ($this->record->managers as $ruser) {
2964 if (isset($this->coursecontacts[$ruser->id])) {
2965 // Only display a user once with the highest sortorder role.
2966 continue;
2968 $user = new stdClass();
2969 $user = username_load_fields_from_object($user, $ruser, null, array('id', 'username'));
2970 $role = new stdClass();
2971 $role->id = $ruser->roleid;
2972 $role->name = $ruser->rolename;
2973 $role->shortname = $ruser->roleshortname;
2974 $role->coursealias = $ruser->rolecoursealias;
2976 $this->coursecontacts[$user->id] = array(
2977 'user' => $user,
2978 'role' => $role,
2979 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2980 'username' => fullname($user, $canviewfullnames)
2984 return $this->coursecontacts;
2988 * Checks if course has any associated overview files
2990 * @return bool
2992 public function has_course_overviewfiles() {
2993 global $CFG;
2994 if (empty($CFG->courseoverviewfileslimit)) {
2995 return false;
2997 $fs = get_file_storage();
2998 $context = context_course::instance($this->id);
2999 return !$fs->is_area_empty($context->id, 'course', 'overviewfiles');
3003 * Returns all course overview files
3005 * @return array array of stored_file objects
3007 public function get_course_overviewfiles() {
3008 global $CFG;
3009 if (empty($CFG->courseoverviewfileslimit)) {
3010 return array();
3012 require_once($CFG->libdir. '/filestorage/file_storage.php');
3013 require_once($CFG->dirroot. '/course/lib.php');
3014 $fs = get_file_storage();
3015 $context = context_course::instance($this->id);
3016 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
3017 if (count($files)) {
3018 $overviewfilesoptions = course_overviewfiles_options($this->id);
3019 $acceptedtypes = $overviewfilesoptions['accepted_types'];
3020 if ($acceptedtypes !== '*') {
3021 // Filter only files with allowed extensions.
3022 require_once($CFG->libdir. '/filelib.php');
3023 foreach ($files as $key => $file) {
3024 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
3025 unset($files[$key]);
3029 if (count($files) > $CFG->courseoverviewfileslimit) {
3030 // Return no more than $CFG->courseoverviewfileslimit files.
3031 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
3034 return $files;
3038 * Magic method to check if property is set
3040 * @param string $name
3041 * @return bool
3043 public function __isset($name) {
3044 return isset($this->record->$name);
3048 * Magic method to get a course property
3050 * Returns any field from table course (retrieves it from DB if it was not retrieved before)
3052 * @param string $name
3053 * @return mixed
3055 public function __get($name) {
3056 global $DB;
3057 if (property_exists($this->record, $name)) {
3058 return $this->record->$name;
3059 } else if ($name === 'summary' || $name === 'summaryformat') {
3060 // Retrieve fields summary and summaryformat together because they are most likely to be used together.
3061 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
3062 $this->record->summary = $record->summary;
3063 $this->record->summaryformat = $record->summaryformat;
3064 return $this->record->$name;
3065 } else if (array_key_exists($name, $DB->get_columns('course'))) {
3066 // Another field from table 'course' that was not retrieved.
3067 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
3068 return $this->record->$name;
3070 debugging('Invalid course property accessed! '.$name);
3071 return null;
3075 * All properties are read only, sorry.
3077 * @param string $name
3079 public function __unset($name) {
3080 debugging('Can not unset '.get_class($this).' instance properties!');
3084 * Magic setter method, we do not want anybody to modify properties from the outside
3086 * @param string $name
3087 * @param mixed $value
3089 public function __set($name, $value) {
3090 debugging('Can not change '.get_class($this).' instance properties!');
3094 * Create an iterator because magic vars can't be seen by 'foreach'.
3095 * Exclude context fields
3097 * Implementing method from interface IteratorAggregate
3099 * @return ArrayIterator
3101 public function getIterator() {
3102 $ret = array('id' => $this->record->id);
3103 foreach ($this->record as $property => $value) {
3104 $ret[$property] = $value;
3106 return new ArrayIterator($ret);
3110 * Returns the name of this course as it should be displayed within a list.
3111 * @return string
3113 public function get_formatted_name() {
3114 return format_string(get_course_display_name_for_list($this), true, $this->get_context());
3118 * Returns the formatted fullname for this course.
3119 * @return string
3121 public function get_formatted_fullname() {
3122 return format_string($this->__get('fullname'), true, $this->get_context());
3126 * Returns the formatted shortname for this course.
3127 * @return string
3129 public function get_formatted_shortname() {
3130 return format_string($this->__get('shortname'), true, $this->get_context());
3134 * Returns true if the current user can access this course.
3135 * @return bool
3137 public function can_access() {
3138 if ($this->canaccess === null) {
3139 $this->canaccess = can_access_course($this->record);
3141 return $this->canaccess;
3145 * Returns true if the user can edit this courses settings.
3147 * Note: this function does not check that the current user can access the course.
3148 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3150 * @return bool
3152 public function can_edit() {
3153 return has_capability('moodle/course:update', $this->get_context());
3157 * Returns true if the user can change the visibility of this course.
3159 * Note: this function does not check that the current user can access the course.
3160 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3162 * @return bool
3164 public function can_change_visibility() {
3165 // You must be able to both hide a course and view the hidden course.
3166 return has_all_capabilities(array('moodle/course:visibility', 'moodle/course:viewhiddencourses'), $this->get_context());
3170 * Returns the context for this course.
3171 * @return context_course
3173 public function get_context() {
3174 return context_course::instance($this->__get('id'));
3178 * Returns true if this course is visible to the current user.
3179 * @return bool
3181 public function is_uservisible() {
3182 return $this->visible || has_capability('moodle/course:viewhiddencourses', $this->get_context());
3186 * Returns true if the current user can review enrolments for this course.
3188 * Note: this function does not check that the current user can access the course.
3189 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3191 * @return bool
3193 public function can_review_enrolments() {
3194 return has_capability('moodle/course:enrolreview', $this->get_context());
3198 * Returns true if the current user can delete this course.
3200 * Note: this function does not check that the current user can access the course.
3201 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3203 * @return bool
3205 public function can_delete() {
3206 return can_delete_course($this->id);
3210 * Returns true if the current user can backup this course.
3212 * Note: this function does not check that the current user can access the course.
3213 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3215 * @return bool
3217 public function can_backup() {
3218 return has_capability('moodle/backup:backupcourse', $this->get_context());
3222 * Returns true if the current user can restore this course.
3224 * Note: this function does not check that the current user can access the course.
3225 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3227 * @return bool
3229 public function can_restore() {
3230 return has_capability('moodle/restore:restorecourse', $this->get_context());
3235 * An array of records that is sortable by many fields.
3237 * For more info on the ArrayObject class have a look at php.net.
3239 * @package core
3240 * @subpackage course
3241 * @copyright 2013 Sam Hemelryk
3242 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3244 class coursecat_sortable_records extends ArrayObject {
3247 * An array of sortable fields.
3248 * Gets set temporarily when sort is called.
3249 * @var array
3251 protected $sortfields = array();
3254 * Sorts this array using the given fields.
3256 * @param array $records
3257 * @param array $fields
3258 * @return array
3260 public static function sort(array $records, array $fields) {
3261 $records = new coursecat_sortable_records($records);
3262 $records->sortfields = $fields;
3263 $records->uasort(array($records, 'sort_by_many_fields'));
3264 return $records->getArrayCopy();
3268 * Sorts the two records based upon many fields.
3270 * This method should not be called itself, please call $sort instead.
3271 * It has been marked as access private as such.
3273 * @access private
3274 * @param stdClass $a
3275 * @param stdClass $b
3276 * @return int
3278 public function sort_by_many_fields($a, $b) {
3279 foreach ($this->sortfields as $field => $mult) {
3280 // Nulls first.
3281 if (is_null($a->$field) && !is_null($b->$field)) {
3282 return -$mult;
3284 if (is_null($b->$field) && !is_null($a->$field)) {
3285 return $mult;
3288 if (is_string($a->$field) || is_string($b->$field)) {
3289 // String fields.
3290 if ($cmp = strcoll($a->$field, $b->$field)) {
3291 return $mult * $cmp;
3293 } else {
3294 // Int fields.
3295 if ($a->$field > $b->$field) {
3296 return $mult;
3298 if ($a->$field < $b->$field) {
3299 return -$mult;
3303 return 0;