Merge branch 'MDL-61839-master' of git://github.com/mihailges/moodle
[moodle.git] / lib / coursecatlib.php
blob8833387190a0ef29ce6624a44fcb4f8061fb1184
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 the given 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 * @param int|stdClass $user The user id or object. By default (null) checks the visibility to the current user.
230 * @return null|coursecat
231 * @throws moodle_exception
233 public static function get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false, $user = null) {
234 if (!$id) {
235 if (!isset(self::$coursecat0)) {
236 $record = new stdClass();
237 $record->id = 0;
238 $record->visible = 1;
239 $record->depth = 0;
240 $record->path = '';
241 self::$coursecat0 = new coursecat($record);
243 return self::$coursecat0;
245 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
246 $coursecat = $coursecatrecordcache->get($id);
247 if ($coursecat === false) {
248 if ($records = self::get_records('cc.id = :id', array('id' => $id))) {
249 $record = reset($records);
250 $coursecat = new coursecat($record);
251 // Store in cache.
252 $coursecatrecordcache->set($id, $coursecat);
255 if ($coursecat && ($alwaysreturnhidden || $coursecat->is_uservisible($user))) {
256 return $coursecat;
257 } else {
258 if ($strictness == MUST_EXIST) {
259 throw new moodle_exception('unknowncategory');
262 return null;
266 * Load many coursecat objects.
268 * @global moodle_database $DB
269 * @param array $ids An array of category ID's to load.
270 * @return coursecat[]
272 public static function get_many(array $ids) {
273 global $DB;
274 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
275 $categories = $coursecatrecordcache->get_many($ids);
276 $toload = array();
277 foreach ($categories as $id => $result) {
278 if ($result === false) {
279 $toload[] = $id;
282 if (!empty($toload)) {
283 list($where, $params) = $DB->get_in_or_equal($toload, SQL_PARAMS_NAMED);
284 $records = self::get_records('cc.id '.$where, $params);
285 $toset = array();
286 foreach ($records as $record) {
287 $categories[$record->id] = new coursecat($record);
288 $toset[$record->id] = $categories[$record->id];
290 $coursecatrecordcache->set_many($toset);
292 return $categories;
296 * Load all coursecat objects.
298 * @param array $options Options:
299 * @param bool $options.returnhidden Return categories even if they are hidden
300 * @return coursecat[]
302 public static function get_all($options = []) {
303 global $DB;
305 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
307 $catcontextsql = \context_helper::get_preload_record_columns_sql('ctx');
308 $catsql = "SELECT cc.*, {$catcontextsql}
309 FROM {course_categories} cc
310 JOIN {context} ctx ON cc.id = ctx.instanceid";
311 $catsqlwhere = "WHERE ctx.contextlevel = :contextlevel";
312 $catsqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC";
314 $catrs = $DB->get_recordset_sql("{$catsql} {$catsqlwhere} {$catsqlorder}", [
315 'contextlevel' => CONTEXT_COURSECAT,
318 $types['categories'] = [];
319 $categories = [];
320 $toset = [];
321 foreach ($catrs as $record) {
322 $category = new coursecat($record);
323 $toset[$category->id] = $category;
325 if (!empty($options['returnhidden']) || $category->is_uservisible()) {
326 $categories[$record->id] = $category;
329 $catrs->close();
331 $coursecatrecordcache->set_many($toset);
333 return $categories;
338 * Returns the first found category
340 * Note that if there are no categories visible to the current user on the first level,
341 * the invisible category may be returned
343 * @return coursecat
345 public static function get_default() {
346 if ($visiblechildren = self::get(0)->get_children()) {
347 $defcategory = reset($visiblechildren);
348 } else {
349 $toplevelcategories = self::get_tree(0);
350 $defcategoryid = $toplevelcategories[0];
351 $defcategory = self::get($defcategoryid, MUST_EXIST, true);
353 return $defcategory;
357 * Restores the object after it has been externally modified in DB for example
358 * during {@link fix_course_sortorder()}
360 protected function restore() {
361 // Update all fields in the current object.
362 $newrecord = self::get($this->id, MUST_EXIST, true);
363 foreach (self::$coursecatfields as $key => $unused) {
364 $this->$key = $newrecord->$key;
369 * Creates a new category either from form data or from raw data
371 * Please note that this function does not verify access control.
373 * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
375 * Category visibility is inherited from parent unless $data->visible = 0 is specified
377 * @param array|stdClass $data
378 * @param array $editoroptions if specified, the data is considered to be
379 * form data and file_postupdate_standard_editor() is being called to
380 * process images in description.
381 * @return coursecat
382 * @throws moodle_exception
384 public static function create($data, $editoroptions = null) {
385 global $DB, $CFG;
386 $data = (object)$data;
387 $newcategory = new stdClass();
389 $newcategory->descriptionformat = FORMAT_MOODLE;
390 $newcategory->description = '';
391 // Copy all description* fields regardless of whether this is form data or direct field update.
392 foreach ($data as $key => $value) {
393 if (preg_match("/^description/", $key)) {
394 $newcategory->$key = $value;
398 if (empty($data->name)) {
399 throw new moodle_exception('categorynamerequired');
401 if (core_text::strlen($data->name) > 255) {
402 throw new moodle_exception('categorytoolong');
404 $newcategory->name = $data->name;
406 // Validate and set idnumber.
407 if (isset($data->idnumber)) {
408 if (core_text::strlen($data->idnumber) > 100) {
409 throw new moodle_exception('idnumbertoolong');
411 if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
412 throw new moodle_exception('categoryidnumbertaken');
414 $newcategory->idnumber = $data->idnumber;
417 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
418 $newcategory->theme = $data->theme;
421 if (empty($data->parent)) {
422 $parent = self::get(0);
423 } else {
424 $parent = self::get($data->parent, MUST_EXIST, true);
426 $newcategory->parent = $parent->id;
427 $newcategory->depth = $parent->depth + 1;
429 // By default category is visible, unless visible = 0 is specified or parent category is hidden.
430 if (isset($data->visible) && !$data->visible) {
431 // Create a hidden category.
432 $newcategory->visible = $newcategory->visibleold = 0;
433 } else {
434 // Create a category that inherits visibility from parent.
435 $newcategory->visible = $parent->visible;
436 // In case parent is hidden, when it changes visibility this new subcategory will automatically become visible too.
437 $newcategory->visibleold = 1;
440 $newcategory->sortorder = 0;
441 $newcategory->timemodified = time();
443 $newcategory->id = $DB->insert_record('course_categories', $newcategory);
445 // Update path (only possible after we know the category id.
446 $path = $parent->path . '/' . $newcategory->id;
447 $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));
449 // We should mark the context as dirty.
450 context_coursecat::instance($newcategory->id)->mark_dirty();
452 fix_course_sortorder();
454 // If this is data from form results, save embedded files and update description.
455 $categorycontext = context_coursecat::instance($newcategory->id);
456 if ($editoroptions) {
457 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
458 'coursecat', 'description', 0);
460 // Update only fields description and descriptionformat.
461 $updatedata = new stdClass();
462 $updatedata->id = $newcategory->id;
463 $updatedata->description = $newcategory->description;
464 $updatedata->descriptionformat = $newcategory->descriptionformat;
465 $DB->update_record('course_categories', $updatedata);
468 $event = \core\event\course_category_created::create(array(
469 'objectid' => $newcategory->id,
470 'context' => $categorycontext
472 $event->trigger();
474 cache_helper::purge_by_event('changesincoursecat');
476 return self::get($newcategory->id, MUST_EXIST, true);
480 * Updates the record with either form data or raw data
482 * Please note that this function does not verify access control.
484 * This function calls coursecat::change_parent_raw if field 'parent' is updated.
485 * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
486 * Visibility is changed first and then parent is changed. This means that
487 * if parent category is hidden, the current category will become hidden
488 * too and it may overwrite whatever was set in field 'visible'.
490 * Note that fields 'path' and 'depth' can not be updated manually
491 * Also coursecat::update() can not directly update the field 'sortoder'
493 * @param array|stdClass $data
494 * @param array $editoroptions if specified, the data is considered to be
495 * form data and file_postupdate_standard_editor() is being called to
496 * process images in description.
497 * @throws moodle_exception
499 public function update($data, $editoroptions = null) {
500 global $DB, $CFG;
501 if (!$this->id) {
502 // There is no actual DB record associated with root category.
503 return;
506 $data = (object)$data;
507 $newcategory = new stdClass();
508 $newcategory->id = $this->id;
510 // Copy all description* fields regardless of whether this is form data or direct field update.
511 foreach ($data as $key => $value) {
512 if (preg_match("/^description/", $key)) {
513 $newcategory->$key = $value;
517 if (isset($data->name) && empty($data->name)) {
518 throw new moodle_exception('categorynamerequired');
521 if (!empty($data->name) && $data->name !== $this->name) {
522 if (core_text::strlen($data->name) > 255) {
523 throw new moodle_exception('categorytoolong');
525 $newcategory->name = $data->name;
528 if (isset($data->idnumber) && $data->idnumber !== $this->idnumber) {
529 if (core_text::strlen($data->idnumber) > 100) {
530 throw new moodle_exception('idnumbertoolong');
532 if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
533 throw new moodle_exception('categoryidnumbertaken');
535 $newcategory->idnumber = $data->idnumber;
538 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
539 $newcategory->theme = $data->theme;
542 $changes = false;
543 if (isset($data->visible)) {
544 if ($data->visible) {
545 $changes = $this->show_raw();
546 } else {
547 $changes = $this->hide_raw(0);
551 if (isset($data->parent) && $data->parent != $this->parent) {
552 if ($changes) {
553 cache_helper::purge_by_event('changesincoursecat');
555 $parentcat = self::get($data->parent, MUST_EXIST, true);
556 $this->change_parent_raw($parentcat);
557 fix_course_sortorder();
560 $newcategory->timemodified = time();
562 $categorycontext = $this->get_context();
563 if ($editoroptions) {
564 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
565 'coursecat', 'description', 0);
567 $DB->update_record('course_categories', $newcategory);
569 $event = \core\event\course_category_updated::create(array(
570 'objectid' => $newcategory->id,
571 'context' => $categorycontext
573 $event->trigger();
575 fix_course_sortorder();
576 // Purge cache even if fix_course_sortorder() did not do it.
577 cache_helper::purge_by_event('changesincoursecat');
579 // Update all fields in the current object.
580 $this->restore();
584 * Checks if this course category is visible to a user.
586 * Please note that methods coursecat::get (without 3rd argumet),
587 * coursecat::get_children(), etc. return only visible categories so it is
588 * usually not needed to call this function outside of this class
590 * @param int|stdClass $user The user id or object. By default (null) checks the visibility to the current user.
591 * @return bool
593 public function is_uservisible($user = null) {
594 return !$this->id || $this->visible ||
595 has_capability('moodle/category:viewhiddencategories', $this->get_context(), $user);
599 * Returns the complete corresponding record from DB table course_categories
601 * Mostly used in deprecated functions
603 * @return stdClass
605 public function get_db_record() {
606 global $DB;
607 if ($record = $DB->get_record('course_categories', array('id' => $this->id))) {
608 return $record;
609 } else {
610 return (object)convert_to_array($this);
615 * Returns the entry from categories tree and makes sure the application-level tree cache is built
617 * The following keys can be requested:
619 * 'countall' - total number of categories in the system (always present)
620 * 0 - array of ids of top-level categories (always present)
621 * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
622 * $id (int) - array of ids of categories that are direct children of category with id $id. If
623 * category with id $id does not exist returns false. If category has no children returns empty array
624 * $id.'i' - array of ids of children categories that have visible=0
626 * @param int|string $id
627 * @return mixed
629 protected static function get_tree($id) {
630 global $DB;
631 $coursecattreecache = cache::make('core', 'coursecattree');
632 $rv = $coursecattreecache->get($id);
633 if ($rv !== false) {
634 return $rv;
636 // Re-build the tree.
637 $sql = "SELECT cc.id, cc.parent, cc.visible
638 FROM {course_categories} cc
639 ORDER BY cc.sortorder";
640 $rs = $DB->get_recordset_sql($sql, array());
641 $all = array(0 => array(), '0i' => array());
642 $count = 0;
643 foreach ($rs as $record) {
644 $all[$record->id] = array();
645 $all[$record->id. 'i'] = array();
646 if (array_key_exists($record->parent, $all)) {
647 $all[$record->parent][] = $record->id;
648 if (!$record->visible) {
649 $all[$record->parent. 'i'][] = $record->id;
651 } else {
652 // Parent not found. This is data consistency error but next fix_course_sortorder() should fix it.
653 $all[0][] = $record->id;
654 if (!$record->visible) {
655 $all['0i'][] = $record->id;
658 $count++;
660 $rs->close();
661 if (!$count) {
662 // No categories found.
663 // This may happen after upgrade of a very old moodle version.
664 // In new versions the default category is created on install.
665 $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
666 set_config('defaultrequestcategory', $defcoursecat->id);
667 $all[0] = array($defcoursecat->id);
668 $all[$defcoursecat->id] = array();
669 $count++;
671 // We must add countall to all in case it was the requested ID.
672 $all['countall'] = $count;
673 $coursecattreecache->set_many($all);
674 if (array_key_exists($id, $all)) {
675 return $all[$id];
677 // Requested non-existing category.
678 return array();
682 * Returns number of ALL categories in the system regardless if
683 * they are visible to current user or not
685 * @return int
687 public static function count_all() {
688 return self::get_tree('countall');
692 * Retrieves number of records from course_categories table
694 * Only cached fields are retrieved. Records are ready for preloading context
696 * @param string $whereclause
697 * @param array $params
698 * @return array array of stdClass objects
700 protected static function get_records($whereclause, $params) {
701 global $DB;
702 // Retrieve from DB only the fields that need to be stored in cache.
703 $fields = array_keys(array_filter(self::$coursecatfields));
704 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
705 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
706 FROM {course_categories} cc
707 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
708 WHERE ". $whereclause." ORDER BY cc.sortorder";
709 return $DB->get_records_sql($sql,
710 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
714 * Resets course contact caches when role assignments were changed
716 * @param int $roleid role id that was given or taken away
717 * @param context $context context where role assignment has been changed
719 public static function role_assignment_changed($roleid, $context) {
720 global $CFG, $DB;
722 if ($context->contextlevel > CONTEXT_COURSE) {
723 // No changes to course contacts if role was assigned on the module/block level.
724 return;
727 // Trigger a purge for all caches listening for changes to category enrolment.
728 cache_helper::purge_by_event('changesincategoryenrolment');
730 if (!$CFG->coursecontact || !in_array($roleid, explode(',', $CFG->coursecontact))) {
731 // The role is not one of course contact roles.
732 return;
735 // Remove from cache course contacts of all affected courses.
736 $cache = cache::make('core', 'coursecontacts');
737 if ($context->contextlevel == CONTEXT_COURSE) {
738 $cache->delete($context->instanceid);
739 } else if ($context->contextlevel == CONTEXT_SYSTEM) {
740 $cache->purge();
741 } else {
742 $sql = "SELECT ctx.instanceid
743 FROM {context} ctx
744 WHERE ctx.path LIKE ? AND ctx.contextlevel = ?";
745 $params = array($context->path . '/%', CONTEXT_COURSE);
746 if ($courses = $DB->get_fieldset_sql($sql, $params)) {
747 $cache->delete_many($courses);
753 * Executed when user enrolment was changed to check if course
754 * contacts cache needs to be cleared
756 * @param int $courseid course id
757 * @param int $userid user id
758 * @param int $status new enrolment status (0 - active, 1 - suspended)
759 * @param int $timestart new enrolment time start
760 * @param int $timeend new enrolment time end
762 public static function user_enrolment_changed($courseid, $userid,
763 $status, $timestart = null, $timeend = null) {
764 $cache = cache::make('core', 'coursecontacts');
765 $contacts = $cache->get($courseid);
766 if ($contacts === false) {
767 // The contacts for the affected course were not cached anyway.
768 return;
770 $enrolmentactive = ($status == 0) &&
771 (!$timestart || $timestart < time()) &&
772 (!$timeend || $timeend > time());
773 if (!$enrolmentactive) {
774 $isincontacts = false;
775 foreach ($contacts as $contact) {
776 if ($contact->id == $userid) {
777 $isincontacts = true;
780 if (!$isincontacts) {
781 // Changed user's enrolment does not exist or is not active,
782 // and he is not in cached course contacts, no changes to be made.
783 return;
786 // Either enrolment of manager was deleted/suspended
787 // or user enrolment was added or activated.
788 // In order to see if the course contacts for this course need
789 // changing we would need to make additional queries, they will
790 // slow down bulk enrolment changes. It is better just to remove
791 // course contacts cache for this course.
792 $cache->delete($courseid);
796 * Given list of DB records from table course populates each record with list of users with course contact roles
798 * This function fills the courses with raw information as {@link get_role_users()} would do.
799 * See also {@link course_in_list::get_course_contacts()} for more readable return
801 * $courses[$i]->managers = array(
802 * $roleassignmentid => $roleuser,
803 * ...
804 * );
806 * where $roleuser is an stdClass with the following properties:
808 * $roleuser->raid - role assignment id
809 * $roleuser->id - user id
810 * $roleuser->username
811 * $roleuser->firstname
812 * $roleuser->lastname
813 * $roleuser->rolecoursealias
814 * $roleuser->rolename
815 * $roleuser->sortorder - role sortorder
816 * $roleuser->roleid
817 * $roleuser->roleshortname
819 * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
821 * @param array $courses
823 public static function preload_course_contacts(&$courses) {
824 global $CFG, $DB;
825 if (empty($courses) || empty($CFG->coursecontact)) {
826 return;
828 $managerroles = explode(',', $CFG->coursecontact);
829 $cache = cache::make('core', 'coursecontacts');
830 $cacheddata = $cache->get_many(array_keys($courses));
831 $courseids = array();
832 foreach (array_keys($courses) as $id) {
833 if ($cacheddata[$id] !== false) {
834 $courses[$id]->managers = $cacheddata[$id];
835 } else {
836 $courseids[] = $id;
840 // Array $courseids now stores list of ids of courses for which we still need to retrieve contacts.
841 if (empty($courseids)) {
842 return;
845 // First build the array of all context ids of the courses and their categories.
846 $allcontexts = array();
847 foreach ($courseids as $id) {
848 $context = context_course::instance($id);
849 $courses[$id]->managers = array();
850 foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
851 if (!isset($allcontexts[$ctxid])) {
852 $allcontexts[$ctxid] = array();
854 $allcontexts[$ctxid][] = $id;
858 // Fetch list of all users with course contact roles in any of the courses contexts or parent contexts.
859 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
860 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
861 list($sort, $sortparams) = users_order_by_sql('u');
862 $notdeleted = array('notdeleted'=>0);
863 $allnames = get_all_user_name_fields(true, 'u');
864 $sql = "SELECT ra.contextid, ra.id AS raid,
865 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
866 rn.name AS rolecoursealias, u.id, u.username, $allnames
867 FROM {role_assignments} ra
868 JOIN {user} u ON ra.userid = u.id
869 JOIN {role} r ON ra.roleid = r.id
870 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
871 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
872 ORDER BY r.sortorder, $sort";
873 $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
874 $checkenrolments = array();
875 foreach ($rs as $ra) {
876 foreach ($allcontexts[$ra->contextid] as $id) {
877 $courses[$id]->managers[$ra->raid] = $ra;
878 if (!isset($checkenrolments[$id])) {
879 $checkenrolments[$id] = array();
881 $checkenrolments[$id][] = $ra->id;
884 $rs->close();
886 // Remove from course contacts users who are not enrolled in the course.
887 $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
888 foreach ($checkenrolments as $id => $userids) {
889 if (empty($enrolleduserids[$id])) {
890 $courses[$id]->managers = array();
891 } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
892 foreach ($courses[$id]->managers as $raid => $ra) {
893 if (in_array($ra->id, $notenrolled)) {
894 unset($courses[$id]->managers[$raid]);
900 // Set the cache.
901 $values = array();
902 foreach ($courseids as $id) {
903 $values[$id] = $courses[$id]->managers;
905 $cache->set_many($values);
909 * Verify user enrollments for multiple course-user combinations
911 * @param array $courseusers array where keys are course ids and values are array
912 * of users in this course whose enrolment we wish to verify
913 * @return array same structure as input array but values list only users from input
914 * who are enrolled in the course
916 protected static function ensure_users_enrolled($courseusers) {
917 global $DB;
918 // If the input array is too big, split it into chunks.
919 $maxcoursesinquery = 20;
920 if (count($courseusers) > $maxcoursesinquery) {
921 $rv = array();
922 for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
923 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
924 $rv = $rv + self::ensure_users_enrolled($chunk);
926 return $rv;
929 // Create a query verifying valid user enrolments for the number of courses.
930 $sql = "SELECT DISTINCT e.courseid, ue.userid
931 FROM {user_enrolments} ue
932 JOIN {enrol} e ON e.id = ue.enrolid
933 WHERE ue.status = :active
934 AND e.status = :enabled
935 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
936 $now = round(time(), -2); // Rounding helps caching in DB.
937 $params = array('enabled' => ENROL_INSTANCE_ENABLED,
938 'active' => ENROL_USER_ACTIVE,
939 'now1' => $now, 'now2' => $now);
940 $cnt = 0;
941 $subsqls = array();
942 $enrolled = array();
943 foreach ($courseusers as $id => $userids) {
944 $enrolled[$id] = array();
945 if (count($userids)) {
946 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
947 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
948 $params = $params + array('courseid'.$cnt => $id) + $params2;
949 $cnt++;
952 if (count($subsqls)) {
953 $sql .= "AND (". join(' OR ', $subsqls).")";
954 $rs = $DB->get_recordset_sql($sql, $params);
955 foreach ($rs as $record) {
956 $enrolled[$record->courseid][] = $record->userid;
958 $rs->close();
960 return $enrolled;
964 * Retrieves number of records from course table
966 * Not all fields are retrieved. Records are ready for preloading context
968 * @param string $whereclause
969 * @param array $params
970 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
971 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
972 * on not visible courses
973 * @return array array of stdClass objects
975 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
976 global $DB;
977 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
978 $fields = array('c.id', 'c.category', 'c.sortorder',
979 'c.shortname', 'c.fullname', 'c.idnumber',
980 'c.startdate', 'c.enddate', 'c.visible', 'c.cacherev');
981 if (!empty($options['summary'])) {
982 $fields[] = 'c.summary';
983 $fields[] = 'c.summaryformat';
984 } else {
985 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
987 $sql = "SELECT ". join(',', $fields). ", $ctxselect
988 FROM {course} c
989 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
990 WHERE ". $whereclause." ORDER BY c.sortorder";
991 $list = $DB->get_records_sql($sql,
992 array('contextcourse' => CONTEXT_COURSE) + $params);
994 if ($checkvisibility) {
995 // Loop through all records and make sure we only return the courses accessible by user.
996 foreach ($list as $course) {
997 if (isset($list[$course->id]->hassummary)) {
998 $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
1000 if (empty($course->visible)) {
1001 // Load context only if we need to check capability.
1002 context_helper::preload_from_record($course);
1003 if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1004 unset($list[$course->id]);
1010 // Preload course contacts if necessary.
1011 if (!empty($options['coursecontacts'])) {
1012 self::preload_course_contacts($list);
1014 return $list;
1018 * Returns array of ids of children categories that current user can not see
1020 * This data is cached in user session cache
1022 * @return array
1024 protected function get_not_visible_children_ids() {
1025 global $DB;
1026 $coursecatcache = cache::make('core', 'coursecat');
1027 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
1028 // We never checked visible children before.
1029 $hidden = self::get_tree($this->id.'i');
1030 $invisibleids = array();
1031 if ($hidden) {
1032 // Preload categories contexts.
1033 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
1034 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1035 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
1036 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
1037 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
1038 foreach ($contexts as $record) {
1039 context_helper::preload_from_record($record);
1041 // Check that user has 'viewhiddencategories' capability for each hidden category.
1042 foreach ($hidden as $id) {
1043 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
1044 $invisibleids[] = $id;
1048 $coursecatcache->set('ic'. $this->id, $invisibleids);
1050 return $invisibleids;
1054 * Sorts list of records by several fields
1056 * @param array $records array of stdClass objects
1057 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
1058 * @return int
1060 protected static function sort_records(&$records, $sortfields) {
1061 if (empty($records)) {
1062 return;
1064 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname).
1065 if (array_key_exists('displayname', $sortfields)) {
1066 foreach ($records as $key => $record) {
1067 if (!isset($record->displayname)) {
1068 $records[$key]->displayname = get_course_display_name_for_list($record);
1072 // Sorting by one field - use core_collator.
1073 if (count($sortfields) == 1) {
1074 $property = key($sortfields);
1075 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
1076 $sortflag = core_collator::SORT_NUMERIC;
1077 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
1078 $sortflag = core_collator::SORT_STRING;
1079 } else {
1080 $sortflag = core_collator::SORT_REGULAR;
1082 core_collator::asort_objects_by_property($records, $property, $sortflag);
1083 if ($sortfields[$property] < 0) {
1084 $records = array_reverse($records, true);
1086 return;
1088 $records = coursecat_sortable_records::sort($records, $sortfields);
1092 * Returns array of children categories visible to the current user
1094 * @param array $options options for retrieving children
1095 * - sort - list of fields to sort. Example
1096 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
1097 * will sort by idnumber asc, name asc and id desc.
1098 * Default: array('sortorder' => 1)
1099 * Only cached fields may be used for sorting!
1100 * - offset
1101 * - limit - maximum number of children to return, 0 or null for no limit
1102 * @return coursecat[] Array of coursecat objects indexed by category id
1104 public function get_children($options = array()) {
1105 global $DB;
1106 $coursecatcache = cache::make('core', 'coursecat');
1108 // Get default values for options.
1109 if (!empty($options['sort']) && is_array($options['sort'])) {
1110 $sortfields = $options['sort'];
1111 } else {
1112 $sortfields = array('sortorder' => 1);
1114 $limit = null;
1115 if (!empty($options['limit']) && (int)$options['limit']) {
1116 $limit = (int)$options['limit'];
1118 $offset = 0;
1119 if (!empty($options['offset']) && (int)$options['offset']) {
1120 $offset = (int)$options['offset'];
1123 // First retrieve list of user-visible and sorted children ids from cache.
1124 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
1125 if ($sortedids === false) {
1126 $sortfieldskeys = array_keys($sortfields);
1127 if ($sortfieldskeys[0] === 'sortorder') {
1128 // No DB requests required to build the list of ids sorted by sortorder.
1129 // We can easily ignore other sort fields because sortorder is always different.
1130 $sortedids = self::get_tree($this->id);
1131 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
1132 $sortedids = array_diff($sortedids, $invisibleids);
1133 if ($sortfields['sortorder'] == -1) {
1134 $sortedids = array_reverse($sortedids, true);
1137 } else {
1138 // We need to retrieve and sort all children. Good thing that it is done only on first request.
1139 if ($invisibleids = $this->get_not_visible_children_ids()) {
1140 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
1141 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
1142 array('parent' => $this->id) + $params);
1143 } else {
1144 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
1146 self::sort_records($records, $sortfields);
1147 $sortedids = array_keys($records);
1149 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
1152 if (empty($sortedids)) {
1153 return array();
1156 // Now retrieive and return categories.
1157 if ($offset || $limit) {
1158 $sortedids = array_slice($sortedids, $offset, $limit);
1160 if (isset($records)) {
1161 // Easy, we have already retrieved records.
1162 if ($offset || $limit) {
1163 $records = array_slice($records, $offset, $limit, true);
1165 } else {
1166 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
1167 $records = self::get_records('cc.id '. $sql, array('parent' => $this->id) + $params);
1170 $rv = array();
1171 foreach ($sortedids as $id) {
1172 if (isset($records[$id])) {
1173 $rv[$id] = new coursecat($records[$id]);
1176 return $rv;
1180 * Returns an array of ids of categories that are (direct and indirect) children
1181 * of this category.
1183 * @return int[]
1185 public function get_all_children_ids() {
1186 $children = [];
1187 $walk = [$this->id];
1188 while (count($walk) > 0) {
1189 $catid = array_pop($walk);
1190 $directchildren = self::get_tree($catid);
1191 if ($directchildren !== false && count($directchildren) > 0) {
1192 $walk = array_merge($walk, $directchildren);
1193 $children = array_merge($children, $directchildren);
1197 return $children;
1201 * Returns true if the user has the manage capability on any category.
1203 * This method uses the coursecat cache and an entry `has_manage_capability` to speed up
1204 * calls to this method.
1206 * @return bool
1208 public static function has_manage_capability_on_any() {
1209 return self::has_capability_on_any('moodle/category:manage');
1213 * Checks if the user has at least one of the given capabilities on any category.
1215 * @param array|string $capabilities One or more capabilities to check. Check made is an OR.
1216 * @return bool
1218 public static function has_capability_on_any($capabilities) {
1219 global $DB;
1220 if (!isloggedin() || isguestuser()) {
1221 return false;
1224 if (!is_array($capabilities)) {
1225 $capabilities = array($capabilities);
1227 $keys = array();
1228 foreach ($capabilities as $capability) {
1229 $keys[$capability] = sha1($capability);
1232 /* @var cache_session $cache */
1233 $cache = cache::make('core', 'coursecat');
1234 $hascapability = $cache->get_many($keys);
1235 $needtoload = false;
1236 foreach ($hascapability as $capability) {
1237 if ($capability === '1') {
1238 return true;
1239 } else if ($capability === false) {
1240 $needtoload = true;
1243 if ($needtoload === false) {
1244 // All capabilities were retrieved and the user didn't have any.
1245 return false;
1248 $haskey = null;
1249 $fields = context_helper::get_preload_record_columns_sql('ctx');
1250 $sql = "SELECT ctx.instanceid AS categoryid, $fields
1251 FROM {context} ctx
1252 WHERE contextlevel = :contextlevel
1253 ORDER BY depth ASC";
1254 $params = array('contextlevel' => CONTEXT_COURSECAT);
1255 $recordset = $DB->get_recordset_sql($sql, $params);
1256 foreach ($recordset as $context) {
1257 context_helper::preload_from_record($context);
1258 $context = context_coursecat::instance($context->categoryid);
1259 foreach ($capabilities as $capability) {
1260 if (has_capability($capability, $context)) {
1261 $haskey = $capability;
1262 break 2;
1266 $recordset->close();
1267 if ($haskey === null) {
1268 $data = array();
1269 foreach ($keys as $key) {
1270 $data[$key] = '0';
1272 $cache->set_many($data);
1273 return false;
1274 } else {
1275 $cache->set($haskey, '1');
1276 return true;
1281 * Returns true if the user can resort any category.
1282 * @return bool
1284 public static function can_resort_any() {
1285 return self::has_manage_capability_on_any();
1289 * Returns true if the user can change the parent of any category.
1290 * @return bool
1292 public static function can_change_parent_any() {
1293 return self::has_manage_capability_on_any();
1297 * Returns number of subcategories visible to the current user
1299 * @return int
1301 public function get_children_count() {
1302 $sortedids = self::get_tree($this->id);
1303 $invisibleids = $this->get_not_visible_children_ids();
1304 return count($sortedids) - count($invisibleids);
1308 * Returns true if the category has ANY children, including those not visible to the user
1310 * @return boolean
1312 public function has_children() {
1313 $allchildren = self::get_tree($this->id);
1314 return !empty($allchildren);
1318 * Returns true if the category has courses in it (count does not include courses
1319 * in child categories)
1321 * @return bool
1323 public function has_courses() {
1324 global $DB;
1325 return $DB->record_exists_sql("select 1 from {course} where category = ?",
1326 array($this->id));
1330 * Get the link used to view this course category.
1332 * @return \moodle_url
1334 public function get_view_link() {
1335 return new \moodle_url('/course/index.php', [
1336 'categoryid' => $this->id,
1341 * Searches courses
1343 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1344 * to this when somebody edits courses or categories, however it is very
1345 * difficult to keep track of all possible changes that may affect list of courses.
1347 * @param array $search contains search criterias, such as:
1348 * - search - search string
1349 * - blocklist - id of block (if we are searching for courses containing specific block0
1350 * - modulelist - name of module (if we are searching for courses containing specific module
1351 * - tagid - id of tag
1352 * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
1353 * search is always category-independent
1354 * @param array $requiredcapabilites List of capabilities required to see return course.
1355 * @return course_in_list[]
1357 public static function search_courses($search, $options = array(), $requiredcapabilities = array()) {
1358 global $DB;
1359 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1360 $limit = !empty($options['limit']) ? $options['limit'] : null;
1361 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1363 $coursecatcache = cache::make('core', 'coursecat');
1364 $cachekey = 's-'. serialize(
1365 $search + array('sort' => $sortfields) + array('requiredcapabilities' => $requiredcapabilities)
1367 $cntcachekey = 'scnt-'. serialize($search);
1369 $ids = $coursecatcache->get($cachekey);
1370 if ($ids !== false) {
1371 // We already cached last search result.
1372 $ids = array_slice($ids, $offset, $limit);
1373 $courses = array();
1374 if (!empty($ids)) {
1375 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1376 $records = self::get_course_records("c.id ". $sql, $params, $options);
1377 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1378 if (!empty($options['coursecontacts'])) {
1379 self::preload_course_contacts($records);
1381 // If option 'idonly' is specified no further action is needed, just return list of ids.
1382 if (!empty($options['idonly'])) {
1383 return array_keys($records);
1385 // Prepare the list of course_in_list objects.
1386 foreach ($ids as $id) {
1387 $courses[$id] = new course_in_list($records[$id]);
1390 return $courses;
1393 $preloadcoursecontacts = !empty($options['coursecontacts']);
1394 unset($options['coursecontacts']);
1396 // Empty search string will return all results.
1397 if (!isset($search['search'])) {
1398 $search['search'] = '';
1401 if (empty($search['blocklist']) && empty($search['modulelist']) && empty($search['tagid'])) {
1402 // Search courses that have specified words in their names/summaries.
1403 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1405 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount, $requiredcapabilities);
1406 self::sort_records($courselist, $sortfields);
1407 $coursecatcache->set($cachekey, array_keys($courselist));
1408 $coursecatcache->set($cntcachekey, $totalcount);
1409 $records = array_slice($courselist, $offset, $limit, true);
1410 } else {
1411 if (!empty($search['blocklist'])) {
1412 // Search courses that have block with specified id.
1413 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1414 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1415 WHERE bi.blockname = :blockname)';
1416 $params = array('blockname' => $blockname);
1417 } else if (!empty($search['modulelist'])) {
1418 // Search courses that have module with specified name.
1419 $where = "c.id IN (SELECT DISTINCT module.course ".
1420 "FROM {".$search['modulelist']."} module)";
1421 $params = array();
1422 } else if (!empty($search['tagid'])) {
1423 // Search courses that are tagged with the specified tag.
1424 $where = "c.id IN (SELECT t.itemid ".
1425 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype AND t.component = :component)";
1426 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course', 'component' => 'core');
1427 if (!empty($search['ctx'])) {
1428 $rec = isset($search['rec']) ? $search['rec'] : true;
1429 $parentcontext = context::instance_by_id($search['ctx']);
1430 if ($parentcontext->contextlevel == CONTEXT_SYSTEM && $rec) {
1431 // Parent context is system context and recursive is set to yes.
1432 // Nothing to filter - all courses fall into this condition.
1433 } else if ($rec) {
1434 // Filter all courses in the parent context at any level.
1435 $where .= ' AND ctx.path LIKE :contextpath';
1436 $params['contextpath'] = $parentcontext->path . '%';
1437 } else if ($parentcontext->contextlevel == CONTEXT_COURSECAT) {
1438 // All courses in the given course category.
1439 $where .= ' AND c.category = :category';
1440 $params['category'] = $parentcontext->instanceid;
1441 } else {
1442 // No courses will satisfy the context criterion, do not bother searching.
1443 $where = '1=0';
1446 } else {
1447 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1448 return array();
1450 $courselist = self::get_course_records($where, $params, $options, true);
1451 if (!empty($requiredcapabilities)) {
1452 foreach ($courselist as $key => $course) {
1453 context_helper::preload_from_record($course);
1454 $coursecontext = context_course::instance($course->id);
1455 if (!has_all_capabilities($requiredcapabilities, $coursecontext)) {
1456 unset($courselist[$key]);
1460 self::sort_records($courselist, $sortfields);
1461 $coursecatcache->set($cachekey, array_keys($courselist));
1462 $coursecatcache->set($cntcachekey, count($courselist));
1463 $records = array_slice($courselist, $offset, $limit, true);
1466 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1467 if (!empty($preloadcoursecontacts)) {
1468 self::preload_course_contacts($records);
1470 // If option 'idonly' is specified no further action is needed, just return list of ids.
1471 if (!empty($options['idonly'])) {
1472 return array_keys($records);
1474 // Prepare the list of course_in_list objects.
1475 $courses = array();
1476 foreach ($records as $record) {
1477 $courses[$record->id] = new course_in_list($record);
1479 return $courses;
1483 * Returns number of courses in the search results
1485 * It is recommended to call this function after {@link coursecat::search_courses()}
1486 * and not before because only course ids are cached. Otherwise search_courses() may
1487 * perform extra DB queries.
1489 * @param array $search search criteria, see method search_courses() for more details
1490 * @param array $options display options. They do not affect the result but
1491 * the 'sort' property is used in cache key for storing list of course ids
1492 * @param array $requiredcapabilites List of capabilities required to see return course.
1493 * @return int
1495 public static function search_courses_count($search, $options = array(), $requiredcapabilities = array()) {
1496 $coursecatcache = cache::make('core', 'coursecat');
1497 $cntcachekey = 'scnt-'. serialize($search) . serialize($requiredcapabilities);
1498 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1499 // Cached value not found. Retrieve ALL courses and return their count.
1500 unset($options['offset']);
1501 unset($options['limit']);
1502 unset($options['summary']);
1503 unset($options['coursecontacts']);
1504 $options['idonly'] = true;
1505 $courses = self::search_courses($search, $options, $requiredcapabilities);
1506 $cnt = count($courses);
1508 return $cnt;
1512 * Retrieves the list of courses accessible by user
1514 * Not all information is cached, try to avoid calling this method
1515 * twice in the same request.
1517 * The following fields are always retrieved:
1518 * - id, visible, fullname, shortname, idnumber, category, sortorder
1520 * If you plan to use properties/methods course_in_list::$summary and/or
1521 * course_in_list::get_course_contacts()
1522 * you can preload this information using appropriate 'options'. Otherwise
1523 * they will be retrieved from DB on demand and it may end with bigger DB load.
1525 * Note that method course_in_list::has_summary() will not perform additional
1526 * DB queries even if $options['summary'] is not specified
1528 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1529 * to this when somebody edits courses or categories, however it is very
1530 * difficult to keep track of all possible changes that may affect list of courses.
1532 * @param array $options options for retrieving children
1533 * - recursive - return courses from subcategories as well. Use with care,
1534 * this may be a huge list!
1535 * - summary - preloads fields 'summary' and 'summaryformat'
1536 * - coursecontacts - preloads course contacts
1537 * - sort - list of fields to sort. Example
1538 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1539 * will sort by idnumber asc, shortname asc and id desc.
1540 * Default: array('sortorder' => 1)
1541 * Only cached fields may be used for sorting!
1542 * - offset
1543 * - limit - maximum number of children to return, 0 or null for no limit
1544 * - idonly - returns the array or course ids instead of array of objects
1545 * used only in get_courses_count()
1546 * @return course_in_list[]
1548 public function get_courses($options = array()) {
1549 global $DB;
1550 $recursive = !empty($options['recursive']);
1551 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1552 $limit = !empty($options['limit']) ? $options['limit'] : null;
1553 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1555 // Check if this category is hidden.
1556 // Also 0-category never has courses unless this is recursive call.
1557 if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1558 return array();
1561 $coursecatcache = cache::make('core', 'coursecat');
1562 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1563 '-'. serialize($sortfields);
1564 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1566 // Check if we have already cached results.
1567 $ids = $coursecatcache->get($cachekey);
1568 if ($ids !== false) {
1569 // We already cached last search result and it did not expire yet.
1570 $ids = array_slice($ids, $offset, $limit);
1571 $courses = array();
1572 if (!empty($ids)) {
1573 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1574 $records = self::get_course_records("c.id ". $sql, $params, $options);
1575 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1576 if (!empty($options['coursecontacts'])) {
1577 self::preload_course_contacts($records);
1579 // If option 'idonly' is specified no further action is needed, just return list of ids.
1580 if (!empty($options['idonly'])) {
1581 return array_keys($records);
1583 // Prepare the list of course_in_list objects.
1584 foreach ($ids as $id) {
1585 $courses[$id] = new course_in_list($records[$id]);
1588 return $courses;
1591 // Retrieve list of courses in category.
1592 $where = 'c.id <> :siteid';
1593 $params = array('siteid' => SITEID);
1594 if ($recursive) {
1595 if ($this->id) {
1596 $context = context_coursecat::instance($this->id);
1597 $where .= ' AND ctx.path like :path';
1598 $params['path'] = $context->path. '/%';
1600 } else {
1601 $where .= ' AND c.category = :categoryid';
1602 $params['categoryid'] = $this->id;
1604 // Get list of courses without preloaded coursecontacts because we don't need them for every course.
1605 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1607 // Sort and cache list.
1608 self::sort_records($list, $sortfields);
1609 $coursecatcache->set($cachekey, array_keys($list));
1610 $coursecatcache->set($cntcachekey, count($list));
1612 // Apply offset/limit, convert to course_in_list and return.
1613 $courses = array();
1614 if (isset($list)) {
1615 if ($offset || $limit) {
1616 $list = array_slice($list, $offset, $limit, true);
1618 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1619 if (!empty($options['coursecontacts'])) {
1620 self::preload_course_contacts($list);
1622 // If option 'idonly' is specified no further action is needed, just return list of ids.
1623 if (!empty($options['idonly'])) {
1624 return array_keys($list);
1626 // Prepare the list of course_in_list objects.
1627 foreach ($list as $record) {
1628 $courses[$record->id] = new course_in_list($record);
1631 return $courses;
1635 * Returns number of courses visible to the user
1637 * @param array $options similar to get_courses() except some options do not affect
1638 * number of courses (i.e. sort, summary, offset, limit etc.)
1639 * @return int
1641 public function get_courses_count($options = array()) {
1642 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1643 $coursecatcache = cache::make('core', 'coursecat');
1644 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1645 // Cached value not found. Retrieve ALL courses and return their count.
1646 unset($options['offset']);
1647 unset($options['limit']);
1648 unset($options['summary']);
1649 unset($options['coursecontacts']);
1650 $options['idonly'] = true;
1651 $courses = $this->get_courses($options);
1652 $cnt = count($courses);
1654 return $cnt;
1658 * Returns true if the user is able to delete this category.
1660 * Note if this category contains any courses this isn't a full check, it will need to be accompanied by a call to either
1661 * {@link coursecat::can_delete_full()} or {@link coursecat::can_move_content_to()} depending upon what the user wished to do.
1663 * @return boolean
1665 public function can_delete() {
1666 if (!$this->has_manage_capability()) {
1667 return false;
1669 return $this->parent_has_manage_capability();
1673 * Returns true if user can delete current category and all its contents
1675 * To be able to delete course category the user must have permission
1676 * 'moodle/category:manage' in ALL child course categories AND
1677 * be able to delete all courses
1679 * @return bool
1681 public function can_delete_full() {
1682 global $DB;
1683 if (!$this->id) {
1684 // Fool-proof.
1685 return false;
1688 $context = $this->get_context();
1689 if (!$this->is_uservisible() ||
1690 !has_capability('moodle/category:manage', $context)) {
1691 return false;
1694 // Check all child categories (not only direct children).
1695 $sql = context_helper::get_preload_record_columns_sql('ctx');
1696 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1697 ' FROM {context} ctx '.
1698 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1699 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1700 array($context->path. '/%', CONTEXT_COURSECAT));
1701 foreach ($childcategories as $childcat) {
1702 context_helper::preload_from_record($childcat);
1703 $childcontext = context_coursecat::instance($childcat->id);
1704 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1705 !has_capability('moodle/category:manage', $childcontext)) {
1706 return false;
1710 // Check courses.
1711 $sql = context_helper::get_preload_record_columns_sql('ctx');
1712 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1713 $sql. ' FROM {context} ctx '.
1714 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1715 array('pathmask' => $context->path. '/%',
1716 'courselevel' => CONTEXT_COURSE));
1717 foreach ($coursescontexts as $ctxrecord) {
1718 context_helper::preload_from_record($ctxrecord);
1719 if (!can_delete_course($ctxrecord->courseid)) {
1720 return false;
1724 return true;
1728 * Recursively delete category including all subcategories and courses
1730 * Function {@link coursecat::can_delete_full()} MUST be called prior
1731 * to calling this function because there is no capability check
1732 * inside this function
1734 * @param boolean $showfeedback display some notices
1735 * @return array return deleted courses
1736 * @throws moodle_exception
1738 public function delete_full($showfeedback = true) {
1739 global $CFG, $DB;
1741 require_once($CFG->libdir.'/gradelib.php');
1742 require_once($CFG->libdir.'/questionlib.php');
1743 require_once($CFG->dirroot.'/cohort/lib.php');
1745 // Make sure we won't timeout when deleting a lot of courses.
1746 $settimeout = core_php_time_limit::raise();
1748 // Allow plugins to use this category before we completely delete it.
1749 if ($pluginsfunction = get_plugins_with_function('pre_course_category_delete')) {
1750 $category = $this->get_db_record();
1751 foreach ($pluginsfunction as $plugintype => $plugins) {
1752 foreach ($plugins as $pluginfunction) {
1753 $pluginfunction($category);
1758 $deletedcourses = array();
1760 // Get children. Note, we don't want to use cache here because it would be rebuilt too often.
1761 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1762 foreach ($children as $record) {
1763 $coursecat = new coursecat($record);
1764 $deletedcourses += $coursecat->delete_full($showfeedback);
1767 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1768 foreach ($courses as $course) {
1769 if (!delete_course($course, false)) {
1770 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1772 $deletedcourses[] = $course;
1776 // Move or delete cohorts in this context.
1777 cohort_delete_category($this);
1779 // Now delete anything that may depend on course category context.
1780 grade_course_category_delete($this->id, 0, $showfeedback);
1781 if (!question_delete_course_category($this, 0, $showfeedback)) {
1782 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1785 // Delete all events in the category.
1786 $DB->delete_records('event', array('categoryid' => $this->id));
1788 // Finally delete the category and it's context.
1789 $DB->delete_records('course_categories', array('id' => $this->id));
1791 $coursecatcontext = context_coursecat::instance($this->id);
1792 $coursecatcontext->delete();
1794 cache_helper::purge_by_event('changesincoursecat');
1796 // Trigger a course category deleted event.
1797 /* @var \core\event\course_category_deleted $event */
1798 $event = \core\event\course_category_deleted::create(array(
1799 'objectid' => $this->id,
1800 'context' => $coursecatcontext,
1801 'other' => array('name' => $this->name)
1803 $event->set_coursecat($this);
1804 $event->trigger();
1806 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1807 if ($this->id == $CFG->defaultrequestcategory) {
1808 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1810 return $deletedcourses;
1814 * Checks if user can delete this category and move content (courses, subcategories and questions)
1815 * to another category. If yes returns the array of possible target categories names
1817 * If user can not manage this category or it is completely empty - empty array will be returned
1819 * @return array
1821 public function move_content_targets_list() {
1822 global $CFG;
1823 require_once($CFG->libdir . '/questionlib.php');
1824 $context = $this->get_context();
1825 if (!$this->is_uservisible() ||
1826 !has_capability('moodle/category:manage', $context)) {
1827 // User is not able to manage current category, he is not able to delete it.
1828 // No possible target categories.
1829 return array();
1832 $testcaps = array();
1833 // If this category has courses in it, user must have 'course:create' capability in target category.
1834 if ($this->has_courses()) {
1835 $testcaps[] = 'moodle/course:create';
1837 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1838 if ($this->has_children() || question_context_has_any_questions($context)) {
1839 $testcaps[] = 'moodle/category:manage';
1841 if (!empty($testcaps)) {
1842 // Return list of categories excluding this one and it's children.
1843 return self::make_categories_list($testcaps, $this->id);
1846 // Category is completely empty, no need in target for contents.
1847 return array();
1851 * Checks if user has capability to move all category content to the new parent before
1852 * removing this category
1854 * @param int $newcatid
1855 * @return bool
1857 public function can_move_content_to($newcatid) {
1858 global $CFG;
1859 require_once($CFG->libdir . '/questionlib.php');
1860 $context = $this->get_context();
1861 if (!$this->is_uservisible() ||
1862 !has_capability('moodle/category:manage', $context)) {
1863 return false;
1865 $testcaps = array();
1866 // If this category has courses in it, user must have 'course:create' capability in target category.
1867 if ($this->has_courses()) {
1868 $testcaps[] = 'moodle/course:create';
1870 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1871 if ($this->has_children() || question_context_has_any_questions($context)) {
1872 $testcaps[] = 'moodle/category:manage';
1874 if (!empty($testcaps)) {
1875 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1878 // There is no content but still return true.
1879 return true;
1883 * Deletes a category and moves all content (children, courses and questions) to the new parent
1885 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1886 * must be called prior
1888 * @param int $newparentid
1889 * @param bool $showfeedback
1890 * @return bool
1892 public function delete_move($newparentid, $showfeedback = false) {
1893 global $CFG, $DB, $OUTPUT;
1895 require_once($CFG->libdir.'/gradelib.php');
1896 require_once($CFG->libdir.'/questionlib.php');
1897 require_once($CFG->dirroot.'/cohort/lib.php');
1899 // Get all objects and lists because later the caches will be reset so.
1900 // We don't need to make extra queries.
1901 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1902 $catname = $this->get_formatted_name();
1903 $children = $this->get_children();
1904 $params = array('category' => $this->id);
1905 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', $params);
1906 $context = $this->get_context();
1908 if ($children) {
1909 foreach ($children as $childcat) {
1910 $childcat->change_parent_raw($newparentcat);
1911 // Log action.
1912 $event = \core\event\course_category_updated::create(array(
1913 'objectid' => $childcat->id,
1914 'context' => $childcat->get_context()
1916 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $childcat->id,
1917 $childcat->id));
1918 $event->trigger();
1920 fix_course_sortorder();
1923 if ($coursesids) {
1924 require_once($CFG->dirroot.'/course/lib.php');
1925 if (!move_courses($coursesids, $newparentid)) {
1926 if ($showfeedback) {
1927 echo $OUTPUT->notification("Error moving courses");
1929 return false;
1931 if ($showfeedback) {
1932 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1936 // Move or delete cohorts in this context.
1937 cohort_delete_category($this);
1939 // Now delete anything that may depend on course category context.
1940 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1941 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1942 if ($showfeedback) {
1943 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1945 return false;
1948 // Finally delete the category and it's context.
1949 $DB->delete_records('course_categories', array('id' => $this->id));
1950 $context->delete();
1952 // Trigger a course category deleted event.
1953 /* @var \core\event\course_category_deleted $event */
1954 $event = \core\event\course_category_deleted::create(array(
1955 'objectid' => $this->id,
1956 'context' => $context,
1957 'other' => array('name' => $this->name)
1959 $event->set_coursecat($this);
1960 $event->trigger();
1962 cache_helper::purge_by_event('changesincoursecat');
1964 if ($showfeedback) {
1965 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1968 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1969 if ($this->id == $CFG->defaultrequestcategory) {
1970 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1972 return true;
1976 * Checks if user can move current category to the new parent
1978 * This checks if new parent category exists, user has manage cap there
1979 * and new parent is not a child of this category
1981 * @param int|stdClass|coursecat $newparentcat
1982 * @return bool
1984 public function can_change_parent($newparentcat) {
1985 if (!has_capability('moodle/category:manage', $this->get_context())) {
1986 return false;
1988 if (is_object($newparentcat)) {
1989 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1990 } else {
1991 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1993 if (!$newparentcat) {
1994 return false;
1996 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1997 // Can not move to itself or it's own child.
1998 return false;
2000 if ($newparentcat->id) {
2001 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
2002 } else {
2003 return has_capability('moodle/category:manage', context_system::instance());
2008 * Moves the category under another parent category. All associated contexts are moved as well
2010 * This is protected function, use change_parent() or update() from outside of this class
2012 * @see coursecat::change_parent()
2013 * @see coursecat::update()
2015 * @param coursecat $newparentcat
2016 * @throws moodle_exception
2018 protected function change_parent_raw(coursecat $newparentcat) {
2019 global $DB;
2021 $context = $this->get_context();
2023 $hidecat = false;
2024 if (empty($newparentcat->id)) {
2025 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
2026 $newparent = context_system::instance();
2027 } else {
2028 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
2029 // Can not move to itself or it's own child.
2030 throw new moodle_exception('cannotmovecategory');
2032 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
2033 $newparent = context_coursecat::instance($newparentcat->id);
2035 if (!$newparentcat->visible and $this->visible) {
2036 // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children
2037 // will be restored properly.
2038 $hidecat = true;
2041 $this->parent = $newparentcat->id;
2043 $context->update_moved($newparent);
2045 // Now make it last in new category.
2046 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
2048 if ($hidecat) {
2049 fix_course_sortorder();
2050 $this->restore();
2051 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must
2052 // become visible again.
2053 $this->hide_raw(1);
2058 * Efficiently moves a category - NOTE that this can have
2059 * a huge impact access-control-wise...
2061 * Note that this function does not check capabilities.
2063 * Example of usage:
2064 * $coursecat = coursecat::get($categoryid);
2065 * if ($coursecat->can_change_parent($newparentcatid)) {
2066 * $coursecat->change_parent($newparentcatid);
2069 * This function does not update field course_categories.timemodified
2070 * If you want to update timemodified, use
2071 * $coursecat->update(array('parent' => $newparentcat));
2073 * @param int|stdClass|coursecat $newparentcat
2075 public function change_parent($newparentcat) {
2076 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
2077 if (is_object($newparentcat)) {
2078 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
2079 } else {
2080 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
2082 if ($newparentcat->id != $this->parent) {
2083 $this->change_parent_raw($newparentcat);
2084 fix_course_sortorder();
2085 cache_helper::purge_by_event('changesincoursecat');
2086 $this->restore();
2088 $event = \core\event\course_category_updated::create(array(
2089 'objectid' => $this->id,
2090 'context' => $this->get_context()
2092 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $this->id, $this->id));
2093 $event->trigger();
2098 * Hide course category and child course and subcategories
2100 * If this category has changed the parent and is moved under hidden
2101 * category we will want to store it's current visibility state in
2102 * the field 'visibleold'. If admin clicked 'hide' for this particular
2103 * category, the field 'visibleold' should become 0.
2105 * All subcategories and courses will have their current visibility in the field visibleold
2107 * This is protected function, use hide() or update() from outside of this class
2109 * @see coursecat::hide()
2110 * @see coursecat::update()
2112 * @param int $visibleold value to set in field $visibleold for this category
2113 * @return bool whether changes have been made and caches need to be purged afterwards
2115 protected function hide_raw($visibleold = 0) {
2116 global $DB;
2117 $changes = false;
2119 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing.
2120 if ($this->id && $this->__get('visibleold') != $visibleold) {
2121 $this->visibleold = $visibleold;
2122 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
2123 $changes = true;
2125 if (!$this->visible || !$this->id) {
2126 // Already hidden or can not be hidden.
2127 return $changes;
2130 $this->visible = 0;
2131 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
2132 // Store visible flag so that we can return to it if we immediately unhide.
2133 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id));
2134 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
2135 // Get all child categories and hide too.
2136 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
2137 foreach ($subcats as $cat) {
2138 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
2139 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
2140 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
2141 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
2144 return true;
2148 * Hide course category and child course and subcategories
2150 * Note that there is no capability check inside this function
2152 * This function does not update field course_categories.timemodified
2153 * If you want to update timemodified, use
2154 * $coursecat->update(array('visible' => 0));
2156 public function hide() {
2157 if ($this->hide_raw(0)) {
2158 cache_helper::purge_by_event('changesincoursecat');
2160 $event = \core\event\course_category_updated::create(array(
2161 'objectid' => $this->id,
2162 'context' => $this->get_context()
2164 $event->set_legacy_logdata(array(SITEID, 'category', 'hide', 'editcategory.php?id=' . $this->id, $this->id));
2165 $event->trigger();
2170 * Show course category and restores visibility for child course and subcategories
2172 * Note that there is no capability check inside this function
2174 * This is protected function, use show() or update() from outside of this class
2176 * @see coursecat::show()
2177 * @see coursecat::update()
2179 * @return bool whether changes have been made and caches need to be purged afterwards
2181 protected function show_raw() {
2182 global $DB;
2184 if ($this->visible) {
2185 // Already visible.
2186 return false;
2189 $this->visible = 1;
2190 $this->visibleold = 1;
2191 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
2192 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
2193 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
2194 // Get all child categories and unhide too.
2195 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
2196 foreach ($subcats as $cat) {
2197 if ($cat->visibleold) {
2198 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
2200 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
2203 return true;
2207 * Show course category and restores visibility for child course and subcategories
2209 * Note that there is no capability check inside this function
2211 * This function does not update field course_categories.timemodified
2212 * If you want to update timemodified, use
2213 * $coursecat->update(array('visible' => 1));
2215 public function show() {
2216 if ($this->show_raw()) {
2217 cache_helper::purge_by_event('changesincoursecat');
2219 $event = \core\event\course_category_updated::create(array(
2220 'objectid' => $this->id,
2221 'context' => $this->get_context()
2223 $event->set_legacy_logdata(array(SITEID, 'category', 'show', 'editcategory.php?id=' . $this->id, $this->id));
2224 $event->trigger();
2229 * Returns name of the category formatted as a string
2231 * @param array $options formatting options other than context
2232 * @return string
2234 public function get_formatted_name($options = array()) {
2235 if ($this->id) {
2236 $context = $this->get_context();
2237 return format_string($this->name, true, array('context' => $context) + $options);
2238 } else {
2239 return get_string('top');
2244 * Get the nested name of this category, with all of it's parents.
2246 * @param bool $includelinks Whether to wrap each name in the view link for that category.
2247 * @param string $separator The string between each name.
2248 * @param array $options Formatting options.
2249 * @return string
2251 public function get_nested_name($includelinks = true, $separator = ' / ', $options = []) {
2252 // Get the name of hierarchical name of this category.
2253 $parents = $this->get_parents();
2254 $categories = static::get_many($parents);
2255 $categories[] = $this;
2257 $names = array_map(function($category) use ($options, $includelinks) {
2258 if ($includelinks) {
2259 return html_writer::link($category->get_view_link(), $category->get_formatted_name($options));
2260 } else {
2261 return $category->get_formatted_name($options);
2264 }, $categories);
2266 return implode($separator, $names);
2270 * Returns ids of all parents of the category. Last element in the return array is the direct parent
2272 * For example, if you have a tree of categories like:
2273 * Miscellaneous (id = 1)
2274 * Subcategory (id = 2)
2275 * Sub-subcategory (id = 4)
2276 * Other category (id = 3)
2278 * coursecat::get(1)->get_parents() == array()
2279 * coursecat::get(2)->get_parents() == array(1)
2280 * coursecat::get(4)->get_parents() == array(1, 2);
2282 * Note that this method does not check if all parents are accessible by current user
2284 * @return array of category ids
2286 public function get_parents() {
2287 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
2288 array_pop($parents);
2289 return $parents;
2293 * This function returns a nice list representing category tree
2294 * for display or to use in a form <select> element
2296 * List is cached for 10 minutes
2298 * For example, if you have a tree of categories like:
2299 * Miscellaneous (id = 1)
2300 * Subcategory (id = 2)
2301 * Sub-subcategory (id = 4)
2302 * Other category (id = 3)
2303 * Then after calling this function you will have
2304 * array(1 => 'Miscellaneous',
2305 * 2 => 'Miscellaneous / Subcategory',
2306 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2307 * 3 => 'Other category');
2309 * If you specify $requiredcapability, then only categories where the current
2310 * user has that capability will be added to $list.
2311 * If you only have $requiredcapability in a child category, not the parent,
2312 * then the child catgegory will still be included.
2314 * If you specify the option $excludeid, then that category, and all its children,
2315 * are omitted from the tree. This is useful when you are doing something like
2316 * moving categories, where you do not want to allow people to move a category
2317 * to be the child of itself.
2319 * See also {@link make_categories_options()}
2321 * @param string/array $requiredcapability if given, only categories where the current
2322 * user has this capability will be returned. Can also be an array of capabilities,
2323 * in which case they are all required.
2324 * @param integer $excludeid Exclude this category and its children from the lists built.
2325 * @param string $separator string to use as a separator between parent and child category. Default ' / '
2326 * @return array of strings
2328 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
2329 global $DB;
2330 $coursecatcache = cache::make('core', 'coursecat');
2332 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids
2333 // with requried cap ($thislist).
2334 $currentlang = current_language();
2335 $basecachekey = $currentlang . '_catlist';
2336 $baselist = $coursecatcache->get($basecachekey);
2337 $thislist = false;
2338 $thiscachekey = null;
2339 if (!empty($requiredcapability)) {
2340 $requiredcapability = (array)$requiredcapability;
2341 $thiscachekey = 'catlist:'. serialize($requiredcapability);
2342 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
2343 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
2345 } else if ($baselist !== false) {
2346 $thislist = array_keys($baselist);
2349 if ($baselist === false) {
2350 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
2351 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2352 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
2353 FROM {course_categories} cc
2354 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
2355 ORDER BY cc.sortorder";
2356 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2357 $baselist = array();
2358 $thislist = array();
2359 foreach ($rs as $record) {
2360 // If the category's parent is not visible to the user, it is not visible as well.
2361 if (!$record->parent || isset($baselist[$record->parent])) {
2362 context_helper::preload_from_record($record);
2363 $context = context_coursecat::instance($record->id);
2364 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
2365 // No cap to view category, added to neither $baselist nor $thislist.
2366 continue;
2368 $baselist[$record->id] = array(
2369 'name' => format_string($record->name, true, array('context' => $context)),
2370 'path' => $record->path
2372 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
2373 // No required capability, added to $baselist but not to $thislist.
2374 continue;
2376 $thislist[] = $record->id;
2379 $rs->close();
2380 $coursecatcache->set($basecachekey, $baselist);
2381 if (!empty($requiredcapability)) {
2382 $coursecatcache->set($thiscachekey, join(',', $thislist));
2384 } else if ($thislist === false) {
2385 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
2386 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2387 $sql = "SELECT ctx.instanceid AS id, $ctxselect
2388 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
2389 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2390 $thislist = array();
2391 foreach (array_keys($baselist) as $id) {
2392 context_helper::preload_from_record($contexts[$id]);
2393 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
2394 $thislist[] = $id;
2397 $coursecatcache->set($thiscachekey, join(',', $thislist));
2400 // Now build the array of strings to return, mind $separator and $excludeid.
2401 $names = array();
2402 foreach ($thislist as $id) {
2403 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
2404 if (!$excludeid || !in_array($excludeid, $path)) {
2405 $namechunks = array();
2406 foreach ($path as $parentid) {
2407 $namechunks[] = $baselist[$parentid]['name'];
2409 $names[$id] = join($separator, $namechunks);
2412 return $names;
2416 * Prepares the object for caching. Works like the __sleep method.
2418 * implementing method from interface cacheable_object
2420 * @return array ready to be cached
2422 public function prepare_to_cache() {
2423 $a = array();
2424 foreach (self::$coursecatfields as $property => $cachedirectives) {
2425 if ($cachedirectives !== null) {
2426 list($shortname, $defaultvalue) = $cachedirectives;
2427 if ($this->$property !== $defaultvalue) {
2428 $a[$shortname] = $this->$property;
2432 $context = $this->get_context();
2433 $a['xi'] = $context->id;
2434 $a['xp'] = $context->path;
2435 return $a;
2439 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2441 * implementing method from interface cacheable_object
2443 * @param array $a
2444 * @return coursecat
2446 public static function wake_from_cache($a) {
2447 $record = new stdClass;
2448 foreach (self::$coursecatfields as $property => $cachedirectives) {
2449 if ($cachedirectives !== null) {
2450 list($shortname, $defaultvalue) = $cachedirectives;
2451 if (array_key_exists($shortname, $a)) {
2452 $record->$property = $a[$shortname];
2453 } else {
2454 $record->$property = $defaultvalue;
2458 $record->ctxid = $a['xi'];
2459 $record->ctxpath = $a['xp'];
2460 $record->ctxdepth = $record->depth + 1;
2461 $record->ctxlevel = CONTEXT_COURSECAT;
2462 $record->ctxinstance = $record->id;
2463 return new coursecat($record, true);
2467 * Returns true if the user is able to create a top level category.
2468 * @return bool
2470 public static function can_create_top_level_category() {
2471 return has_capability('moodle/category:manage', context_system::instance());
2475 * Returns the category context.
2476 * @return context_coursecat
2478 public function get_context() {
2479 if ($this->id === 0) {
2480 // This is the special top level category object.
2481 return context_system::instance();
2482 } else {
2483 return context_coursecat::instance($this->id);
2488 * Returns true if the user is able to manage this category.
2489 * @return bool
2491 public function has_manage_capability() {
2492 if ($this->hasmanagecapability === null) {
2493 $this->hasmanagecapability = has_capability('moodle/category:manage', $this->get_context());
2495 return $this->hasmanagecapability;
2499 * Returns true if the user has the manage capability on the parent category.
2500 * @return bool
2502 public function parent_has_manage_capability() {
2503 return has_capability('moodle/category:manage', get_category_or_system_context($this->parent));
2507 * Returns true if the current user can create subcategories of this category.
2508 * @return bool
2510 public function can_create_subcategory() {
2511 return $this->has_manage_capability();
2515 * Returns true if the user can resort this categories sub categories and courses.
2516 * Must have manage capability and be able to see all subcategories.
2517 * @return bool
2519 public function can_resort_subcategories() {
2520 return $this->has_manage_capability() && !$this->get_not_visible_children_ids();
2524 * Returns true if the user can resort the courses within this category.
2525 * Must have manage capability and be able to see all courses.
2526 * @return bool
2528 public function can_resort_courses() {
2529 return $this->has_manage_capability() && $this->coursecount == $this->get_courses_count();
2533 * Returns true of the user can change the sortorder of this category (resort in the parent category)
2534 * @return bool
2536 public function can_change_sortorder() {
2537 return $this->id && $this->get_parent_coursecat()->can_resort_subcategories();
2541 * Returns true if the current user can create a course within this category.
2542 * @return bool
2544 public function can_create_course() {
2545 return has_capability('moodle/course:create', $this->get_context());
2549 * Returns true if the current user can edit this categories settings.
2550 * @return bool
2552 public function can_edit() {
2553 return $this->has_manage_capability();
2557 * Returns true if the current user can review role assignments for this category.
2558 * @return bool
2560 public function can_review_roles() {
2561 return has_capability('moodle/role:assign', $this->get_context());
2565 * Returns true if the current user can review permissions for this category.
2566 * @return bool
2568 public function can_review_permissions() {
2569 return has_any_capability(array(
2570 'moodle/role:assign',
2571 'moodle/role:safeoverride',
2572 'moodle/role:override',
2573 'moodle/role:assign'
2574 ), $this->get_context());
2578 * Returns true if the current user can review cohorts for this category.
2579 * @return bool
2581 public function can_review_cohorts() {
2582 return has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->get_context());
2586 * Returns true if the current user can review filter settings for this category.
2587 * @return bool
2589 public function can_review_filters() {
2590 return has_capability('moodle/filter:manage', $this->get_context()) &&
2591 count(filter_get_available_in_context($this->get_context()))>0;
2595 * Returns true if the current user is able to change the visbility of this category.
2596 * @return bool
2598 public function can_change_visibility() {
2599 return $this->parent_has_manage_capability();
2603 * Returns true if the user can move courses out of this category.
2604 * @return bool
2606 public function can_move_courses_out_of() {
2607 return $this->has_manage_capability();
2611 * Returns true if the user can move courses into this category.
2612 * @return bool
2614 public function can_move_courses_into() {
2615 return $this->has_manage_capability();
2619 * Returns true if the user is able to restore a course into this category as a new course.
2620 * @return bool
2622 public function can_restore_courses_into() {
2623 return has_capability('moodle/restore:restorecourse', $this->get_context());
2627 * Resorts the sub categories of this category by the given field.
2629 * @param string $field One of name, idnumber or descending values of each (appended desc)
2630 * @param bool $cleanup If true cleanup will be done, if false you will need to do it manually later.
2631 * @return bool True on success.
2632 * @throws coding_exception
2634 public function resort_subcategories($field, $cleanup = true) {
2635 global $DB;
2636 $desc = false;
2637 if (substr($field, -4) === "desc") {
2638 $desc = true;
2639 $field = substr($field, 0, -4); // Remove "desc" from field name.
2641 if ($field !== 'name' && $field !== 'idnumber') {
2642 throw new coding_exception('Invalid field requested');
2644 $children = $this->get_children();
2645 core_collator::asort_objects_by_property($children, $field, core_collator::SORT_NATURAL);
2646 if (!empty($desc)) {
2647 $children = array_reverse($children);
2649 $i = 1;
2650 foreach ($children as $cat) {
2651 $i++;
2652 $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id));
2653 $i += $cat->coursecount;
2655 if ($cleanup) {
2656 self::resort_categories_cleanup();
2658 return true;
2662 * Cleans things up after categories have been resorted.
2663 * @param bool $includecourses If set to true we know courses have been resorted as well.
2665 public static function resort_categories_cleanup($includecourses = false) {
2666 // This should not be needed but we do it just to be safe.
2667 fix_course_sortorder();
2668 cache_helper::purge_by_event('changesincoursecat');
2669 if ($includecourses) {
2670 cache_helper::purge_by_event('changesincourse');
2675 * Resort the courses within this category by the given field.
2677 * @param string $field One of fullname, shortname, idnumber or descending values of each (appended desc)
2678 * @param bool $cleanup
2679 * @return bool True for success.
2680 * @throws coding_exception
2682 public function resort_courses($field, $cleanup = true) {
2683 global $DB;
2684 $desc = false;
2685 if (substr($field, -4) === "desc") {
2686 $desc = true;
2687 $field = substr($field, 0, -4); // Remove "desc" from field name.
2689 if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber' && $field !== 'timecreated') {
2690 // This is ultra important as we use $field in an SQL statement below this.
2691 throw new coding_exception('Invalid field requested');
2693 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
2694 $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields
2695 FROM {course} c
2696 LEFT JOIN {context} ctx ON ctx.instanceid = c.id
2697 WHERE ctx.contextlevel = :ctxlevel AND
2698 c.category = :categoryid";
2699 $params = array(
2700 'ctxlevel' => CONTEXT_COURSE,
2701 'categoryid' => $this->id
2703 $courses = $DB->get_records_sql($sql, $params);
2704 if (count($courses) > 0) {
2705 foreach ($courses as $courseid => $course) {
2706 context_helper::preload_from_record($course);
2707 if ($field === 'idnumber') {
2708 $course->sortby = $course->idnumber;
2709 } else {
2710 // It'll require formatting.
2711 $options = array(
2712 'context' => context_course::instance($course->id)
2714 // We format the string first so that it appears as the user would see it.
2715 // This ensures the sorting makes sense to them. However it won't necessarily make
2716 // sense to everyone if things like multilang filters are enabled.
2717 // We then strip any tags as we don't want things such as image tags skewing the
2718 // sort results.
2719 $course->sortby = strip_tags(format_string($course->$field, true, $options));
2721 // We set it back here rather than using references as there is a bug with using
2722 // references in a foreach before passing as an arg by reference.
2723 $courses[$courseid] = $course;
2725 // Sort the courses.
2726 core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL);
2727 if (!empty($desc)) {
2728 $courses = array_reverse($courses);
2730 $i = 1;
2731 foreach ($courses as $course) {
2732 $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id));
2733 $i++;
2735 if ($cleanup) {
2736 // This should not be needed but we do it just to be safe.
2737 fix_course_sortorder();
2738 cache_helper::purge_by_event('changesincourse');
2741 return true;
2745 * Changes the sort order of this categories parent shifting this category up or down one.
2747 * @global \moodle_database $DB
2748 * @param bool $up If set to true the category is shifted up one spot, else its moved down.
2749 * @return bool True on success, false otherwise.
2751 public function change_sortorder_by_one($up) {
2752 global $DB;
2753 $params = array($this->sortorder, $this->parent);
2754 if ($up) {
2755 $select = 'sortorder < ? AND parent = ?';
2756 $sort = 'sortorder DESC';
2757 } else {
2758 $select = 'sortorder > ? AND parent = ?';
2759 $sort = 'sortorder ASC';
2761 fix_course_sortorder();
2762 $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1);
2763 $swapcategory = reset($swapcategory);
2764 if ($swapcategory) {
2765 $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id));
2766 $DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id));
2767 $this->sortorder = $swapcategory->sortorder;
2769 $event = \core\event\course_category_updated::create(array(
2770 'objectid' => $this->id,
2771 'context' => $this->get_context()
2773 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'management.php?categoryid=' . $this->id,
2774 $this->id));
2775 $event->trigger();
2777 // Finally reorder courses.
2778 fix_course_sortorder();
2779 cache_helper::purge_by_event('changesincoursecat');
2780 return true;
2782 return false;
2786 * Returns the parent coursecat object for this category.
2788 * @return coursecat
2790 public function get_parent_coursecat() {
2791 return self::get($this->parent);
2796 * Returns true if the user is able to request a new course be created.
2797 * @return bool
2799 public function can_request_course() {
2800 global $CFG;
2801 if (empty($CFG->enablecourserequests) || $this->id != $CFG->defaultrequestcategory) {
2802 return false;
2804 return !$this->can_create_course() && has_capability('moodle/course:request', $this->get_context());
2808 * Returns true if the user can approve course requests.
2809 * @return bool
2811 public static function can_approve_course_requests() {
2812 global $CFG, $DB;
2813 if (empty($CFG->enablecourserequests)) {
2814 return false;
2816 $context = context_system::instance();
2817 if (!has_capability('moodle/site:approvecourse', $context)) {
2818 return false;
2820 if (!$DB->record_exists('course_request', array())) {
2821 return false;
2823 return true;
2828 * Class to store information about one course in a list of courses
2830 * Not all information may be retrieved when object is created but
2831 * it will be retrieved on demand when appropriate property or method is
2832 * called.
2834 * Instances of this class are usually returned by functions
2835 * {@link coursecat::search_courses()}
2836 * and
2837 * {@link coursecat::get_courses()}
2839 * @property-read int $id
2840 * @property-read int $category Category ID
2841 * @property-read int $sortorder
2842 * @property-read string $fullname
2843 * @property-read string $shortname
2844 * @property-read string $idnumber
2845 * @property-read string $summary Course summary. 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 int $summaryformat Summary format. Field is present if coursecat::get_courses()
2848 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2849 * @property-read string $format Course format. Retrieved from DB on first request
2850 * @property-read int $showgrades Retrieved from DB on first request
2851 * @property-read int $newsitems Retrieved from DB on first request
2852 * @property-read int $startdate
2853 * @property-read int $enddate
2854 * @property-read int $marker Retrieved from DB on first request
2855 * @property-read int $maxbytes Retrieved from DB on first request
2856 * @property-read int $legacyfiles Retrieved from DB on first request
2857 * @property-read int $showreports Retrieved from DB on first request
2858 * @property-read int $visible
2859 * @property-read int $visibleold Retrieved from DB on first request
2860 * @property-read int $groupmode Retrieved from DB on first request
2861 * @property-read int $groupmodeforce Retrieved from DB on first request
2862 * @property-read int $defaultgroupingid Retrieved from DB on first request
2863 * @property-read string $lang Retrieved from DB on first request
2864 * @property-read string $theme Retrieved from DB on first request
2865 * @property-read int $timecreated Retrieved from DB on first request
2866 * @property-read int $timemodified Retrieved from DB on first request
2867 * @property-read int $requested Retrieved from DB on first request
2868 * @property-read int $enablecompletion Retrieved from DB on first request
2869 * @property-read int $completionnotify Retrieved from DB on first request
2870 * @property-read int $cacherev
2872 * @package core
2873 * @subpackage course
2874 * @copyright 2013 Marina Glancy
2875 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2877 class course_in_list implements IteratorAggregate {
2879 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2880 protected $record;
2882 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2883 protected $coursecontacts;
2885 /** @var bool true if the current user can access the course, false otherwise. */
2886 protected $canaccess = null;
2889 * Creates an instance of the class from record
2891 * @param stdClass $record except fields from course table it may contain
2892 * field hassummary indicating that summary field is not empty.
2893 * Also it is recommended to have context fields here ready for
2894 * context preloading
2896 public function __construct(stdClass $record) {
2897 context_helper::preload_from_record($record);
2898 $this->record = new stdClass();
2899 foreach ($record as $key => $value) {
2900 $this->record->$key = $value;
2905 * Indicates if the course has non-empty summary field
2907 * @return bool
2909 public function has_summary() {
2910 if (isset($this->record->hassummary)) {
2911 return !empty($this->record->hassummary);
2913 if (!isset($this->record->summary)) {
2914 // We need to retrieve summary.
2915 $this->__get('summary');
2917 return !empty($this->record->summary);
2921 * Indicates if the course have course contacts to display
2923 * @return bool
2925 public function has_course_contacts() {
2926 if (!isset($this->record->managers)) {
2927 $courses = array($this->id => &$this->record);
2928 coursecat::preload_course_contacts($courses);
2930 return !empty($this->record->managers);
2934 * Returns list of course contacts (usually teachers) to display in course link
2936 * Roles to display are set up in $CFG->coursecontact
2938 * The result is the list of users where user id is the key and the value
2939 * is an array with elements:
2940 * - 'user' - object containing basic user information
2941 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2942 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2943 * - 'username' => fullname($user, $canviewfullnames)
2945 * @return array
2947 public function get_course_contacts() {
2948 global $CFG;
2949 if (empty($CFG->coursecontact)) {
2950 // No roles are configured to be displayed as course contacts.
2951 return array();
2953 if ($this->coursecontacts === null) {
2954 $this->coursecontacts = array();
2955 $context = context_course::instance($this->id);
2957 if (!isset($this->record->managers)) {
2958 // Preload course contacts from DB.
2959 $courses = array($this->id => &$this->record);
2960 coursecat::preload_course_contacts($courses);
2963 // Build return array with full roles names (for this course context) and users names.
2964 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2965 foreach ($this->record->managers as $ruser) {
2966 if (isset($this->coursecontacts[$ruser->id])) {
2967 // Only display a user once with the highest sortorder role.
2968 continue;
2970 $user = new stdClass();
2971 $user = username_load_fields_from_object($user, $ruser, null, array('id', 'username'));
2972 $role = new stdClass();
2973 $role->id = $ruser->roleid;
2974 $role->name = $ruser->rolename;
2975 $role->shortname = $ruser->roleshortname;
2976 $role->coursealias = $ruser->rolecoursealias;
2978 $this->coursecontacts[$user->id] = array(
2979 'user' => $user,
2980 'role' => $role,
2981 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2982 'username' => fullname($user, $canviewfullnames)
2986 return $this->coursecontacts;
2990 * Checks if course has any associated overview files
2992 * @return bool
2994 public function has_course_overviewfiles() {
2995 global $CFG;
2996 if (empty($CFG->courseoverviewfileslimit)) {
2997 return false;
2999 $fs = get_file_storage();
3000 $context = context_course::instance($this->id);
3001 return !$fs->is_area_empty($context->id, 'course', 'overviewfiles');
3005 * Returns all course overview files
3007 * @return array array of stored_file objects
3009 public function get_course_overviewfiles() {
3010 global $CFG;
3011 if (empty($CFG->courseoverviewfileslimit)) {
3012 return array();
3014 require_once($CFG->libdir. '/filestorage/file_storage.php');
3015 require_once($CFG->dirroot. '/course/lib.php');
3016 $fs = get_file_storage();
3017 $context = context_course::instance($this->id);
3018 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
3019 if (count($files)) {
3020 $overviewfilesoptions = course_overviewfiles_options($this->id);
3021 $acceptedtypes = $overviewfilesoptions['accepted_types'];
3022 if ($acceptedtypes !== '*') {
3023 // Filter only files with allowed extensions.
3024 require_once($CFG->libdir. '/filelib.php');
3025 foreach ($files as $key => $file) {
3026 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
3027 unset($files[$key]);
3031 if (count($files) > $CFG->courseoverviewfileslimit) {
3032 // Return no more than $CFG->courseoverviewfileslimit files.
3033 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
3036 return $files;
3040 * Magic method to check if property is set
3042 * @param string $name
3043 * @return bool
3045 public function __isset($name) {
3046 return isset($this->record->$name);
3050 * Magic method to get a course property
3052 * Returns any field from table course (retrieves it from DB if it was not retrieved before)
3054 * @param string $name
3055 * @return mixed
3057 public function __get($name) {
3058 global $DB;
3059 if (property_exists($this->record, $name)) {
3060 return $this->record->$name;
3061 } else if ($name === 'summary' || $name === 'summaryformat') {
3062 // Retrieve fields summary and summaryformat together because they are most likely to be used together.
3063 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
3064 $this->record->summary = $record->summary;
3065 $this->record->summaryformat = $record->summaryformat;
3066 return $this->record->$name;
3067 } else if (array_key_exists($name, $DB->get_columns('course'))) {
3068 // Another field from table 'course' that was not retrieved.
3069 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
3070 return $this->record->$name;
3072 debugging('Invalid course property accessed! '.$name);
3073 return null;
3077 * All properties are read only, sorry.
3079 * @param string $name
3081 public function __unset($name) {
3082 debugging('Can not unset '.get_class($this).' instance properties!');
3086 * Magic setter method, we do not want anybody to modify properties from the outside
3088 * @param string $name
3089 * @param mixed $value
3091 public function __set($name, $value) {
3092 debugging('Can not change '.get_class($this).' instance properties!');
3096 * Create an iterator because magic vars can't be seen by 'foreach'.
3097 * Exclude context fields
3099 * Implementing method from interface IteratorAggregate
3101 * @return ArrayIterator
3103 public function getIterator() {
3104 $ret = array('id' => $this->record->id);
3105 foreach ($this->record as $property => $value) {
3106 $ret[$property] = $value;
3108 return new ArrayIterator($ret);
3112 * Returns the name of this course as it should be displayed within a list.
3113 * @return string
3115 public function get_formatted_name() {
3116 return format_string(get_course_display_name_for_list($this), true, $this->get_context());
3120 * Returns the formatted fullname for this course.
3121 * @return string
3123 public function get_formatted_fullname() {
3124 return format_string($this->__get('fullname'), true, $this->get_context());
3128 * Returns the formatted shortname for this course.
3129 * @return string
3131 public function get_formatted_shortname() {
3132 return format_string($this->__get('shortname'), true, $this->get_context());
3136 * Returns true if the current user can access this course.
3137 * @return bool
3139 public function can_access() {
3140 if ($this->canaccess === null) {
3141 $this->canaccess = can_access_course($this->record);
3143 return $this->canaccess;
3147 * Returns true if the user can edit this courses settings.
3149 * Note: this function does not check that the current user can access the course.
3150 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3152 * @return bool
3154 public function can_edit() {
3155 return has_capability('moodle/course:update', $this->get_context());
3159 * Returns true if the user can change the visibility of this course.
3161 * Note: this function does not check that the current user can access the course.
3162 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3164 * @return bool
3166 public function can_change_visibility() {
3167 // You must be able to both hide a course and view the hidden course.
3168 return has_all_capabilities(array('moodle/course:visibility', 'moodle/course:viewhiddencourses'), $this->get_context());
3172 * Returns the context for this course.
3173 * @return context_course
3175 public function get_context() {
3176 return context_course::instance($this->__get('id'));
3180 * Returns true if this course is visible to the current user.
3181 * @return bool
3183 public function is_uservisible() {
3184 return $this->visible || has_capability('moodle/course:viewhiddencourses', $this->get_context());
3188 * Returns true if the current user can review enrolments for this course.
3190 * Note: this function does not check that the current user can access the course.
3191 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3193 * @return bool
3195 public function can_review_enrolments() {
3196 return has_capability('moodle/course:enrolreview', $this->get_context());
3200 * Returns true if the current user can delete this course.
3202 * Note: this function does not check that the current user can access the course.
3203 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3205 * @return bool
3207 public function can_delete() {
3208 return can_delete_course($this->id);
3212 * Returns true if the current user can backup this course.
3214 * Note: this function does not check that the current user can access the course.
3215 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3217 * @return bool
3219 public function can_backup() {
3220 return has_capability('moodle/backup:backupcourse', $this->get_context());
3224 * Returns true if the current user can restore this course.
3226 * Note: this function does not check that the current user can access the course.
3227 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3229 * @return bool
3231 public function can_restore() {
3232 return has_capability('moodle/restore:restorecourse', $this->get_context());
3237 * An array of records that is sortable by many fields.
3239 * For more info on the ArrayObject class have a look at php.net.
3241 * @package core
3242 * @subpackage course
3243 * @copyright 2013 Sam Hemelryk
3244 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3246 class coursecat_sortable_records extends ArrayObject {
3249 * An array of sortable fields.
3250 * Gets set temporarily when sort is called.
3251 * @var array
3253 protected $sortfields = array();
3256 * Sorts this array using the given fields.
3258 * @param array $records
3259 * @param array $fields
3260 * @return array
3262 public static function sort(array $records, array $fields) {
3263 $records = new coursecat_sortable_records($records);
3264 $records->sortfields = $fields;
3265 $records->uasort(array($records, 'sort_by_many_fields'));
3266 return $records->getArrayCopy();
3270 * Sorts the two records based upon many fields.
3272 * This method should not be called itself, please call $sort instead.
3273 * It has been marked as access private as such.
3275 * @access private
3276 * @param stdClass $a
3277 * @param stdClass $b
3278 * @return int
3280 public function sort_by_many_fields($a, $b) {
3281 foreach ($this->sortfields as $field => $mult) {
3282 // Nulls first.
3283 if (is_null($a->$field) && !is_null($b->$field)) {
3284 return -$mult;
3286 if (is_null($b->$field) && !is_null($a->$field)) {
3287 return $mult;
3290 if (is_string($a->$field) || is_string($b->$field)) {
3291 // String fields.
3292 if ($cmp = strcoll($a->$field, $b->$field)) {
3293 return $mult * $cmp;
3295 } else {
3296 // Int fields.
3297 if ($a->$field > $b->$field) {
3298 return $mult;
3300 if ($a->$field < $b->$field) {
3301 return -$mult;
3305 return 0;