weekly release 3.2.1+
[moodle.git] / lib / coursecatlib.php
blobd8ce7b8cfa95b5412cdaef6132bb26114dc2b58c
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Contains class coursecat reponsible for course category operations
20 * @package core
21 * @subpackage course
22 * @copyright 2013 Marina Glancy
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /**
29 * Class to store, cache, render and manage course category
31 * @property-read int $id
32 * @property-read string $name
33 * @property-read string $idnumber
34 * @property-read string $description
35 * @property-read int $descriptionformat
36 * @property-read int $parent
37 * @property-read int $sortorder
38 * @property-read int $coursecount
39 * @property-read int $visible
40 * @property-read int $visibleold
41 * @property-read int $timemodified
42 * @property-read int $depth
43 * @property-read string $path
44 * @property-read string $theme
46 * @package core
47 * @subpackage course
48 * @copyright 2013 Marina Glancy
49 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
51 class coursecat implements renderable, cacheable_object, IteratorAggregate {
52 /** @var coursecat stores pseudo category with id=0. Use coursecat::get(0) to retrieve */
53 protected static $coursecat0;
55 /** @var array list of all fields and their short name and default value for caching */
56 protected static $coursecatfields = array(
57 'id' => array('id', 0),
58 'name' => array('na', ''),
59 'idnumber' => array('in', null),
60 'description' => null, // Not cached.
61 'descriptionformat' => null, // Not cached.
62 'parent' => array('pa', 0),
63 'sortorder' => array('so', 0),
64 'coursecount' => array('cc', 0),
65 'visible' => array('vi', 1),
66 'visibleold' => null, // Not cached.
67 'timemodified' => null, // Not cached.
68 'depth' => array('dh', 1),
69 'path' => array('ph', null),
70 'theme' => null, // Not cached.
73 /** @var int */
74 protected $id;
76 /** @var string */
77 protected $name = '';
79 /** @var string */
80 protected $idnumber = null;
82 /** @var string */
83 protected $description = false;
85 /** @var int */
86 protected $descriptionformat = false;
88 /** @var int */
89 protected $parent = 0;
91 /** @var int */
92 protected $sortorder = 0;
94 /** @var int */
95 protected $coursecount = false;
97 /** @var int */
98 protected $visible = 1;
100 /** @var int */
101 protected $visibleold = false;
103 /** @var int */
104 protected $timemodified = false;
106 /** @var int */
107 protected $depth = 0;
109 /** @var string */
110 protected $path = '';
112 /** @var string */
113 protected $theme = false;
115 /** @var bool */
116 protected $fromcache;
118 /** @var bool */
119 protected $hasmanagecapability = null;
122 * Magic setter method, we do not want anybody to modify properties from the outside
124 * @param string $name
125 * @param mixed $value
127 public function __set($name, $value) {
128 debugging('Can not change coursecat instance properties!', DEBUG_DEVELOPER);
132 * Magic method getter, redirects to read only values. Queries from DB the fields that were not cached
134 * @param string $name
135 * @return mixed
137 public function __get($name) {
138 global $DB;
139 if (array_key_exists($name, self::$coursecatfields)) {
140 if ($this->$name === false) {
141 // Property was not retrieved from DB, retrieve all not retrieved fields.
142 $notretrievedfields = array_diff_key(self::$coursecatfields, array_filter(self::$coursecatfields));
143 $record = $DB->get_record('course_categories', array('id' => $this->id),
144 join(',', array_keys($notretrievedfields)), MUST_EXIST);
145 foreach ($record as $key => $value) {
146 $this->$key = $value;
149 return $this->$name;
151 debugging('Invalid coursecat property accessed! '.$name, DEBUG_DEVELOPER);
152 return null;
156 * Full support for isset on our magic read only properties.
158 * @param string $name
159 * @return bool
161 public function __isset($name) {
162 if (array_key_exists($name, self::$coursecatfields)) {
163 return isset($this->$name);
165 return false;
169 * All properties are read only, sorry.
171 * @param string $name
173 public function __unset($name) {
174 debugging('Can not unset coursecat instance properties!', DEBUG_DEVELOPER);
178 * Create an iterator because magic vars can't be seen by 'foreach'.
180 * implementing method from interface IteratorAggregate
182 * @return ArrayIterator
184 public function getIterator() {
185 $ret = array();
186 foreach (self::$coursecatfields as $property => $unused) {
187 if ($this->$property !== false) {
188 $ret[$property] = $this->$property;
191 return new ArrayIterator($ret);
195 * Constructor
197 * Constructor is protected, use coursecat::get($id) to retrieve category
199 * @param stdClass $record record from DB (may not contain all fields)
200 * @param bool $fromcache whether it is being restored from cache
202 protected function __construct(stdClass $record, $fromcache = false) {
203 context_helper::preload_from_record($record);
204 foreach ($record as $key => $val) {
205 if (array_key_exists($key, self::$coursecatfields)) {
206 $this->$key = $val;
209 $this->fromcache = $fromcache;
213 * Returns coursecat object for requested category
215 * If category is not visible to user it is treated as non existing
216 * unless $alwaysreturnhidden is set to true
218 * If id is 0, the pseudo object for root category is returned (convenient
219 * for calling other functions such as get_children())
221 * @param int $id category id
222 * @param int $strictness whether to throw an exception (MUST_EXIST) or
223 * return null (IGNORE_MISSING) in case the category is not found or
224 * not visible to current user
225 * @param bool $alwaysreturnhidden set to true if you want an object to be
226 * returned even if this category is not visible to the current user
227 * (category is hidden and user does not have
228 * 'moodle/category:viewhiddencategories' capability). Use with care!
229 * @return null|coursecat
230 * @throws moodle_exception
232 public static function get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false) {
233 if (!$id) {
234 if (!isset(self::$coursecat0)) {
235 $record = new stdClass();
236 $record->id = 0;
237 $record->visible = 1;
238 $record->depth = 0;
239 $record->path = '';
240 self::$coursecat0 = new coursecat($record);
242 return self::$coursecat0;
244 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
245 $coursecat = $coursecatrecordcache->get($id);
246 if ($coursecat === false) {
247 if ($records = self::get_records('cc.id = :id', array('id' => $id))) {
248 $record = reset($records);
249 $coursecat = new coursecat($record);
250 // Store in cache.
251 $coursecatrecordcache->set($id, $coursecat);
254 if ($coursecat && ($alwaysreturnhidden || $coursecat->is_uservisible())) {
255 return $coursecat;
256 } else {
257 if ($strictness == MUST_EXIST) {
258 throw new moodle_exception('unknowncategory');
261 return null;
265 * Load many coursecat objects.
267 * @global moodle_database $DB
268 * @param array $ids An array of category ID's to load.
269 * @return coursecat[]
271 public static function get_many(array $ids) {
272 global $DB;
273 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
274 $categories = $coursecatrecordcache->get_many($ids);
275 $toload = array();
276 foreach ($categories as $id => $result) {
277 if ($result === false) {
278 $toload[] = $id;
281 if (!empty($toload)) {
282 list($where, $params) = $DB->get_in_or_equal($toload, SQL_PARAMS_NAMED);
283 $records = self::get_records('cc.id '.$where, $params);
284 $toset = array();
285 foreach ($records as $record) {
286 $categories[$record->id] = new coursecat($record);
287 $toset[$record->id] = $categories[$record->id];
289 $coursecatrecordcache->set_many($toset);
291 return $categories;
295 * Returns the first found category
297 * Note that if there are no categories visible to the current user on the first level,
298 * the invisible category may be returned
300 * @return coursecat
302 public static function get_default() {
303 if ($visiblechildren = self::get(0)->get_children()) {
304 $defcategory = reset($visiblechildren);
305 } else {
306 $toplevelcategories = self::get_tree(0);
307 $defcategoryid = $toplevelcategories[0];
308 $defcategory = self::get($defcategoryid, MUST_EXIST, true);
310 return $defcategory;
314 * Restores the object after it has been externally modified in DB for example
315 * during {@link fix_course_sortorder()}
317 protected function restore() {
318 // Update all fields in the current object.
319 $newrecord = self::get($this->id, MUST_EXIST, true);
320 foreach (self::$coursecatfields as $key => $unused) {
321 $this->$key = $newrecord->$key;
326 * Creates a new category either from form data or from raw data
328 * Please note that this function does not verify access control.
330 * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
332 * Category visibility is inherited from parent unless $data->visible = 0 is specified
334 * @param array|stdClass $data
335 * @param array $editoroptions if specified, the data is considered to be
336 * form data and file_postupdate_standard_editor() is being called to
337 * process images in description.
338 * @return coursecat
339 * @throws moodle_exception
341 public static function create($data, $editoroptions = null) {
342 global $DB, $CFG;
343 $data = (object)$data;
344 $newcategory = new stdClass();
346 $newcategory->descriptionformat = FORMAT_MOODLE;
347 $newcategory->description = '';
348 // Copy all description* fields regardless of whether this is form data or direct field update.
349 foreach ($data as $key => $value) {
350 if (preg_match("/^description/", $key)) {
351 $newcategory->$key = $value;
355 if (empty($data->name)) {
356 throw new moodle_exception('categorynamerequired');
358 if (core_text::strlen($data->name) > 255) {
359 throw new moodle_exception('categorytoolong');
361 $newcategory->name = $data->name;
363 // Validate and set idnumber.
364 if (isset($data->idnumber)) {
365 if (core_text::strlen($data->idnumber) > 100) {
366 throw new moodle_exception('idnumbertoolong');
368 if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
369 throw new moodle_exception('categoryidnumbertaken');
371 $newcategory->idnumber = $data->idnumber;
374 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
375 $newcategory->theme = $data->theme;
378 if (empty($data->parent)) {
379 $parent = self::get(0);
380 } else {
381 $parent = self::get($data->parent, MUST_EXIST, true);
383 $newcategory->parent = $parent->id;
384 $newcategory->depth = $parent->depth + 1;
386 // By default category is visible, unless visible = 0 is specified or parent category is hidden.
387 if (isset($data->visible) && !$data->visible) {
388 // Create a hidden category.
389 $newcategory->visible = $newcategory->visibleold = 0;
390 } else {
391 // Create a category that inherits visibility from parent.
392 $newcategory->visible = $parent->visible;
393 // In case parent is hidden, when it changes visibility this new subcategory will automatically become visible too.
394 $newcategory->visibleold = 1;
397 $newcategory->sortorder = 0;
398 $newcategory->timemodified = time();
400 $newcategory->id = $DB->insert_record('course_categories', $newcategory);
402 // Update path (only possible after we know the category id.
403 $path = $parent->path . '/' . $newcategory->id;
404 $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));
406 // We should mark the context as dirty.
407 context_coursecat::instance($newcategory->id)->mark_dirty();
409 fix_course_sortorder();
411 // If this is data from form results, save embedded files and update description.
412 $categorycontext = context_coursecat::instance($newcategory->id);
413 if ($editoroptions) {
414 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
415 'coursecat', 'description', 0);
417 // Update only fields description and descriptionformat.
418 $updatedata = new stdClass();
419 $updatedata->id = $newcategory->id;
420 $updatedata->description = $newcategory->description;
421 $updatedata->descriptionformat = $newcategory->descriptionformat;
422 $DB->update_record('course_categories', $updatedata);
425 $event = \core\event\course_category_created::create(array(
426 'objectid' => $newcategory->id,
427 'context' => $categorycontext
429 $event->trigger();
431 cache_helper::purge_by_event('changesincoursecat');
433 return self::get($newcategory->id, MUST_EXIST, true);
437 * Updates the record with either form data or raw data
439 * Please note that this function does not verify access control.
441 * This function calls coursecat::change_parent_raw if field 'parent' is updated.
442 * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
443 * Visibility is changed first and then parent is changed. This means that
444 * if parent category is hidden, the current category will become hidden
445 * too and it may overwrite whatever was set in field 'visible'.
447 * Note that fields 'path' and 'depth' can not be updated manually
448 * Also coursecat::update() can not directly update the field 'sortoder'
450 * @param array|stdClass $data
451 * @param array $editoroptions if specified, the data is considered to be
452 * form data and file_postupdate_standard_editor() is being called to
453 * process images in description.
454 * @throws moodle_exception
456 public function update($data, $editoroptions = null) {
457 global $DB, $CFG;
458 if (!$this->id) {
459 // There is no actual DB record associated with root category.
460 return;
463 $data = (object)$data;
464 $newcategory = new stdClass();
465 $newcategory->id = $this->id;
467 // Copy all description* fields regardless of whether this is form data or direct field update.
468 foreach ($data as $key => $value) {
469 if (preg_match("/^description/", $key)) {
470 $newcategory->$key = $value;
474 if (isset($data->name) && empty($data->name)) {
475 throw new moodle_exception('categorynamerequired');
478 if (!empty($data->name) && $data->name !== $this->name) {
479 if (core_text::strlen($data->name) > 255) {
480 throw new moodle_exception('categorytoolong');
482 $newcategory->name = $data->name;
485 if (isset($data->idnumber) && $data->idnumber !== $this->idnumber) {
486 if (core_text::strlen($data->idnumber) > 100) {
487 throw new moodle_exception('idnumbertoolong');
489 if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
490 throw new moodle_exception('categoryidnumbertaken');
492 $newcategory->idnumber = $data->idnumber;
495 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
496 $newcategory->theme = $data->theme;
499 $changes = false;
500 if (isset($data->visible)) {
501 if ($data->visible) {
502 $changes = $this->show_raw();
503 } else {
504 $changes = $this->hide_raw(0);
508 if (isset($data->parent) && $data->parent != $this->parent) {
509 if ($changes) {
510 cache_helper::purge_by_event('changesincoursecat');
512 $parentcat = self::get($data->parent, MUST_EXIST, true);
513 $this->change_parent_raw($parentcat);
514 fix_course_sortorder();
517 $newcategory->timemodified = time();
519 $categorycontext = $this->get_context();
520 if ($editoroptions) {
521 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
522 'coursecat', 'description', 0);
524 $DB->update_record('course_categories', $newcategory);
526 $event = \core\event\course_category_updated::create(array(
527 'objectid' => $newcategory->id,
528 'context' => $categorycontext
530 $event->trigger();
532 fix_course_sortorder();
533 // Purge cache even if fix_course_sortorder() did not do it.
534 cache_helper::purge_by_event('changesincoursecat');
536 // Update all fields in the current object.
537 $this->restore();
541 * Checks if this course category is visible to current user
543 * Please note that methods coursecat::get (without 3rd argumet),
544 * coursecat::get_children(), etc. return only visible categories so it is
545 * usually not needed to call this function outside of this class
547 * @return bool
549 public function is_uservisible() {
550 return !$this->id || $this->visible ||
551 has_capability('moodle/category:viewhiddencategories', $this->get_context());
555 * Returns the complete corresponding record from DB table course_categories
557 * Mostly used in deprecated functions
559 * @return stdClass
561 public function get_db_record() {
562 global $DB;
563 if ($record = $DB->get_record('course_categories', array('id' => $this->id))) {
564 return $record;
565 } else {
566 return (object)convert_to_array($this);
571 * Returns the entry from categories tree and makes sure the application-level tree cache is built
573 * The following keys can be requested:
575 * 'countall' - total number of categories in the system (always present)
576 * 0 - array of ids of top-level categories (always present)
577 * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
578 * $id (int) - array of ids of categories that are direct children of category with id $id. If
579 * category with id $id does not exist returns false. If category has no children returns empty array
580 * $id.'i' - array of ids of children categories that have visible=0
582 * @param int|string $id
583 * @return mixed
585 protected static function get_tree($id) {
586 global $DB;
587 $coursecattreecache = cache::make('core', 'coursecattree');
588 $rv = $coursecattreecache->get($id);
589 if ($rv !== false) {
590 return $rv;
592 // Re-build the tree.
593 $sql = "SELECT cc.id, cc.parent, cc.visible
594 FROM {course_categories} cc
595 ORDER BY cc.sortorder";
596 $rs = $DB->get_recordset_sql($sql, array());
597 $all = array(0 => array(), '0i' => array());
598 $count = 0;
599 foreach ($rs as $record) {
600 $all[$record->id] = array();
601 $all[$record->id. 'i'] = array();
602 if (array_key_exists($record->parent, $all)) {
603 $all[$record->parent][] = $record->id;
604 if (!$record->visible) {
605 $all[$record->parent. 'i'][] = $record->id;
607 } else {
608 // Parent not found. This is data consistency error but next fix_course_sortorder() should fix it.
609 $all[0][] = $record->id;
610 if (!$record->visible) {
611 $all['0i'][] = $record->id;
614 $count++;
616 $rs->close();
617 if (!$count) {
618 // No categories found.
619 // This may happen after upgrade of a very old moodle version.
620 // In new versions the default category is created on install.
621 $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
622 set_config('defaultrequestcategory', $defcoursecat->id);
623 $all[0] = array($defcoursecat->id);
624 $all[$defcoursecat->id] = array();
625 $count++;
627 // We must add countall to all in case it was the requested ID.
628 $all['countall'] = $count;
629 foreach ($all as $key => $children) {
630 $coursecattreecache->set($key, $children);
632 if (array_key_exists($id, $all)) {
633 return $all[$id];
635 // Requested non-existing category.
636 return array();
640 * Returns number of ALL categories in the system regardless if
641 * they are visible to current user or not
643 * @return int
645 public static function count_all() {
646 return self::get_tree('countall');
650 * Retrieves number of records from course_categories table
652 * Only cached fields are retrieved. Records are ready for preloading context
654 * @param string $whereclause
655 * @param array $params
656 * @return array array of stdClass objects
658 protected static function get_records($whereclause, $params) {
659 global $DB;
660 // Retrieve from DB only the fields that need to be stored in cache.
661 $fields = array_keys(array_filter(self::$coursecatfields));
662 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
663 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
664 FROM {course_categories} cc
665 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
666 WHERE ". $whereclause." ORDER BY cc.sortorder";
667 return $DB->get_records_sql($sql,
668 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
672 * Resets course contact caches when role assignments were changed
674 * @param int $roleid role id that was given or taken away
675 * @param context $context context where role assignment has been changed
677 public static function role_assignment_changed($roleid, $context) {
678 global $CFG, $DB;
680 if ($context->contextlevel > CONTEXT_COURSE) {
681 // No changes to course contacts if role was assigned on the module/block level.
682 return;
685 if (!$CFG->coursecontact || !in_array($roleid, explode(',', $CFG->coursecontact))) {
686 // The role is not one of course contact roles.
687 return;
690 // Remove from cache course contacts of all affected courses.
691 $cache = cache::make('core', 'coursecontacts');
692 if ($context->contextlevel == CONTEXT_COURSE) {
693 $cache->delete($context->instanceid);
694 } else if ($context->contextlevel == CONTEXT_SYSTEM) {
695 $cache->purge();
696 } else {
697 $sql = "SELECT ctx.instanceid
698 FROM {context} ctx
699 WHERE ctx.path LIKE ? AND ctx.contextlevel = ?";
700 $params = array($context->path . '/%', CONTEXT_COURSE);
701 if ($courses = $DB->get_fieldset_sql($sql, $params)) {
702 $cache->delete_many($courses);
708 * Executed when user enrolment was changed to check if course
709 * contacts cache needs to be cleared
711 * @param int $courseid course id
712 * @param int $userid user id
713 * @param int $status new enrolment status (0 - active, 1 - suspended)
714 * @param int $timestart new enrolment time start
715 * @param int $timeend new enrolment time end
717 public static function user_enrolment_changed($courseid, $userid,
718 $status, $timestart = null, $timeend = null) {
719 $cache = cache::make('core', 'coursecontacts');
720 $contacts = $cache->get($courseid);
721 if ($contacts === false) {
722 // The contacts for the affected course were not cached anyway.
723 return;
725 $enrolmentactive = ($status == 0) &&
726 (!$timestart || $timestart < time()) &&
727 (!$timeend || $timeend > time());
728 if (!$enrolmentactive) {
729 $isincontacts = false;
730 foreach ($contacts as $contact) {
731 if ($contact->id == $userid) {
732 $isincontacts = true;
735 if (!$isincontacts) {
736 // Changed user's enrolment does not exist or is not active,
737 // and he is not in cached course contacts, no changes to be made.
738 return;
741 // Either enrolment of manager was deleted/suspended
742 // or user enrolment was added or activated.
743 // In order to see if the course contacts for this course need
744 // changing we would need to make additional queries, they will
745 // slow down bulk enrolment changes. It is better just to remove
746 // course contacts cache for this course.
747 $cache->delete($courseid);
751 * Given list of DB records from table course populates each record with list of users with course contact roles
753 * This function fills the courses with raw information as {@link get_role_users()} would do.
754 * See also {@link course_in_list::get_course_contacts()} for more readable return
756 * $courses[$i]->managers = array(
757 * $roleassignmentid => $roleuser,
758 * ...
759 * );
761 * where $roleuser is an stdClass with the following properties:
763 * $roleuser->raid - role assignment id
764 * $roleuser->id - user id
765 * $roleuser->username
766 * $roleuser->firstname
767 * $roleuser->lastname
768 * $roleuser->rolecoursealias
769 * $roleuser->rolename
770 * $roleuser->sortorder - role sortorder
771 * $roleuser->roleid
772 * $roleuser->roleshortname
774 * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
776 * @param array $courses
778 public static function preload_course_contacts(&$courses) {
779 global $CFG, $DB;
780 if (empty($courses) || empty($CFG->coursecontact)) {
781 return;
783 $managerroles = explode(',', $CFG->coursecontact);
784 $cache = cache::make('core', 'coursecontacts');
785 $cacheddata = $cache->get_many(array_keys($courses));
786 $courseids = array();
787 foreach (array_keys($courses) as $id) {
788 if ($cacheddata[$id] !== false) {
789 $courses[$id]->managers = $cacheddata[$id];
790 } else {
791 $courseids[] = $id;
795 // Array $courseids now stores list of ids of courses for which we still need to retrieve contacts.
796 if (empty($courseids)) {
797 return;
800 // First build the array of all context ids of the courses and their categories.
801 $allcontexts = array();
802 foreach ($courseids as $id) {
803 $context = context_course::instance($id);
804 $courses[$id]->managers = array();
805 foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
806 if (!isset($allcontexts[$ctxid])) {
807 $allcontexts[$ctxid] = array();
809 $allcontexts[$ctxid][] = $id;
813 // Fetch list of all users with course contact roles in any of the courses contexts or parent contexts.
814 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
815 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
816 list($sort, $sortparams) = users_order_by_sql('u');
817 $notdeleted = array('notdeleted'=>0);
818 $allnames = get_all_user_name_fields(true, 'u');
819 $sql = "SELECT ra.contextid, ra.id AS raid,
820 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
821 rn.name AS rolecoursealias, u.id, u.username, $allnames
822 FROM {role_assignments} ra
823 JOIN {user} u ON ra.userid = u.id
824 JOIN {role} r ON ra.roleid = r.id
825 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
826 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
827 ORDER BY r.sortorder, $sort";
828 $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
829 $checkenrolments = array();
830 foreach ($rs as $ra) {
831 foreach ($allcontexts[$ra->contextid] as $id) {
832 $courses[$id]->managers[$ra->raid] = $ra;
833 if (!isset($checkenrolments[$id])) {
834 $checkenrolments[$id] = array();
836 $checkenrolments[$id][] = $ra->id;
839 $rs->close();
841 // Remove from course contacts users who are not enrolled in the course.
842 $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
843 foreach ($checkenrolments as $id => $userids) {
844 if (empty($enrolleduserids[$id])) {
845 $courses[$id]->managers = array();
846 } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
847 foreach ($courses[$id]->managers as $raid => $ra) {
848 if (in_array($ra->id, $notenrolled)) {
849 unset($courses[$id]->managers[$raid]);
855 // Set the cache.
856 $values = array();
857 foreach ($courseids as $id) {
858 $values[$id] = $courses[$id]->managers;
860 $cache->set_many($values);
864 * Verify user enrollments for multiple course-user combinations
866 * @param array $courseusers array where keys are course ids and values are array
867 * of users in this course whose enrolment we wish to verify
868 * @return array same structure as input array but values list only users from input
869 * who are enrolled in the course
871 protected static function ensure_users_enrolled($courseusers) {
872 global $DB;
873 // If the input array is too big, split it into chunks.
874 $maxcoursesinquery = 20;
875 if (count($courseusers) > $maxcoursesinquery) {
876 $rv = array();
877 for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
878 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
879 $rv = $rv + self::ensure_users_enrolled($chunk);
881 return $rv;
884 // Create a query verifying valid user enrolments for the number of courses.
885 $sql = "SELECT DISTINCT e.courseid, ue.userid
886 FROM {user_enrolments} ue
887 JOIN {enrol} e ON e.id = ue.enrolid
888 WHERE ue.status = :active
889 AND e.status = :enabled
890 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
891 $now = round(time(), -2); // Rounding helps caching in DB.
892 $params = array('enabled' => ENROL_INSTANCE_ENABLED,
893 'active' => ENROL_USER_ACTIVE,
894 'now1' => $now, 'now2' => $now);
895 $cnt = 0;
896 $subsqls = array();
897 $enrolled = array();
898 foreach ($courseusers as $id => $userids) {
899 $enrolled[$id] = array();
900 if (count($userids)) {
901 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
902 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
903 $params = $params + array('courseid'.$cnt => $id) + $params2;
904 $cnt++;
907 if (count($subsqls)) {
908 $sql .= "AND (". join(' OR ', $subsqls).")";
909 $rs = $DB->get_recordset_sql($sql, $params);
910 foreach ($rs as $record) {
911 $enrolled[$record->courseid][] = $record->userid;
913 $rs->close();
915 return $enrolled;
919 * Retrieves number of records from course table
921 * Not all fields are retrieved. Records are ready for preloading context
923 * @param string $whereclause
924 * @param array $params
925 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
926 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
927 * on not visible courses
928 * @return array array of stdClass objects
930 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
931 global $DB;
932 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
933 $fields = array('c.id', 'c.category', 'c.sortorder',
934 'c.shortname', 'c.fullname', 'c.idnumber',
935 'c.startdate', 'c.enddate', 'c.visible', 'c.cacherev');
936 if (!empty($options['summary'])) {
937 $fields[] = 'c.summary';
938 $fields[] = 'c.summaryformat';
939 } else {
940 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
942 $sql = "SELECT ". join(',', $fields). ", $ctxselect
943 FROM {course} c
944 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
945 WHERE ". $whereclause." ORDER BY c.sortorder";
946 $list = $DB->get_records_sql($sql,
947 array('contextcourse' => CONTEXT_COURSE) + $params);
949 if ($checkvisibility) {
950 // Loop through all records and make sure we only return the courses accessible by user.
951 foreach ($list as $course) {
952 if (isset($list[$course->id]->hassummary)) {
953 $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
955 if (empty($course->visible)) {
956 // Load context only if we need to check capability.
957 context_helper::preload_from_record($course);
958 if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
959 unset($list[$course->id]);
965 // Preload course contacts if necessary.
966 if (!empty($options['coursecontacts'])) {
967 self::preload_course_contacts($list);
969 return $list;
973 * Returns array of ids of children categories that current user can not see
975 * This data is cached in user session cache
977 * @return array
979 protected function get_not_visible_children_ids() {
980 global $DB;
981 $coursecatcache = cache::make('core', 'coursecat');
982 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
983 // We never checked visible children before.
984 $hidden = self::get_tree($this->id.'i');
985 $invisibleids = array();
986 if ($hidden) {
987 // Preload categories contexts.
988 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
989 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
990 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
991 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
992 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
993 foreach ($contexts as $record) {
994 context_helper::preload_from_record($record);
996 // Check that user has 'viewhiddencategories' capability for each hidden category.
997 foreach ($hidden as $id) {
998 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
999 $invisibleids[] = $id;
1003 $coursecatcache->set('ic'. $this->id, $invisibleids);
1005 return $invisibleids;
1009 * Sorts list of records by several fields
1011 * @param array $records array of stdClass objects
1012 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
1013 * @return int
1015 protected static function sort_records(&$records, $sortfields) {
1016 if (empty($records)) {
1017 return;
1019 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname).
1020 if (array_key_exists('displayname', $sortfields)) {
1021 foreach ($records as $key => $record) {
1022 if (!isset($record->displayname)) {
1023 $records[$key]->displayname = get_course_display_name_for_list($record);
1027 // Sorting by one field - use core_collator.
1028 if (count($sortfields) == 1) {
1029 $property = key($sortfields);
1030 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
1031 $sortflag = core_collator::SORT_NUMERIC;
1032 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
1033 $sortflag = core_collator::SORT_STRING;
1034 } else {
1035 $sortflag = core_collator::SORT_REGULAR;
1037 core_collator::asort_objects_by_property($records, $property, $sortflag);
1038 if ($sortfields[$property] < 0) {
1039 $records = array_reverse($records, true);
1041 return;
1043 $records = coursecat_sortable_records::sort($records, $sortfields);
1047 * Returns array of children categories visible to the current user
1049 * @param array $options options for retrieving children
1050 * - sort - list of fields to sort. Example
1051 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
1052 * will sort by idnumber asc, name asc and id desc.
1053 * Default: array('sortorder' => 1)
1054 * Only cached fields may be used for sorting!
1055 * - offset
1056 * - limit - maximum number of children to return, 0 or null for no limit
1057 * @return coursecat[] Array of coursecat objects indexed by category id
1059 public function get_children($options = array()) {
1060 global $DB;
1061 $coursecatcache = cache::make('core', 'coursecat');
1063 // Get default values for options.
1064 if (!empty($options['sort']) && is_array($options['sort'])) {
1065 $sortfields = $options['sort'];
1066 } else {
1067 $sortfields = array('sortorder' => 1);
1069 $limit = null;
1070 if (!empty($options['limit']) && (int)$options['limit']) {
1071 $limit = (int)$options['limit'];
1073 $offset = 0;
1074 if (!empty($options['offset']) && (int)$options['offset']) {
1075 $offset = (int)$options['offset'];
1078 // First retrieve list of user-visible and sorted children ids from cache.
1079 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
1080 if ($sortedids === false) {
1081 $sortfieldskeys = array_keys($sortfields);
1082 if ($sortfieldskeys[0] === 'sortorder') {
1083 // No DB requests required to build the list of ids sorted by sortorder.
1084 // We can easily ignore other sort fields because sortorder is always different.
1085 $sortedids = self::get_tree($this->id);
1086 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
1087 $sortedids = array_diff($sortedids, $invisibleids);
1088 if ($sortfields['sortorder'] == -1) {
1089 $sortedids = array_reverse($sortedids, true);
1092 } else {
1093 // We need to retrieve and sort all children. Good thing that it is done only on first request.
1094 if ($invisibleids = $this->get_not_visible_children_ids()) {
1095 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
1096 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
1097 array('parent' => $this->id) + $params);
1098 } else {
1099 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
1101 self::sort_records($records, $sortfields);
1102 $sortedids = array_keys($records);
1104 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
1107 if (empty($sortedids)) {
1108 return array();
1111 // Now retrieive and return categories.
1112 if ($offset || $limit) {
1113 $sortedids = array_slice($sortedids, $offset, $limit);
1115 if (isset($records)) {
1116 // Easy, we have already retrieved records.
1117 if ($offset || $limit) {
1118 $records = array_slice($records, $offset, $limit, true);
1120 } else {
1121 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
1122 $records = self::get_records('cc.id '. $sql, array('parent' => $this->id) + $params);
1125 $rv = array();
1126 foreach ($sortedids as $id) {
1127 if (isset($records[$id])) {
1128 $rv[$id] = new coursecat($records[$id]);
1131 return $rv;
1135 * Returns true if the user has the manage capability on any category.
1137 * This method uses the coursecat cache and an entry `has_manage_capability` to speed up
1138 * calls to this method.
1140 * @return bool
1142 public static function has_manage_capability_on_any() {
1143 return self::has_capability_on_any('moodle/category:manage');
1147 * Checks if the user has at least one of the given capabilities on any category.
1149 * @param array|string $capabilities One or more capabilities to check. Check made is an OR.
1150 * @return bool
1152 public static function has_capability_on_any($capabilities) {
1153 global $DB;
1154 if (!isloggedin() || isguestuser()) {
1155 return false;
1158 if (!is_array($capabilities)) {
1159 $capabilities = array($capabilities);
1161 $keys = array();
1162 foreach ($capabilities as $capability) {
1163 $keys[$capability] = sha1($capability);
1166 /* @var cache_session $cache */
1167 $cache = cache::make('core', 'coursecat');
1168 $hascapability = $cache->get_many($keys);
1169 $needtoload = false;
1170 foreach ($hascapability as $capability) {
1171 if ($capability === '1') {
1172 return true;
1173 } else if ($capability === false) {
1174 $needtoload = true;
1177 if ($needtoload === false) {
1178 // All capabilities were retrieved and the user didn't have any.
1179 return false;
1182 $haskey = null;
1183 $fields = context_helper::get_preload_record_columns_sql('ctx');
1184 $sql = "SELECT ctx.instanceid AS categoryid, $fields
1185 FROM {context} ctx
1186 WHERE contextlevel = :contextlevel
1187 ORDER BY depth ASC";
1188 $params = array('contextlevel' => CONTEXT_COURSECAT);
1189 $recordset = $DB->get_recordset_sql($sql, $params);
1190 foreach ($recordset as $context) {
1191 context_helper::preload_from_record($context);
1192 $context = context_coursecat::instance($context->categoryid);
1193 foreach ($capabilities as $capability) {
1194 if (has_capability($capability, $context)) {
1195 $haskey = $capability;
1196 break 2;
1200 $recordset->close();
1201 if ($haskey === null) {
1202 $data = array();
1203 foreach ($keys as $key) {
1204 $data[$key] = '0';
1206 $cache->set_many($data);
1207 return false;
1208 } else {
1209 $cache->set($haskey, '1');
1210 return true;
1215 * Returns true if the user can resort any category.
1216 * @return bool
1218 public static function can_resort_any() {
1219 return self::has_manage_capability_on_any();
1223 * Returns true if the user can change the parent of any category.
1224 * @return bool
1226 public static function can_change_parent_any() {
1227 return self::has_manage_capability_on_any();
1231 * Returns number of subcategories visible to the current user
1233 * @return int
1235 public function get_children_count() {
1236 $sortedids = self::get_tree($this->id);
1237 $invisibleids = $this->get_not_visible_children_ids();
1238 return count($sortedids) - count($invisibleids);
1242 * Returns true if the category has ANY children, including those not visible to the user
1244 * @return boolean
1246 public function has_children() {
1247 $allchildren = self::get_tree($this->id);
1248 return !empty($allchildren);
1252 * Returns true if the category has courses in it (count does not include courses
1253 * in child categories)
1255 * @return bool
1257 public function has_courses() {
1258 global $DB;
1259 return $DB->record_exists_sql("select 1 from {course} where category = ?",
1260 array($this->id));
1264 * Searches courses
1266 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1267 * to this when somebody edits courses or categories, however it is very
1268 * difficult to keep track of all possible changes that may affect list of courses.
1270 * @param array $search contains search criterias, such as:
1271 * - search - search string
1272 * - blocklist - id of block (if we are searching for courses containing specific block0
1273 * - modulelist - name of module (if we are searching for courses containing specific module
1274 * - tagid - id of tag
1275 * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
1276 * search is always category-independent
1277 * @param array $requiredcapabilites List of capabilities required to see return course.
1278 * @return course_in_list[]
1280 public static function search_courses($search, $options = array(), $requiredcapabilities = array()) {
1281 global $DB;
1282 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1283 $limit = !empty($options['limit']) ? $options['limit'] : null;
1284 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1286 $coursecatcache = cache::make('core', 'coursecat');
1287 $cachekey = 's-'. serialize(
1288 $search + array('sort' => $sortfields) + array('requiredcapabilities' => $requiredcapabilities)
1290 $cntcachekey = 'scnt-'. serialize($search);
1292 $ids = $coursecatcache->get($cachekey);
1293 if ($ids !== false) {
1294 // We already cached last search result.
1295 $ids = array_slice($ids, $offset, $limit);
1296 $courses = array();
1297 if (!empty($ids)) {
1298 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1299 $records = self::get_course_records("c.id ". $sql, $params, $options);
1300 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1301 if (!empty($options['coursecontacts'])) {
1302 self::preload_course_contacts($records);
1304 // If option 'idonly' is specified no further action is needed, just return list of ids.
1305 if (!empty($options['idonly'])) {
1306 return array_keys($records);
1308 // Prepare the list of course_in_list objects.
1309 foreach ($ids as $id) {
1310 $courses[$id] = new course_in_list($records[$id]);
1313 return $courses;
1316 $preloadcoursecontacts = !empty($options['coursecontacts']);
1317 unset($options['coursecontacts']);
1319 // Empty search string will return all results.
1320 if (!isset($search['search'])) {
1321 $search['search'] = '';
1324 if (empty($search['blocklist']) && empty($search['modulelist']) && empty($search['tagid'])) {
1325 // Search courses that have specified words in their names/summaries.
1326 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1328 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount, $requiredcapabilities);
1329 self::sort_records($courselist, $sortfields);
1330 $coursecatcache->set($cachekey, array_keys($courselist));
1331 $coursecatcache->set($cntcachekey, $totalcount);
1332 $records = array_slice($courselist, $offset, $limit, true);
1333 } else {
1334 if (!empty($search['blocklist'])) {
1335 // Search courses that have block with specified id.
1336 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1337 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1338 WHERE bi.blockname = :blockname)';
1339 $params = array('blockname' => $blockname);
1340 } else if (!empty($search['modulelist'])) {
1341 // Search courses that have module with specified name.
1342 $where = "c.id IN (SELECT DISTINCT module.course ".
1343 "FROM {".$search['modulelist']."} module)";
1344 $params = array();
1345 } else if (!empty($search['tagid'])) {
1346 // Search courses that are tagged with the specified tag.
1347 $where = "c.id IN (SELECT t.itemid ".
1348 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype AND t.component = :component)";
1349 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course', 'component' => 'core');
1350 if (!empty($search['ctx'])) {
1351 $rec = isset($search['rec']) ? $search['rec'] : true;
1352 $parentcontext = context::instance_by_id($search['ctx']);
1353 if ($parentcontext->contextlevel == CONTEXT_SYSTEM && $rec) {
1354 // Parent context is system context and recursive is set to yes.
1355 // Nothing to filter - all courses fall into this condition.
1356 } else if ($rec) {
1357 // Filter all courses in the parent context at any level.
1358 $where .= ' AND ctx.path LIKE :contextpath';
1359 $params['contextpath'] = $parentcontext->path . '%';
1360 } else if ($parentcontext->contextlevel == CONTEXT_COURSECAT) {
1361 // All courses in the given course category.
1362 $where .= ' AND c.category = :category';
1363 $params['category'] = $parentcontext->instanceid;
1364 } else {
1365 // No courses will satisfy the context criterion, do not bother searching.
1366 $where = '1=0';
1369 } else {
1370 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1371 return array();
1373 $courselist = self::get_course_records($where, $params, $options, true);
1374 if (!empty($requiredcapabilities)) {
1375 foreach ($courselist as $key => $course) {
1376 context_helper::preload_from_record($course);
1377 $coursecontext = context_course::instance($course->id);
1378 if (!has_all_capabilities($requiredcapabilities, $coursecontext)) {
1379 unset($courselist[$key]);
1383 self::sort_records($courselist, $sortfields);
1384 $coursecatcache->set($cachekey, array_keys($courselist));
1385 $coursecatcache->set($cntcachekey, count($courselist));
1386 $records = array_slice($courselist, $offset, $limit, true);
1389 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1390 if (!empty($preloadcoursecontacts)) {
1391 self::preload_course_contacts($records);
1393 // If option 'idonly' is specified no further action is needed, just return list of ids.
1394 if (!empty($options['idonly'])) {
1395 return array_keys($records);
1397 // Prepare the list of course_in_list objects.
1398 $courses = array();
1399 foreach ($records as $record) {
1400 $courses[$record->id] = new course_in_list($record);
1402 return $courses;
1406 * Returns number of courses in the search results
1408 * It is recommended to call this function after {@link coursecat::search_courses()}
1409 * and not before because only course ids are cached. Otherwise search_courses() may
1410 * perform extra DB queries.
1412 * @param array $search search criteria, see method search_courses() for more details
1413 * @param array $options display options. They do not affect the result but
1414 * the 'sort' property is used in cache key for storing list of course ids
1415 * @param array $requiredcapabilites List of capabilities required to see return course.
1416 * @return int
1418 public static function search_courses_count($search, $options = array(), $requiredcapabilities = array()) {
1419 $coursecatcache = cache::make('core', 'coursecat');
1420 $cntcachekey = 'scnt-'. serialize($search) . serialize($requiredcapabilities);
1421 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1422 // Cached value not found. Retrieve ALL courses and return their count.
1423 unset($options['offset']);
1424 unset($options['limit']);
1425 unset($options['summary']);
1426 unset($options['coursecontacts']);
1427 $options['idonly'] = true;
1428 $courses = self::search_courses($search, $options, $requiredcapabilities);
1429 $cnt = count($courses);
1431 return $cnt;
1435 * Retrieves the list of courses accessible by user
1437 * Not all information is cached, try to avoid calling this method
1438 * twice in the same request.
1440 * The following fields are always retrieved:
1441 * - id, visible, fullname, shortname, idnumber, category, sortorder
1443 * If you plan to use properties/methods course_in_list::$summary and/or
1444 * course_in_list::get_course_contacts()
1445 * you can preload this information using appropriate 'options'. Otherwise
1446 * they will be retrieved from DB on demand and it may end with bigger DB load.
1448 * Note that method course_in_list::has_summary() will not perform additional
1449 * DB queries even if $options['summary'] is not specified
1451 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1452 * to this when somebody edits courses or categories, however it is very
1453 * difficult to keep track of all possible changes that may affect list of courses.
1455 * @param array $options options for retrieving children
1456 * - recursive - return courses from subcategories as well. Use with care,
1457 * this may be a huge list!
1458 * - summary - preloads fields 'summary' and 'summaryformat'
1459 * - coursecontacts - preloads course contacts
1460 * - sort - list of fields to sort. Example
1461 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1462 * will sort by idnumber asc, shortname asc and id desc.
1463 * Default: array('sortorder' => 1)
1464 * Only cached fields may be used for sorting!
1465 * - offset
1466 * - limit - maximum number of children to return, 0 or null for no limit
1467 * - idonly - returns the array or course ids instead of array of objects
1468 * used only in get_courses_count()
1469 * @return course_in_list[]
1471 public function get_courses($options = array()) {
1472 global $DB;
1473 $recursive = !empty($options['recursive']);
1474 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1475 $limit = !empty($options['limit']) ? $options['limit'] : null;
1476 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1478 // Check if this category is hidden.
1479 // Also 0-category never has courses unless this is recursive call.
1480 if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1481 return array();
1484 $coursecatcache = cache::make('core', 'coursecat');
1485 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1486 '-'. serialize($sortfields);
1487 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1489 // Check if we have already cached results.
1490 $ids = $coursecatcache->get($cachekey);
1491 if ($ids !== false) {
1492 // We already cached last search result and it did not expire yet.
1493 $ids = array_slice($ids, $offset, $limit);
1494 $courses = array();
1495 if (!empty($ids)) {
1496 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1497 $records = self::get_course_records("c.id ". $sql, $params, $options);
1498 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1499 if (!empty($options['coursecontacts'])) {
1500 self::preload_course_contacts($records);
1502 // If option 'idonly' is specified no further action is needed, just return list of ids.
1503 if (!empty($options['idonly'])) {
1504 return array_keys($records);
1506 // Prepare the list of course_in_list objects.
1507 foreach ($ids as $id) {
1508 $courses[$id] = new course_in_list($records[$id]);
1511 return $courses;
1514 // Retrieve list of courses in category.
1515 $where = 'c.id <> :siteid';
1516 $params = array('siteid' => SITEID);
1517 if ($recursive) {
1518 if ($this->id) {
1519 $context = context_coursecat::instance($this->id);
1520 $where .= ' AND ctx.path like :path';
1521 $params['path'] = $context->path. '/%';
1523 } else {
1524 $where .= ' AND c.category = :categoryid';
1525 $params['categoryid'] = $this->id;
1527 // Get list of courses without preloaded coursecontacts because we don't need them for every course.
1528 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1530 // Sort and cache list.
1531 self::sort_records($list, $sortfields);
1532 $coursecatcache->set($cachekey, array_keys($list));
1533 $coursecatcache->set($cntcachekey, count($list));
1535 // Apply offset/limit, convert to course_in_list and return.
1536 $courses = array();
1537 if (isset($list)) {
1538 if ($offset || $limit) {
1539 $list = array_slice($list, $offset, $limit, true);
1541 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1542 if (!empty($options['coursecontacts'])) {
1543 self::preload_course_contacts($list);
1545 // If option 'idonly' is specified no further action is needed, just return list of ids.
1546 if (!empty($options['idonly'])) {
1547 return array_keys($list);
1549 // Prepare the list of course_in_list objects.
1550 foreach ($list as $record) {
1551 $courses[$record->id] = new course_in_list($record);
1554 return $courses;
1558 * Returns number of courses visible to the user
1560 * @param array $options similar to get_courses() except some options do not affect
1561 * number of courses (i.e. sort, summary, offset, limit etc.)
1562 * @return int
1564 public function get_courses_count($options = array()) {
1565 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1566 $coursecatcache = cache::make('core', 'coursecat');
1567 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1568 // Cached value not found. Retrieve ALL courses and return their count.
1569 unset($options['offset']);
1570 unset($options['limit']);
1571 unset($options['summary']);
1572 unset($options['coursecontacts']);
1573 $options['idonly'] = true;
1574 $courses = $this->get_courses($options);
1575 $cnt = count($courses);
1577 return $cnt;
1581 * Returns true if the user is able to delete this category.
1583 * Note if this category contains any courses this isn't a full check, it will need to be accompanied by a call to either
1584 * {@link coursecat::can_delete_full()} or {@link coursecat::can_move_content_to()} depending upon what the user wished to do.
1586 * @return boolean
1588 public function can_delete() {
1589 if (!$this->has_manage_capability()) {
1590 return false;
1592 return $this->parent_has_manage_capability();
1596 * Returns true if user can delete current category and all its contents
1598 * To be able to delete course category the user must have permission
1599 * 'moodle/category:manage' in ALL child course categories AND
1600 * be able to delete all courses
1602 * @return bool
1604 public function can_delete_full() {
1605 global $DB;
1606 if (!$this->id) {
1607 // Fool-proof.
1608 return false;
1611 $context = $this->get_context();
1612 if (!$this->is_uservisible() ||
1613 !has_capability('moodle/category:manage', $context)) {
1614 return false;
1617 // Check all child categories (not only direct children).
1618 $sql = context_helper::get_preload_record_columns_sql('ctx');
1619 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1620 ' FROM {context} ctx '.
1621 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1622 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1623 array($context->path. '/%', CONTEXT_COURSECAT));
1624 foreach ($childcategories as $childcat) {
1625 context_helper::preload_from_record($childcat);
1626 $childcontext = context_coursecat::instance($childcat->id);
1627 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1628 !has_capability('moodle/category:manage', $childcontext)) {
1629 return false;
1633 // Check courses.
1634 $sql = context_helper::get_preload_record_columns_sql('ctx');
1635 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1636 $sql. ' FROM {context} ctx '.
1637 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1638 array('pathmask' => $context->path. '/%',
1639 'courselevel' => CONTEXT_COURSE));
1640 foreach ($coursescontexts as $ctxrecord) {
1641 context_helper::preload_from_record($ctxrecord);
1642 if (!can_delete_course($ctxrecord->courseid)) {
1643 return false;
1647 return true;
1651 * Recursively delete category including all subcategories and courses
1653 * Function {@link coursecat::can_delete_full()} MUST be called prior
1654 * to calling this function because there is no capability check
1655 * inside this function
1657 * @param boolean $showfeedback display some notices
1658 * @return array return deleted courses
1659 * @throws moodle_exception
1661 public function delete_full($showfeedback = true) {
1662 global $CFG, $DB;
1664 require_once($CFG->libdir.'/gradelib.php');
1665 require_once($CFG->libdir.'/questionlib.php');
1666 require_once($CFG->dirroot.'/cohort/lib.php');
1668 // Make sure we won't timeout when deleting a lot of courses.
1669 $settimeout = core_php_time_limit::raise();
1671 // Allow plugins to use this category before we completely delete it.
1672 if ($pluginsfunction = get_plugins_with_function('pre_course_category_delete')) {
1673 $category = $this->get_db_record();
1674 foreach ($pluginsfunction as $plugintype => $plugins) {
1675 foreach ($plugins as $pluginfunction) {
1676 $pluginfunction($category);
1681 $deletedcourses = array();
1683 // Get children. Note, we don't want to use cache here because it would be rebuilt too often.
1684 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1685 foreach ($children as $record) {
1686 $coursecat = new coursecat($record);
1687 $deletedcourses += $coursecat->delete_full($showfeedback);
1690 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1691 foreach ($courses as $course) {
1692 if (!delete_course($course, false)) {
1693 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1695 $deletedcourses[] = $course;
1699 // Move or delete cohorts in this context.
1700 cohort_delete_category($this);
1702 // Now delete anything that may depend on course category context.
1703 grade_course_category_delete($this->id, 0, $showfeedback);
1704 if (!question_delete_course_category($this, 0, $showfeedback)) {
1705 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1708 // Finally delete the category and it's context.
1709 $DB->delete_records('course_categories', array('id' => $this->id));
1711 $coursecatcontext = context_coursecat::instance($this->id);
1712 $coursecatcontext->delete();
1714 cache_helper::purge_by_event('changesincoursecat');
1716 // Trigger a course category deleted event.
1717 /* @var \core\event\course_category_deleted $event */
1718 $event = \core\event\course_category_deleted::create(array(
1719 'objectid' => $this->id,
1720 'context' => $coursecatcontext,
1721 'other' => array('name' => $this->name)
1723 $event->set_coursecat($this);
1724 $event->trigger();
1726 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1727 if ($this->id == $CFG->defaultrequestcategory) {
1728 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1730 return $deletedcourses;
1734 * Checks if user can delete this category and move content (courses, subcategories and questions)
1735 * to another category. If yes returns the array of possible target categories names
1737 * If user can not manage this category or it is completely empty - empty array will be returned
1739 * @return array
1741 public function move_content_targets_list() {
1742 global $CFG;
1743 require_once($CFG->libdir . '/questionlib.php');
1744 $context = $this->get_context();
1745 if (!$this->is_uservisible() ||
1746 !has_capability('moodle/category:manage', $context)) {
1747 // User is not able to manage current category, he is not able to delete it.
1748 // No possible target categories.
1749 return array();
1752 $testcaps = array();
1753 // If this category has courses in it, user must have 'course:create' capability in target category.
1754 if ($this->has_courses()) {
1755 $testcaps[] = 'moodle/course:create';
1757 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1758 if ($this->has_children() || question_context_has_any_questions($context)) {
1759 $testcaps[] = 'moodle/category:manage';
1761 if (!empty($testcaps)) {
1762 // Return list of categories excluding this one and it's children.
1763 return self::make_categories_list($testcaps, $this->id);
1766 // Category is completely empty, no need in target for contents.
1767 return array();
1771 * Checks if user has capability to move all category content to the new parent before
1772 * removing this category
1774 * @param int $newcatid
1775 * @return bool
1777 public function can_move_content_to($newcatid) {
1778 global $CFG;
1779 require_once($CFG->libdir . '/questionlib.php');
1780 $context = $this->get_context();
1781 if (!$this->is_uservisible() ||
1782 !has_capability('moodle/category:manage', $context)) {
1783 return false;
1785 $testcaps = array();
1786 // If this category has courses in it, user must have 'course:create' capability in target category.
1787 if ($this->has_courses()) {
1788 $testcaps[] = 'moodle/course:create';
1790 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1791 if ($this->has_children() || question_context_has_any_questions($context)) {
1792 $testcaps[] = 'moodle/category:manage';
1794 if (!empty($testcaps)) {
1795 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1798 // There is no content but still return true.
1799 return true;
1803 * Deletes a category and moves all content (children, courses and questions) to the new parent
1805 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1806 * must be called prior
1808 * @param int $newparentid
1809 * @param bool $showfeedback
1810 * @return bool
1812 public function delete_move($newparentid, $showfeedback = false) {
1813 global $CFG, $DB, $OUTPUT;
1815 require_once($CFG->libdir.'/gradelib.php');
1816 require_once($CFG->libdir.'/questionlib.php');
1817 require_once($CFG->dirroot.'/cohort/lib.php');
1819 // Get all objects and lists because later the caches will be reset so.
1820 // We don't need to make extra queries.
1821 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1822 $catname = $this->get_formatted_name();
1823 $children = $this->get_children();
1824 $params = array('category' => $this->id);
1825 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', $params);
1826 $context = $this->get_context();
1828 if ($children) {
1829 foreach ($children as $childcat) {
1830 $childcat->change_parent_raw($newparentcat);
1831 // Log action.
1832 $event = \core\event\course_category_updated::create(array(
1833 'objectid' => $childcat->id,
1834 'context' => $childcat->get_context()
1836 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $childcat->id,
1837 $childcat->id));
1838 $event->trigger();
1840 fix_course_sortorder();
1843 if ($coursesids) {
1844 if (!move_courses($coursesids, $newparentid)) {
1845 if ($showfeedback) {
1846 echo $OUTPUT->notification("Error moving courses");
1848 return false;
1850 if ($showfeedback) {
1851 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1855 // Move or delete cohorts in this context.
1856 cohort_delete_category($this);
1858 // Now delete anything that may depend on course category context.
1859 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1860 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1861 if ($showfeedback) {
1862 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1864 return false;
1867 // Finally delete the category and it's context.
1868 $DB->delete_records('course_categories', array('id' => $this->id));
1869 $context->delete();
1871 // Trigger a course category deleted event.
1872 /* @var \core\event\course_category_deleted $event */
1873 $event = \core\event\course_category_deleted::create(array(
1874 'objectid' => $this->id,
1875 'context' => $context,
1876 'other' => array('name' => $this->name)
1878 $event->set_coursecat($this);
1879 $event->trigger();
1881 cache_helper::purge_by_event('changesincoursecat');
1883 if ($showfeedback) {
1884 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1887 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1888 if ($this->id == $CFG->defaultrequestcategory) {
1889 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1891 return true;
1895 * Checks if user can move current category to the new parent
1897 * This checks if new parent category exists, user has manage cap there
1898 * and new parent is not a child of this category
1900 * @param int|stdClass|coursecat $newparentcat
1901 * @return bool
1903 public function can_change_parent($newparentcat) {
1904 if (!has_capability('moodle/category:manage', $this->get_context())) {
1905 return false;
1907 if (is_object($newparentcat)) {
1908 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1909 } else {
1910 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1912 if (!$newparentcat) {
1913 return false;
1915 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1916 // Can not move to itself or it's own child.
1917 return false;
1919 if ($newparentcat->id) {
1920 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
1921 } else {
1922 return has_capability('moodle/category:manage', context_system::instance());
1927 * Moves the category under another parent category. All associated contexts are moved as well
1929 * This is protected function, use change_parent() or update() from outside of this class
1931 * @see coursecat::change_parent()
1932 * @see coursecat::update()
1934 * @param coursecat $newparentcat
1935 * @throws moodle_exception
1937 protected function change_parent_raw(coursecat $newparentcat) {
1938 global $DB;
1940 $context = $this->get_context();
1942 $hidecat = false;
1943 if (empty($newparentcat->id)) {
1944 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1945 $newparent = context_system::instance();
1946 } else {
1947 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1948 // Can not move to itself or it's own child.
1949 throw new moodle_exception('cannotmovecategory');
1951 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
1952 $newparent = context_coursecat::instance($newparentcat->id);
1954 if (!$newparentcat->visible and $this->visible) {
1955 // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children
1956 // will be restored properly.
1957 $hidecat = true;
1960 $this->parent = $newparentcat->id;
1962 $context->update_moved($newparent);
1964 // Now make it last in new category.
1965 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
1967 if ($hidecat) {
1968 fix_course_sortorder();
1969 $this->restore();
1970 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must
1971 // become visible again.
1972 $this->hide_raw(1);
1977 * Efficiently moves a category - NOTE that this can have
1978 * a huge impact access-control-wise...
1980 * Note that this function does not check capabilities.
1982 * Example of usage:
1983 * $coursecat = coursecat::get($categoryid);
1984 * if ($coursecat->can_change_parent($newparentcatid)) {
1985 * $coursecat->change_parent($newparentcatid);
1988 * This function does not update field course_categories.timemodified
1989 * If you want to update timemodified, use
1990 * $coursecat->update(array('parent' => $newparentcat));
1992 * @param int|stdClass|coursecat $newparentcat
1994 public function change_parent($newparentcat) {
1995 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1996 if (is_object($newparentcat)) {
1997 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
1998 } else {
1999 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
2001 if ($newparentcat->id != $this->parent) {
2002 $this->change_parent_raw($newparentcat);
2003 fix_course_sortorder();
2004 cache_helper::purge_by_event('changesincoursecat');
2005 $this->restore();
2007 $event = \core\event\course_category_updated::create(array(
2008 'objectid' => $this->id,
2009 'context' => $this->get_context()
2011 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $this->id, $this->id));
2012 $event->trigger();
2017 * Hide course category and child course and subcategories
2019 * If this category has changed the parent and is moved under hidden
2020 * category we will want to store it's current visibility state in
2021 * the field 'visibleold'. If admin clicked 'hide' for this particular
2022 * category, the field 'visibleold' should become 0.
2024 * All subcategories and courses will have their current visibility in the field visibleold
2026 * This is protected function, use hide() or update() from outside of this class
2028 * @see coursecat::hide()
2029 * @see coursecat::update()
2031 * @param int $visibleold value to set in field $visibleold for this category
2032 * @return bool whether changes have been made and caches need to be purged afterwards
2034 protected function hide_raw($visibleold = 0) {
2035 global $DB;
2036 $changes = false;
2038 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing.
2039 if ($this->id && $this->__get('visibleold') != $visibleold) {
2040 $this->visibleold = $visibleold;
2041 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
2042 $changes = true;
2044 if (!$this->visible || !$this->id) {
2045 // Already hidden or can not be hidden.
2046 return $changes;
2049 $this->visible = 0;
2050 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
2051 // Store visible flag so that we can return to it if we immediately unhide.
2052 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id));
2053 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
2054 // Get all child categories and hide too.
2055 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
2056 foreach ($subcats as $cat) {
2057 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
2058 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
2059 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
2060 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
2063 return true;
2067 * Hide course category and child course and subcategories
2069 * Note that there is no capability check inside this function
2071 * This function does not update field course_categories.timemodified
2072 * If you want to update timemodified, use
2073 * $coursecat->update(array('visible' => 0));
2075 public function hide() {
2076 if ($this->hide_raw(0)) {
2077 cache_helper::purge_by_event('changesincoursecat');
2079 $event = \core\event\course_category_updated::create(array(
2080 'objectid' => $this->id,
2081 'context' => $this->get_context()
2083 $event->set_legacy_logdata(array(SITEID, 'category', 'hide', 'editcategory.php?id=' . $this->id, $this->id));
2084 $event->trigger();
2089 * Show course category and restores visibility for child course and subcategories
2091 * Note that there is no capability check inside this function
2093 * This is protected function, use show() or update() from outside of this class
2095 * @see coursecat::show()
2096 * @see coursecat::update()
2098 * @return bool whether changes have been made and caches need to be purged afterwards
2100 protected function show_raw() {
2101 global $DB;
2103 if ($this->visible) {
2104 // Already visible.
2105 return false;
2108 $this->visible = 1;
2109 $this->visibleold = 1;
2110 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
2111 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
2112 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
2113 // Get all child categories and unhide too.
2114 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
2115 foreach ($subcats as $cat) {
2116 if ($cat->visibleold) {
2117 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
2119 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
2122 return true;
2126 * Show course category and restores visibility for child course and subcategories
2128 * Note that there is no capability check inside this function
2130 * This function does not update field course_categories.timemodified
2131 * If you want to update timemodified, use
2132 * $coursecat->update(array('visible' => 1));
2134 public function show() {
2135 if ($this->show_raw()) {
2136 cache_helper::purge_by_event('changesincoursecat');
2138 $event = \core\event\course_category_updated::create(array(
2139 'objectid' => $this->id,
2140 'context' => $this->get_context()
2142 $event->set_legacy_logdata(array(SITEID, 'category', 'show', 'editcategory.php?id=' . $this->id, $this->id));
2143 $event->trigger();
2148 * Returns name of the category formatted as a string
2150 * @param array $options formatting options other than context
2151 * @return string
2153 public function get_formatted_name($options = array()) {
2154 if ($this->id) {
2155 $context = $this->get_context();
2156 return format_string($this->name, true, array('context' => $context) + $options);
2157 } else {
2158 return get_string('top');
2163 * Returns ids of all parents of the category. Last element in the return array is the direct parent
2165 * For example, if you have a tree of categories like:
2166 * Miscellaneous (id = 1)
2167 * Subcategory (id = 2)
2168 * Sub-subcategory (id = 4)
2169 * Other category (id = 3)
2171 * coursecat::get(1)->get_parents() == array()
2172 * coursecat::get(2)->get_parents() == array(1)
2173 * coursecat::get(4)->get_parents() == array(1, 2);
2175 * Note that this method does not check if all parents are accessible by current user
2177 * @return array of category ids
2179 public function get_parents() {
2180 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
2181 array_pop($parents);
2182 return $parents;
2186 * This function returns a nice list representing category tree
2187 * for display or to use in a form <select> element
2189 * List is cached for 10 minutes
2191 * For example, if you have a tree of categories like:
2192 * Miscellaneous (id = 1)
2193 * Subcategory (id = 2)
2194 * Sub-subcategory (id = 4)
2195 * Other category (id = 3)
2196 * Then after calling this function you will have
2197 * array(1 => 'Miscellaneous',
2198 * 2 => 'Miscellaneous / Subcategory',
2199 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2200 * 3 => 'Other category');
2202 * If you specify $requiredcapability, then only categories where the current
2203 * user has that capability will be added to $list.
2204 * If you only have $requiredcapability in a child category, not the parent,
2205 * then the child catgegory will still be included.
2207 * If you specify the option $excludeid, then that category, and all its children,
2208 * are omitted from the tree. This is useful when you are doing something like
2209 * moving categories, where you do not want to allow people to move a category
2210 * to be the child of itself.
2212 * See also {@link make_categories_options()}
2214 * @param string/array $requiredcapability if given, only categories where the current
2215 * user has this capability will be returned. Can also be an array of capabilities,
2216 * in which case they are all required.
2217 * @param integer $excludeid Exclude this category and its children from the lists built.
2218 * @param string $separator string to use as a separator between parent and child category. Default ' / '
2219 * @return array of strings
2221 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
2222 global $DB;
2223 $coursecatcache = cache::make('core', 'coursecat');
2225 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids
2226 // with requried cap ($thislist).
2227 $currentlang = current_language();
2228 $basecachekey = $currentlang . '_catlist';
2229 $baselist = $coursecatcache->get($basecachekey);
2230 $thislist = false;
2231 $thiscachekey = null;
2232 if (!empty($requiredcapability)) {
2233 $requiredcapability = (array)$requiredcapability;
2234 $thiscachekey = 'catlist:'. serialize($requiredcapability);
2235 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
2236 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
2238 } else if ($baselist !== false) {
2239 $thislist = array_keys($baselist);
2242 if ($baselist === false) {
2243 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
2244 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2245 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
2246 FROM {course_categories} cc
2247 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
2248 ORDER BY cc.sortorder";
2249 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2250 $baselist = array();
2251 $thislist = array();
2252 foreach ($rs as $record) {
2253 // If the category's parent is not visible to the user, it is not visible as well.
2254 if (!$record->parent || isset($baselist[$record->parent])) {
2255 context_helper::preload_from_record($record);
2256 $context = context_coursecat::instance($record->id);
2257 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
2258 // No cap to view category, added to neither $baselist nor $thislist.
2259 continue;
2261 $baselist[$record->id] = array(
2262 'name' => format_string($record->name, true, array('context' => $context)),
2263 'path' => $record->path
2265 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
2266 // No required capability, added to $baselist but not to $thislist.
2267 continue;
2269 $thislist[] = $record->id;
2272 $rs->close();
2273 $coursecatcache->set($basecachekey, $baselist);
2274 if (!empty($requiredcapability)) {
2275 $coursecatcache->set($thiscachekey, join(',', $thislist));
2277 } else if ($thislist === false) {
2278 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
2279 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2280 $sql = "SELECT ctx.instanceid AS id, $ctxselect
2281 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
2282 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2283 $thislist = array();
2284 foreach (array_keys($baselist) as $id) {
2285 context_helper::preload_from_record($contexts[$id]);
2286 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
2287 $thislist[] = $id;
2290 $coursecatcache->set($thiscachekey, join(',', $thislist));
2293 // Now build the array of strings to return, mind $separator and $excludeid.
2294 $names = array();
2295 foreach ($thislist as $id) {
2296 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
2297 if (!$excludeid || !in_array($excludeid, $path)) {
2298 $namechunks = array();
2299 foreach ($path as $parentid) {
2300 $namechunks[] = $baselist[$parentid]['name'];
2302 $names[$id] = join($separator, $namechunks);
2305 return $names;
2309 * Prepares the object for caching. Works like the __sleep method.
2311 * implementing method from interface cacheable_object
2313 * @return array ready to be cached
2315 public function prepare_to_cache() {
2316 $a = array();
2317 foreach (self::$coursecatfields as $property => $cachedirectives) {
2318 if ($cachedirectives !== null) {
2319 list($shortname, $defaultvalue) = $cachedirectives;
2320 if ($this->$property !== $defaultvalue) {
2321 $a[$shortname] = $this->$property;
2325 $context = $this->get_context();
2326 $a['xi'] = $context->id;
2327 $a['xp'] = $context->path;
2328 return $a;
2332 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2334 * implementing method from interface cacheable_object
2336 * @param array $a
2337 * @return coursecat
2339 public static function wake_from_cache($a) {
2340 $record = new stdClass;
2341 foreach (self::$coursecatfields as $property => $cachedirectives) {
2342 if ($cachedirectives !== null) {
2343 list($shortname, $defaultvalue) = $cachedirectives;
2344 if (array_key_exists($shortname, $a)) {
2345 $record->$property = $a[$shortname];
2346 } else {
2347 $record->$property = $defaultvalue;
2351 $record->ctxid = $a['xi'];
2352 $record->ctxpath = $a['xp'];
2353 $record->ctxdepth = $record->depth + 1;
2354 $record->ctxlevel = CONTEXT_COURSECAT;
2355 $record->ctxinstance = $record->id;
2356 return new coursecat($record, true);
2360 * Returns true if the user is able to create a top level category.
2361 * @return bool
2363 public static function can_create_top_level_category() {
2364 return has_capability('moodle/category:manage', context_system::instance());
2368 * Returns the category context.
2369 * @return context_coursecat
2371 public function get_context() {
2372 if ($this->id === 0) {
2373 // This is the special top level category object.
2374 return context_system::instance();
2375 } else {
2376 return context_coursecat::instance($this->id);
2381 * Returns true if the user is able to manage this category.
2382 * @return bool
2384 public function has_manage_capability() {
2385 if ($this->hasmanagecapability === null) {
2386 $this->hasmanagecapability = has_capability('moodle/category:manage', $this->get_context());
2388 return $this->hasmanagecapability;
2392 * Returns true if the user has the manage capability on the parent category.
2393 * @return bool
2395 public function parent_has_manage_capability() {
2396 return has_capability('moodle/category:manage', get_category_or_system_context($this->parent));
2400 * Returns true if the current user can create subcategories of this category.
2401 * @return bool
2403 public function can_create_subcategory() {
2404 return $this->has_manage_capability();
2408 * Returns true if the user can resort this categories sub categories and courses.
2409 * Must have manage capability and be able to see all subcategories.
2410 * @return bool
2412 public function can_resort_subcategories() {
2413 return $this->has_manage_capability() && !$this->get_not_visible_children_ids();
2417 * Returns true if the user can resort the courses within this category.
2418 * Must have manage capability and be able to see all courses.
2419 * @return bool
2421 public function can_resort_courses() {
2422 return $this->has_manage_capability() && $this->coursecount == $this->get_courses_count();
2426 * Returns true of the user can change the sortorder of this category (resort in the parent category)
2427 * @return bool
2429 public function can_change_sortorder() {
2430 return $this->id && $this->get_parent_coursecat()->can_resort_subcategories();
2434 * Returns true if the current user can create a course within this category.
2435 * @return bool
2437 public function can_create_course() {
2438 return has_capability('moodle/course:create', $this->get_context());
2442 * Returns true if the current user can edit this categories settings.
2443 * @return bool
2445 public function can_edit() {
2446 return $this->has_manage_capability();
2450 * Returns true if the current user can review role assignments for this category.
2451 * @return bool
2453 public function can_review_roles() {
2454 return has_capability('moodle/role:assign', $this->get_context());
2458 * Returns true if the current user can review permissions for this category.
2459 * @return bool
2461 public function can_review_permissions() {
2462 return has_any_capability(array(
2463 'moodle/role:assign',
2464 'moodle/role:safeoverride',
2465 'moodle/role:override',
2466 'moodle/role:assign'
2467 ), $this->get_context());
2471 * Returns true if the current user can review cohorts for this category.
2472 * @return bool
2474 public function can_review_cohorts() {
2475 return has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->get_context());
2479 * Returns true if the current user can review filter settings for this category.
2480 * @return bool
2482 public function can_review_filters() {
2483 return has_capability('moodle/filter:manage', $this->get_context()) &&
2484 count(filter_get_available_in_context($this->get_context()))>0;
2488 * Returns true if the current user is able to change the visbility of this category.
2489 * @return bool
2491 public function can_change_visibility() {
2492 return $this->parent_has_manage_capability();
2496 * Returns true if the user can move courses out of this category.
2497 * @return bool
2499 public function can_move_courses_out_of() {
2500 return $this->has_manage_capability();
2504 * Returns true if the user can move courses into this category.
2505 * @return bool
2507 public function can_move_courses_into() {
2508 return $this->has_manage_capability();
2512 * Returns true if the user is able to restore a course into this category as a new course.
2513 * @return bool
2515 public function can_restore_courses_into() {
2516 return has_capability('moodle/restore:restorecourse', $this->get_context());
2520 * Resorts the sub categories of this category by the given field.
2522 * @param string $field One of name, idnumber or descending values of each (appended desc)
2523 * @param bool $cleanup If true cleanup will be done, if false you will need to do it manually later.
2524 * @return bool True on success.
2525 * @throws coding_exception
2527 public function resort_subcategories($field, $cleanup = true) {
2528 global $DB;
2529 $desc = false;
2530 if (substr($field, -4) === "desc") {
2531 $desc = true;
2532 $field = substr($field, 0, -4); // Remove "desc" from field name.
2534 if ($field !== 'name' && $field !== 'idnumber') {
2535 throw new coding_exception('Invalid field requested');
2537 $children = $this->get_children();
2538 core_collator::asort_objects_by_property($children, $field, core_collator::SORT_NATURAL);
2539 if (!empty($desc)) {
2540 $children = array_reverse($children);
2542 $i = 1;
2543 foreach ($children as $cat) {
2544 $i++;
2545 $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id));
2546 $i += $cat->coursecount;
2548 if ($cleanup) {
2549 self::resort_categories_cleanup();
2551 return true;
2555 * Cleans things up after categories have been resorted.
2556 * @param bool $includecourses If set to true we know courses have been resorted as well.
2558 public static function resort_categories_cleanup($includecourses = false) {
2559 // This should not be needed but we do it just to be safe.
2560 fix_course_sortorder();
2561 cache_helper::purge_by_event('changesincoursecat');
2562 if ($includecourses) {
2563 cache_helper::purge_by_event('changesincourse');
2568 * Resort the courses within this category by the given field.
2570 * @param string $field One of fullname, shortname, idnumber or descending values of each (appended desc)
2571 * @param bool $cleanup
2572 * @return bool True for success.
2573 * @throws coding_exception
2575 public function resort_courses($field, $cleanup = true) {
2576 global $DB;
2577 $desc = false;
2578 if (substr($field, -4) === "desc") {
2579 $desc = true;
2580 $field = substr($field, 0, -4); // Remove "desc" from field name.
2582 if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber' && $field !== 'timecreated') {
2583 // This is ultra important as we use $field in an SQL statement below this.
2584 throw new coding_exception('Invalid field requested');
2586 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
2587 $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields
2588 FROM {course} c
2589 LEFT JOIN {context} ctx ON ctx.instanceid = c.id
2590 WHERE ctx.contextlevel = :ctxlevel AND
2591 c.category = :categoryid";
2592 $params = array(
2593 'ctxlevel' => CONTEXT_COURSE,
2594 'categoryid' => $this->id
2596 $courses = $DB->get_records_sql($sql, $params);
2597 if (count($courses) > 0) {
2598 foreach ($courses as $courseid => $course) {
2599 context_helper::preload_from_record($course);
2600 if ($field === 'idnumber') {
2601 $course->sortby = $course->idnumber;
2602 } else {
2603 // It'll require formatting.
2604 $options = array(
2605 'context' => context_course::instance($course->id)
2607 // We format the string first so that it appears as the user would see it.
2608 // This ensures the sorting makes sense to them. However it won't necessarily make
2609 // sense to everyone if things like multilang filters are enabled.
2610 // We then strip any tags as we don't want things such as image tags skewing the
2611 // sort results.
2612 $course->sortby = strip_tags(format_string($course->$field, true, $options));
2614 // We set it back here rather than using references as there is a bug with using
2615 // references in a foreach before passing as an arg by reference.
2616 $courses[$courseid] = $course;
2618 // Sort the courses.
2619 core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL);
2620 if (!empty($desc)) {
2621 $courses = array_reverse($courses);
2623 $i = 1;
2624 foreach ($courses as $course) {
2625 $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id));
2626 $i++;
2628 if ($cleanup) {
2629 // This should not be needed but we do it just to be safe.
2630 fix_course_sortorder();
2631 cache_helper::purge_by_event('changesincourse');
2634 return true;
2638 * Changes the sort order of this categories parent shifting this category up or down one.
2640 * @global \moodle_database $DB
2641 * @param bool $up If set to true the category is shifted up one spot, else its moved down.
2642 * @return bool True on success, false otherwise.
2644 public function change_sortorder_by_one($up) {
2645 global $DB;
2646 $params = array($this->sortorder, $this->parent);
2647 if ($up) {
2648 $select = 'sortorder < ? AND parent = ?';
2649 $sort = 'sortorder DESC';
2650 } else {
2651 $select = 'sortorder > ? AND parent = ?';
2652 $sort = 'sortorder ASC';
2654 fix_course_sortorder();
2655 $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1);
2656 $swapcategory = reset($swapcategory);
2657 if ($swapcategory) {
2658 $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id));
2659 $DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id));
2660 $this->sortorder = $swapcategory->sortorder;
2662 $event = \core\event\course_category_updated::create(array(
2663 'objectid' => $this->id,
2664 'context' => $this->get_context()
2666 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'management.php?categoryid=' . $this->id,
2667 $this->id));
2668 $event->trigger();
2670 // Finally reorder courses.
2671 fix_course_sortorder();
2672 cache_helper::purge_by_event('changesincoursecat');
2673 return true;
2675 return false;
2679 * Returns the parent coursecat object for this category.
2681 * @return coursecat
2683 public function get_parent_coursecat() {
2684 return self::get($this->parent);
2689 * Returns true if the user is able to request a new course be created.
2690 * @return bool
2692 public function can_request_course() {
2693 global $CFG;
2694 if (empty($CFG->enablecourserequests) || $this->id != $CFG->defaultrequestcategory) {
2695 return false;
2697 return !$this->can_create_course() && has_capability('moodle/course:request', $this->get_context());
2701 * Returns true if the user can approve course requests.
2702 * @return bool
2704 public static function can_approve_course_requests() {
2705 global $CFG, $DB;
2706 if (empty($CFG->enablecourserequests)) {
2707 return false;
2709 $context = context_system::instance();
2710 if (!has_capability('moodle/site:approvecourse', $context)) {
2711 return false;
2713 if (!$DB->record_exists('course_request', array())) {
2714 return false;
2716 return true;
2721 * Class to store information about one course in a list of courses
2723 * Not all information may be retrieved when object is created but
2724 * it will be retrieved on demand when appropriate property or method is
2725 * called.
2727 * Instances of this class are usually returned by functions
2728 * {@link coursecat::search_courses()}
2729 * and
2730 * {@link coursecat::get_courses()}
2732 * @property-read int $id
2733 * @property-read int $category Category ID
2734 * @property-read int $sortorder
2735 * @property-read string $fullname
2736 * @property-read string $shortname
2737 * @property-read string $idnumber
2738 * @property-read string $summary Course summary. Field is present if coursecat::get_courses()
2739 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2740 * @property-read int $summaryformat Summary format. Field is present if coursecat::get_courses()
2741 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2742 * @property-read string $format Course format. Retrieved from DB on first request
2743 * @property-read int $showgrades Retrieved from DB on first request
2744 * @property-read int $newsitems Retrieved from DB on first request
2745 * @property-read int $startdate
2746 * @property-read int $enddate
2747 * @property-read int $marker Retrieved from DB on first request
2748 * @property-read int $maxbytes Retrieved from DB on first request
2749 * @property-read int $legacyfiles Retrieved from DB on first request
2750 * @property-read int $showreports Retrieved from DB on first request
2751 * @property-read int $visible
2752 * @property-read int $visibleold Retrieved from DB on first request
2753 * @property-read int $groupmode Retrieved from DB on first request
2754 * @property-read int $groupmodeforce Retrieved from DB on first request
2755 * @property-read int $defaultgroupingid Retrieved from DB on first request
2756 * @property-read string $lang Retrieved from DB on first request
2757 * @property-read string $theme Retrieved from DB on first request
2758 * @property-read int $timecreated Retrieved from DB on first request
2759 * @property-read int $timemodified Retrieved from DB on first request
2760 * @property-read int $requested Retrieved from DB on first request
2761 * @property-read int $enablecompletion Retrieved from DB on first request
2762 * @property-read int $completionnotify Retrieved from DB on first request
2763 * @property-read int $cacherev
2765 * @package core
2766 * @subpackage course
2767 * @copyright 2013 Marina Glancy
2768 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2770 class course_in_list implements IteratorAggregate {
2772 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2773 protected $record;
2775 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2776 protected $coursecontacts;
2778 /** @var bool true if the current user can access the course, false otherwise. */
2779 protected $canaccess = null;
2782 * Creates an instance of the class from record
2784 * @param stdClass $record except fields from course table it may contain
2785 * field hassummary indicating that summary field is not empty.
2786 * Also it is recommended to have context fields here ready for
2787 * context preloading
2789 public function __construct(stdClass $record) {
2790 context_helper::preload_from_record($record);
2791 $this->record = new stdClass();
2792 foreach ($record as $key => $value) {
2793 $this->record->$key = $value;
2798 * Indicates if the course has non-empty summary field
2800 * @return bool
2802 public function has_summary() {
2803 if (isset($this->record->hassummary)) {
2804 return !empty($this->record->hassummary);
2806 if (!isset($this->record->summary)) {
2807 // We need to retrieve summary.
2808 $this->__get('summary');
2810 return !empty($this->record->summary);
2814 * Indicates if the course have course contacts to display
2816 * @return bool
2818 public function has_course_contacts() {
2819 if (!isset($this->record->managers)) {
2820 $courses = array($this->id => &$this->record);
2821 coursecat::preload_course_contacts($courses);
2823 return !empty($this->record->managers);
2827 * Returns list of course contacts (usually teachers) to display in course link
2829 * Roles to display are set up in $CFG->coursecontact
2831 * The result is the list of users where user id is the key and the value
2832 * is an array with elements:
2833 * - 'user' - object containing basic user information
2834 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2835 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2836 * - 'username' => fullname($user, $canviewfullnames)
2838 * @return array
2840 public function get_course_contacts() {
2841 global $CFG;
2842 if (empty($CFG->coursecontact)) {
2843 // No roles are configured to be displayed as course contacts.
2844 return array();
2846 if ($this->coursecontacts === null) {
2847 $this->coursecontacts = array();
2848 $context = context_course::instance($this->id);
2850 if (!isset($this->record->managers)) {
2851 // Preload course contacts from DB.
2852 $courses = array($this->id => &$this->record);
2853 coursecat::preload_course_contacts($courses);
2856 // Build return array with full roles names (for this course context) and users names.
2857 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2858 foreach ($this->record->managers as $ruser) {
2859 if (isset($this->coursecontacts[$ruser->id])) {
2860 // Only display a user once with the highest sortorder role.
2861 continue;
2863 $user = new stdClass();
2864 $user = username_load_fields_from_object($user, $ruser, null, array('id', 'username'));
2865 $role = new stdClass();
2866 $role->id = $ruser->roleid;
2867 $role->name = $ruser->rolename;
2868 $role->shortname = $ruser->roleshortname;
2869 $role->coursealias = $ruser->rolecoursealias;
2871 $this->coursecontacts[$user->id] = array(
2872 'user' => $user,
2873 'role' => $role,
2874 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2875 'username' => fullname($user, $canviewfullnames)
2879 return $this->coursecontacts;
2883 * Checks if course has any associated overview files
2885 * @return bool
2887 public function has_course_overviewfiles() {
2888 global $CFG;
2889 if (empty($CFG->courseoverviewfileslimit)) {
2890 return false;
2892 $fs = get_file_storage();
2893 $context = context_course::instance($this->id);
2894 return !$fs->is_area_empty($context->id, 'course', 'overviewfiles');
2898 * Returns all course overview files
2900 * @return array array of stored_file objects
2902 public function get_course_overviewfiles() {
2903 global $CFG;
2904 if (empty($CFG->courseoverviewfileslimit)) {
2905 return array();
2907 require_once($CFG->libdir. '/filestorage/file_storage.php');
2908 require_once($CFG->dirroot. '/course/lib.php');
2909 $fs = get_file_storage();
2910 $context = context_course::instance($this->id);
2911 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2912 if (count($files)) {
2913 $overviewfilesoptions = course_overviewfiles_options($this->id);
2914 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2915 if ($acceptedtypes !== '*') {
2916 // Filter only files with allowed extensions.
2917 require_once($CFG->libdir. '/filelib.php');
2918 foreach ($files as $key => $file) {
2919 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2920 unset($files[$key]);
2924 if (count($files) > $CFG->courseoverviewfileslimit) {
2925 // Return no more than $CFG->courseoverviewfileslimit files.
2926 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
2929 return $files;
2933 * Magic method to check if property is set
2935 * @param string $name
2936 * @return bool
2938 public function __isset($name) {
2939 return isset($this->record->$name);
2943 * Magic method to get a course property
2945 * Returns any field from table course (retrieves it from DB if it was not retrieved before)
2947 * @param string $name
2948 * @return mixed
2950 public function __get($name) {
2951 global $DB;
2952 if (property_exists($this->record, $name)) {
2953 return $this->record->$name;
2954 } else if ($name === 'summary' || $name === 'summaryformat') {
2955 // Retrieve fields summary and summaryformat together because they are most likely to be used together.
2956 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
2957 $this->record->summary = $record->summary;
2958 $this->record->summaryformat = $record->summaryformat;
2959 return $this->record->$name;
2960 } else if (array_key_exists($name, $DB->get_columns('course'))) {
2961 // Another field from table 'course' that was not retrieved.
2962 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
2963 return $this->record->$name;
2965 debugging('Invalid course property accessed! '.$name);
2966 return null;
2970 * All properties are read only, sorry.
2972 * @param string $name
2974 public function __unset($name) {
2975 debugging('Can not unset '.get_class($this).' instance properties!');
2979 * Magic setter method, we do not want anybody to modify properties from the outside
2981 * @param string $name
2982 * @param mixed $value
2984 public function __set($name, $value) {
2985 debugging('Can not change '.get_class($this).' instance properties!');
2989 * Create an iterator because magic vars can't be seen by 'foreach'.
2990 * Exclude context fields
2992 * Implementing method from interface IteratorAggregate
2994 * @return ArrayIterator
2996 public function getIterator() {
2997 $ret = array('id' => $this->record->id);
2998 foreach ($this->record as $property => $value) {
2999 $ret[$property] = $value;
3001 return new ArrayIterator($ret);
3005 * Returns the name of this course as it should be displayed within a list.
3006 * @return string
3008 public function get_formatted_name() {
3009 return format_string(get_course_display_name_for_list($this), true, $this->get_context());
3013 * Returns the formatted fullname for this course.
3014 * @return string
3016 public function get_formatted_fullname() {
3017 return format_string($this->__get('fullname'), true, $this->get_context());
3021 * Returns the formatted shortname for this course.
3022 * @return string
3024 public function get_formatted_shortname() {
3025 return format_string($this->__get('shortname'), true, $this->get_context());
3029 * Returns true if the current user can access this course.
3030 * @return bool
3032 public function can_access() {
3033 if ($this->canaccess === null) {
3034 $this->canaccess = can_access_course($this->record);
3036 return $this->canaccess;
3040 * Returns true if the user can edit this courses settings.
3042 * Note: this function does not check that the current user can access the course.
3043 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3045 * @return bool
3047 public function can_edit() {
3048 return has_capability('moodle/course:update', $this->get_context());
3052 * Returns true if the user can change the visibility of this course.
3054 * Note: this function does not check that the current user can access the course.
3055 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3057 * @return bool
3059 public function can_change_visibility() {
3060 // You must be able to both hide a course and view the hidden course.
3061 return has_all_capabilities(array('moodle/course:visibility', 'moodle/course:viewhiddencourses'), $this->get_context());
3065 * Returns the context for this course.
3066 * @return context_course
3068 public function get_context() {
3069 return context_course::instance($this->__get('id'));
3073 * Returns true if this course is visible to the current user.
3074 * @return bool
3076 public function is_uservisible() {
3077 return $this->visible || has_capability('moodle/course:viewhiddencourses', $this->get_context());
3081 * Returns true if the current user can review enrolments for this course.
3083 * Note: this function does not check that the current user can access the course.
3084 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3086 * @return bool
3088 public function can_review_enrolments() {
3089 return has_capability('moodle/course:enrolreview', $this->get_context());
3093 * Returns true if the current user can delete this course.
3095 * Note: this function does not check that the current user can access the course.
3096 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3098 * @return bool
3100 public function can_delete() {
3101 return can_delete_course($this->id);
3105 * Returns true if the current user can backup this course.
3107 * Note: this function does not check that the current user can access the course.
3108 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3110 * @return bool
3112 public function can_backup() {
3113 return has_capability('moodle/backup:backupcourse', $this->get_context());
3117 * Returns true if the current user can restore this course.
3119 * Note: this function does not check that the current user can access the course.
3120 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3122 * @return bool
3124 public function can_restore() {
3125 return has_capability('moodle/restore:restorecourse', $this->get_context());
3130 * An array of records that is sortable by many fields.
3132 * For more info on the ArrayObject class have a look at php.net.
3134 * @package core
3135 * @subpackage course
3136 * @copyright 2013 Sam Hemelryk
3137 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3139 class coursecat_sortable_records extends ArrayObject {
3142 * An array of sortable fields.
3143 * Gets set temporarily when sort is called.
3144 * @var array
3146 protected $sortfields = array();
3149 * Sorts this array using the given fields.
3151 * @param array $records
3152 * @param array $fields
3153 * @return array
3155 public static function sort(array $records, array $fields) {
3156 $records = new coursecat_sortable_records($records);
3157 $records->sortfields = $fields;
3158 $records->uasort(array($records, 'sort_by_many_fields'));
3159 return $records->getArrayCopy();
3163 * Sorts the two records based upon many fields.
3165 * This method should not be called itself, please call $sort instead.
3166 * It has been marked as access private as such.
3168 * @access private
3169 * @param stdClass $a
3170 * @param stdClass $b
3171 * @return int
3173 public function sort_by_many_fields($a, $b) {
3174 foreach ($this->sortfields as $field => $mult) {
3175 // Nulls first.
3176 if (is_null($a->$field) && !is_null($b->$field)) {
3177 return -$mult;
3179 if (is_null($b->$field) && !is_null($a->$field)) {
3180 return $mult;
3183 if (is_string($a->$field) || is_string($b->$field)) {
3184 // String fields.
3185 if ($cmp = strcoll($a->$field, $b->$field)) {
3186 return $mult * $cmp;
3188 } else {
3189 // Int fields.
3190 if ($a->$field > $b->$field) {
3191 return $mult;
3193 if ($a->$field < $b->$field) {
3194 return -$mult;
3198 return 0;