Merge branch 'wip-MDL-51834-master' of https://github.com/kwiliarty/moodle
[moodle.git] / lib / coursecatlib.php
blobdf83db667171b743befd8ae5fd2f1f727f41c034
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 * @return course_in_list[]
1281 public static function search_courses($search, $options = array()) {
1282 global $DB;
1283 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1284 $limit = !empty($options['limit']) ? $options['limit'] : null;
1285 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1287 $coursecatcache = cache::make('core', 'coursecat');
1288 $cachekey = 's-'. serialize($search + array('sort' => $sortfields));
1289 $cntcachekey = 'scnt-'. serialize($search);
1291 $ids = $coursecatcache->get($cachekey);
1292 if ($ids !== false) {
1293 // We already cached last search result.
1294 $ids = array_slice($ids, $offset, $limit);
1295 $courses = array();
1296 if (!empty($ids)) {
1297 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1298 $records = self::get_course_records("c.id ". $sql, $params, $options);
1299 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1300 if (!empty($options['coursecontacts'])) {
1301 self::preload_course_contacts($records);
1303 // If option 'idonly' is specified no further action is needed, just return list of ids.
1304 if (!empty($options['idonly'])) {
1305 return array_keys($records);
1307 // Prepare the list of course_in_list objects.
1308 foreach ($ids as $id) {
1309 $courses[$id] = new course_in_list($records[$id]);
1312 return $courses;
1315 $preloadcoursecontacts = !empty($options['coursecontacts']);
1316 unset($options['coursecontacts']);
1318 if (!empty($search['search'])) {
1319 // Search courses that have specified words in their names/summaries.
1320 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1321 $searchterms = array_filter($searchterms, create_function('$v', 'return strlen($v) > 1;'));
1322 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount);
1323 self::sort_records($courselist, $sortfields);
1324 $coursecatcache->set($cachekey, array_keys($courselist));
1325 $coursecatcache->set($cntcachekey, $totalcount);
1326 $records = array_slice($courselist, $offset, $limit, true);
1327 } else {
1328 if (!empty($search['blocklist'])) {
1329 // Search courses that have block with specified id.
1330 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1331 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1332 WHERE bi.blockname = :blockname)';
1333 $params = array('blockname' => $blockname);
1334 } else if (!empty($search['modulelist'])) {
1335 // Search courses that have module with specified name.
1336 $where = "c.id IN (SELECT DISTINCT module.course ".
1337 "FROM {".$search['modulelist']."} module)";
1338 $params = array();
1339 } else if (!empty($search['tagid'])) {
1340 // Search courses that are tagged with the specified tag.
1341 $where = "c.id IN (SELECT t.itemid ".
1342 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype)";
1343 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course');
1344 } else {
1345 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1346 return array();
1348 $courselist = self::get_course_records($where, $params, $options, true);
1349 self::sort_records($courselist, $sortfields);
1350 $coursecatcache->set($cachekey, array_keys($courselist));
1351 $coursecatcache->set($cntcachekey, count($courselist));
1352 $records = array_slice($courselist, $offset, $limit, true);
1355 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1356 if (!empty($preloadcoursecontacts)) {
1357 self::preload_course_contacts($records);
1359 // If option 'idonly' is specified no further action is needed, just return list of ids.
1360 if (!empty($options['idonly'])) {
1361 return array_keys($records);
1363 // Prepare the list of course_in_list objects.
1364 $courses = array();
1365 foreach ($records as $record) {
1366 $courses[$record->id] = new course_in_list($record);
1368 return $courses;
1372 * Returns number of courses in the search results
1374 * It is recommended to call this function after {@link coursecat::search_courses()}
1375 * and not before because only course ids are cached. Otherwise search_courses() may
1376 * perform extra DB queries.
1378 * @param array $search search criteria, see method search_courses() for more details
1379 * @param array $options display options. They do not affect the result but
1380 * the 'sort' property is used in cache key for storing list of course ids
1381 * @return int
1383 public static function search_courses_count($search, $options = array()) {
1384 $coursecatcache = cache::make('core', 'coursecat');
1385 $cntcachekey = 'scnt-'. serialize($search);
1386 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1387 // Cached value not found. Retrieve ALL courses and return their count.
1388 unset($options['offset']);
1389 unset($options['limit']);
1390 unset($options['summary']);
1391 unset($options['coursecontacts']);
1392 $options['idonly'] = true;
1393 $courses = self::search_courses($search, $options);
1394 $cnt = count($courses);
1396 return $cnt;
1400 * Retrieves the list of courses accessible by user
1402 * Not all information is cached, try to avoid calling this method
1403 * twice in the same request.
1405 * The following fields are always retrieved:
1406 * - id, visible, fullname, shortname, idnumber, category, sortorder
1408 * If you plan to use properties/methods course_in_list::$summary and/or
1409 * course_in_list::get_course_contacts()
1410 * you can preload this information using appropriate 'options'. Otherwise
1411 * they will be retrieved from DB on demand and it may end with bigger DB load.
1413 * Note that method course_in_list::has_summary() will not perform additional
1414 * DB queries even if $options['summary'] is not specified
1416 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1417 * to this when somebody edits courses or categories, however it is very
1418 * difficult to keep track of all possible changes that may affect list of courses.
1420 * @param array $options options for retrieving children
1421 * - recursive - return courses from subcategories as well. Use with care,
1422 * this may be a huge list!
1423 * - summary - preloads fields 'summary' and 'summaryformat'
1424 * - coursecontacts - preloads course contacts
1425 * - sort - list of fields to sort. Example
1426 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1427 * will sort by idnumber asc, shortname asc and id desc.
1428 * Default: array('sortorder' => 1)
1429 * Only cached fields may be used for sorting!
1430 * - offset
1431 * - limit - maximum number of children to return, 0 or null for no limit
1432 * - idonly - returns the array or course ids instead of array of objects
1433 * used only in get_courses_count()
1434 * @return course_in_list[]
1436 public function get_courses($options = array()) {
1437 global $DB;
1438 $recursive = !empty($options['recursive']);
1439 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1440 $limit = !empty($options['limit']) ? $options['limit'] : null;
1441 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1443 // Check if this category is hidden.
1444 // Also 0-category never has courses unless this is recursive call.
1445 if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1446 return array();
1449 $coursecatcache = cache::make('core', 'coursecat');
1450 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1451 '-'. serialize($sortfields);
1452 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1454 // Check if we have already cached results.
1455 $ids = $coursecatcache->get($cachekey);
1456 if ($ids !== false) {
1457 // We already cached last search result and it did not expire yet.
1458 $ids = array_slice($ids, $offset, $limit);
1459 $courses = array();
1460 if (!empty($ids)) {
1461 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1462 $records = self::get_course_records("c.id ". $sql, $params, $options);
1463 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1464 if (!empty($options['coursecontacts'])) {
1465 self::preload_course_contacts($records);
1467 // If option 'idonly' is specified no further action is needed, just return list of ids.
1468 if (!empty($options['idonly'])) {
1469 return array_keys($records);
1471 // Prepare the list of course_in_list objects.
1472 foreach ($ids as $id) {
1473 $courses[$id] = new course_in_list($records[$id]);
1476 return $courses;
1479 // Retrieve list of courses in category.
1480 $where = 'c.id <> :siteid';
1481 $params = array('siteid' => SITEID);
1482 if ($recursive) {
1483 if ($this->id) {
1484 $context = context_coursecat::instance($this->id);
1485 $where .= ' AND ctx.path like :path';
1486 $params['path'] = $context->path. '/%';
1488 } else {
1489 $where .= ' AND c.category = :categoryid';
1490 $params['categoryid'] = $this->id;
1492 // Get list of courses without preloaded coursecontacts because we don't need them for every course.
1493 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1495 // Sort and cache list.
1496 self::sort_records($list, $sortfields);
1497 $coursecatcache->set($cachekey, array_keys($list));
1498 $coursecatcache->set($cntcachekey, count($list));
1500 // Apply offset/limit, convert to course_in_list and return.
1501 $courses = array();
1502 if (isset($list)) {
1503 if ($offset || $limit) {
1504 $list = array_slice($list, $offset, $limit, true);
1506 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1507 if (!empty($options['coursecontacts'])) {
1508 self::preload_course_contacts($list);
1510 // If option 'idonly' is specified no further action is needed, just return list of ids.
1511 if (!empty($options['idonly'])) {
1512 return array_keys($list);
1514 // Prepare the list of course_in_list objects.
1515 foreach ($list as $record) {
1516 $courses[$record->id] = new course_in_list($record);
1519 return $courses;
1523 * Returns number of courses visible to the user
1525 * @param array $options similar to get_courses() except some options do not affect
1526 * number of courses (i.e. sort, summary, offset, limit etc.)
1527 * @return int
1529 public function get_courses_count($options = array()) {
1530 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1531 $coursecatcache = cache::make('core', 'coursecat');
1532 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1533 // Cached value not found. Retrieve ALL courses and return their count.
1534 unset($options['offset']);
1535 unset($options['limit']);
1536 unset($options['summary']);
1537 unset($options['coursecontacts']);
1538 $options['idonly'] = true;
1539 $courses = $this->get_courses($options);
1540 $cnt = count($courses);
1542 return $cnt;
1546 * Returns true if the user is able to delete this category.
1548 * Note if this category contains any courses this isn't a full check, it will need to be accompanied by a call to either
1549 * {@link coursecat::can_delete_full()} or {@link coursecat::can_move_content_to()} depending upon what the user wished to do.
1551 * @return boolean
1553 public function can_delete() {
1554 if (!$this->has_manage_capability()) {
1555 return false;
1557 return $this->parent_has_manage_capability();
1561 * Returns true if user can delete current category and all its contents
1563 * To be able to delete course category the user must have permission
1564 * 'moodle/category:manage' in ALL child course categories AND
1565 * be able to delete all courses
1567 * @return bool
1569 public function can_delete_full() {
1570 global $DB;
1571 if (!$this->id) {
1572 // Fool-proof.
1573 return false;
1576 $context = $this->get_context();
1577 if (!$this->is_uservisible() ||
1578 !has_capability('moodle/category:manage', $context)) {
1579 return false;
1582 // Check all child categories (not only direct children).
1583 $sql = context_helper::get_preload_record_columns_sql('ctx');
1584 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1585 ' FROM {context} ctx '.
1586 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1587 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1588 array($context->path. '/%', CONTEXT_COURSECAT));
1589 foreach ($childcategories as $childcat) {
1590 context_helper::preload_from_record($childcat);
1591 $childcontext = context_coursecat::instance($childcat->id);
1592 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1593 !has_capability('moodle/category:manage', $childcontext)) {
1594 return false;
1598 // Check courses.
1599 $sql = context_helper::get_preload_record_columns_sql('ctx');
1600 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1601 $sql. ' FROM {context} ctx '.
1602 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1603 array('pathmask' => $context->path. '/%',
1604 'courselevel' => CONTEXT_COURSE));
1605 foreach ($coursescontexts as $ctxrecord) {
1606 context_helper::preload_from_record($ctxrecord);
1607 if (!can_delete_course($ctxrecord->courseid)) {
1608 return false;
1612 return true;
1616 * Recursively delete category including all subcategories and courses
1618 * Function {@link coursecat::can_delete_full()} MUST be called prior
1619 * to calling this function because there is no capability check
1620 * inside this function
1622 * @param boolean $showfeedback display some notices
1623 * @return array return deleted courses
1624 * @throws moodle_exception
1626 public function delete_full($showfeedback = true) {
1627 global $CFG, $DB;
1629 require_once($CFG->libdir.'/gradelib.php');
1630 require_once($CFG->libdir.'/questionlib.php');
1631 require_once($CFG->dirroot.'/cohort/lib.php');
1633 // Make sure we won't timeout when deleting a lot of courses.
1634 $settimeout = core_php_time_limit::raise();
1636 $deletedcourses = array();
1638 // Get children. Note, we don't want to use cache here because it would be rebuilt too often.
1639 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1640 foreach ($children as $record) {
1641 $coursecat = new coursecat($record);
1642 $deletedcourses += $coursecat->delete_full($showfeedback);
1645 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1646 foreach ($courses as $course) {
1647 if (!delete_course($course, false)) {
1648 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1650 $deletedcourses[] = $course;
1654 // Move or delete cohorts in this context.
1655 cohort_delete_category($this);
1657 // Now delete anything that may depend on course category context.
1658 grade_course_category_delete($this->id, 0, $showfeedback);
1659 if (!question_delete_course_category($this, 0, $showfeedback)) {
1660 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1663 // Finally delete the category and it's context.
1664 $DB->delete_records('course_categories', array('id' => $this->id));
1666 $coursecatcontext = context_coursecat::instance($this->id);
1667 $coursecatcontext->delete();
1669 cache_helper::purge_by_event('changesincoursecat');
1671 // Trigger a course category deleted event.
1672 /* @var \core\event\course_category_deleted $event */
1673 $event = \core\event\course_category_deleted::create(array(
1674 'objectid' => $this->id,
1675 'context' => $coursecatcontext,
1676 'other' => array('name' => $this->name)
1678 $event->set_coursecat($this);
1679 $event->trigger();
1681 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1682 if ($this->id == $CFG->defaultrequestcategory) {
1683 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1685 return $deletedcourses;
1689 * Checks if user can delete this category and move content (courses, subcategories and questions)
1690 * to another category. If yes returns the array of possible target categories names
1692 * If user can not manage this category or it is completely empty - empty array will be returned
1694 * @return array
1696 public function move_content_targets_list() {
1697 global $CFG;
1698 require_once($CFG->libdir . '/questionlib.php');
1699 $context = $this->get_context();
1700 if (!$this->is_uservisible() ||
1701 !has_capability('moodle/category:manage', $context)) {
1702 // User is not able to manage current category, he is not able to delete it.
1703 // No possible target categories.
1704 return array();
1707 $testcaps = array();
1708 // If this category has courses in it, user must have 'course:create' capability in target category.
1709 if ($this->has_courses()) {
1710 $testcaps[] = 'moodle/course:create';
1712 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1713 if ($this->has_children() || question_context_has_any_questions($context)) {
1714 $testcaps[] = 'moodle/category:manage';
1716 if (!empty($testcaps)) {
1717 // Return list of categories excluding this one and it's children.
1718 return self::make_categories_list($testcaps, $this->id);
1721 // Category is completely empty, no need in target for contents.
1722 return array();
1726 * Checks if user has capability to move all category content to the new parent before
1727 * removing this category
1729 * @param int $newcatid
1730 * @return bool
1732 public function can_move_content_to($newcatid) {
1733 global $CFG;
1734 require_once($CFG->libdir . '/questionlib.php');
1735 $context = $this->get_context();
1736 if (!$this->is_uservisible() ||
1737 !has_capability('moodle/category:manage', $context)) {
1738 return false;
1740 $testcaps = array();
1741 // If this category has courses in it, user must have 'course:create' capability in target category.
1742 if ($this->has_courses()) {
1743 $testcaps[] = 'moodle/course:create';
1745 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1746 if ($this->has_children() || question_context_has_any_questions($context)) {
1747 $testcaps[] = 'moodle/category:manage';
1749 if (!empty($testcaps)) {
1750 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1753 // There is no content but still return true.
1754 return true;
1758 * Deletes a category and moves all content (children, courses and questions) to the new parent
1760 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1761 * must be called prior
1763 * @param int $newparentid
1764 * @param bool $showfeedback
1765 * @return bool
1767 public function delete_move($newparentid, $showfeedback = false) {
1768 global $CFG, $DB, $OUTPUT;
1770 require_once($CFG->libdir.'/gradelib.php');
1771 require_once($CFG->libdir.'/questionlib.php');
1772 require_once($CFG->dirroot.'/cohort/lib.php');
1774 // Get all objects and lists because later the caches will be reset so.
1775 // We don't need to make extra queries.
1776 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1777 $catname = $this->get_formatted_name();
1778 $children = $this->get_children();
1779 $params = array('category' => $this->id);
1780 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', $params);
1781 $context = $this->get_context();
1783 if ($children) {
1784 foreach ($children as $childcat) {
1785 $childcat->change_parent_raw($newparentcat);
1786 // Log action.
1787 $event = \core\event\course_category_updated::create(array(
1788 'objectid' => $childcat->id,
1789 'context' => $childcat->get_context()
1791 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $childcat->id,
1792 $childcat->id));
1793 $event->trigger();
1795 fix_course_sortorder();
1798 if ($coursesids) {
1799 if (!move_courses($coursesids, $newparentid)) {
1800 if ($showfeedback) {
1801 echo $OUTPUT->notification("Error moving courses");
1803 return false;
1805 if ($showfeedback) {
1806 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1810 // Move or delete cohorts in this context.
1811 cohort_delete_category($this);
1813 // Now delete anything that may depend on course category context.
1814 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1815 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1816 if ($showfeedback) {
1817 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1819 return false;
1822 // Finally delete the category and it's context.
1823 $DB->delete_records('course_categories', array('id' => $this->id));
1824 $context->delete();
1826 // Trigger a course category deleted event.
1827 /* @var \core\event\course_category_deleted $event */
1828 $event = \core\event\course_category_deleted::create(array(
1829 'objectid' => $this->id,
1830 'context' => $context,
1831 'other' => array('name' => $this->name)
1833 $event->set_coursecat($this);
1834 $event->trigger();
1836 cache_helper::purge_by_event('changesincoursecat');
1838 if ($showfeedback) {
1839 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1842 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1843 if ($this->id == $CFG->defaultrequestcategory) {
1844 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1846 return true;
1850 * Checks if user can move current category to the new parent
1852 * This checks if new parent category exists, user has manage cap there
1853 * and new parent is not a child of this category
1855 * @param int|stdClass|coursecat $newparentcat
1856 * @return bool
1858 public function can_change_parent($newparentcat) {
1859 if (!has_capability('moodle/category:manage', $this->get_context())) {
1860 return false;
1862 if (is_object($newparentcat)) {
1863 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1864 } else {
1865 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1867 if (!$newparentcat) {
1868 return false;
1870 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1871 // Can not move to itself or it's own child.
1872 return false;
1874 if ($newparentcat->id) {
1875 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
1876 } else {
1877 return has_capability('moodle/category:manage', context_system::instance());
1882 * Moves the category under another parent category. All associated contexts are moved as well
1884 * This is protected function, use change_parent() or update() from outside of this class
1886 * @see coursecat::change_parent()
1887 * @see coursecat::update()
1889 * @param coursecat $newparentcat
1890 * @throws moodle_exception
1892 protected function change_parent_raw(coursecat $newparentcat) {
1893 global $DB;
1895 $context = $this->get_context();
1897 $hidecat = false;
1898 if (empty($newparentcat->id)) {
1899 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1900 $newparent = context_system::instance();
1901 } else {
1902 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1903 // Can not move to itself or it's own child.
1904 throw new moodle_exception('cannotmovecategory');
1906 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
1907 $newparent = context_coursecat::instance($newparentcat->id);
1909 if (!$newparentcat->visible and $this->visible) {
1910 // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children
1911 // will be restored properly.
1912 $hidecat = true;
1915 $this->parent = $newparentcat->id;
1917 $context->update_moved($newparent);
1919 // Now make it last in new category.
1920 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
1922 if ($hidecat) {
1923 fix_course_sortorder();
1924 $this->restore();
1925 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must
1926 // become visible again.
1927 $this->hide_raw(1);
1932 * Efficiently moves a category - NOTE that this can have
1933 * a huge impact access-control-wise...
1935 * Note that this function does not check capabilities.
1937 * Example of usage:
1938 * $coursecat = coursecat::get($categoryid);
1939 * if ($coursecat->can_change_parent($newparentcatid)) {
1940 * $coursecat->change_parent($newparentcatid);
1943 * This function does not update field course_categories.timemodified
1944 * If you want to update timemodified, use
1945 * $coursecat->update(array('parent' => $newparentcat));
1947 * @param int|stdClass|coursecat $newparentcat
1949 public function change_parent($newparentcat) {
1950 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1951 if (is_object($newparentcat)) {
1952 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
1953 } else {
1954 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
1956 if ($newparentcat->id != $this->parent) {
1957 $this->change_parent_raw($newparentcat);
1958 fix_course_sortorder();
1959 cache_helper::purge_by_event('changesincoursecat');
1960 $this->restore();
1962 $event = \core\event\course_category_updated::create(array(
1963 'objectid' => $this->id,
1964 'context' => $this->get_context()
1966 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $this->id, $this->id));
1967 $event->trigger();
1972 * Hide course category and child course and subcategories
1974 * If this category has changed the parent and is moved under hidden
1975 * category we will want to store it's current visibility state in
1976 * the field 'visibleold'. If admin clicked 'hide' for this particular
1977 * category, the field 'visibleold' should become 0.
1979 * All subcategories and courses will have their current visibility in the field visibleold
1981 * This is protected function, use hide() or update() from outside of this class
1983 * @see coursecat::hide()
1984 * @see coursecat::update()
1986 * @param int $visibleold value to set in field $visibleold for this category
1987 * @return bool whether changes have been made and caches need to be purged afterwards
1989 protected function hide_raw($visibleold = 0) {
1990 global $DB;
1991 $changes = false;
1993 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing.
1994 if ($this->id && $this->__get('visibleold') != $visibleold) {
1995 $this->visibleold = $visibleold;
1996 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
1997 $changes = true;
1999 if (!$this->visible || !$this->id) {
2000 // Already hidden or can not be hidden.
2001 return $changes;
2004 $this->visible = 0;
2005 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
2006 // Store visible flag so that we can return to it if we immediately unhide.
2007 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id));
2008 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
2009 // Get all child categories and hide too.
2010 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
2011 foreach ($subcats as $cat) {
2012 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
2013 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
2014 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
2015 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
2018 return true;
2022 * Hide course category and child course and subcategories
2024 * Note that there is no capability check inside this function
2026 * This function does not update field course_categories.timemodified
2027 * If you want to update timemodified, use
2028 * $coursecat->update(array('visible' => 0));
2030 public function hide() {
2031 if ($this->hide_raw(0)) {
2032 cache_helper::purge_by_event('changesincoursecat');
2034 $event = \core\event\course_category_updated::create(array(
2035 'objectid' => $this->id,
2036 'context' => $this->get_context()
2038 $event->set_legacy_logdata(array(SITEID, 'category', 'hide', 'editcategory.php?id=' . $this->id, $this->id));
2039 $event->trigger();
2044 * Show course category and restores visibility for child course and subcategories
2046 * Note that there is no capability check inside this function
2048 * This is protected function, use show() or update() from outside of this class
2050 * @see coursecat::show()
2051 * @see coursecat::update()
2053 * @return bool whether changes have been made and caches need to be purged afterwards
2055 protected function show_raw() {
2056 global $DB;
2058 if ($this->visible) {
2059 // Already visible.
2060 return false;
2063 $this->visible = 1;
2064 $this->visibleold = 1;
2065 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
2066 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
2067 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
2068 // Get all child categories and unhide too.
2069 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
2070 foreach ($subcats as $cat) {
2071 if ($cat->visibleold) {
2072 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
2074 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
2077 return true;
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 function does not update field course_categories.timemodified
2086 * If you want to update timemodified, use
2087 * $coursecat->update(array('visible' => 1));
2089 public function show() {
2090 if ($this->show_raw()) {
2091 cache_helper::purge_by_event('changesincoursecat');
2093 $event = \core\event\course_category_updated::create(array(
2094 'objectid' => $this->id,
2095 'context' => $this->get_context()
2097 $event->set_legacy_logdata(array(SITEID, 'category', 'show', 'editcategory.php?id=' . $this->id, $this->id));
2098 $event->trigger();
2103 * Returns name of the category formatted as a string
2105 * @param array $options formatting options other than context
2106 * @return string
2108 public function get_formatted_name($options = array()) {
2109 if ($this->id) {
2110 $context = $this->get_context();
2111 return format_string($this->name, true, array('context' => $context) + $options);
2112 } else {
2113 return get_string('top');
2118 * Returns ids of all parents of the category. Last element in the return array is the direct parent
2120 * For example, if you have a tree of categories like:
2121 * Miscellaneous (id = 1)
2122 * Subcategory (id = 2)
2123 * Sub-subcategory (id = 4)
2124 * Other category (id = 3)
2126 * coursecat::get(1)->get_parents() == array()
2127 * coursecat::get(2)->get_parents() == array(1)
2128 * coursecat::get(4)->get_parents() == array(1, 2);
2130 * Note that this method does not check if all parents are accessible by current user
2132 * @return array of category ids
2134 public function get_parents() {
2135 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
2136 array_pop($parents);
2137 return $parents;
2141 * This function returns a nice list representing category tree
2142 * for display or to use in a form <select> element
2144 * List is cached for 10 minutes
2146 * For example, if you have a tree of categories like:
2147 * Miscellaneous (id = 1)
2148 * Subcategory (id = 2)
2149 * Sub-subcategory (id = 4)
2150 * Other category (id = 3)
2151 * Then after calling this function you will have
2152 * array(1 => 'Miscellaneous',
2153 * 2 => 'Miscellaneous / Subcategory',
2154 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2155 * 3 => 'Other category');
2157 * If you specify $requiredcapability, then only categories where the current
2158 * user has that capability will be added to $list.
2159 * If you only have $requiredcapability in a child category, not the parent,
2160 * then the child catgegory will still be included.
2162 * If you specify the option $excludeid, then that category, and all its children,
2163 * are omitted from the tree. This is useful when you are doing something like
2164 * moving categories, where you do not want to allow people to move a category
2165 * to be the child of itself.
2167 * See also {@link make_categories_options()}
2169 * @param string/array $requiredcapability if given, only categories where the current
2170 * user has this capability will be returned. Can also be an array of capabilities,
2171 * in which case they are all required.
2172 * @param integer $excludeid Exclude this category and its children from the lists built.
2173 * @param string $separator string to use as a separator between parent and child category. Default ' / '
2174 * @return array of strings
2176 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
2177 global $DB;
2178 $coursecatcache = cache::make('core', 'coursecat');
2180 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids
2181 // with requried cap ($thislist).
2182 $currentlang = current_language();
2183 $basecachekey = $currentlang . '_catlist';
2184 $baselist = $coursecatcache->get($basecachekey);
2185 $thislist = false;
2186 $thiscachekey = null;
2187 if (!empty($requiredcapability)) {
2188 $requiredcapability = (array)$requiredcapability;
2189 $thiscachekey = 'catlist:'. serialize($requiredcapability);
2190 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
2191 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
2193 } else if ($baselist !== false) {
2194 $thislist = array_keys($baselist);
2197 if ($baselist === false) {
2198 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
2199 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2200 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
2201 FROM {course_categories} cc
2202 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
2203 ORDER BY cc.sortorder";
2204 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2205 $baselist = array();
2206 $thislist = array();
2207 foreach ($rs as $record) {
2208 // If the category's parent is not visible to the user, it is not visible as well.
2209 if (!$record->parent || isset($baselist[$record->parent])) {
2210 context_helper::preload_from_record($record);
2211 $context = context_coursecat::instance($record->id);
2212 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
2213 // No cap to view category, added to neither $baselist nor $thislist.
2214 continue;
2216 $baselist[$record->id] = array(
2217 'name' => format_string($record->name, true, array('context' => $context)),
2218 'path' => $record->path
2220 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
2221 // No required capability, added to $baselist but not to $thislist.
2222 continue;
2224 $thislist[] = $record->id;
2227 $rs->close();
2228 $coursecatcache->set($basecachekey, $baselist);
2229 if (!empty($requiredcapability)) {
2230 $coursecatcache->set($thiscachekey, join(',', $thislist));
2232 } else if ($thislist === false) {
2233 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
2234 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2235 $sql = "SELECT ctx.instanceid AS id, $ctxselect
2236 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
2237 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2238 $thislist = array();
2239 foreach (array_keys($baselist) as $id) {
2240 context_helper::preload_from_record($contexts[$id]);
2241 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
2242 $thislist[] = $id;
2245 $coursecatcache->set($thiscachekey, join(',', $thislist));
2248 // Now build the array of strings to return, mind $separator and $excludeid.
2249 $names = array();
2250 foreach ($thislist as $id) {
2251 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
2252 if (!$excludeid || !in_array($excludeid, $path)) {
2253 $namechunks = array();
2254 foreach ($path as $parentid) {
2255 $namechunks[] = $baselist[$parentid]['name'];
2257 $names[$id] = join($separator, $namechunks);
2260 return $names;
2264 * Prepares the object for caching. Works like the __sleep method.
2266 * implementing method from interface cacheable_object
2268 * @return array ready to be cached
2270 public function prepare_to_cache() {
2271 $a = array();
2272 foreach (self::$coursecatfields as $property => $cachedirectives) {
2273 if ($cachedirectives !== null) {
2274 list($shortname, $defaultvalue) = $cachedirectives;
2275 if ($this->$property !== $defaultvalue) {
2276 $a[$shortname] = $this->$property;
2280 $context = $this->get_context();
2281 $a['xi'] = $context->id;
2282 $a['xp'] = $context->path;
2283 return $a;
2287 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2289 * implementing method from interface cacheable_object
2291 * @param array $a
2292 * @return coursecat
2294 public static function wake_from_cache($a) {
2295 $record = new stdClass;
2296 foreach (self::$coursecatfields as $property => $cachedirectives) {
2297 if ($cachedirectives !== null) {
2298 list($shortname, $defaultvalue) = $cachedirectives;
2299 if (array_key_exists($shortname, $a)) {
2300 $record->$property = $a[$shortname];
2301 } else {
2302 $record->$property = $defaultvalue;
2306 $record->ctxid = $a['xi'];
2307 $record->ctxpath = $a['xp'];
2308 $record->ctxdepth = $record->depth + 1;
2309 $record->ctxlevel = CONTEXT_COURSECAT;
2310 $record->ctxinstance = $record->id;
2311 return new coursecat($record, true);
2315 * Returns true if the user is able to create a top level category.
2316 * @return bool
2318 public static function can_create_top_level_category() {
2319 return has_capability('moodle/category:manage', context_system::instance());
2323 * Returns the category context.
2324 * @return context_coursecat
2326 public function get_context() {
2327 if ($this->id === 0) {
2328 // This is the special top level category object.
2329 return context_system::instance();
2330 } else {
2331 return context_coursecat::instance($this->id);
2336 * Returns true if the user is able to manage this category.
2337 * @return bool
2339 public function has_manage_capability() {
2340 if ($this->hasmanagecapability === null) {
2341 $this->hasmanagecapability = has_capability('moodle/category:manage', $this->get_context());
2343 return $this->hasmanagecapability;
2347 * Returns true if the user has the manage capability on the parent category.
2348 * @return bool
2350 public function parent_has_manage_capability() {
2351 return has_capability('moodle/category:manage', get_category_or_system_context($this->parent));
2355 * Returns true if the current user can create subcategories of this category.
2356 * @return bool
2358 public function can_create_subcategory() {
2359 return $this->has_manage_capability();
2363 * Returns true if the user can resort this categories sub categories and courses.
2364 * Must have manage capability and be able to see all subcategories.
2365 * @return bool
2367 public function can_resort_subcategories() {
2368 return $this->has_manage_capability() && !$this->get_not_visible_children_ids();
2372 * Returns true if the user can resort the courses within this category.
2373 * Must have manage capability and be able to see all courses.
2374 * @return bool
2376 public function can_resort_courses() {
2377 return $this->has_manage_capability() && $this->coursecount == $this->get_courses_count();
2381 * Returns true of the user can change the sortorder of this category (resort in the parent category)
2382 * @return bool
2384 public function can_change_sortorder() {
2385 return $this->id && $this->get_parent_coursecat()->can_resort_subcategories();
2389 * Returns true if the current user can create a course within this category.
2390 * @return bool
2392 public function can_create_course() {
2393 return has_capability('moodle/course:create', $this->get_context());
2397 * Returns true if the current user can edit this categories settings.
2398 * @return bool
2400 public function can_edit() {
2401 return $this->has_manage_capability();
2405 * Returns true if the current user can review role assignments for this category.
2406 * @return bool
2408 public function can_review_roles() {
2409 return has_capability('moodle/role:assign', $this->get_context());
2413 * Returns true if the current user can review permissions for this category.
2414 * @return bool
2416 public function can_review_permissions() {
2417 return has_any_capability(array(
2418 'moodle/role:assign',
2419 'moodle/role:safeoverride',
2420 'moodle/role:override',
2421 'moodle/role:assign'
2422 ), $this->get_context());
2426 * Returns true if the current user can review cohorts for this category.
2427 * @return bool
2429 public function can_review_cohorts() {
2430 return has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->get_context());
2434 * Returns true if the current user can review filter settings for this category.
2435 * @return bool
2437 public function can_review_filters() {
2438 return has_capability('moodle/filter:manage', $this->get_context()) &&
2439 count(filter_get_available_in_context($this->get_context()))>0;
2443 * Returns true if the current user is able to change the visbility of this category.
2444 * @return bool
2446 public function can_change_visibility() {
2447 return $this->parent_has_manage_capability();
2451 * Returns true if the user can move courses out of this category.
2452 * @return bool
2454 public function can_move_courses_out_of() {
2455 return $this->has_manage_capability();
2459 * Returns true if the user can move courses into this category.
2460 * @return bool
2462 public function can_move_courses_into() {
2463 return $this->has_manage_capability();
2467 * Returns true if the user is able to restore a course into this category as a new course.
2468 * @return bool
2470 public function can_restore_courses_into() {
2471 return has_capability('moodle/restore:restorecourse', $this->get_context());
2475 * Resorts the sub categories of this category by the given field.
2477 * @param string $field One of name, idnumber or descending values of each (appended desc)
2478 * @param bool $cleanup If true cleanup will be done, if false you will need to do it manually later.
2479 * @return bool True on success.
2480 * @throws coding_exception
2482 public function resort_subcategories($field, $cleanup = true) {
2483 global $DB;
2484 $desc = false;
2485 if (substr($field, -4) === "desc") {
2486 $desc = true;
2487 $field = substr($field, 0, -4); // Remove "desc" from field name.
2489 if ($field !== 'name' && $field !== 'idnumber') {
2490 throw new coding_exception('Invalid field requested');
2492 $children = $this->get_children();
2493 core_collator::asort_objects_by_property($children, $field, core_collator::SORT_NATURAL);
2494 if (!empty($desc)) {
2495 $children = array_reverse($children);
2497 $i = 1;
2498 foreach ($children as $cat) {
2499 $i++;
2500 $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id));
2501 $i += $cat->coursecount;
2503 if ($cleanup) {
2504 self::resort_categories_cleanup();
2506 return true;
2510 * Cleans things up after categories have been resorted.
2511 * @param bool $includecourses If set to true we know courses have been resorted as well.
2513 public static function resort_categories_cleanup($includecourses = false) {
2514 // This should not be needed but we do it just to be safe.
2515 fix_course_sortorder();
2516 cache_helper::purge_by_event('changesincoursecat');
2517 if ($includecourses) {
2518 cache_helper::purge_by_event('changesincourse');
2523 * Resort the courses within this category by the given field.
2525 * @param string $field One of fullname, shortname, idnumber or descending values of each (appended desc)
2526 * @param bool $cleanup
2527 * @return bool True for success.
2528 * @throws coding_exception
2530 public function resort_courses($field, $cleanup = true) {
2531 global $DB;
2532 $desc = false;
2533 if (substr($field, -4) === "desc") {
2534 $desc = true;
2535 $field = substr($field, 0, -4); // Remove "desc" from field name.
2537 if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber' && $field !== 'timecreated') {
2538 // This is ultra important as we use $field in an SQL statement below this.
2539 throw new coding_exception('Invalid field requested');
2541 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
2542 $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields
2543 FROM {course} c
2544 LEFT JOIN {context} ctx ON ctx.instanceid = c.id
2545 WHERE ctx.contextlevel = :ctxlevel AND
2546 c.category = :categoryid";
2547 $params = array(
2548 'ctxlevel' => CONTEXT_COURSE,
2549 'categoryid' => $this->id
2551 $courses = $DB->get_records_sql($sql, $params);
2552 if (count($courses) > 0) {
2553 foreach ($courses as $courseid => $course) {
2554 context_helper::preload_from_record($course);
2555 if ($field === 'idnumber') {
2556 $course->sortby = $course->idnumber;
2557 } else {
2558 // It'll require formatting.
2559 $options = array(
2560 'context' => context_course::instance($course->id)
2562 // We format the string first so that it appears as the user would see it.
2563 // This ensures the sorting makes sense to them. However it won't necessarily make
2564 // sense to everyone if things like multilang filters are enabled.
2565 // We then strip any tags as we don't want things such as image tags skewing the
2566 // sort results.
2567 $course->sortby = strip_tags(format_string($course->$field, true, $options));
2569 // We set it back here rather than using references as there is a bug with using
2570 // references in a foreach before passing as an arg by reference.
2571 $courses[$courseid] = $course;
2573 // Sort the courses.
2574 core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL);
2575 if (!empty($desc)) {
2576 $courses = array_reverse($courses);
2578 $i = 1;
2579 foreach ($courses as $course) {
2580 $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id));
2581 $i++;
2583 if ($cleanup) {
2584 // This should not be needed but we do it just to be safe.
2585 fix_course_sortorder();
2586 cache_helper::purge_by_event('changesincourse');
2589 return true;
2593 * Changes the sort order of this categories parent shifting this category up or down one.
2595 * @global \moodle_database $DB
2596 * @param bool $up If set to true the category is shifted up one spot, else its moved down.
2597 * @return bool True on success, false otherwise.
2599 public function change_sortorder_by_one($up) {
2600 global $DB;
2601 $params = array($this->sortorder, $this->parent);
2602 if ($up) {
2603 $select = 'sortorder < ? AND parent = ?';
2604 $sort = 'sortorder DESC';
2605 } else {
2606 $select = 'sortorder > ? AND parent = ?';
2607 $sort = 'sortorder ASC';
2609 fix_course_sortorder();
2610 $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1);
2611 $swapcategory = reset($swapcategory);
2612 if ($swapcategory) {
2613 $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id));
2614 $DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id));
2615 $this->sortorder = $swapcategory->sortorder;
2617 $event = \core\event\course_category_updated::create(array(
2618 'objectid' => $this->id,
2619 'context' => $this->get_context()
2621 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'management.php?categoryid=' . $this->id,
2622 $this->id));
2623 $event->trigger();
2625 // Finally reorder courses.
2626 fix_course_sortorder();
2627 cache_helper::purge_by_event('changesincoursecat');
2628 return true;
2630 return false;
2634 * Returns the parent coursecat object for this category.
2636 * @return coursecat
2638 public function get_parent_coursecat() {
2639 return self::get($this->parent);
2644 * Returns true if the user is able to request a new course be created.
2645 * @return bool
2647 public function can_request_course() {
2648 global $CFG;
2649 if (empty($CFG->enablecourserequests) || $this->id != $CFG->defaultrequestcategory) {
2650 return false;
2652 return !$this->can_create_course() && has_capability('moodle/course:request', $this->get_context());
2656 * Returns true if the user can approve course requests.
2657 * @return bool
2659 public static function can_approve_course_requests() {
2660 global $CFG, $DB;
2661 if (empty($CFG->enablecourserequests)) {
2662 return false;
2664 $context = context_system::instance();
2665 if (!has_capability('moodle/site:approvecourse', $context)) {
2666 return false;
2668 if (!$DB->record_exists('course_request', array())) {
2669 return false;
2671 return true;
2676 * Class to store information about one course in a list of courses
2678 * Not all information may be retrieved when object is created but
2679 * it will be retrieved on demand when appropriate property or method is
2680 * called.
2682 * Instances of this class are usually returned by functions
2683 * {@link coursecat::search_courses()}
2684 * and
2685 * {@link coursecat::get_courses()}
2687 * @property-read int $id
2688 * @property-read int $category Category ID
2689 * @property-read int $sortorder
2690 * @property-read string $fullname
2691 * @property-read string $shortname
2692 * @property-read string $idnumber
2693 * @property-read string $summary Course summary. Field is present if coursecat::get_courses()
2694 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2695 * @property-read int $summaryformat Summary format. Field is present if coursecat::get_courses()
2696 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2697 * @property-read string $format Course format. Retrieved from DB on first request
2698 * @property-read int $showgrades Retrieved from DB on first request
2699 * @property-read int $newsitems Retrieved from DB on first request
2700 * @property-read int $startdate
2701 * @property-read int $marker Retrieved from DB on first request
2702 * @property-read int $maxbytes Retrieved from DB on first request
2703 * @property-read int $legacyfiles Retrieved from DB on first request
2704 * @property-read int $showreports Retrieved from DB on first request
2705 * @property-read int $visible
2706 * @property-read int $visibleold Retrieved from DB on first request
2707 * @property-read int $groupmode Retrieved from DB on first request
2708 * @property-read int $groupmodeforce Retrieved from DB on first request
2709 * @property-read int $defaultgroupingid Retrieved from DB on first request
2710 * @property-read string $lang Retrieved from DB on first request
2711 * @property-read string $theme Retrieved from DB on first request
2712 * @property-read int $timecreated Retrieved from DB on first request
2713 * @property-read int $timemodified Retrieved from DB on first request
2714 * @property-read int $requested Retrieved from DB on first request
2715 * @property-read int $enablecompletion Retrieved from DB on first request
2716 * @property-read int $completionnotify Retrieved from DB on first request
2717 * @property-read int $cacherev
2719 * @package core
2720 * @subpackage course
2721 * @copyright 2013 Marina Glancy
2722 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2724 class course_in_list implements IteratorAggregate {
2726 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2727 protected $record;
2729 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2730 protected $coursecontacts;
2732 /** @var bool true if the current user can access the course, false otherwise. */
2733 protected $canaccess = null;
2736 * Creates an instance of the class from record
2738 * @param stdClass $record except fields from course table it may contain
2739 * field hassummary indicating that summary field is not empty.
2740 * Also it is recommended to have context fields here ready for
2741 * context preloading
2743 public function __construct(stdClass $record) {
2744 context_helper::preload_from_record($record);
2745 $this->record = new stdClass();
2746 foreach ($record as $key => $value) {
2747 $this->record->$key = $value;
2752 * Indicates if the course has non-empty summary field
2754 * @return bool
2756 public function has_summary() {
2757 if (isset($this->record->hassummary)) {
2758 return !empty($this->record->hassummary);
2760 if (!isset($this->record->summary)) {
2761 // We need to retrieve summary.
2762 $this->__get('summary');
2764 return !empty($this->record->summary);
2768 * Indicates if the course have course contacts to display
2770 * @return bool
2772 public function has_course_contacts() {
2773 if (!isset($this->record->managers)) {
2774 $courses = array($this->id => &$this->record);
2775 coursecat::preload_course_contacts($courses);
2777 return !empty($this->record->managers);
2781 * Returns list of course contacts (usually teachers) to display in course link
2783 * Roles to display are set up in $CFG->coursecontact
2785 * The result is the list of users where user id is the key and the value
2786 * is an array with elements:
2787 * - 'user' - object containing basic user information
2788 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2789 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2790 * - 'username' => fullname($user, $canviewfullnames)
2792 * @return array
2794 public function get_course_contacts() {
2795 global $CFG;
2796 if (empty($CFG->coursecontact)) {
2797 // No roles are configured to be displayed as course contacts.
2798 return array();
2800 if ($this->coursecontacts === null) {
2801 $this->coursecontacts = array();
2802 $context = context_course::instance($this->id);
2804 if (!isset($this->record->managers)) {
2805 // Preload course contacts from DB.
2806 $courses = array($this->id => &$this->record);
2807 coursecat::preload_course_contacts($courses);
2810 // Build return array with full roles names (for this course context) and users names.
2811 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2812 foreach ($this->record->managers as $ruser) {
2813 if (isset($this->coursecontacts[$ruser->id])) {
2814 // Only display a user once with the highest sortorder role.
2815 continue;
2817 $user = new stdClass();
2818 $user = username_load_fields_from_object($user, $ruser, null, array('id', 'username'));
2819 $role = new stdClass();
2820 $role->id = $ruser->roleid;
2821 $role->name = $ruser->rolename;
2822 $role->shortname = $ruser->roleshortname;
2823 $role->coursealias = $ruser->rolecoursealias;
2825 $this->coursecontacts[$user->id] = array(
2826 'user' => $user,
2827 'role' => $role,
2828 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2829 'username' => fullname($user, $canviewfullnames)
2833 return $this->coursecontacts;
2837 * Checks if course has any associated overview files
2839 * @return bool
2841 public function has_course_overviewfiles() {
2842 global $CFG;
2843 if (empty($CFG->courseoverviewfileslimit)) {
2844 return false;
2846 $fs = get_file_storage();
2847 $context = context_course::instance($this->id);
2848 return !$fs->is_area_empty($context->id, 'course', 'overviewfiles');
2852 * Returns all course overview files
2854 * @return array array of stored_file objects
2856 public function get_course_overviewfiles() {
2857 global $CFG;
2858 if (empty($CFG->courseoverviewfileslimit)) {
2859 return array();
2861 require_once($CFG->libdir. '/filestorage/file_storage.php');
2862 require_once($CFG->dirroot. '/course/lib.php');
2863 $fs = get_file_storage();
2864 $context = context_course::instance($this->id);
2865 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2866 if (count($files)) {
2867 $overviewfilesoptions = course_overviewfiles_options($this->id);
2868 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2869 if ($acceptedtypes !== '*') {
2870 // Filter only files with allowed extensions.
2871 require_once($CFG->libdir. '/filelib.php');
2872 foreach ($files as $key => $file) {
2873 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2874 unset($files[$key]);
2878 if (count($files) > $CFG->courseoverviewfileslimit) {
2879 // Return no more than $CFG->courseoverviewfileslimit files.
2880 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
2883 return $files;
2887 * Magic method to check if property is set
2889 * @param string $name
2890 * @return bool
2892 public function __isset($name) {
2893 return isset($this->record->$name);
2897 * Magic method to get a course property
2899 * Returns any field from table course (retrieves it from DB if it was not retrieved before)
2901 * @param string $name
2902 * @return mixed
2904 public function __get($name) {
2905 global $DB;
2906 if (property_exists($this->record, $name)) {
2907 return $this->record->$name;
2908 } else if ($name === 'summary' || $name === 'summaryformat') {
2909 // Retrieve fields summary and summaryformat together because they are most likely to be used together.
2910 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
2911 $this->record->summary = $record->summary;
2912 $this->record->summaryformat = $record->summaryformat;
2913 return $this->record->$name;
2914 } else if (array_key_exists($name, $DB->get_columns('course'))) {
2915 // Another field from table 'course' that was not retrieved.
2916 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
2917 return $this->record->$name;
2919 debugging('Invalid course property accessed! '.$name);
2920 return null;
2924 * All properties are read only, sorry.
2926 * @param string $name
2928 public function __unset($name) {
2929 debugging('Can not unset '.get_class($this).' instance properties!');
2933 * Magic setter method, we do not want anybody to modify properties from the outside
2935 * @param string $name
2936 * @param mixed $value
2938 public function __set($name, $value) {
2939 debugging('Can not change '.get_class($this).' instance properties!');
2943 * Create an iterator because magic vars can't be seen by 'foreach'.
2944 * Exclude context fields
2946 * Implementing method from interface IteratorAggregate
2948 * @return ArrayIterator
2950 public function getIterator() {
2951 $ret = array('id' => $this->record->id);
2952 foreach ($this->record as $property => $value) {
2953 $ret[$property] = $value;
2955 return new ArrayIterator($ret);
2959 * Returns the name of this course as it should be displayed within a list.
2960 * @return string
2962 public function get_formatted_name() {
2963 return format_string(get_course_display_name_for_list($this), true, $this->get_context());
2967 * Returns the formatted fullname for this course.
2968 * @return string
2970 public function get_formatted_fullname() {
2971 return format_string($this->__get('fullname'), true, $this->get_context());
2975 * Returns the formatted shortname for this course.
2976 * @return string
2978 public function get_formatted_shortname() {
2979 return format_string($this->__get('shortname'), true, $this->get_context());
2983 * Returns true if the current user can access this course.
2984 * @return bool
2986 public function can_access() {
2987 if ($this->canaccess === null) {
2988 $this->canaccess = can_access_course($this->record);
2990 return $this->canaccess;
2994 * Returns true if the user can edit this courses settings.
2996 * Note: this function does not check that the current user can access the course.
2997 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2999 * @return bool
3001 public function can_edit() {
3002 return has_capability('moodle/course:update', $this->get_context());
3006 * Returns true if the user can change the visibility of this course.
3008 * Note: this function does not check that the current user can access the course.
3009 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3011 * @return bool
3013 public function can_change_visibility() {
3014 // You must be able to both hide a course and view the hidden course.
3015 return has_all_capabilities(array('moodle/course:visibility', 'moodle/course:viewhiddencourses'), $this->get_context());
3019 * Returns the context for this course.
3020 * @return context_course
3022 public function get_context() {
3023 return context_course::instance($this->__get('id'));
3027 * Returns true if this course is visible to the current user.
3028 * @return bool
3030 public function is_uservisible() {
3031 return $this->visible || has_capability('moodle/course:viewhiddencourses', $this->get_context());
3035 * Returns true if the current user can review enrolments for this course.
3037 * Note: this function does not check that the current user can access the course.
3038 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3040 * @return bool
3042 public function can_review_enrolments() {
3043 return has_capability('moodle/course:enrolreview', $this->get_context());
3047 * Returns true if the current user can delete this course.
3049 * Note: this function does not check that the current user can access the course.
3050 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3052 * @return bool
3054 public function can_delete() {
3055 return can_delete_course($this->id);
3059 * Returns true if the current user can backup this course.
3061 * Note: this function does not check that the current user can access the course.
3062 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3064 * @return bool
3066 public function can_backup() {
3067 return has_capability('moodle/backup:backupcourse', $this->get_context());
3071 * Returns true if the current user can restore this course.
3073 * Note: this function does not check that the current user can access the course.
3074 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
3076 * @return bool
3078 public function can_restore() {
3079 return has_capability('moodle/restore:restorecourse', $this->get_context());
3084 * An array of records that is sortable by many fields.
3086 * For more info on the ArrayObject class have a look at php.net.
3088 * @package core
3089 * @subpackage course
3090 * @copyright 2013 Sam Hemelryk
3091 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3093 class coursecat_sortable_records extends ArrayObject {
3096 * An array of sortable fields.
3097 * Gets set temporarily when sort is called.
3098 * @var array
3100 protected $sortfields = array();
3103 * Sorts this array using the given fields.
3105 * @param array $records
3106 * @param array $fields
3107 * @return array
3109 public static function sort(array $records, array $fields) {
3110 $records = new coursecat_sortable_records($records);
3111 $records->sortfields = $fields;
3112 $records->uasort(array($records, 'sort_by_many_fields'));
3113 return $records->getArrayCopy();
3117 * Sorts the two records based upon many fields.
3119 * This method should not be called itself, please call $sort instead.
3120 * It has been marked as access private as such.
3122 * @access private
3123 * @param stdClass $a
3124 * @param stdClass $b
3125 * @return int
3127 public function sort_by_many_fields($a, $b) {
3128 foreach ($this->sortfields as $field => $mult) {
3129 // Nulls first.
3130 if (is_null($a->$field) && !is_null($b->$field)) {
3131 return -$mult;
3133 if (is_null($b->$field) && !is_null($a->$field)) {
3134 return $mult;
3137 if (is_string($a->$field) || is_string($b->$field)) {
3138 // String fields.
3139 if ($cmp = strcoll($a->$field, $b->$field)) {
3140 return $mult * $cmp;
3142 } else {
3143 // Int fields.
3144 if ($a->$field > $b->$field) {
3145 return $mult;
3147 if ($a->$field < $b->$field) {
3148 return -$mult;
3152 return 0;