Merge branch 'MDL-53323' of https://github.com/mr-russ/moodle
[moodle.git] / lib / coursecatlib.php
blobfb6a4eded14e414e5f661e342593d898a89d7655
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 (!empty($data->idnumber)) {
365 if (core_text::strlen($data->idnumber) > 100) {
366 throw new moodle_exception('idnumbertoolong');
368 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
369 throw new moodle_exception('categoryidnumbertaken');
372 if (isset($data->idnumber)) {
373 $newcategory->idnumber = $data->idnumber;
376 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
377 $newcategory->theme = $data->theme;
380 if (empty($data->parent)) {
381 $parent = self::get(0);
382 } else {
383 $parent = self::get($data->parent, MUST_EXIST, true);
385 $newcategory->parent = $parent->id;
386 $newcategory->depth = $parent->depth + 1;
388 // By default category is visible, unless visible = 0 is specified or parent category is hidden.
389 if (isset($data->visible) && !$data->visible) {
390 // Create a hidden category.
391 $newcategory->visible = $newcategory->visibleold = 0;
392 } else {
393 // Create a category that inherits visibility from parent.
394 $newcategory->visible = $parent->visible;
395 // In case parent is hidden, when it changes visibility this new subcategory will automatically become visible too.
396 $newcategory->visibleold = 1;
399 $newcategory->sortorder = 0;
400 $newcategory->timemodified = time();
402 $newcategory->id = $DB->insert_record('course_categories', $newcategory);
404 // Update path (only possible after we know the category id.
405 $path = $parent->path . '/' . $newcategory->id;
406 $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));
408 // We should mark the context as dirty.
409 context_coursecat::instance($newcategory->id)->mark_dirty();
411 fix_course_sortorder();
413 // If this is data from form results, save embedded files and update description.
414 $categorycontext = context_coursecat::instance($newcategory->id);
415 if ($editoroptions) {
416 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
417 'coursecat', 'description', 0);
419 // Update only fields description and descriptionformat.
420 $updatedata = new stdClass();
421 $updatedata->id = $newcategory->id;
422 $updatedata->description = $newcategory->description;
423 $updatedata->descriptionformat = $newcategory->descriptionformat;
424 $DB->update_record('course_categories', $updatedata);
427 $event = \core\event\course_category_created::create(array(
428 'objectid' => $newcategory->id,
429 'context' => $categorycontext
431 $event->trigger();
433 cache_helper::purge_by_event('changesincoursecat');
435 return self::get($newcategory->id, MUST_EXIST, true);
439 * Updates the record with either form data or raw data
441 * Please note that this function does not verify access control.
443 * This function calls coursecat::change_parent_raw if field 'parent' is updated.
444 * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
445 * Visibility is changed first and then parent is changed. This means that
446 * if parent category is hidden, the current category will become hidden
447 * too and it may overwrite whatever was set in field 'visible'.
449 * Note that fields 'path' and 'depth' can not be updated manually
450 * Also coursecat::update() can not directly update the field 'sortoder'
452 * @param array|stdClass $data
453 * @param array $editoroptions if specified, the data is considered to be
454 * form data and file_postupdate_standard_editor() is being called to
455 * process images in description.
456 * @throws moodle_exception
458 public function update($data, $editoroptions = null) {
459 global $DB, $CFG;
460 if (!$this->id) {
461 // There is no actual DB record associated with root category.
462 return;
465 $data = (object)$data;
466 $newcategory = new stdClass();
467 $newcategory->id = $this->id;
469 // Copy all description* fields regardless of whether this is form data or direct field update.
470 foreach ($data as $key => $value) {
471 if (preg_match("/^description/", $key)) {
472 $newcategory->$key = $value;
476 if (isset($data->name) && empty($data->name)) {
477 throw new moodle_exception('categorynamerequired');
480 if (!empty($data->name) && $data->name !== $this->name) {
481 if (core_text::strlen($data->name) > 255) {
482 throw new moodle_exception('categorytoolong');
484 $newcategory->name = $data->name;
487 if (isset($data->idnumber) && $data->idnumber != $this->idnumber) {
488 if (core_text::strlen($data->idnumber) > 100) {
489 throw new moodle_exception('idnumbertoolong');
491 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
492 throw new moodle_exception('categoryidnumbertaken');
494 $newcategory->idnumber = $data->idnumber;
497 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
498 $newcategory->theme = $data->theme;
501 $changes = false;
502 if (isset($data->visible)) {
503 if ($data->visible) {
504 $changes = $this->show_raw();
505 } else {
506 $changes = $this->hide_raw(0);
510 if (isset($data->parent) && $data->parent != $this->parent) {
511 if ($changes) {
512 cache_helper::purge_by_event('changesincoursecat');
514 $parentcat = self::get($data->parent, MUST_EXIST, true);
515 $this->change_parent_raw($parentcat);
516 fix_course_sortorder();
519 $newcategory->timemodified = time();
521 $categorycontext = $this->get_context();
522 if ($editoroptions) {
523 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
524 'coursecat', 'description', 0);
526 $DB->update_record('course_categories', $newcategory);
528 $event = \core\event\course_category_updated::create(array(
529 'objectid' => $newcategory->id,
530 'context' => $categorycontext
532 $event->trigger();
534 fix_course_sortorder();
535 // Purge cache even if fix_course_sortorder() did not do it.
536 cache_helper::purge_by_event('changesincoursecat');
538 // Update all fields in the current object.
539 $this->restore();
543 * Checks if this course category is visible to current user
545 * Please note that methods coursecat::get (without 3rd argumet),
546 * coursecat::get_children(), etc. return only visible categories so it is
547 * usually not needed to call this function outside of this class
549 * @return bool
551 public function is_uservisible() {
552 return !$this->id || $this->visible ||
553 has_capability('moodle/category:viewhiddencategories', $this->get_context());
557 * Returns the complete corresponding record from DB table course_categories
559 * Mostly used in deprecated functions
561 * @return stdClass
563 public function get_db_record() {
564 global $DB;
565 if ($record = $DB->get_record('course_categories', array('id' => $this->id))) {
566 return $record;
567 } else {
568 return (object)convert_to_array($this);
573 * Returns the entry from categories tree and makes sure the application-level tree cache is built
575 * The following keys can be requested:
577 * 'countall' - total number of categories in the system (always present)
578 * 0 - array of ids of top-level categories (always present)
579 * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
580 * $id (int) - array of ids of categories that are direct children of category with id $id. If
581 * category with id $id does not exist returns false. If category has no children returns empty array
582 * $id.'i' - array of ids of children categories that have visible=0
584 * @param int|string $id
585 * @return mixed
587 protected static function get_tree($id) {
588 global $DB;
589 $coursecattreecache = cache::make('core', 'coursecattree');
590 $rv = $coursecattreecache->get($id);
591 if ($rv !== false) {
592 return $rv;
594 // Re-build the tree.
595 $sql = "SELECT cc.id, cc.parent, cc.visible
596 FROM {course_categories} cc
597 ORDER BY cc.sortorder";
598 $rs = $DB->get_recordset_sql($sql, array());
599 $all = array(0 => array(), '0i' => array());
600 $count = 0;
601 foreach ($rs as $record) {
602 $all[$record->id] = array();
603 $all[$record->id. 'i'] = array();
604 if (array_key_exists($record->parent, $all)) {
605 $all[$record->parent][] = $record->id;
606 if (!$record->visible) {
607 $all[$record->parent. 'i'][] = $record->id;
609 } else {
610 // Parent not found. This is data consistency error but next fix_course_sortorder() should fix it.
611 $all[0][] = $record->id;
612 if (!$record->visible) {
613 $all['0i'][] = $record->id;
616 $count++;
618 $rs->close();
619 if (!$count) {
620 // No categories found.
621 // This may happen after upgrade of a very old moodle version.
622 // In new versions the default category is created on install.
623 $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
624 set_config('defaultrequestcategory', $defcoursecat->id);
625 $all[0] = array($defcoursecat->id);
626 $all[$defcoursecat->id] = array();
627 $count++;
629 // We must add countall to all in case it was the requested ID.
630 $all['countall'] = $count;
631 foreach ($all as $key => $children) {
632 $coursecattreecache->set($key, $children);
634 if (array_key_exists($id, $all)) {
635 return $all[$id];
637 // Requested non-existing category.
638 return array();
642 * Returns number of ALL categories in the system regardless if
643 * they are visible to current user or not
645 * @return int
647 public static function count_all() {
648 return self::get_tree('countall');
652 * Retrieves number of records from course_categories table
654 * Only cached fields are retrieved. Records are ready for preloading context
656 * @param string $whereclause
657 * @param array $params
658 * @return array array of stdClass objects
660 protected static function get_records($whereclause, $params) {
661 global $DB;
662 // Retrieve from DB only the fields that need to be stored in cache.
663 $fields = array_keys(array_filter(self::$coursecatfields));
664 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
665 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
666 FROM {course_categories} cc
667 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
668 WHERE ". $whereclause." ORDER BY cc.sortorder";
669 return $DB->get_records_sql($sql,
670 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
674 * Resets course contact caches when role assignments were changed
676 * @param int $roleid role id that was given or taken away
677 * @param context $context context where role assignment has been changed
679 public static function role_assignment_changed($roleid, $context) {
680 global $CFG, $DB;
682 if ($context->contextlevel > CONTEXT_COURSE) {
683 // No changes to course contacts if role was assigned on the module/block level.
684 return;
687 if (!$CFG->coursecontact || !in_array($roleid, explode(',', $CFG->coursecontact))) {
688 // The role is not one of course contact roles.
689 return;
692 // Remove from cache course contacts of all affected courses.
693 $cache = cache::make('core', 'coursecontacts');
694 if ($context->contextlevel == CONTEXT_COURSE) {
695 $cache->delete($context->instanceid);
696 } else if ($context->contextlevel == CONTEXT_SYSTEM) {
697 $cache->purge();
698 } else {
699 $sql = "SELECT ctx.instanceid
700 FROM {context} ctx
701 WHERE ctx.path LIKE ? AND ctx.contextlevel = ?";
702 $params = array($context->path . '/%', CONTEXT_COURSE);
703 if ($courses = $DB->get_fieldset_sql($sql, $params)) {
704 $cache->delete_many($courses);
710 * Executed when user enrolment was changed to check if course
711 * contacts cache needs to be cleared
713 * @param int $courseid course id
714 * @param int $userid user id
715 * @param int $status new enrolment status (0 - active, 1 - suspended)
716 * @param int $timestart new enrolment time start
717 * @param int $timeend new enrolment time end
719 public static function user_enrolment_changed($courseid, $userid,
720 $status, $timestart = null, $timeend = null) {
721 $cache = cache::make('core', 'coursecontacts');
722 $contacts = $cache->get($courseid);
723 if ($contacts === false) {
724 // The contacts for the affected course were not cached anyway.
725 return;
727 $enrolmentactive = ($status == 0) &&
728 (!$timestart || $timestart < time()) &&
729 (!$timeend || $timeend > time());
730 if (!$enrolmentactive) {
731 $isincontacts = false;
732 foreach ($contacts as $contact) {
733 if ($contact->id == $userid) {
734 $isincontacts = true;
737 if (!$isincontacts) {
738 // Changed user's enrolment does not exist or is not active,
739 // and he is not in cached course contacts, no changes to be made.
740 return;
743 // Either enrolment of manager was deleted/suspended
744 // or user enrolment was added or activated.
745 // In order to see if the course contacts for this course need
746 // changing we would need to make additional queries, they will
747 // slow down bulk enrolment changes. It is better just to remove
748 // course contacts cache for this course.
749 $cache->delete($courseid);
753 * Given list of DB records from table course populates each record with list of users with course contact roles
755 * This function fills the courses with raw information as {@link get_role_users()} would do.
756 * See also {@link course_in_list::get_course_contacts()} for more readable return
758 * $courses[$i]->managers = array(
759 * $roleassignmentid => $roleuser,
760 * ...
761 * );
763 * where $roleuser is an stdClass with the following properties:
765 * $roleuser->raid - role assignment id
766 * $roleuser->id - user id
767 * $roleuser->username
768 * $roleuser->firstname
769 * $roleuser->lastname
770 * $roleuser->rolecoursealias
771 * $roleuser->rolename
772 * $roleuser->sortorder - role sortorder
773 * $roleuser->roleid
774 * $roleuser->roleshortname
776 * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
778 * @param array $courses
780 public static function preload_course_contacts(&$courses) {
781 global $CFG, $DB;
782 if (empty($courses) || empty($CFG->coursecontact)) {
783 return;
785 $managerroles = explode(',', $CFG->coursecontact);
786 $cache = cache::make('core', 'coursecontacts');
787 $cacheddata = $cache->get_many(array_keys($courses));
788 $courseids = array();
789 foreach (array_keys($courses) as $id) {
790 if ($cacheddata[$id] !== false) {
791 $courses[$id]->managers = $cacheddata[$id];
792 } else {
793 $courseids[] = $id;
797 // Array $courseids now stores list of ids of courses for which we still need to retrieve contacts.
798 if (empty($courseids)) {
799 return;
802 // First build the array of all context ids of the courses and their categories.
803 $allcontexts = array();
804 foreach ($courseids as $id) {
805 $context = context_course::instance($id);
806 $courses[$id]->managers = array();
807 foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
808 if (!isset($allcontexts[$ctxid])) {
809 $allcontexts[$ctxid] = array();
811 $allcontexts[$ctxid][] = $id;
815 // Fetch list of all users with course contact roles in any of the courses contexts or parent contexts.
816 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
817 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
818 list($sort, $sortparams) = users_order_by_sql('u');
819 $notdeleted = array('notdeleted'=>0);
820 $allnames = get_all_user_name_fields(true, 'u');
821 $sql = "SELECT ra.contextid, ra.id AS raid,
822 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
823 rn.name AS rolecoursealias, u.id, u.username, $allnames
824 FROM {role_assignments} ra
825 JOIN {user} u ON ra.userid = u.id
826 JOIN {role} r ON ra.roleid = r.id
827 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
828 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
829 ORDER BY r.sortorder, $sort";
830 $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
831 $checkenrolments = array();
832 foreach ($rs as $ra) {
833 foreach ($allcontexts[$ra->contextid] as $id) {
834 $courses[$id]->managers[$ra->raid] = $ra;
835 if (!isset($checkenrolments[$id])) {
836 $checkenrolments[$id] = array();
838 $checkenrolments[$id][] = $ra->id;
841 $rs->close();
843 // Remove from course contacts users who are not enrolled in the course.
844 $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
845 foreach ($checkenrolments as $id => $userids) {
846 if (empty($enrolleduserids[$id])) {
847 $courses[$id]->managers = array();
848 } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
849 foreach ($courses[$id]->managers as $raid => $ra) {
850 if (in_array($ra->id, $notenrolled)) {
851 unset($courses[$id]->managers[$raid]);
857 // Set the cache.
858 $values = array();
859 foreach ($courseids as $id) {
860 $values[$id] = $courses[$id]->managers;
862 $cache->set_many($values);
866 * Verify user enrollments for multiple course-user combinations
868 * @param array $courseusers array where keys are course ids and values are array
869 * of users in this course whose enrolment we wish to verify
870 * @return array same structure as input array but values list only users from input
871 * who are enrolled in the course
873 protected static function ensure_users_enrolled($courseusers) {
874 global $DB;
875 // If the input array is too big, split it into chunks.
876 $maxcoursesinquery = 20;
877 if (count($courseusers) > $maxcoursesinquery) {
878 $rv = array();
879 for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
880 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
881 $rv = $rv + self::ensure_users_enrolled($chunk);
883 return $rv;
886 // Create a query verifying valid user enrolments for the number of courses.
887 $sql = "SELECT DISTINCT e.courseid, ue.userid
888 FROM {user_enrolments} ue
889 JOIN {enrol} e ON e.id = ue.enrolid
890 WHERE ue.status = :active
891 AND e.status = :enabled
892 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
893 $now = round(time(), -2); // Rounding helps caching in DB.
894 $params = array('enabled' => ENROL_INSTANCE_ENABLED,
895 'active' => ENROL_USER_ACTIVE,
896 'now1' => $now, 'now2' => $now);
897 $cnt = 0;
898 $subsqls = array();
899 $enrolled = array();
900 foreach ($courseusers as $id => $userids) {
901 $enrolled[$id] = array();
902 if (count($userids)) {
903 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
904 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
905 $params = $params + array('courseid'.$cnt => $id) + $params2;
906 $cnt++;
909 if (count($subsqls)) {
910 $sql .= "AND (". join(' OR ', $subsqls).")";
911 $rs = $DB->get_recordset_sql($sql, $params);
912 foreach ($rs as $record) {
913 $enrolled[$record->courseid][] = $record->userid;
915 $rs->close();
917 return $enrolled;
921 * Retrieves number of records from course table
923 * Not all fields are retrieved. Records are ready for preloading context
925 * @param string $whereclause
926 * @param array $params
927 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
928 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
929 * on not visible courses
930 * @return array array of stdClass objects
932 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
933 global $DB;
934 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
935 $fields = array('c.id', 'c.category', 'c.sortorder',
936 'c.shortname', 'c.fullname', 'c.idnumber',
937 'c.startdate', 'c.visible', 'c.cacherev');
938 if (!empty($options['summary'])) {
939 $fields[] = 'c.summary';
940 $fields[] = 'c.summaryformat';
941 } else {
942 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
944 $sql = "SELECT ". join(',', $fields). ", $ctxselect
945 FROM {course} c
946 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
947 WHERE ". $whereclause." ORDER BY c.sortorder";
948 $list = $DB->get_records_sql($sql,
949 array('contextcourse' => CONTEXT_COURSE) + $params);
951 if ($checkvisibility) {
952 // Loop through all records and make sure we only return the courses accessible by user.
953 foreach ($list as $course) {
954 if (isset($list[$course->id]->hassummary)) {
955 $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
957 if (empty($course->visible)) {
958 // Load context only if we need to check capability.
959 context_helper::preload_from_record($course);
960 if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
961 unset($list[$course->id]);
967 // Preload course contacts if necessary.
968 if (!empty($options['coursecontacts'])) {
969 self::preload_course_contacts($list);
971 return $list;
975 * Returns array of ids of children categories that current user can not see
977 * This data is cached in user session cache
979 * @return array
981 protected function get_not_visible_children_ids() {
982 global $DB;
983 $coursecatcache = cache::make('core', 'coursecat');
984 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
985 // We never checked visible children before.
986 $hidden = self::get_tree($this->id.'i');
987 $invisibleids = array();
988 if ($hidden) {
989 // Preload categories contexts.
990 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
991 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
992 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
993 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
994 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
995 foreach ($contexts as $record) {
996 context_helper::preload_from_record($record);
998 // Check that user has 'viewhiddencategories' capability for each hidden category.
999 foreach ($hidden as $id) {
1000 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
1001 $invisibleids[] = $id;
1005 $coursecatcache->set('ic'. $this->id, $invisibleids);
1007 return $invisibleids;
1011 * Sorts list of records by several fields
1013 * @param array $records array of stdClass objects
1014 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
1015 * @return int
1017 protected static function sort_records(&$records, $sortfields) {
1018 if (empty($records)) {
1019 return;
1021 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname).
1022 if (array_key_exists('displayname', $sortfields)) {
1023 foreach ($records as $key => $record) {
1024 if (!isset($record->displayname)) {
1025 $records[$key]->displayname = get_course_display_name_for_list($record);
1029 // Sorting by one field - use core_collator.
1030 if (count($sortfields) == 1) {
1031 $property = key($sortfields);
1032 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
1033 $sortflag = core_collator::SORT_NUMERIC;
1034 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
1035 $sortflag = core_collator::SORT_STRING;
1036 } else {
1037 $sortflag = core_collator::SORT_REGULAR;
1039 core_collator::asort_objects_by_property($records, $property, $sortflag);
1040 if ($sortfields[$property] < 0) {
1041 $records = array_reverse($records, true);
1043 return;
1045 $records = coursecat_sortable_records::sort($records, $sortfields);
1049 * Returns array of children categories visible to the current user
1051 * @param array $options options for retrieving children
1052 * - sort - list of fields to sort. Example
1053 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
1054 * will sort by idnumber asc, name asc and id desc.
1055 * Default: array('sortorder' => 1)
1056 * Only cached fields may be used for sorting!
1057 * - offset
1058 * - limit - maximum number of children to return, 0 or null for no limit
1059 * @return coursecat[] Array of coursecat objects indexed by category id
1061 public function get_children($options = array()) {
1062 global $DB;
1063 $coursecatcache = cache::make('core', 'coursecat');
1065 // Get default values for options.
1066 if (!empty($options['sort']) && is_array($options['sort'])) {
1067 $sortfields = $options['sort'];
1068 } else {
1069 $sortfields = array('sortorder' => 1);
1071 $limit = null;
1072 if (!empty($options['limit']) && (int)$options['limit']) {
1073 $limit = (int)$options['limit'];
1075 $offset = 0;
1076 if (!empty($options['offset']) && (int)$options['offset']) {
1077 $offset = (int)$options['offset'];
1080 // First retrieve list of user-visible and sorted children ids from cache.
1081 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
1082 if ($sortedids === false) {
1083 $sortfieldskeys = array_keys($sortfields);
1084 if ($sortfieldskeys[0] === 'sortorder') {
1085 // No DB requests required to build the list of ids sorted by sortorder.
1086 // We can easily ignore other sort fields because sortorder is always different.
1087 $sortedids = self::get_tree($this->id);
1088 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
1089 $sortedids = array_diff($sortedids, $invisibleids);
1090 if ($sortfields['sortorder'] == -1) {
1091 $sortedids = array_reverse($sortedids, true);
1094 } else {
1095 // We need to retrieve and sort all children. Good thing that it is done only on first request.
1096 if ($invisibleids = $this->get_not_visible_children_ids()) {
1097 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
1098 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
1099 array('parent' => $this->id) + $params);
1100 } else {
1101 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
1103 self::sort_records($records, $sortfields);
1104 $sortedids = array_keys($records);
1106 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
1109 if (empty($sortedids)) {
1110 return array();
1113 // Now retrieive and return categories.
1114 if ($offset || $limit) {
1115 $sortedids = array_slice($sortedids, $offset, $limit);
1117 if (isset($records)) {
1118 // Easy, we have already retrieved records.
1119 if ($offset || $limit) {
1120 $records = array_slice($records, $offset, $limit, true);
1122 } else {
1123 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
1124 $records = self::get_records('cc.id '. $sql, array('parent' => $this->id) + $params);
1127 $rv = array();
1128 foreach ($sortedids as $id) {
1129 if (isset($records[$id])) {
1130 $rv[$id] = new coursecat($records[$id]);
1133 return $rv;
1137 * Returns true if the user has the manage capability on any category.
1139 * This method uses the coursecat cache and an entry `has_manage_capability` to speed up
1140 * calls to this method.
1142 * @return bool
1144 public static function has_manage_capability_on_any() {
1145 return self::has_capability_on_any('moodle/category:manage');
1149 * Checks if the user has at least one of the given capabilities on any category.
1151 * @param array|string $capabilities One or more capabilities to check. Check made is an OR.
1152 * @return bool
1154 public static function has_capability_on_any($capabilities) {
1155 global $DB;
1156 if (!isloggedin() || isguestuser()) {
1157 return false;
1160 if (!is_array($capabilities)) {
1161 $capabilities = array($capabilities);
1163 $keys = array();
1164 foreach ($capabilities as $capability) {
1165 $keys[$capability] = sha1($capability);
1168 /* @var cache_session $cache */
1169 $cache = cache::make('core', 'coursecat');
1170 $hascapability = $cache->get_many($keys);
1171 $needtoload = false;
1172 foreach ($hascapability as $capability) {
1173 if ($capability === '1') {
1174 return true;
1175 } else if ($capability === false) {
1176 $needtoload = true;
1179 if ($needtoload === false) {
1180 // All capabilities were retrieved and the user didn't have any.
1181 return false;
1184 $haskey = null;
1185 $fields = context_helper::get_preload_record_columns_sql('ctx');
1186 $sql = "SELECT ctx.instanceid AS categoryid, $fields
1187 FROM {context} ctx
1188 WHERE contextlevel = :contextlevel
1189 ORDER BY depth ASC";
1190 $params = array('contextlevel' => CONTEXT_COURSECAT);
1191 $recordset = $DB->get_recordset_sql($sql, $params);
1192 foreach ($recordset as $context) {
1193 context_helper::preload_from_record($context);
1194 $context = context_coursecat::instance($context->categoryid);
1195 foreach ($capabilities as $capability) {
1196 if (has_capability($capability, $context)) {
1197 $haskey = $capability;
1198 break 2;
1202 $recordset->close();
1203 if ($haskey === null) {
1204 $data = array();
1205 foreach ($keys as $key) {
1206 $data[$key] = '0';
1208 $cache->set_many($data);
1209 return false;
1210 } else {
1211 $cache->set($haskey, '1');
1212 return true;
1217 * Returns true if the user can resort any category.
1218 * @return bool
1220 public static function can_resort_any() {
1221 return self::has_manage_capability_on_any();
1225 * Returns true if the user can change the parent of any category.
1226 * @return bool
1228 public static function can_change_parent_any() {
1229 return self::has_manage_capability_on_any();
1233 * Returns number of subcategories visible to the current user
1235 * @return int
1237 public function get_children_count() {
1238 $sortedids = self::get_tree($this->id);
1239 $invisibleids = $this->get_not_visible_children_ids();
1240 return count($sortedids) - count($invisibleids);
1244 * Returns true if the category has ANY children, including those not visible to the user
1246 * @return boolean
1248 public function has_children() {
1249 $allchildren = self::get_tree($this->id);
1250 return !empty($allchildren);
1254 * Returns true if the category has courses in it (count does not include courses
1255 * in child categories)
1257 * @return bool
1259 public function has_courses() {
1260 global $DB;
1261 return $DB->record_exists_sql("select 1 from {course} where category = ?",
1262 array($this->id));
1266 * Searches courses
1268 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1269 * to this when somebody edits courses or categories, however it is very
1270 * difficult to keep track of all possible changes that may affect list of courses.
1272 * @param array $search contains search criterias, such as:
1273 * - search - search string
1274 * - blocklist - id of block (if we are searching for courses containing specific block0
1275 * - modulelist - name of module (if we are searching for courses containing specific module
1276 * - tagid - id of tag
1277 * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
1278 * search is always category-independent
1279 * @param array $requiredcapabilites List of capabilities required to see return course.
1280 * @return course_in_list[]
1282 public static function search_courses($search, $options = array(), $requiredcapabilities = array()) {
1283 global $DB;
1284 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1285 $limit = !empty($options['limit']) ? $options['limit'] : null;
1286 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1288 $coursecatcache = cache::make('core', 'coursecat');
1289 $cachekey = 's-'. serialize(
1290 $search + array('sort' => $sortfields) + array('requiredcapabilities' => $requiredcapabilities)
1292 $cntcachekey = 'scnt-'. serialize($search);
1294 $ids = $coursecatcache->get($cachekey);
1295 if ($ids !== false) {
1296 // We already cached last search result.
1297 $ids = array_slice($ids, $offset, $limit);
1298 $courses = array();
1299 if (!empty($ids)) {
1300 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1301 $records = self::get_course_records("c.id ". $sql, $params, $options);
1302 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1303 if (!empty($options['coursecontacts'])) {
1304 self::preload_course_contacts($records);
1306 // If option 'idonly' is specified no further action is needed, just return list of ids.
1307 if (!empty($options['idonly'])) {
1308 return array_keys($records);
1310 // Prepare the list of course_in_list objects.
1311 foreach ($ids as $id) {
1312 $courses[$id] = new course_in_list($records[$id]);
1315 return $courses;
1318 $preloadcoursecontacts = !empty($options['coursecontacts']);
1319 unset($options['coursecontacts']);
1321 // Empty search string will return all results.
1322 if (!isset($search['search'])) {
1323 $search['search'] = '';
1326 if (empty($search['blocklist']) && empty($search['modulelist']) && empty($search['tagid'])) {
1327 // Search courses that have specified words in their names/summaries.
1328 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1330 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount, $requiredcapabilities);
1331 self::sort_records($courselist, $sortfields);
1332 $coursecatcache->set($cachekey, array_keys($courselist));
1333 $coursecatcache->set($cntcachekey, $totalcount);
1334 $records = array_slice($courselist, $offset, $limit, true);
1335 } else {
1336 if (!empty($search['blocklist'])) {
1337 // Search courses that have block with specified id.
1338 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1339 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1340 WHERE bi.blockname = :blockname)';
1341 $params = array('blockname' => $blockname);
1342 } else if (!empty($search['modulelist'])) {
1343 // Search courses that have module with specified name.
1344 $where = "c.id IN (SELECT DISTINCT module.course ".
1345 "FROM {".$search['modulelist']."} module)";
1346 $params = array();
1347 } else if (!empty($search['tagid'])) {
1348 // Search courses that are tagged with the specified tag.
1349 $where = "c.id IN (SELECT t.itemid ".
1350 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype AND t.component = :component)";
1351 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course', 'component' => 'core');
1352 if (!empty($search['ctx'])) {
1353 $rec = isset($search['rec']) ? $search['rec'] : true;
1354 $parentcontext = context::instance_by_id($search['ctx']);
1355 if ($parentcontext->contextlevel == CONTEXT_SYSTEM && $rec) {
1356 // Parent context is system context and recursive is set to yes.
1357 // Nothing to filter - all courses fall into this condition.
1358 } else if ($rec) {
1359 // Filter all courses in the parent context at any level.
1360 $where .= ' AND ctx.path LIKE :contextpath';
1361 $params['contextpath'] = $parentcontext->path . '%';
1362 } else if ($parentcontext->contextlevel == CONTEXT_COURSECAT) {
1363 // All courses in the given course category.
1364 $where .= ' AND c.category = :category';
1365 $params['category'] = $parentcontext->instanceid;
1366 } else {
1367 // No courses will satisfy the context criterion, do not bother searching.
1368 $where = '1=0';
1371 } else {
1372 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1373 return array();
1375 $courselist = self::get_course_records($where, $params, $options, true);
1376 if (!empty($requiredcapabilities)) {
1377 foreach ($courselist as $key => $course) {
1378 context_helper::preload_from_record($course);
1379 $coursecontext = context_course::instance($course->id);
1380 if (!has_all_capabilities($requiredcapabilities, $coursecontext)) {
1381 unset($courselist[$key]);
1385 self::sort_records($courselist, $sortfields);
1386 $coursecatcache->set($cachekey, array_keys($courselist));
1387 $coursecatcache->set($cntcachekey, count($courselist));
1388 $records = array_slice($courselist, $offset, $limit, true);
1391 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1392 if (!empty($preloadcoursecontacts)) {
1393 self::preload_course_contacts($records);
1395 // If option 'idonly' is specified no further action is needed, just return list of ids.
1396 if (!empty($options['idonly'])) {
1397 return array_keys($records);
1399 // Prepare the list of course_in_list objects.
1400 $courses = array();
1401 foreach ($records as $record) {
1402 $courses[$record->id] = new course_in_list($record);
1404 return $courses;
1408 * Returns number of courses in the search results
1410 * It is recommended to call this function after {@link coursecat::search_courses()}
1411 * and not before because only course ids are cached. Otherwise search_courses() may
1412 * perform extra DB queries.
1414 * @param array $search search criteria, see method search_courses() for more details
1415 * @param array $options display options. They do not affect the result but
1416 * the 'sort' property is used in cache key for storing list of course ids
1417 * @param array $requiredcapabilites List of capabilities required to see return course.
1418 * @return int
1420 public static function search_courses_count($search, $options = array(), $requiredcapabilities = array()) {
1421 $coursecatcache = cache::make('core', 'coursecat');
1422 $cntcachekey = 'scnt-'. serialize($search) . serialize($requiredcapabilities);
1423 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1424 // Cached value not found. Retrieve ALL courses and return their count.
1425 unset($options['offset']);
1426 unset($options['limit']);
1427 unset($options['summary']);
1428 unset($options['coursecontacts']);
1429 $options['idonly'] = true;
1430 $courses = self::search_courses($search, $options, $requiredcapabilities);
1431 $cnt = count($courses);
1433 return $cnt;
1437 * Retrieves the list of courses accessible by user
1439 * Not all information is cached, try to avoid calling this method
1440 * twice in the same request.
1442 * The following fields are always retrieved:
1443 * - id, visible, fullname, shortname, idnumber, category, sortorder
1445 * If you plan to use properties/methods course_in_list::$summary and/or
1446 * course_in_list::get_course_contacts()
1447 * you can preload this information using appropriate 'options'. Otherwise
1448 * they will be retrieved from DB on demand and it may end with bigger DB load.
1450 * Note that method course_in_list::has_summary() will not perform additional
1451 * DB queries even if $options['summary'] is not specified
1453 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1454 * to this when somebody edits courses or categories, however it is very
1455 * difficult to keep track of all possible changes that may affect list of courses.
1457 * @param array $options options for retrieving children
1458 * - recursive - return courses from subcategories as well. Use with care,
1459 * this may be a huge list!
1460 * - summary - preloads fields 'summary' and 'summaryformat'
1461 * - coursecontacts - preloads course contacts
1462 * - sort - list of fields to sort. Example
1463 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1464 * will sort by idnumber asc, shortname asc and id desc.
1465 * Default: array('sortorder' => 1)
1466 * Only cached fields may be used for sorting!
1467 * - offset
1468 * - limit - maximum number of children to return, 0 or null for no limit
1469 * - idonly - returns the array or course ids instead of array of objects
1470 * used only in get_courses_count()
1471 * @return course_in_list[]
1473 public function get_courses($options = array()) {
1474 global $DB;
1475 $recursive = !empty($options['recursive']);
1476 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1477 $limit = !empty($options['limit']) ? $options['limit'] : null;
1478 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1480 // Check if this category is hidden.
1481 // Also 0-category never has courses unless this is recursive call.
1482 if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1483 return array();
1486 $coursecatcache = cache::make('core', 'coursecat');
1487 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1488 '-'. serialize($sortfields);
1489 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1491 // Check if we have already cached results.
1492 $ids = $coursecatcache->get($cachekey);
1493 if ($ids !== false) {
1494 // We already cached last search result and it did not expire yet.
1495 $ids = array_slice($ids, $offset, $limit);
1496 $courses = array();
1497 if (!empty($ids)) {
1498 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1499 $records = self::get_course_records("c.id ". $sql, $params, $options);
1500 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1501 if (!empty($options['coursecontacts'])) {
1502 self::preload_course_contacts($records);
1504 // If option 'idonly' is specified no further action is needed, just return list of ids.
1505 if (!empty($options['idonly'])) {
1506 return array_keys($records);
1508 // Prepare the list of course_in_list objects.
1509 foreach ($ids as $id) {
1510 $courses[$id] = new course_in_list($records[$id]);
1513 return $courses;
1516 // Retrieve list of courses in category.
1517 $where = 'c.id <> :siteid';
1518 $params = array('siteid' => SITEID);
1519 if ($recursive) {
1520 if ($this->id) {
1521 $context = context_coursecat::instance($this->id);
1522 $where .= ' AND ctx.path like :path';
1523 $params['path'] = $context->path. '/%';
1525 } else {
1526 $where .= ' AND c.category = :categoryid';
1527 $params['categoryid'] = $this->id;
1529 // Get list of courses without preloaded coursecontacts because we don't need them for every course.
1530 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1532 // Sort and cache list.
1533 self::sort_records($list, $sortfields);
1534 $coursecatcache->set($cachekey, array_keys($list));
1535 $coursecatcache->set($cntcachekey, count($list));
1537 // Apply offset/limit, convert to course_in_list and return.
1538 $courses = array();
1539 if (isset($list)) {
1540 if ($offset || $limit) {
1541 $list = array_slice($list, $offset, $limit, true);
1543 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1544 if (!empty($options['coursecontacts'])) {
1545 self::preload_course_contacts($list);
1547 // If option 'idonly' is specified no further action is needed, just return list of ids.
1548 if (!empty($options['idonly'])) {
1549 return array_keys($list);
1551 // Prepare the list of course_in_list objects.
1552 foreach ($list as $record) {
1553 $courses[$record->id] = new course_in_list($record);
1556 return $courses;
1560 * Returns number of courses visible to the user
1562 * @param array $options similar to get_courses() except some options do not affect
1563 * number of courses (i.e. sort, summary, offset, limit etc.)
1564 * @return int
1566 public function get_courses_count($options = array()) {
1567 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1568 $coursecatcache = cache::make('core', 'coursecat');
1569 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1570 // Cached value not found. Retrieve ALL courses and return their count.
1571 unset($options['offset']);
1572 unset($options['limit']);
1573 unset($options['summary']);
1574 unset($options['coursecontacts']);
1575 $options['idonly'] = true;
1576 $courses = $this->get_courses($options);
1577 $cnt = count($courses);
1579 return $cnt;
1583 * Returns true if the user is able to delete this category.
1585 * Note if this category contains any courses this isn't a full check, it will need to be accompanied by a call to either
1586 * {@link coursecat::can_delete_full()} or {@link coursecat::can_move_content_to()} depending upon what the user wished to do.
1588 * @return boolean
1590 public function can_delete() {
1591 if (!$this->has_manage_capability()) {
1592 return false;
1594 return $this->parent_has_manage_capability();
1598 * Returns true if user can delete current category and all its contents
1600 * To be able to delete course category the user must have permission
1601 * 'moodle/category:manage' in ALL child course categories AND
1602 * be able to delete all courses
1604 * @return bool
1606 public function can_delete_full() {
1607 global $DB;
1608 if (!$this->id) {
1609 // Fool-proof.
1610 return false;
1613 $context = $this->get_context();
1614 if (!$this->is_uservisible() ||
1615 !has_capability('moodle/category:manage', $context)) {
1616 return false;
1619 // Check all child categories (not only direct children).
1620 $sql = context_helper::get_preload_record_columns_sql('ctx');
1621 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1622 ' FROM {context} ctx '.
1623 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1624 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1625 array($context->path. '/%', CONTEXT_COURSECAT));
1626 foreach ($childcategories as $childcat) {
1627 context_helper::preload_from_record($childcat);
1628 $childcontext = context_coursecat::instance($childcat->id);
1629 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1630 !has_capability('moodle/category:manage', $childcontext)) {
1631 return false;
1635 // Check courses.
1636 $sql = context_helper::get_preload_record_columns_sql('ctx');
1637 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1638 $sql. ' FROM {context} ctx '.
1639 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1640 array('pathmask' => $context->path. '/%',
1641 'courselevel' => CONTEXT_COURSE));
1642 foreach ($coursescontexts as $ctxrecord) {
1643 context_helper::preload_from_record($ctxrecord);
1644 if (!can_delete_course($ctxrecord->courseid)) {
1645 return false;
1649 return true;
1653 * Recursively delete category including all subcategories and courses
1655 * Function {@link coursecat::can_delete_full()} MUST be called prior
1656 * to calling this function because there is no capability check
1657 * inside this function
1659 * @param boolean $showfeedback display some notices
1660 * @return array return deleted courses
1661 * @throws moodle_exception
1663 public function delete_full($showfeedback = true) {
1664 global $CFG, $DB;
1666 require_once($CFG->libdir.'/gradelib.php');
1667 require_once($CFG->libdir.'/questionlib.php');
1668 require_once($CFG->dirroot.'/cohort/lib.php');
1670 // Make sure we won't timeout when deleting a lot of courses.
1671 $settimeout = core_php_time_limit::raise();
1673 $deletedcourses = array();
1675 // Get children. Note, we don't want to use cache here because it would be rebuilt too often.
1676 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1677 foreach ($children as $record) {
1678 $coursecat = new coursecat($record);
1679 $deletedcourses += $coursecat->delete_full($showfeedback);
1682 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1683 foreach ($courses as $course) {
1684 if (!delete_course($course, false)) {
1685 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1687 $deletedcourses[] = $course;
1691 // Move or delete cohorts in this context.
1692 cohort_delete_category($this);
1694 // Now delete anything that may depend on course category context.
1695 grade_course_category_delete($this->id, 0, $showfeedback);
1696 if (!question_delete_course_category($this, 0, $showfeedback)) {
1697 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1700 // Finally delete the category and it's context.
1701 $DB->delete_records('course_categories', array('id' => $this->id));
1703 $coursecatcontext = context_coursecat::instance($this->id);
1704 $coursecatcontext->delete();
1706 cache_helper::purge_by_event('changesincoursecat');
1708 // Trigger a course category deleted event.
1709 /* @var \core\event\course_category_deleted $event */
1710 $event = \core\event\course_category_deleted::create(array(
1711 'objectid' => $this->id,
1712 'context' => $coursecatcontext,
1713 'other' => array('name' => $this->name)
1715 $event->set_coursecat($this);
1716 $event->trigger();
1718 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1719 if ($this->id == $CFG->defaultrequestcategory) {
1720 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1722 return $deletedcourses;
1726 * Checks if user can delete this category and move content (courses, subcategories and questions)
1727 * to another category. If yes returns the array of possible target categories names
1729 * If user can not manage this category or it is completely empty - empty array will be returned
1731 * @return array
1733 public function move_content_targets_list() {
1734 global $CFG;
1735 require_once($CFG->libdir . '/questionlib.php');
1736 $context = $this->get_context();
1737 if (!$this->is_uservisible() ||
1738 !has_capability('moodle/category:manage', $context)) {
1739 // User is not able to manage current category, he is not able to delete it.
1740 // No possible target categories.
1741 return array();
1744 $testcaps = array();
1745 // If this category has courses in it, user must have 'course:create' capability in target category.
1746 if ($this->has_courses()) {
1747 $testcaps[] = 'moodle/course:create';
1749 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1750 if ($this->has_children() || question_context_has_any_questions($context)) {
1751 $testcaps[] = 'moodle/category:manage';
1753 if (!empty($testcaps)) {
1754 // Return list of categories excluding this one and it's children.
1755 return self::make_categories_list($testcaps, $this->id);
1758 // Category is completely empty, no need in target for contents.
1759 return array();
1763 * Checks if user has capability to move all category content to the new parent before
1764 * removing this category
1766 * @param int $newcatid
1767 * @return bool
1769 public function can_move_content_to($newcatid) {
1770 global $CFG;
1771 require_once($CFG->libdir . '/questionlib.php');
1772 $context = $this->get_context();
1773 if (!$this->is_uservisible() ||
1774 !has_capability('moodle/category:manage', $context)) {
1775 return false;
1777 $testcaps = array();
1778 // If this category has courses in it, user must have 'course:create' capability in target category.
1779 if ($this->has_courses()) {
1780 $testcaps[] = 'moodle/course:create';
1782 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1783 if ($this->has_children() || question_context_has_any_questions($context)) {
1784 $testcaps[] = 'moodle/category:manage';
1786 if (!empty($testcaps)) {
1787 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1790 // There is no content but still return true.
1791 return true;
1795 * Deletes a category and moves all content (children, courses and questions) to the new parent
1797 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1798 * must be called prior
1800 * @param int $newparentid
1801 * @param bool $showfeedback
1802 * @return bool
1804 public function delete_move($newparentid, $showfeedback = false) {
1805 global $CFG, $DB, $OUTPUT;
1807 require_once($CFG->libdir.'/gradelib.php');
1808 require_once($CFG->libdir.'/questionlib.php');
1809 require_once($CFG->dirroot.'/cohort/lib.php');
1811 // Get all objects and lists because later the caches will be reset so.
1812 // We don't need to make extra queries.
1813 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1814 $catname = $this->get_formatted_name();
1815 $children = $this->get_children();
1816 $params = array('category' => $this->id);
1817 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', $params);
1818 $context = $this->get_context();
1820 if ($children) {
1821 foreach ($children as $childcat) {
1822 $childcat->change_parent_raw($newparentcat);
1823 // Log action.
1824 $event = \core\event\course_category_updated::create(array(
1825 'objectid' => $childcat->id,
1826 'context' => $childcat->get_context()
1828 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $childcat->id,
1829 $childcat->id));
1830 $event->trigger();
1832 fix_course_sortorder();
1835 if ($coursesids) {
1836 if (!move_courses($coursesids, $newparentid)) {
1837 if ($showfeedback) {
1838 echo $OUTPUT->notification("Error moving courses");
1840 return false;
1842 if ($showfeedback) {
1843 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1847 // Move or delete cohorts in this context.
1848 cohort_delete_category($this);
1850 // Now delete anything that may depend on course category context.
1851 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1852 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1853 if ($showfeedback) {
1854 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1856 return false;
1859 // Finally delete the category and it's context.
1860 $DB->delete_records('course_categories', array('id' => $this->id));
1861 $context->delete();
1863 // Trigger a course category deleted event.
1864 /* @var \core\event\course_category_deleted $event */
1865 $event = \core\event\course_category_deleted::create(array(
1866 'objectid' => $this->id,
1867 'context' => $context,
1868 'other' => array('name' => $this->name)
1870 $event->set_coursecat($this);
1871 $event->trigger();
1873 cache_helper::purge_by_event('changesincoursecat');
1875 if ($showfeedback) {
1876 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1879 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1880 if ($this->id == $CFG->defaultrequestcategory) {
1881 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1883 return true;
1887 * Checks if user can move current category to the new parent
1889 * This checks if new parent category exists, user has manage cap there
1890 * and new parent is not a child of this category
1892 * @param int|stdClass|coursecat $newparentcat
1893 * @return bool
1895 public function can_change_parent($newparentcat) {
1896 if (!has_capability('moodle/category:manage', $this->get_context())) {
1897 return false;
1899 if (is_object($newparentcat)) {
1900 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1901 } else {
1902 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1904 if (!$newparentcat) {
1905 return false;
1907 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1908 // Can not move to itself or it's own child.
1909 return false;
1911 if ($newparentcat->id) {
1912 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
1913 } else {
1914 return has_capability('moodle/category:manage', context_system::instance());
1919 * Moves the category under another parent category. All associated contexts are moved as well
1921 * This is protected function, use change_parent() or update() from outside of this class
1923 * @see coursecat::change_parent()
1924 * @see coursecat::update()
1926 * @param coursecat $newparentcat
1927 * @throws moodle_exception
1929 protected function change_parent_raw(coursecat $newparentcat) {
1930 global $DB;
1932 $context = $this->get_context();
1934 $hidecat = false;
1935 if (empty($newparentcat->id)) {
1936 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1937 $newparent = context_system::instance();
1938 } else {
1939 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1940 // Can not move to itself or it's own child.
1941 throw new moodle_exception('cannotmovecategory');
1943 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
1944 $newparent = context_coursecat::instance($newparentcat->id);
1946 if (!$newparentcat->visible and $this->visible) {
1947 // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children
1948 // will be restored properly.
1949 $hidecat = true;
1952 $this->parent = $newparentcat->id;
1954 $context->update_moved($newparent);
1956 // Now make it last in new category.
1957 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
1959 if ($hidecat) {
1960 fix_course_sortorder();
1961 $this->restore();
1962 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must
1963 // become visible again.
1964 $this->hide_raw(1);
1969 * Efficiently moves a category - NOTE that this can have
1970 * a huge impact access-control-wise...
1972 * Note that this function does not check capabilities.
1974 * Example of usage:
1975 * $coursecat = coursecat::get($categoryid);
1976 * if ($coursecat->can_change_parent($newparentcatid)) {
1977 * $coursecat->change_parent($newparentcatid);
1980 * This function does not update field course_categories.timemodified
1981 * If you want to update timemodified, use
1982 * $coursecat->update(array('parent' => $newparentcat));
1984 * @param int|stdClass|coursecat $newparentcat
1986 public function change_parent($newparentcat) {
1987 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1988 if (is_object($newparentcat)) {
1989 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
1990 } else {
1991 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
1993 if ($newparentcat->id != $this->parent) {
1994 $this->change_parent_raw($newparentcat);
1995 fix_course_sortorder();
1996 cache_helper::purge_by_event('changesincoursecat');
1997 $this->restore();
1999 $event = \core\event\course_category_updated::create(array(
2000 'objectid' => $this->id,
2001 'context' => $this->get_context()
2003 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $this->id, $this->id));
2004 $event->trigger();
2009 * Hide course category and child course and subcategories
2011 * If this category has changed the parent and is moved under hidden
2012 * category we will want to store it's current visibility state in
2013 * the field 'visibleold'. If admin clicked 'hide' for this particular
2014 * category, the field 'visibleold' should become 0.
2016 * All subcategories and courses will have their current visibility in the field visibleold
2018 * This is protected function, use hide() or update() from outside of this class
2020 * @see coursecat::hide()
2021 * @see coursecat::update()
2023 * @param int $visibleold value to set in field $visibleold for this category
2024 * @return bool whether changes have been made and caches need to be purged afterwards
2026 protected function hide_raw($visibleold = 0) {
2027 global $DB;
2028 $changes = false;
2030 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing.
2031 if ($this->id && $this->__get('visibleold') != $visibleold) {
2032 $this->visibleold = $visibleold;
2033 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
2034 $changes = true;
2036 if (!$this->visible || !$this->id) {
2037 // Already hidden or can not be hidden.
2038 return $changes;
2041 $this->visible = 0;
2042 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
2043 // Store visible flag so that we can return to it if we immediately unhide.
2044 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id));
2045 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
2046 // Get all child categories and hide too.
2047 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
2048 foreach ($subcats as $cat) {
2049 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
2050 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
2051 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
2052 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
2055 return true;
2059 * Hide course category and child course and subcategories
2061 * Note that there is no capability check inside this function
2063 * This function does not update field course_categories.timemodified
2064 * If you want to update timemodified, use
2065 * $coursecat->update(array('visible' => 0));
2067 public function hide() {
2068 if ($this->hide_raw(0)) {
2069 cache_helper::purge_by_event('changesincoursecat');
2071 $event = \core\event\course_category_updated::create(array(
2072 'objectid' => $this->id,
2073 'context' => $this->get_context()
2075 $event->set_legacy_logdata(array(SITEID, 'category', 'hide', 'editcategory.php?id=' . $this->id, $this->id));
2076 $event->trigger();
2081 * Show course category and restores visibility for child course and subcategories
2083 * Note that there is no capability check inside this function
2085 * This is protected function, use show() or update() from outside of this class
2087 * @see coursecat::show()
2088 * @see coursecat::update()
2090 * @return bool whether changes have been made and caches need to be purged afterwards
2092 protected function show_raw() {
2093 global $DB;
2095 if ($this->visible) {
2096 // Already visible.
2097 return false;
2100 $this->visible = 1;
2101 $this->visibleold = 1;
2102 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
2103 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
2104 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
2105 // Get all child categories and unhide too.
2106 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
2107 foreach ($subcats as $cat) {
2108 if ($cat->visibleold) {
2109 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
2111 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
2114 return true;
2118 * Show course category and restores visibility for child course and subcategories
2120 * Note that there is no capability check inside this function
2122 * This function does not update field course_categories.timemodified
2123 * If you want to update timemodified, use
2124 * $coursecat->update(array('visible' => 1));
2126 public function show() {
2127 if ($this->show_raw()) {
2128 cache_helper::purge_by_event('changesincoursecat');
2130 $event = \core\event\course_category_updated::create(array(
2131 'objectid' => $this->id,
2132 'context' => $this->get_context()
2134 $event->set_legacy_logdata(array(SITEID, 'category', 'show', 'editcategory.php?id=' . $this->id, $this->id));
2135 $event->trigger();
2140 * Returns name of the category formatted as a string
2142 * @param array $options formatting options other than context
2143 * @return string
2145 public function get_formatted_name($options = array()) {
2146 if ($this->id) {
2147 $context = $this->get_context();
2148 return format_string($this->name, true, array('context' => $context) + $options);
2149 } else {
2150 return get_string('top');
2155 * Returns ids of all parents of the category. Last element in the return array is the direct parent
2157 * For example, if you have a tree of categories like:
2158 * Miscellaneous (id = 1)
2159 * Subcategory (id = 2)
2160 * Sub-subcategory (id = 4)
2161 * Other category (id = 3)
2163 * coursecat::get(1)->get_parents() == array()
2164 * coursecat::get(2)->get_parents() == array(1)
2165 * coursecat::get(4)->get_parents() == array(1, 2);
2167 * Note that this method does not check if all parents are accessible by current user
2169 * @return array of category ids
2171 public function get_parents() {
2172 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
2173 array_pop($parents);
2174 return $parents;
2178 * This function returns a nice list representing category tree
2179 * for display or to use in a form <select> element
2181 * List is cached for 10 minutes
2183 * For example, if you have a tree of categories like:
2184 * Miscellaneous (id = 1)
2185 * Subcategory (id = 2)
2186 * Sub-subcategory (id = 4)
2187 * Other category (id = 3)
2188 * Then after calling this function you will have
2189 * array(1 => 'Miscellaneous',
2190 * 2 => 'Miscellaneous / Subcategory',
2191 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2192 * 3 => 'Other category');
2194 * If you specify $requiredcapability, then only categories where the current
2195 * user has that capability will be added to $list.
2196 * If you only have $requiredcapability in a child category, not the parent,
2197 * then the child catgegory will still be included.
2199 * If you specify the option $excludeid, then that category, and all its children,
2200 * are omitted from the tree. This is useful when you are doing something like
2201 * moving categories, where you do not want to allow people to move a category
2202 * to be the child of itself.
2204 * See also {@link make_categories_options()}
2206 * @param string/array $requiredcapability if given, only categories where the current
2207 * user has this capability will be returned. Can also be an array of capabilities,
2208 * in which case they are all required.
2209 * @param integer $excludeid Exclude this category and its children from the lists built.
2210 * @param string $separator string to use as a separator between parent and child category. Default ' / '
2211 * @return array of strings
2213 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
2214 global $DB;
2215 $coursecatcache = cache::make('core', 'coursecat');
2217 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids
2218 // with requried cap ($thislist).
2219 $currentlang = current_language();
2220 $basecachekey = $currentlang . '_catlist';
2221 $baselist = $coursecatcache->get($basecachekey);
2222 $thislist = false;
2223 $thiscachekey = null;
2224 if (!empty($requiredcapability)) {
2225 $requiredcapability = (array)$requiredcapability;
2226 $thiscachekey = 'catlist:'. serialize($requiredcapability);
2227 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
2228 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
2230 } else if ($baselist !== false) {
2231 $thislist = array_keys($baselist);
2234 if ($baselist === false) {
2235 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
2236 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2237 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
2238 FROM {course_categories} cc
2239 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
2240 ORDER BY cc.sortorder";
2241 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2242 $baselist = array();
2243 $thislist = array();
2244 foreach ($rs as $record) {
2245 // If the category's parent is not visible to the user, it is not visible as well.
2246 if (!$record->parent || isset($baselist[$record->parent])) {
2247 context_helper::preload_from_record($record);
2248 $context = context_coursecat::instance($record->id);
2249 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
2250 // No cap to view category, added to neither $baselist nor $thislist.
2251 continue;
2253 $baselist[$record->id] = array(
2254 'name' => format_string($record->name, true, array('context' => $context)),
2255 'path' => $record->path
2257 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
2258 // No required capability, added to $baselist but not to $thislist.
2259 continue;
2261 $thislist[] = $record->id;
2264 $rs->close();
2265 $coursecatcache->set($basecachekey, $baselist);
2266 if (!empty($requiredcapability)) {
2267 $coursecatcache->set($thiscachekey, join(',', $thislist));
2269 } else if ($thislist === false) {
2270 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
2271 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2272 $sql = "SELECT ctx.instanceid AS id, $ctxselect
2273 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
2274 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2275 $thislist = array();
2276 foreach (array_keys($baselist) as $id) {
2277 context_helper::preload_from_record($contexts[$id]);
2278 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
2279 $thislist[] = $id;
2282 $coursecatcache->set($thiscachekey, join(',', $thislist));
2285 // Now build the array of strings to return, mind $separator and $excludeid.
2286 $names = array();
2287 foreach ($thislist as $id) {
2288 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
2289 if (!$excludeid || !in_array($excludeid, $path)) {
2290 $namechunks = array();
2291 foreach ($path as $parentid) {
2292 $namechunks[] = $baselist[$parentid]['name'];
2294 $names[$id] = join($separator, $namechunks);
2297 return $names;
2301 * Prepares the object for caching. Works like the __sleep method.
2303 * implementing method from interface cacheable_object
2305 * @return array ready to be cached
2307 public function prepare_to_cache() {
2308 $a = array();
2309 foreach (self::$coursecatfields as $property => $cachedirectives) {
2310 if ($cachedirectives !== null) {
2311 list($shortname, $defaultvalue) = $cachedirectives;
2312 if ($this->$property !== $defaultvalue) {
2313 $a[$shortname] = $this->$property;
2317 $context = $this->get_context();
2318 $a['xi'] = $context->id;
2319 $a['xp'] = $context->path;
2320 return $a;
2324 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2326 * implementing method from interface cacheable_object
2328 * @param array $a
2329 * @return coursecat
2331 public static function wake_from_cache($a) {
2332 $record = new stdClass;
2333 foreach (self::$coursecatfields as $property => $cachedirectives) {
2334 if ($cachedirectives !== null) {
2335 list($shortname, $defaultvalue) = $cachedirectives;
2336 if (array_key_exists($shortname, $a)) {
2337 $record->$property = $a[$shortname];
2338 } else {
2339 $record->$property = $defaultvalue;
2343 $record->ctxid = $a['xi'];
2344 $record->ctxpath = $a['xp'];
2345 $record->ctxdepth = $record->depth + 1;
2346 $record->ctxlevel = CONTEXT_COURSECAT;
2347 $record->ctxinstance = $record->id;
2348 return new coursecat($record, true);
2352 * Returns true if the user is able to create a top level category.
2353 * @return bool
2355 public static function can_create_top_level_category() {
2356 return has_capability('moodle/category:manage', context_system::instance());
2360 * Returns the category context.
2361 * @return context_coursecat
2363 public function get_context() {
2364 if ($this->id === 0) {
2365 // This is the special top level category object.
2366 return context_system::instance();
2367 } else {
2368 return context_coursecat::instance($this->id);
2373 * Returns true if the user is able to manage this category.
2374 * @return bool
2376 public function has_manage_capability() {
2377 if ($this->hasmanagecapability === null) {
2378 $this->hasmanagecapability = has_capability('moodle/category:manage', $this->get_context());
2380 return $this->hasmanagecapability;
2384 * Returns true if the user has the manage capability on the parent category.
2385 * @return bool
2387 public function parent_has_manage_capability() {
2388 return has_capability('moodle/category:manage', get_category_or_system_context($this->parent));
2392 * Returns true if the current user can create subcategories of this category.
2393 * @return bool
2395 public function can_create_subcategory() {
2396 return $this->has_manage_capability();
2400 * Returns true if the user can resort this categories sub categories and courses.
2401 * Must have manage capability and be able to see all subcategories.
2402 * @return bool
2404 public function can_resort_subcategories() {
2405 return $this->has_manage_capability() && !$this->get_not_visible_children_ids();
2409 * Returns true if the user can resort the courses within this category.
2410 * Must have manage capability and be able to see all courses.
2411 * @return bool
2413 public function can_resort_courses() {
2414 return $this->has_manage_capability() && $this->coursecount == $this->get_courses_count();
2418 * Returns true of the user can change the sortorder of this category (resort in the parent category)
2419 * @return bool
2421 public function can_change_sortorder() {
2422 return $this->id && $this->get_parent_coursecat()->can_resort_subcategories();
2426 * Returns true if the current user can create a course within this category.
2427 * @return bool
2429 public function can_create_course() {
2430 return has_capability('moodle/course:create', $this->get_context());
2434 * Returns true if the current user can edit this categories settings.
2435 * @return bool
2437 public function can_edit() {
2438 return $this->has_manage_capability();
2442 * Returns true if the current user can review role assignments for this category.
2443 * @return bool
2445 public function can_review_roles() {
2446 return has_capability('moodle/role:assign', $this->get_context());
2450 * Returns true if the current user can review permissions for this category.
2451 * @return bool
2453 public function can_review_permissions() {
2454 return has_any_capability(array(
2455 'moodle/role:assign',
2456 'moodle/role:safeoverride',
2457 'moodle/role:override',
2458 'moodle/role:assign'
2459 ), $this->get_context());
2463 * Returns true if the current user can review cohorts for this category.
2464 * @return bool
2466 public function can_review_cohorts() {
2467 return has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->get_context());
2471 * Returns true if the current user can review filter settings for this category.
2472 * @return bool
2474 public function can_review_filters() {
2475 return has_capability('moodle/filter:manage', $this->get_context()) &&
2476 count(filter_get_available_in_context($this->get_context()))>0;
2480 * Returns true if the current user is able to change the visbility of this category.
2481 * @return bool
2483 public function can_change_visibility() {
2484 return $this->parent_has_manage_capability();
2488 * Returns true if the user can move courses out of this category.
2489 * @return bool
2491 public function can_move_courses_out_of() {
2492 return $this->has_manage_capability();
2496 * Returns true if the user can move courses into this category.
2497 * @return bool
2499 public function can_move_courses_into() {
2500 return $this->has_manage_capability();
2504 * Returns true if the user is able to restore a course into this category as a new course.
2505 * @return bool
2507 public function can_restore_courses_into() {
2508 return has_capability('moodle/restore:restorecourse', $this->get_context());
2512 * Resorts the sub categories of this category by the given field.
2514 * @param string $field One of name, idnumber or descending values of each (appended desc)
2515 * @param bool $cleanup If true cleanup will be done, if false you will need to do it manually later.
2516 * @return bool True on success.
2517 * @throws coding_exception
2519 public function resort_subcategories($field, $cleanup = true) {
2520 global $DB;
2521 $desc = false;
2522 if (substr($field, -4) === "desc") {
2523 $desc = true;
2524 $field = substr($field, 0, -4); // Remove "desc" from field name.
2526 if ($field !== 'name' && $field !== 'idnumber') {
2527 throw new coding_exception('Invalid field requested');
2529 $children = $this->get_children();
2530 core_collator::asort_objects_by_property($children, $field, core_collator::SORT_NATURAL);
2531 if (!empty($desc)) {
2532 $children = array_reverse($children);
2534 $i = 1;
2535 foreach ($children as $cat) {
2536 $i++;
2537 $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id));
2538 $i += $cat->coursecount;
2540 if ($cleanup) {
2541 self::resort_categories_cleanup();
2543 return true;
2547 * Cleans things up after categories have been resorted.
2548 * @param bool $includecourses If set to true we know courses have been resorted as well.
2550 public static function resort_categories_cleanup($includecourses = false) {
2551 // This should not be needed but we do it just to be safe.
2552 fix_course_sortorder();
2553 cache_helper::purge_by_event('changesincoursecat');
2554 if ($includecourses) {
2555 cache_helper::purge_by_event('changesincourse');
2560 * Resort the courses within this category by the given field.
2562 * @param string $field One of fullname, shortname, idnumber or descending values of each (appended desc)
2563 * @param bool $cleanup
2564 * @return bool True for success.
2565 * @throws coding_exception
2567 public function resort_courses($field, $cleanup = true) {
2568 global $DB;
2569 $desc = false;
2570 if (substr($field, -4) === "desc") {
2571 $desc = true;
2572 $field = substr($field, 0, -4); // Remove "desc" from field name.
2574 if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber' && $field !== 'timecreated') {
2575 // This is ultra important as we use $field in an SQL statement below this.
2576 throw new coding_exception('Invalid field requested');
2578 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
2579 $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields
2580 FROM {course} c
2581 LEFT JOIN {context} ctx ON ctx.instanceid = c.id
2582 WHERE ctx.contextlevel = :ctxlevel AND
2583 c.category = :categoryid";
2584 $params = array(
2585 'ctxlevel' => CONTEXT_COURSE,
2586 'categoryid' => $this->id
2588 $courses = $DB->get_records_sql($sql, $params);
2589 if (count($courses) > 0) {
2590 foreach ($courses as $courseid => $course) {
2591 context_helper::preload_from_record($course);
2592 if ($field === 'idnumber') {
2593 $course->sortby = $course->idnumber;
2594 } else {
2595 // It'll require formatting.
2596 $options = array(
2597 'context' => context_course::instance($course->id)
2599 // We format the string first so that it appears as the user would see it.
2600 // This ensures the sorting makes sense to them. However it won't necessarily make
2601 // sense to everyone if things like multilang filters are enabled.
2602 // We then strip any tags as we don't want things such as image tags skewing the
2603 // sort results.
2604 $course->sortby = strip_tags(format_string($course->$field, true, $options));
2606 // We set it back here rather than using references as there is a bug with using
2607 // references in a foreach before passing as an arg by reference.
2608 $courses[$courseid] = $course;
2610 // Sort the courses.
2611 core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL);
2612 if (!empty($desc)) {
2613 $courses = array_reverse($courses);
2615 $i = 1;
2616 foreach ($courses as $course) {
2617 $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id));
2618 $i++;
2620 if ($cleanup) {
2621 // This should not be needed but we do it just to be safe.
2622 fix_course_sortorder();
2623 cache_helper::purge_by_event('changesincourse');
2626 return true;
2630 * Changes the sort order of this categories parent shifting this category up or down one.
2632 * @global \moodle_database $DB
2633 * @param bool $up If set to true the category is shifted up one spot, else its moved down.
2634 * @return bool True on success, false otherwise.
2636 public function change_sortorder_by_one($up) {
2637 global $DB;
2638 $params = array($this->sortorder, $this->parent);
2639 if ($up) {
2640 $select = 'sortorder < ? AND parent = ?';
2641 $sort = 'sortorder DESC';
2642 } else {
2643 $select = 'sortorder > ? AND parent = ?';
2644 $sort = 'sortorder ASC';
2646 fix_course_sortorder();
2647 $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1);
2648 $swapcategory = reset($swapcategory);
2649 if ($swapcategory) {
2650 $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id));
2651 $DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id));
2652 $this->sortorder = $swapcategory->sortorder;
2654 $event = \core\event\course_category_updated::create(array(
2655 'objectid' => $this->id,
2656 'context' => $this->get_context()
2658 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'management.php?categoryid=' . $this->id,
2659 $this->id));
2660 $event->trigger();
2662 // Finally reorder courses.
2663 fix_course_sortorder();
2664 cache_helper::purge_by_event('changesincoursecat');
2665 return true;
2667 return false;
2671 * Returns the parent coursecat object for this category.
2673 * @return coursecat
2675 public function get_parent_coursecat() {
2676 return self::get($this->parent);
2681 * Returns true if the user is able to request a new course be created.
2682 * @return bool
2684 public function can_request_course() {
2685 global $CFG;
2686 if (empty($CFG->enablecourserequests) || $this->id != $CFG->defaultrequestcategory) {
2687 return false;
2689 return !$this->can_create_course() && has_capability('moodle/course:request', $this->get_context());
2693 * Returns true if the user can approve course requests.
2694 * @return bool
2696 public static function can_approve_course_requests() {
2697 global $CFG, $DB;
2698 if (empty($CFG->enablecourserequests)) {
2699 return false;
2701 $context = context_system::instance();
2702 if (!has_capability('moodle/site:approvecourse', $context)) {
2703 return false;
2705 if (!$DB->record_exists('course_request', array())) {
2706 return false;
2708 return true;
2713 * Class to store information about one course in a list of courses
2715 * Not all information may be retrieved when object is created but
2716 * it will be retrieved on demand when appropriate property or method is
2717 * called.
2719 * Instances of this class are usually returned by functions
2720 * {@link coursecat::search_courses()}
2721 * and
2722 * {@link coursecat::get_courses()}
2724 * @property-read int $id
2725 * @property-read int $category Category ID
2726 * @property-read int $sortorder
2727 * @property-read string $fullname
2728 * @property-read string $shortname
2729 * @property-read string $idnumber
2730 * @property-read string $summary Course summary. Field is present if coursecat::get_courses()
2731 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2732 * @property-read int $summaryformat Summary format. Field is present if coursecat::get_courses()
2733 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2734 * @property-read string $format Course format. Retrieved from DB on first request
2735 * @property-read int $showgrades Retrieved from DB on first request
2736 * @property-read int $newsitems Retrieved from DB on first request
2737 * @property-read int $startdate
2738 * @property-read int $marker Retrieved from DB on first request
2739 * @property-read int $maxbytes Retrieved from DB on first request
2740 * @property-read int $legacyfiles Retrieved from DB on first request
2741 * @property-read int $showreports Retrieved from DB on first request
2742 * @property-read int $visible
2743 * @property-read int $visibleold Retrieved from DB on first request
2744 * @property-read int $groupmode Retrieved from DB on first request
2745 * @property-read int $groupmodeforce Retrieved from DB on first request
2746 * @property-read int $defaultgroupingid Retrieved from DB on first request
2747 * @property-read string $lang Retrieved from DB on first request
2748 * @property-read string $theme Retrieved from DB on first request
2749 * @property-read int $timecreated Retrieved from DB on first request
2750 * @property-read int $timemodified Retrieved from DB on first request
2751 * @property-read int $requested Retrieved from DB on first request
2752 * @property-read int $enablecompletion Retrieved from DB on first request
2753 * @property-read int $completionnotify Retrieved from DB on first request
2754 * @property-read int $cacherev
2756 * @package core
2757 * @subpackage course
2758 * @copyright 2013 Marina Glancy
2759 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2761 class course_in_list implements IteratorAggregate {
2763 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2764 protected $record;
2766 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2767 protected $coursecontacts;
2769 /** @var bool true if the current user can access the course, false otherwise. */
2770 protected $canaccess = null;
2773 * Creates an instance of the class from record
2775 * @param stdClass $record except fields from course table it may contain
2776 * field hassummary indicating that summary field is not empty.
2777 * Also it is recommended to have context fields here ready for
2778 * context preloading
2780 public function __construct(stdClass $record) {
2781 context_helper::preload_from_record($record);
2782 $this->record = new stdClass();
2783 foreach ($record as $key => $value) {
2784 $this->record->$key = $value;
2789 * Indicates if the course has non-empty summary field
2791 * @return bool
2793 public function has_summary() {
2794 if (isset($this->record->hassummary)) {
2795 return !empty($this->record->hassummary);
2797 if (!isset($this->record->summary)) {
2798 // We need to retrieve summary.
2799 $this->__get('summary');
2801 return !empty($this->record->summary);
2805 * Indicates if the course have course contacts to display
2807 * @return bool
2809 public function has_course_contacts() {
2810 if (!isset($this->record->managers)) {
2811 $courses = array($this->id => &$this->record);
2812 coursecat::preload_course_contacts($courses);
2814 return !empty($this->record->managers);
2818 * Returns list of course contacts (usually teachers) to display in course link
2820 * Roles to display are set up in $CFG->coursecontact
2822 * The result is the list of users where user id is the key and the value
2823 * is an array with elements:
2824 * - 'user' - object containing basic user information
2825 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2826 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2827 * - 'username' => fullname($user, $canviewfullnames)
2829 * @return array
2831 public function get_course_contacts() {
2832 global $CFG;
2833 if (empty($CFG->coursecontact)) {
2834 // No roles are configured to be displayed as course contacts.
2835 return array();
2837 if ($this->coursecontacts === null) {
2838 $this->coursecontacts = array();
2839 $context = context_course::instance($this->id);
2841 if (!isset($this->record->managers)) {
2842 // Preload course contacts from DB.
2843 $courses = array($this->id => &$this->record);
2844 coursecat::preload_course_contacts($courses);
2847 // Build return array with full roles names (for this course context) and users names.
2848 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2849 foreach ($this->record->managers as $ruser) {
2850 if (isset($this->coursecontacts[$ruser->id])) {
2851 // Only display a user once with the highest sortorder role.
2852 continue;
2854 $user = new stdClass();
2855 $user = username_load_fields_from_object($user, $ruser, null, array('id', 'username'));
2856 $role = new stdClass();
2857 $role->id = $ruser->roleid;
2858 $role->name = $ruser->rolename;
2859 $role->shortname = $ruser->roleshortname;
2860 $role->coursealias = $ruser->rolecoursealias;
2862 $this->coursecontacts[$user->id] = array(
2863 'user' => $user,
2864 'role' => $role,
2865 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2866 'username' => fullname($user, $canviewfullnames)
2870 return $this->coursecontacts;
2874 * Checks if course has any associated overview files
2876 * @return bool
2878 public function has_course_overviewfiles() {
2879 global $CFG;
2880 if (empty($CFG->courseoverviewfileslimit)) {
2881 return false;
2883 $fs = get_file_storage();
2884 $context = context_course::instance($this->id);
2885 return !$fs->is_area_empty($context->id, 'course', 'overviewfiles');
2889 * Returns all course overview files
2891 * @return array array of stored_file objects
2893 public function get_course_overviewfiles() {
2894 global $CFG;
2895 if (empty($CFG->courseoverviewfileslimit)) {
2896 return array();
2898 require_once($CFG->libdir. '/filestorage/file_storage.php');
2899 require_once($CFG->dirroot. '/course/lib.php');
2900 $fs = get_file_storage();
2901 $context = context_course::instance($this->id);
2902 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2903 if (count($files)) {
2904 $overviewfilesoptions = course_overviewfiles_options($this->id);
2905 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2906 if ($acceptedtypes !== '*') {
2907 // Filter only files with allowed extensions.
2908 require_once($CFG->libdir. '/filelib.php');
2909 foreach ($files as $key => $file) {
2910 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2911 unset($files[$key]);
2915 if (count($files) > $CFG->courseoverviewfileslimit) {
2916 // Return no more than $CFG->courseoverviewfileslimit files.
2917 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
2920 return $files;
2924 * Magic method to check if property is set
2926 * @param string $name
2927 * @return bool
2929 public function __isset($name) {
2930 return isset($this->record->$name);
2934 * Magic method to get a course property
2936 * Returns any field from table course (retrieves it from DB if it was not retrieved before)
2938 * @param string $name
2939 * @return mixed
2941 public function __get($name) {
2942 global $DB;
2943 if (property_exists($this->record, $name)) {
2944 return $this->record->$name;
2945 } else if ($name === 'summary' || $name === 'summaryformat') {
2946 // Retrieve fields summary and summaryformat together because they are most likely to be used together.
2947 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
2948 $this->record->summary = $record->summary;
2949 $this->record->summaryformat = $record->summaryformat;
2950 return $this->record->$name;
2951 } else if (array_key_exists($name, $DB->get_columns('course'))) {
2952 // Another field from table 'course' that was not retrieved.
2953 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
2954 return $this->record->$name;
2956 debugging('Invalid course property accessed! '.$name);
2957 return null;
2961 * All properties are read only, sorry.
2963 * @param string $name
2965 public function __unset($name) {
2966 debugging('Can not unset '.get_class($this).' instance properties!');
2970 * Magic setter method, we do not want anybody to modify properties from the outside
2972 * @param string $name
2973 * @param mixed $value
2975 public function __set($name, $value) {
2976 debugging('Can not change '.get_class($this).' instance properties!');
2980 * Create an iterator because magic vars can't be seen by 'foreach'.
2981 * Exclude context fields
2983 * Implementing method from interface IteratorAggregate
2985 * @return ArrayIterator
2987 public function getIterator() {
2988 $ret = array('id' => $this->record->id);
2989 foreach ($this->record as $property => $value) {
2990 $ret[$property] = $value;
2992 return new ArrayIterator($ret);
2996 * Returns the name of this course as it should be displayed within a list.
2997 * @return string
2999 public function get_formatted_name() {
3000 return format_string(get_course_display_name_for_list($this), true, $this->get_context());
3004 * Returns the formatted fullname for this course.
3005 * @return string
3007 public function get_formatted_fullname() {
3008 return format_string($this->__get('fullname'), true, $this->get_context());
3012 * Returns the formatted shortname for this course.
3013 * @return string
3015 public function get_formatted_shortname() {
3016 return format_string($this->__get('shortname'), true, $this->get_context());
3020 * Returns true if the current user can access this course.
3021 * @return bool
3023 public function can_access() {
3024 if ($this->canaccess === null) {
3025 $this->canaccess = can_access_course($this->record);
3027 return $this->canaccess;
3031 * Returns true if the user can edit this courses settings.
3033 * Note: this function does not check that the current user can access the course.
3034 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3036 * @return bool
3038 public function can_edit() {
3039 return has_capability('moodle/course:update', $this->get_context());
3043 * Returns true if the user can change the visibility of this course.
3045 * Note: this function does not check that the current user can access the course.
3046 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3048 * @return bool
3050 public function can_change_visibility() {
3051 // You must be able to both hide a course and view the hidden course.
3052 return has_all_capabilities(array('moodle/course:visibility', 'moodle/course:viewhiddencourses'), $this->get_context());
3056 * Returns the context for this course.
3057 * @return context_course
3059 public function get_context() {
3060 return context_course::instance($this->__get('id'));
3064 * Returns true if this course is visible to the current user.
3065 * @return bool
3067 public function is_uservisible() {
3068 return $this->visible || has_capability('moodle/course:viewhiddencourses', $this->get_context());
3072 * Returns true if the current user can review enrolments for this course.
3074 * Note: this function does not check that the current user can access the course.
3075 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3077 * @return bool
3079 public function can_review_enrolments() {
3080 return has_capability('moodle/course:enrolreview', $this->get_context());
3084 * Returns true if the current user can delete this course.
3086 * Note: this function does not check that the current user can access the course.
3087 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3089 * @return bool
3091 public function can_delete() {
3092 return can_delete_course($this->id);
3096 * Returns true if the current user can backup this course.
3098 * Note: this function does not check that the current user can access the course.
3099 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3101 * @return bool
3103 public function can_backup() {
3104 return has_capability('moodle/backup:backupcourse', $this->get_context());
3108 * Returns true if the current user can restore this course.
3110 * Note: this function does not check that the current user can access the course.
3111 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3113 * @return bool
3115 public function can_restore() {
3116 return has_capability('moodle/restore:restorecourse', $this->get_context());
3121 * An array of records that is sortable by many fields.
3123 * For more info on the ArrayObject class have a look at php.net.
3125 * @package core
3126 * @subpackage course
3127 * @copyright 2013 Sam Hemelryk
3128 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3130 class coursecat_sortable_records extends ArrayObject {
3133 * An array of sortable fields.
3134 * Gets set temporarily when sort is called.
3135 * @var array
3137 protected $sortfields = array();
3140 * Sorts this array using the given fields.
3142 * @param array $records
3143 * @param array $fields
3144 * @return array
3146 public static function sort(array $records, array $fields) {
3147 $records = new coursecat_sortable_records($records);
3148 $records->sortfields = $fields;
3149 $records->uasort(array($records, 'sort_by_many_fields'));
3150 return $records->getArrayCopy();
3154 * Sorts the two records based upon many fields.
3156 * This method should not be called itself, please call $sort instead.
3157 * It has been marked as access private as such.
3159 * @access private
3160 * @param stdClass $a
3161 * @param stdClass $b
3162 * @return int
3164 public function sort_by_many_fields($a, $b) {
3165 foreach ($this->sortfields as $field => $mult) {
3166 // Nulls first.
3167 if (is_null($a->$field) && !is_null($b->$field)) {
3168 return -$mult;
3170 if (is_null($b->$field) && !is_null($a->$field)) {
3171 return $mult;
3174 if (is_string($a->$field) || is_string($b->$field)) {
3175 // String fields.
3176 if ($cmp = strcoll($a->$field, $b->$field)) {
3177 return $mult * $cmp;
3179 } else {
3180 // Int fields.
3181 if ($a->$field > $b->$field) {
3182 return $mult;
3184 if ($a->$field < $b->$field) {
3185 return -$mult;
3189 return 0;