2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Contains class coursecat reponsible for course category operations
22 * @copyright 2013 Marina Glancy
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
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
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 const CACHE_COURSE_CONTACTS_TTL = 3600; // do not fetch course contacts more often than once per hour
57 /** @var array list of all fields and their short name and default value for caching */
58 protected static $coursecatfields = array(
59 'id' => array('id', 0),
60 'name' => array('na', ''),
61 'idnumber' => array('in', null),
62 'description' => null, // not cached
63 'descriptionformat' => null, // not cached
64 'parent' => array('pa', 0),
65 'sortorder' => array('so', 0),
66 'coursecount' => array('cc', 0),
67 'visible' => array('vi', 1),
68 'visibleold' => null, // not cached
69 'timemodified' => null, // not cached
70 'depth' => array('dh', 1),
71 'path' => array('ph', null),
72 'theme' => null, // not cached
82 protected $idnumber = null;
85 protected $description = false;
88 protected $descriptionformat = false;
91 protected $parent = 0;
94 protected $sortorder = 0;
97 protected $coursecount = false;
100 protected $visible = 1;
103 protected $visibleold = false;
106 protected $timemodified = false;
109 protected $depth = 0;
112 protected $path = '';
115 protected $theme = false;
118 protected $fromcache;
120 // ====== magic methods =======
123 * Magic setter method, we do not want anybody to modify properties from the outside
125 * @param string $name
126 * @param mixed $value
128 public function __set($name, $value) {
129 debugging('Can not change coursecat instance properties!', DEBUG_DEVELOPER);
133 * Magic method getter, redirects to read only values. Queries from DB the fields that were not cached
135 * @param string $name
138 public function __get($name) {
140 if (array_key_exists($name, self::$coursecatfields)) {
141 if ($this->$name === false) {
142 // property was not retrieved from DB, retrieve all not retrieved fields
143 $notretrievedfields = array_diff_key(self::$coursecatfields, array_filter(self::$coursecatfields));
144 $record = $DB->get_record('course_categories', array('id' => $this->id),
145 join(',', array_keys($notretrievedfields)), MUST_EXIST);
146 foreach ($record as $key => $value) {
147 $this->$key = $value;
152 debugging('Invalid coursecat property accessed! '.$name, DEBUG_DEVELOPER);
157 * Full support for isset on our magic read only properties.
159 * @param string $name
162 public function __isset($name) {
163 if (array_key_exists($name, self::$coursecatfields)) {
164 return isset($this->$name);
170 * All properties are read only, sorry.
172 * @param string $name
174 public function __unset($name) {
175 debugging('Can not unset coursecat instance properties!', DEBUG_DEVELOPER);
179 * Create an iterator because magic vars can't be seen by 'foreach'.
181 * implementing method from interface IteratorAggregate
183 * @return ArrayIterator
185 public function getIterator() {
187 foreach (self::$coursecatfields as $property => $unused) {
188 if ($this->$property !== false) {
189 $ret[$property] = $this->$property;
192 return new ArrayIterator($ret);
198 * Constructor is protected, use coursecat::get($id) to retrieve category
200 * @param stdClass $record record from DB (may not contain all fields)
201 * @param bool $fromcache whether it is being restored from cache
203 protected function __construct(stdClass $record, $fromcache = false) {
204 context_helper::preload_from_record($record);
205 foreach ($record as $key => $val) {
206 if (array_key_exists($key, self::$coursecatfields)) {
210 $this->fromcache = $fromcache;
214 * Returns coursecat object for requested category
216 * If category is not visible to user it is treated as non existing
217 * unless $alwaysreturnhidden is set to true
219 * If id is 0, the pseudo object for root category is returned (convenient
220 * for calling other functions such as get_children())
222 * @param int $id category id
223 * @param int $strictness whether to throw an exception (MUST_EXIST) or
224 * return null (IGNORE_MISSING) in case the category is not found or
225 * not visible to current user
226 * @param bool $alwaysreturnhidden set to true if you want an object to be
227 * returned even if this category is not visible to the current user
228 * (category is hidden and user does not have
229 * 'moodle/category:viewhiddencategories' capability). Use with care!
230 * @return null|coursecat
232 public static function get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false) {
234 if (!isset(self::$coursecat0)) {
235 $record = new stdClass();
237 $record->visible = 1;
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);
251 $coursecatrecordcache->set($id, $coursecat);
254 if ($coursecat && ($alwaysreturnhidden || $coursecat->is_uservisible())) {
257 if ($strictness == MUST_EXIST) {
258 throw new moodle_exception('unknowcategory');
265 * Returns the first found category
267 * Note that if there are no categories visible to the current user on the first level,
268 * the invisible category may be returned
272 public static function get_default() {
273 if ($visiblechildren = self::get(0)->get_children()) {
274 $defcategory = reset($visiblechildren);
276 $toplevelcategories = self::get_tree(0);
277 $defcategoryid = $toplevelcategories[0];
278 $defcategory = self::get($defcategoryid, MUST_EXIST, true);
284 * Restores the object after it has been externally modified in DB for example
285 * during {@link fix_course_sortorder()}
287 protected function restore() {
288 // update all fields in the current object
289 $newrecord = self::get($this->id, MUST_EXIST, true);
290 foreach (self::$coursecatfields as $key => $unused) {
291 $this->$key = $newrecord->$key;
296 * Creates a new category either from form data or from raw data
298 * Please note that this function does not verify access control.
300 * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
302 * Category visibility is inherited from parent unless $data->visible = 0 is specified
304 * @param array|stdClass $data
305 * @param array $editoroptions if specified, the data is considered to be
306 * form data and file_postupdate_standard_editor() is being called to
307 * process images in description.
309 * @throws moodle_exception
311 public static function create($data, $editoroptions = null) {
313 $data = (object)$data;
314 $newcategory = new stdClass();
316 $newcategory->descriptionformat = FORMAT_MOODLE;
317 $newcategory->description = '';
318 // copy all description* fields regardless of whether this is form data or direct field update
319 foreach ($data as $key => $value) {
320 if (preg_match("/^description/", $key)) {
321 $newcategory->$key = $value;
325 if (empty($data->name)) {
326 throw new moodle_exception('categorynamerequired');
328 if (core_text::strlen($data->name) > 255) {
329 throw new moodle_exception('categorytoolong');
331 $newcategory->name = $data->name;
333 // validate and set idnumber
334 if (!empty($data->idnumber)) {
335 if (core_text::strlen($data->idnumber) > 100) {
336 throw new moodle_exception('idnumbertoolong');
338 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
339 throw new moodle_exception('categoryidnumbertaken');
342 if (isset($data->idnumber)) {
343 $newcategory->idnumber = $data->idnumber;
346 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
347 $newcategory->theme = $data->theme;
350 if (empty($data->parent)) {
351 $parent = self::get(0);
353 $parent = self::get($data->parent, MUST_EXIST, true);
355 $newcategory->parent = $parent->id;
356 $newcategory->depth = $parent->depth + 1;
358 // By default category is visible, unless visible = 0 is specified or parent category is hidden
359 if (isset($data->visible) && !$data->visible) {
360 // create a hidden category
361 $newcategory->visible = $newcategory->visibleold = 0;
363 // create a category that inherits visibility from parent
364 $newcategory->visible = $parent->visible;
365 // in case parent is hidden, when it changes visibility this new subcategory will automatically become visible too
366 $newcategory->visibleold = 1;
369 $newcategory->sortorder = 0;
370 $newcategory->timemodified = time();
372 $newcategory->id = $DB->insert_record('course_categories', $newcategory);
374 // update path (only possible after we know the category id
375 $path = $parent->path . '/' . $newcategory->id;
376 $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));
378 // We should mark the context as dirty
379 context_coursecat::instance($newcategory->id)->mark_dirty();
381 fix_course_sortorder();
383 // if this is data from form results, save embedded files and update description
384 $categorycontext = context_coursecat::instance($newcategory->id);
385 if ($editoroptions) {
386 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext, 'coursecat', 'description', 0);
388 // update only fields description and descriptionformat
389 $updatedata = new stdClass();
390 $updatedata->id = $newcategory->id;
391 $updatedata->description = $newcategory->description;
392 $updatedata->descriptionformat = $newcategory->descriptionformat;
393 $DB->update_record('course_categories', $updatedata);
396 add_to_log(SITEID, "category", 'add', "editcategory.php?id=$newcategory->id", $newcategory->id);
397 cache_helper::purge_by_event('changesincoursecat');
399 return self::get($newcategory->id, MUST_EXIST, true);
403 * Updates the record with either form data or raw data
405 * Please note that this function does not verify access control.
407 * This function calls coursecat::change_parent_raw if field 'parent' is updated.
408 * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
409 * Visibility is changed first and then parent is changed. This means that
410 * if parent category is hidden, the current category will become hidden
411 * too and it may overwrite whatever was set in field 'visible'.
413 * Note that fields 'path' and 'depth' can not be updated manually
414 * Also coursecat::update() can not directly update the field 'sortoder'
416 * @param array|stdClass $data
417 * @param array $editoroptions if specified, the data is considered to be
418 * form data and file_postupdate_standard_editor() is being called to
419 * process images in description.
420 * @throws moodle_exception
422 public function update($data, $editoroptions = null) {
425 // there is no actual DB record associated with root category
429 $data = (object)$data;
430 $newcategory = new stdClass();
431 $newcategory->id = $this->id;
433 // copy all description* fields regardless of whether this is form data or direct field update
434 foreach ($data as $key => $value) {
435 if (preg_match("/^description/", $key)) {
436 $newcategory->$key = $value;
440 if (isset($data->name) && empty($data->name)) {
441 throw new moodle_exception('categorynamerequired');
444 if (!empty($data->name) && $data->name !== $this->name) {
445 if (core_text::strlen($data->name) > 255) {
446 throw new moodle_exception('categorytoolong');
448 $newcategory->name = $data->name;
451 if (isset($data->idnumber) && $data->idnumber != $this->idnumber) {
452 if (core_text::strlen($data->idnumber) > 100) {
453 throw new moodle_exception('idnumbertoolong');
455 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
456 throw new moodle_exception('categoryidnumbertaken');
458 $newcategory->idnumber = $data->idnumber;
461 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
462 $newcategory->theme = $data->theme;
466 if (isset($data->visible)) {
467 if ($data->visible) {
468 $changes = $this->show_raw();
470 $changes = $this->hide_raw(0);
474 if (isset($data->parent) && $data->parent != $this->parent) {
476 cache_helper::purge_by_event('changesincoursecat');
478 $parentcat = self::get($data->parent, MUST_EXIST, true);
479 $this->change_parent_raw($parentcat);
480 fix_course_sortorder();
483 $newcategory->timemodified = time();
485 if ($editoroptions) {
486 $categorycontext = context_coursecat::instance($this->id);
487 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext, 'coursecat', 'description', 0);
489 $DB->update_record('course_categories', $newcategory);
490 add_to_log(SITEID, "category", 'update', "editcategory.php?id=$this->id", $this->id);
491 fix_course_sortorder();
492 // purge cache even if fix_course_sortorder() did not do it
493 cache_helper::purge_by_event('changesincoursecat');
495 // update all fields in the current object
500 * Checks if this course category is visible to current user
502 * Please note that methods coursecat::get (without 3rd argumet),
503 * coursecat::get_children(), etc. return only visible categories so it is
504 * usually not needed to call this function outside of this class
508 public function is_uservisible() {
509 return !$this->id || $this->visible ||
510 has_capability('moodle/category:viewhiddencategories',
511 context_coursecat::instance($this->id));
515 * Returns all categories visible to the current user
517 * This is a generic function that returns an array of
518 * (category id => coursecat object) sorted by sortorder
520 * @see coursecat::get_children()
521 * @see coursecat::get_all_parents()
523 * @return cacheable_object_array array of coursecat objects
525 public static function get_all_visible() {
527 $coursecatcache = cache::make('core', 'coursecat');
528 $ids = $coursecatcache->get('user'. $USER->id);
529 if ($ids === false) {
530 $all = self::get_all_ids();
531 $parentvisible = $all[0];
533 foreach ($all as $id => $children) {
534 if ($id && in_array($id, $parentvisible) &&
535 ($coursecat = self::get($id, IGNORE_MISSING)) &&
536 (!$coursecat->parent || isset($rv[$coursecat->parent]))) {
537 $rv[$id] = $coursecat;
538 $parentvisible += $children;
541 $coursecatcache->set('user'. $USER->id, array_keys($rv));
544 foreach ($ids as $id) {
545 if ($coursecat = self::get($id, IGNORE_MISSING)) {
546 $rv[$id] = $coursecat;
554 * Returns the entry from categories tree and makes sure the application-level tree cache is built
556 * The following keys can be requested:
558 * 'countall' - total number of categories in the system (always present)
559 * 0 - array of ids of top-level categories (always present)
560 * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
561 * $id (int) - array of ids of categories that are direct children of category with id $id. If
562 * category with id $id does not exist returns false. If category has no children returns empty array
563 * $id.'i' - array of ids of children categories that have visible=0
565 * @param int|string $id
568 protected static function get_tree($id) {
570 $coursecattreecache = cache::make('core', 'coursecattree');
571 $rv = $coursecattreecache->get($id);
575 // We did not find the entry in cache but it also can mean that tree is not built.
576 // The keys 0 and 'countall' must always be present if tree is built.
577 if ($id !== 0 && $id !== 'countall' && $coursecattreecache->has('countall')) {
578 // Tree was built, it means the non-existing $id was requested.
581 // Re-build the tree.
582 $sql = "SELECT cc.id, cc.parent, cc.visible
583 FROM {course_categories} cc
584 ORDER BY cc.sortorder";
585 $rs = $DB->get_recordset_sql($sql, array());
586 $all = array(0 => array(), '0i' => array());
588 foreach ($rs as $record) {
589 $all[$record->id] = array();
590 $all[$record->id. 'i'] = array();
591 if (array_key_exists($record->parent, $all)) {
592 $all[$record->parent][] = $record->id;
593 if (!$record->visible) {
594 $all[$record->parent. 'i'][] = $record->id;
597 // parent not found. This is data consistency error but next fix_course_sortorder() should fix it
598 $all[0][] = $record->id;
604 // No categories found.
605 // This may happen after upgrade from very old moodle version. In new versions the default category is created on install.
606 $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
607 set_config('defaultrequestcategory', $defcoursecat->id);
608 $all[0] = array($defcoursecat->id);
609 $all[$defcoursecat->id] = array();
612 $all['countall'] = $count;
613 foreach ($all as $key => $children) {
614 $coursecattreecache->set($key, $children);
616 if (array_key_exists($id, $all)) {
623 * Returns number of ALL categories in the system regardless if
624 * they are visible to current user or not
628 public static function count_all() {
629 return self::get_tree('countall');
633 * Retrieves number of records from course_categories table
635 * Only cached fields are retrieved. Records are ready for preloading context
637 * @param string $whereclause
638 * @param array $params
639 * @return array array of stdClass objects
641 protected static function get_records($whereclause, $params) {
643 // Retrieve from DB only the fields that need to be stored in cache
644 $fields = array_keys(array_filter(self::$coursecatfields));
645 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
646 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
647 FROM {course_categories} cc
648 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
649 WHERE ". $whereclause." ORDER BY cc.sortorder";
650 return $DB->get_records_sql($sql,
651 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
655 * Given list of DB records from table course populates each record with list of users with course contact roles
657 * This function fills the courses with raw information as {@link get_role_users()} would do.
658 * See also {@link course_in_list::get_course_contacts()} for more readable return
660 * $courses[$i]->managers = array(
661 * $roleassignmentid => $roleuser,
665 * where $roleuser is an stdClass with the following properties:
667 * $roleuser->raid - role assignment id
668 * $roleuser->id - user id
669 * $roleuser->username
670 * $roleuser->firstname
671 * $roleuser->lastname
672 * $roleuser->rolecoursealias
673 * $roleuser->rolename
674 * $roleuser->sortorder - role sortorder
676 * $roleuser->roleshortname
678 * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
680 * @param array $courses
682 public static function preload_course_contacts(&$courses) {
684 if (empty($courses) || empty($CFG->coursecontact)) {
687 $managerroles = explode(',', $CFG->coursecontact);
688 $cache = cache::make('core', 'coursecontacts');
689 $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
690 // check if cache was set for the current course contacts and it is not yet expired
691 if (empty($cacheddata['basic']) || $cacheddata['basic']['roles'] !== $CFG->coursecontact ||
692 $cacheddata['basic']['lastreset'] < time() - self::CACHE_COURSE_CONTACTS_TTL) {
695 $cache->set('basic', array('roles' => $CFG->coursecontact, 'lastreset' => time()));
696 $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
698 $courseids = array();
699 foreach (array_keys($courses) as $id) {
700 if ($cacheddata[$id] !== false) {
701 $courses[$id]->managers = $cacheddata[$id];
707 // $courseids now stores list of ids of courses for which we still need to retrieve contacts
708 if (empty($courseids)) {
712 // first build the array of all context ids of the courses and their categories
713 $allcontexts = array();
714 foreach ($courseids as $id) {
715 $context = context_course::instance($id);
716 $courses[$id]->managers = array();
717 foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
718 if (!isset($allcontexts[$ctxid])) {
719 $allcontexts[$ctxid] = array();
721 $allcontexts[$ctxid][] = $id;
725 // fetch list of all users with course contact roles in any of the courses contexts or parent contexts
726 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
727 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
728 list($sort, $sortparams) = users_order_by_sql('u');
729 $notdeleted = array('notdeleted'=>0);
730 $allnames = get_all_user_name_fields(true, 'u');
731 $sql = "SELECT ra.contextid, ra.id AS raid,
732 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
733 rn.name AS rolecoursealias, u.id, u.username, $allnames
734 FROM {role_assignments} ra
735 JOIN {user} u ON ra.userid = u.id
736 JOIN {role} r ON ra.roleid = r.id
737 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
738 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
739 ORDER BY r.sortorder, $sort";
740 $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
741 $checkenrolments = array();
742 foreach($rs as $ra) {
743 foreach ($allcontexts[$ra->contextid] as $id) {
744 $courses[$id]->managers[$ra->raid] = $ra;
745 if (!isset($checkenrolments[$id])) {
746 $checkenrolments[$id] = array();
748 $checkenrolments[$id][] = $ra->id;
753 // remove from course contacts users who are not enrolled in the course
754 $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
755 foreach ($checkenrolments as $id => $userids) {
756 if (empty($enrolleduserids[$id])) {
757 $courses[$id]->managers = array();
758 } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
759 foreach ($courses[$id]->managers as $raid => $ra) {
760 if (in_array($ra->id, $notenrolled)) {
761 unset($courses[$id]->managers[$raid]);
769 foreach ($courseids as $id) {
770 $values[$id] = $courses[$id]->managers;
772 $cache->set_many($values);
776 * Verify user enrollments for multiple course-user combinations
778 * @param array $courseusers array where keys are course ids and values are array
779 * of users in this course whose enrolment we wish to verify
780 * @return array same structure as input array but values list only users from input
781 * who are enrolled in the course
783 protected static function ensure_users_enrolled($courseusers) {
785 // If the input array is too big, split it into chunks
786 $maxcoursesinquery = 20;
787 if (count($courseusers) > $maxcoursesinquery) {
789 for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
790 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
791 $rv = $rv + self::ensure_users_enrolled($chunk);
796 // create a query verifying valid user enrolments for the number of courses
797 $sql = "SELECT DISTINCT e.courseid, ue.userid
798 FROM {user_enrolments} ue
799 JOIN {enrol} e ON e.id = ue.enrolid
800 WHERE ue.status = :active
801 AND e.status = :enabled
802 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
803 $now = round(time(), -2); // rounding helps caching in DB
804 $params = array('enabled' => ENROL_INSTANCE_ENABLED,
805 'active' => ENROL_USER_ACTIVE,
806 'now1' => $now, 'now2' => $now);
810 foreach ($courseusers as $id => $userids) {
811 $enrolled[$id] = array();
812 if (count($userids)) {
813 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
814 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
815 $params = $params + array('courseid'.$cnt => $id) + $params2;
819 if (count($subsqls)) {
820 $sql .= "AND (". join(' OR ', $subsqls).")";
821 $rs = $DB->get_recordset_sql($sql, $params);
822 foreach ($rs as $record) {
823 $enrolled[$record->courseid][] = $record->userid;
831 * Retrieves number of records from course table
833 * Not all fields are retrieved. Records are ready for preloading context
835 * @param string $whereclause
836 * @param array $params
837 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
838 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
839 * on not visible courses
840 * @return array array of stdClass objects
842 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
844 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
845 $fields = array('c.id', 'c.category', 'c.sortorder',
846 'c.shortname', 'c.fullname', 'c.idnumber',
847 'c.startdate', 'c.visible', 'c.cacherev');
848 if (!empty($options['summary'])) {
849 $fields[] = 'c.summary';
850 $fields[] = 'c.summaryformat';
852 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
854 $sql = "SELECT ". join(',', $fields). ", $ctxselect
856 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
857 WHERE ". $whereclause." ORDER BY c.sortorder";
858 $list = $DB->get_records_sql($sql,
859 array('contextcourse' => CONTEXT_COURSE) + $params);
861 if ($checkvisibility) {
862 // Loop through all records and make sure we only return the courses accessible by user.
863 foreach ($list as $course) {
864 if (isset($list[$course->id]->hassummary)) {
865 $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
867 if (empty($course->visible)) {
868 // load context only if we need to check capability
869 context_helper::preload_from_record($course);
870 if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
871 unset($list[$course->id]);
877 // preload course contacts if necessary
878 if (!empty($options['coursecontacts'])) {
879 self::preload_course_contacts($list);
885 * Returns array of ids of children categories that current user can not see
887 * This data is cached in user session cache
891 protected function get_not_visible_children_ids() {
893 $coursecatcache = cache::make('core', 'coursecat');
894 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
895 // we never checked visible children before
896 $hidden = self::get_tree($this->id.'i');
897 $invisibleids = array();
899 // preload categories contexts
900 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
901 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
902 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
903 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
904 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
905 foreach ($contexts as $record) {
906 context_helper::preload_from_record($record);
908 // check that user has 'viewhiddencategories' capability for each hidden category
909 foreach ($hidden as $id) {
910 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
911 $invisibleids[] = $id;
915 $coursecatcache->set('ic'. $this->id, $invisibleids);
917 return $invisibleids;
921 * Sorts list of records by several fields
923 * @param array $records array of stdClass objects
924 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
927 protected static function sort_records(&$records, $sortfields) {
928 if (empty($records)) {
931 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname)
932 if (array_key_exists('displayname', $sortfields)) {
933 foreach ($records as $key => $record) {
934 if (!isset($record->displayname)) {
935 $records[$key]->displayname = get_course_display_name_for_list($record);
939 // sorting by one field - use core_collator
940 if (count($sortfields) == 1) {
941 $property = key($sortfields);
942 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
943 $sortflag = core_collator::SORT_NUMERIC;
944 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
945 $sortflag = core_collator::SORT_STRING;
947 $sortflag = core_collator::SORT_REGULAR;
949 core_collator::asort_objects_by_property($records, $property, $sortflag);
950 if ($sortfields[$property] < 0) {
951 $records = array_reverse($records, true);
955 $records = coursecat_sortable_records::sort($records, $sortfields);
959 * Returns array of children categories visible to the current user
961 * @param array $options options for retrieving children
962 * - sort - list of fields to sort. Example
963 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
964 * will sort by idnumber asc, name asc and id desc.
965 * Default: array('sortorder' => 1)
966 * Only cached fields may be used for sorting!
968 * - limit - maximum number of children to return, 0 or null for no limit
969 * @return array of coursecat objects indexed by category id
971 public function get_children($options = array()) {
973 $coursecatcache = cache::make('core', 'coursecat');
975 // get default values for options
976 if (!empty($options['sort']) && is_array($options['sort'])) {
977 $sortfields = $options['sort'];
979 $sortfields = array('sortorder' => 1);
982 if (!empty($options['limit']) && (int)$options['limit']) {
983 $limit = (int)$options['limit'];
986 if (!empty($options['offset']) && (int)$options['offset']) {
987 $offset = (int)$options['offset'];
990 // first retrieve list of user-visible and sorted children ids from cache
991 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
992 if ($sortedids === false) {
993 $sortfieldskeys = array_keys($sortfields);
994 if ($sortfieldskeys[0] === 'sortorder') {
995 // no DB requests required to build the list of ids sorted by sortorder.
996 // We can easily ignore other sort fields because sortorder is always different
997 $sortedids = self::get_tree($this->id);
998 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
999 $sortedids = array_diff($sortedids, $invisibleids);
1000 if ($sortfields['sortorder'] == -1) {
1001 $sortedids = array_reverse($sortedids, true);
1005 // we need to retrieve and sort all children. Good thing that it is done only on first request
1006 if ($invisibleids = $this->get_not_visible_children_ids()) {
1007 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
1008 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
1009 array('parent' => $this->id) + $params);
1011 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
1013 self::sort_records($records, $sortfields);
1014 $sortedids = array_keys($records);
1016 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
1019 if (empty($sortedids)) {
1023 // now retrieive and return categories
1024 if ($offset || $limit) {
1025 $sortedids = array_slice($sortedids, $offset, $limit);
1027 if (isset($records)) {
1028 // easy, we have already retrieved records
1029 if ($offset || $limit) {
1030 $records = array_slice($records, $offset, $limit, true);
1033 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
1034 $records = self::get_records('cc.id '. $sql,
1035 array('parent' => $this->id) + $params);
1039 foreach ($sortedids as $id) {
1040 if (isset($records[$id])) {
1041 $rv[$id] = new coursecat($records[$id]);
1048 * Returns number of subcategories visible to the current user
1052 public function get_children_count() {
1053 $sortedids = self::get_tree($this->id);
1054 $invisibleids = $this->get_not_visible_children_ids();
1055 return count($sortedids) - count($invisibleids);
1059 * Returns true if the category has ANY children, including those not visible to the user
1063 public function has_children() {
1064 $allchildren = self::get_tree($this->id);
1065 return !empty($allchildren);
1069 * Returns true if the category has courses in it (count does not include courses
1070 * in child categories)
1074 public function has_courses() {
1076 return $DB->record_exists_sql("select 1 from {course} where category = ?",
1083 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1084 * to this when somebody edits courses or categories, however it is very
1085 * difficult to keep track of all possible changes that may affect list of courses.
1087 * @param array $search contains search criterias, such as:
1088 * - search - search string
1089 * - blocklist - id of block (if we are searching for courses containing specific block0
1090 * - modulelist - name of module (if we are searching for courses containing specific module
1091 * - tagid - id of tag
1092 * @param array $options display options, same as in get_courses() except 'recursive' is ignored - search is always category-independent
1093 * @return course_in_list[]
1095 public static function search_courses($search, $options = array()) {
1097 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1098 $limit = !empty($options['limit']) ? $options['limit'] : null;
1099 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1101 $coursecatcache = cache::make('core', 'coursecat');
1102 $cachekey = 's-'. serialize($search + array('sort' => $sortfields));
1103 $cntcachekey = 'scnt-'. serialize($search);
1105 $ids = $coursecatcache->get($cachekey);
1106 if ($ids !== false) {
1107 // we already cached last search result
1108 $ids = array_slice($ids, $offset, $limit);
1111 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1112 $records = self::get_course_records("c.id ". $sql, $params, $options);
1113 foreach ($ids as $id) {
1114 $courses[$id] = new course_in_list($records[$id]);
1120 $preloadcoursecontacts = !empty($options['coursecontacts']);
1121 unset($options['coursecontacts']);
1123 if (!empty($search['search'])) {
1124 // search courses that have specified words in their names/summaries
1125 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1126 $searchterms = array_filter($searchterms, create_function('$v', 'return strlen($v) > 1;'));
1127 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount);
1128 self::sort_records($courselist, $sortfields);
1129 $coursecatcache->set($cachekey, array_keys($courselist));
1130 $coursecatcache->set($cntcachekey, $totalcount);
1131 $records = array_slice($courselist, $offset, $limit, true);
1133 if (!empty($search['blocklist'])) {
1134 // search courses that have block with specified id
1135 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1136 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1137 WHERE bi.blockname = :blockname)';
1138 $params = array('blockname' => $blockname);
1139 } else if (!empty($search['modulelist'])) {
1140 // search courses that have module with specified name
1141 $where = "c.id IN (SELECT DISTINCT module.course ".
1142 "FROM {".$search['modulelist']."} module)";
1144 } else if (!empty($search['tagid'])) {
1145 // search courses that are tagged with the specified tag
1146 $where = "c.id IN (SELECT t.itemid ".
1147 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype)";
1148 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course');
1150 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1153 $courselist = self::get_course_records($where, $params, $options, true);
1154 self::sort_records($courselist, $sortfields);
1155 $coursecatcache->set($cachekey, array_keys($courselist));
1156 $coursecatcache->set($cntcachekey, count($courselist));
1157 $records = array_slice($courselist, $offset, $limit, true);
1160 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1161 if (!empty($preloadcoursecontacts)) {
1162 self::preload_course_contacts($records);
1165 foreach ($records as $record) {
1166 $courses[$record->id] = new course_in_list($record);
1172 * Returns number of courses in the search results
1174 * It is recommended to call this function after {@link coursecat::search_courses()}
1175 * and not before because only course ids are cached. Otherwise search_courses() may
1176 * perform extra DB queries.
1178 * @param array $search search criteria, see method search_courses() for more details
1179 * @param array $options display options. They do not affect the result but
1180 * the 'sort' property is used in cache key for storing list of course ids
1183 public static function search_courses_count($search, $options = array()) {
1184 $coursecatcache = cache::make('core', 'coursecat');
1185 $cntcachekey = 'scnt-'. serialize($search);
1186 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1187 self::search_courses($search, $options);
1188 $cnt = $coursecatcache->get($cntcachekey);
1194 * Retrieves the list of courses accessible by user
1196 * Not all information is cached, try to avoid calling this method
1197 * twice in the same request.
1199 * The following fields are always retrieved:
1200 * - id, visible, fullname, shortname, idnumber, category, sortorder
1202 * If you plan to use properties/methods course_in_list::$summary and/or
1203 * course_in_list::get_course_contacts()
1204 * you can preload this information using appropriate 'options'. Otherwise
1205 * they will be retrieved from DB on demand and it may end with bigger DB load.
1207 * Note that method course_in_list::has_summary() will not perform additional
1208 * DB queries even if $options['summary'] is not specified
1210 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1211 * to this when somebody edits courses or categories, however it is very
1212 * difficult to keep track of all possible changes that may affect list of courses.
1214 * @param array $options options for retrieving children
1215 * - recursive - return courses from subcategories as well. Use with care,
1216 * this may be a huge list!
1217 * - summary - preloads fields 'summary' and 'summaryformat'
1218 * - coursecontacts - preloads course contacts
1219 * - sort - list of fields to sort. Example
1220 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1221 * will sort by idnumber asc, shortname asc and id desc.
1222 * Default: array('sortorder' => 1)
1223 * Only cached fields may be used for sorting!
1225 * - limit - maximum number of children to return, 0 or null for no limit
1226 * @return course_in_list[]
1228 public function get_courses($options = array()) {
1230 $recursive = !empty($options['recursive']);
1231 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1232 $limit = !empty($options['limit']) ? $options['limit'] : null;
1233 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1235 // Check if this category is hidden.
1236 // Also 0-category never has courses unless this is recursive call.
1237 if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1241 $coursecatcache = cache::make('core', 'coursecat');
1242 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1243 '-'. serialize($sortfields);
1244 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1246 // check if we have already cached results
1247 $ids = $coursecatcache->get($cachekey);
1248 if ($ids !== false) {
1249 // we already cached last search result and it did not expire yet
1250 $ids = array_slice($ids, $offset, $limit);
1253 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1254 $records = self::get_course_records("c.id ". $sql, $params, $options);
1255 foreach ($ids as $id) {
1256 $courses[$id] = new course_in_list($records[$id]);
1262 // retrieve list of courses in category
1263 $where = 'c.id <> :siteid';
1264 $params = array('siteid' => SITEID);
1267 $context = context_coursecat::instance($this->id);
1268 $where .= ' AND ctx.path like :path';
1269 $params['path'] = $context->path. '/%';
1272 $where .= ' AND c.category = :categoryid';
1273 $params['categoryid'] = $this->id;
1275 // get list of courses without preloaded coursecontacts because we don't need them for every course
1276 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1278 // sort and cache list
1279 self::sort_records($list, $sortfields);
1280 $coursecatcache->set($cachekey, array_keys($list));
1281 $coursecatcache->set($cntcachekey, count($list));
1283 // Apply offset/limit, convert to course_in_list and return.
1286 if ($offset || $limit) {
1287 $list = array_slice($list, $offset, $limit, true);
1289 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1290 if (!empty($options['coursecontacts'])) {
1291 self::preload_course_contacts($list);
1293 foreach ($list as $record) {
1294 $courses[$record->id] = new course_in_list($record);
1301 * Returns number of courses visible to the user
1303 * @param array $options similar to get_courses() except some options do not affect
1304 * number of courses (i.e. sort, summary, offset, limit etc.)
1307 public function get_courses_count($options = array()) {
1308 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1309 $coursecatcache = cache::make('core', 'coursecat');
1310 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1311 $this->get_courses($options);
1312 $cnt = $coursecatcache->get($cntcachekey);
1318 * Returns true if user can delete current category and all its contents
1320 * To be able to delete course category the user must have permission
1321 * 'moodle/category:manage' in ALL child course categories AND
1322 * be able to delete all courses
1326 public function can_delete_full() {
1333 $context = context_coursecat::instance($this->id);
1334 if (!$this->is_uservisible() ||
1335 !has_capability('moodle/category:manage', $context)) {
1339 // Check all child categories (not only direct children)
1340 $sql = context_helper::get_preload_record_columns_sql('ctx');
1341 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1342 ' FROM {context} ctx '.
1343 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1344 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1345 array($context->path. '/%', CONTEXT_COURSECAT));
1346 foreach ($childcategories as $childcat) {
1347 context_helper::preload_from_record($childcat);
1348 $childcontext = context_coursecat::instance($childcat->id);
1349 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1350 !has_capability('moodle/category:manage', $childcontext)) {
1356 $sql = context_helper::get_preload_record_columns_sql('ctx');
1357 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1358 $sql. ' FROM {context} ctx '.
1359 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1360 array('pathmask' => $context->path. '/%',
1361 'courselevel' => CONTEXT_COURSE));
1362 foreach ($coursescontexts as $ctxrecord) {
1363 context_helper::preload_from_record($ctxrecord);
1364 if (!can_delete_course($ctxrecord->courseid)) {
1373 * Recursively delete category including all subcategories and courses
1375 * Function {@link coursecat::can_delete_full()} MUST be called prior
1376 * to calling this function because there is no capability check
1377 * inside this function
1379 * @param boolean $showfeedback display some notices
1380 * @return array return deleted courses
1382 public function delete_full($showfeedback = true) {
1385 require_once($CFG->libdir.'/gradelib.php');
1386 require_once($CFG->libdir.'/questionlib.php');
1387 require_once($CFG->dirroot.'/cohort/lib.php');
1389 $deletedcourses = array();
1391 // Get children. Note, we don't want to use cache here because
1392 // it would be rebuilt too often
1393 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1394 foreach ($children as $record) {
1395 $coursecat = new coursecat($record);
1396 $deletedcourses += $coursecat->delete_full($showfeedback);
1399 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1400 foreach ($courses as $course) {
1401 if (!delete_course($course, false)) {
1402 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1404 $deletedcourses[] = $course;
1408 // move or delete cohorts in this context
1409 cohort_delete_category($this);
1411 // now delete anything that may depend on course category context
1412 grade_course_category_delete($this->id, 0, $showfeedback);
1413 if (!question_delete_course_category($this, 0, $showfeedback)) {
1414 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1417 // finally delete the category and it's context
1418 $DB->delete_records('course_categories', array('id' => $this->id));
1420 $coursecatcontext = context_coursecat::instance($this->id);
1421 $coursecatcontext->delete();
1423 cache_helper::purge_by_event('changesincoursecat');
1425 // Trigger a course category deleted event.
1426 $event = \core\event\course_category_deleted::create(array(
1427 'objectid' => $this->id,
1428 'context' => $coursecatcontext,
1429 'other' => array('name' => $this->name)
1431 $event->set_legacy_eventdata($this);
1434 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1435 if ($this->id == $CFG->defaultrequestcategory) {
1436 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1438 return $deletedcourses;
1442 * Checks if user can delete this category and move content (courses, subcategories and questions)
1443 * to another category. If yes returns the array of possible target categories names
1445 * If user can not manage this category or it is completely empty - empty array will be returned
1449 public function move_content_targets_list() {
1451 require_once($CFG->libdir . '/questionlib.php');
1452 $context = context_coursecat::instance($this->id);
1453 if (!$this->is_uservisible() ||
1454 !has_capability('moodle/category:manage', $context)) {
1455 // User is not able to manage current category, he is not able to delete it.
1456 // No possible target categories.
1460 $testcaps = array();
1461 // If this category has courses in it, user must have 'course:create' capability in target category.
1462 if ($this->has_courses()) {
1463 $testcaps[] = 'moodle/course:create';
1465 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1466 if ($this->has_children() || question_context_has_any_questions($context)) {
1467 $testcaps[] = 'moodle/category:manage';
1469 if (!empty($testcaps)) {
1470 // return list of categories excluding this one and it's children
1471 return self::make_categories_list($testcaps, $this->id);
1474 // Category is completely empty, no need in target for contents.
1479 * Checks if user has capability to move all category content to the new parent before
1480 * removing this category
1482 * @param int $newcatid
1485 public function can_move_content_to($newcatid) {
1487 require_once($CFG->libdir . '/questionlib.php');
1488 $context = context_coursecat::instance($this->id);
1489 if (!$this->is_uservisible() ||
1490 !has_capability('moodle/category:manage', $context)) {
1493 $testcaps = array();
1494 // If this category has courses in it, user must have 'course:create' capability in target category.
1495 if ($this->has_courses()) {
1496 $testcaps[] = 'moodle/course:create';
1498 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1499 if ($this->has_children() || question_context_has_any_questions($context)) {
1500 $testcaps[] = 'moodle/category:manage';
1502 if (!empty($testcaps)) {
1503 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1506 // there is no content but still return true
1511 * Deletes a category and moves all content (children, courses and questions) to the new parent
1513 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1514 * must be called prior
1516 * @param int $newparentid
1517 * @param bool $showfeedback
1520 public function delete_move($newparentid, $showfeedback = false) {
1521 global $CFG, $DB, $OUTPUT;
1523 require_once($CFG->libdir.'/gradelib.php');
1524 require_once($CFG->libdir.'/questionlib.php');
1525 require_once($CFG->dirroot.'/cohort/lib.php');
1527 // get all objects and lists because later the caches will be reset so
1528 // we don't need to make extra queries
1529 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1530 $catname = $this->get_formatted_name();
1531 $children = $this->get_children();
1532 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', array('category' => $this->id));
1533 $context = context_coursecat::instance($this->id);
1536 foreach ($children as $childcat) {
1537 $childcat->change_parent_raw($newparentcat);
1539 add_to_log(SITEID, "category", "move", "editcategory.php?id=$childcat->id", $childcat->id);
1541 fix_course_sortorder();
1545 if (!move_courses($coursesids, $newparentid)) {
1546 if ($showfeedback) {
1547 echo $OUTPUT->notification("Error moving courses");
1551 if ($showfeedback) {
1552 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1556 // move or delete cohorts in this context
1557 cohort_delete_category($this);
1559 // now delete anything that may depend on course category context
1560 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1561 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1562 if ($showfeedback) {
1563 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1568 // finally delete the category and it's context
1569 $DB->delete_records('course_categories', array('id' => $this->id));
1572 // Trigger a course category deleted event.
1573 $event = \core\event\course_category_deleted::create(array(
1574 'objectid' => $this->id,
1575 'context' => $context,
1576 'other' => array('name' => $this->name)
1578 $event->set_legacy_eventdata($this);
1581 cache_helper::purge_by_event('changesincoursecat');
1583 if ($showfeedback) {
1584 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1587 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1588 if ($this->id == $CFG->defaultrequestcategory) {
1589 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1595 * Checks if user can move current category to the new parent
1597 * This checks if new parent category exists, user has manage cap there
1598 * and new parent is not a child of this category
1600 * @param int|stdClass|coursecat $newparentcat
1603 public function can_change_parent($newparentcat) {
1604 if (!has_capability('moodle/category:manage', context_coursecat::instance($this->id))) {
1607 if (is_object($newparentcat)) {
1608 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1610 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1612 if (!$newparentcat) {
1615 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1616 // can not move to itself or it's own child
1619 if ($newparentcat->id) {
1620 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
1622 return has_capability('moodle/category:manage', context_system::instance());
1627 * Moves the category under another parent category. All associated contexts are moved as well
1629 * This is protected function, use change_parent() or update() from outside of this class
1631 * @see coursecat::change_parent()
1632 * @see coursecat::update()
1634 * @param coursecat $newparentcat
1636 protected function change_parent_raw(coursecat $newparentcat) {
1639 $context = context_coursecat::instance($this->id);
1642 if (empty($newparentcat->id)) {
1643 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1644 $newparent = context_system::instance();
1646 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1647 // can not move to itself or it's own child
1648 throw new moodle_exception('cannotmovecategory');
1650 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
1651 $newparent = context_coursecat::instance($newparentcat->id);
1653 if (!$newparentcat->visible and $this->visible) {
1654 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
1658 $this->parent = $newparentcat->id;
1660 $context->update_moved($newparent);
1662 // now make it last in new category
1663 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
1666 fix_course_sortorder();
1668 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must become visible again.
1674 * Efficiently moves a category - NOTE that this can have
1675 * a huge impact access-control-wise...
1677 * Note that this function does not check capabilities.
1680 * $coursecat = coursecat::get($categoryid);
1681 * if ($coursecat->can_change_parent($newparentcatid)) {
1682 * $coursecat->change_parent($newparentcatid);
1685 * This function does not update field course_categories.timemodified
1686 * If you want to update timemodified, use
1687 * $coursecat->update(array('parent' => $newparentcat));
1689 * @param int|stdClass|coursecat $newparentcat
1691 public function change_parent($newparentcat) {
1692 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1693 if (is_object($newparentcat)) {
1694 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
1696 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
1698 if ($newparentcat->id != $this->parent) {
1699 $this->change_parent_raw($newparentcat);
1700 fix_course_sortorder();
1701 cache_helper::purge_by_event('changesincoursecat');
1703 add_to_log(SITEID, "category", "move", "editcategory.php?id=$this->id", $this->id);
1708 * Hide course category and child course and subcategories
1710 * If this category has changed the parent and is moved under hidden
1711 * category we will want to store it's current visibility state in
1712 * the field 'visibleold'. If admin clicked 'hide' for this particular
1713 * category, the field 'visibleold' should become 0.
1715 * All subcategories and courses will have their current visibility in the field visibleold
1717 * This is protected function, use hide() or update() from outside of this class
1719 * @see coursecat::hide()
1720 * @see coursecat::update()
1722 * @param int $visibleold value to set in field $visibleold for this category
1723 * @return bool whether changes have been made and caches need to be purged afterwards
1725 protected function hide_raw($visibleold = 0) {
1729 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing
1730 if ($this->id && $this->__get('visibleold') != $visibleold) {
1731 $this->visibleold = $visibleold;
1732 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
1735 if (!$this->visible || !$this->id) {
1736 // already hidden or can not be hidden
1741 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
1742 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id)); // store visible flag so that we can return to it if we immediately unhide
1743 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
1744 // get all child categories and hide too
1745 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
1746 foreach ($subcats as $cat) {
1747 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
1748 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
1749 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
1750 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
1757 * Hide course category and child course and subcategories
1759 * Note that there is no capability check inside this function
1761 * This function does not update field course_categories.timemodified
1762 * If you want to update timemodified, use
1763 * $coursecat->update(array('visible' => 0));
1765 public function hide() {
1766 if ($this->hide_raw(0)) {
1767 cache_helper::purge_by_event('changesincoursecat');
1768 add_to_log(SITEID, "category", "hide", "editcategory.php?id=$this->id", $this->id);
1773 * Show course category and restores visibility for child course and subcategories
1775 * Note that there is no capability check inside this function
1777 * This is protected function, use show() or update() from outside of this class
1779 * @see coursecat::show()
1780 * @see coursecat::update()
1782 * @return bool whether changes have been made and caches need to be purged afterwards
1784 protected function show_raw() {
1787 if ($this->visible) {
1793 $this->visibleold = 1;
1794 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
1795 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
1796 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
1797 // get all child categories and unhide too
1798 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
1799 foreach ($subcats as $cat) {
1800 if ($cat->visibleold) {
1801 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
1803 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
1810 * Show course category and restores visibility for child course and subcategories
1812 * Note that there is no capability check inside this function
1814 * This function does not update field course_categories.timemodified
1815 * If you want to update timemodified, use
1816 * $coursecat->update(array('visible' => 1));
1818 public function show() {
1819 if ($this->show_raw()) {
1820 cache_helper::purge_by_event('changesincoursecat');
1821 add_to_log(SITEID, "category", "show", "editcategory.php?id=$this->id", $this->id);
1826 * Returns name of the category formatted as a string
1828 * @param array $options formatting options other than context
1831 public function get_formatted_name($options = array()) {
1833 $context = context_coursecat::instance($this->id);
1834 return format_string($this->name, true, array('context' => $context) + $options);
1836 return ''; // TODO 'Top'?
1841 * Returns ids of all parents of the category. Last element in the return array is the direct parent
1843 * For example, if you have a tree of categories like:
1844 * Miscellaneous (id = 1)
1845 * Subcategory (id = 2)
1846 * Sub-subcategory (id = 4)
1847 * Other category (id = 3)
1849 * coursecat::get(1)->get_parents() == array()
1850 * coursecat::get(2)->get_parents() == array(1)
1851 * coursecat::get(4)->get_parents() == array(1, 2);
1853 * Note that this method does not check if all parents are accessible by current user
1855 * @return array of category ids
1857 public function get_parents() {
1858 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
1859 array_pop($parents);
1864 * This function returns a nice list representing category tree
1865 * for display or to use in a form <select> element
1867 * List is cached for 10 minutes
1869 * For example, if you have a tree of categories like:
1870 * Miscellaneous (id = 1)
1871 * Subcategory (id = 2)
1872 * Sub-subcategory (id = 4)
1873 * Other category (id = 3)
1874 * Then after calling this function you will have
1875 * array(1 => 'Miscellaneous',
1876 * 2 => 'Miscellaneous / Subcategory',
1877 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1878 * 3 => 'Other category');
1880 * If you specify $requiredcapability, then only categories where the current
1881 * user has that capability will be added to $list.
1882 * If you only have $requiredcapability in a child category, not the parent,
1883 * then the child catgegory will still be included.
1885 * If you specify the option $excludeid, then that category, and all its children,
1886 * are omitted from the tree. This is useful when you are doing something like
1887 * moving categories, where you do not want to allow people to move a category
1888 * to be the child of itself.
1890 * See also {@link make_categories_options()}
1892 * @param string/array $requiredcapability if given, only categories where the current
1893 * user has this capability will be returned. Can also be an array of capabilities,
1894 * in which case they are all required.
1895 * @param integer $excludeid Exclude this category and its children from the lists built.
1896 * @param string $separator string to use as a separator between parent and child category. Default ' / '
1897 * @return array of strings
1899 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
1901 $coursecatcache = cache::make('core', 'coursecat');
1903 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids with requried cap ($thislist).
1904 $basecachekey = 'catlist';
1905 $baselist = $coursecatcache->get($basecachekey);
1907 if (!empty($requiredcapability)) {
1908 $requiredcapability = (array)$requiredcapability;
1909 $thiscachekey = 'catlist:'. serialize($requiredcapability);
1910 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
1911 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
1913 } else if ($baselist !== false) {
1914 $thislist = array_keys($baselist);
1917 if ($baselist === false) {
1918 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
1919 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1920 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
1921 FROM {course_categories} cc
1922 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
1923 ORDER BY cc.sortorder";
1924 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
1925 $baselist = array();
1926 $thislist = array();
1927 foreach ($rs as $record) {
1928 // If the category's parent is not visible to the user, it is not visible as well.
1929 if (!$record->parent || isset($baselist[$record->parent])) {
1930 context_helper::preload_from_record($record);
1931 $context = context_coursecat::instance($record->id);
1932 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
1933 // No cap to view category, added to neither $baselist nor $thislist
1936 $baselist[$record->id] = array(
1937 'name' => format_string($record->name, true, array('context' => $context)),
1938 'path' => $record->path
1940 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
1941 // No required capability, added to $baselist but not to $thislist.
1944 $thislist[] = $record->id;
1948 $coursecatcache->set($basecachekey, $baselist);
1949 if (!empty($requiredcapability)) {
1950 $coursecatcache->set($thiscachekey, join(',', $thislist));
1952 } else if ($thislist === false) {
1953 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
1954 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1955 $sql = "SELECT ctx.instanceid AS id, $ctxselect
1956 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
1957 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
1958 $thislist = array();
1959 foreach (array_keys($baselist) as $id) {
1960 context_helper::preload_from_record($contexts[$id]);
1961 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
1965 $coursecatcache->set($thiscachekey, join(',', $thislist));
1968 // Now build the array of strings to return, mind $separator and $excludeid.
1970 foreach ($thislist as $id) {
1971 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
1972 if (!$excludeid || !in_array($excludeid, $path)) {
1973 $namechunks = array();
1974 foreach ($path as $parentid) {
1975 $namechunks[] = $baselist[$parentid]['name'];
1977 $names[$id] = join($separator, $namechunks);
1984 * Prepares the object for caching. Works like the __sleep method.
1986 * implementing method from interface cacheable_object
1988 * @return array ready to be cached
1990 public function prepare_to_cache() {
1992 foreach (self::$coursecatfields as $property => $cachedirectives) {
1993 if ($cachedirectives !== null) {
1994 list($shortname, $defaultvalue) = $cachedirectives;
1995 if ($this->$property !== $defaultvalue) {
1996 $a[$shortname] = $this->$property;
2000 $context = context_coursecat::instance($this->id);
2001 $a['xi'] = $context->id;
2002 $a['xp'] = $context->path;
2007 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2009 * implementing method from interface cacheable_object
2014 public static function wake_from_cache($a) {
2015 $record = new stdClass;
2016 foreach (self::$coursecatfields as $property => $cachedirectives) {
2017 if ($cachedirectives !== null) {
2018 list($shortname, $defaultvalue) = $cachedirectives;
2019 if (array_key_exists($shortname, $a)) {
2020 $record->$property = $a[$shortname];
2022 $record->$property = $defaultvalue;
2026 $record->ctxid = $a['xi'];
2027 $record->ctxpath = $a['xp'];
2028 $record->ctxdepth = $record->depth + 1;
2029 $record->ctxlevel = CONTEXT_COURSECAT;
2030 $record->ctxinstance = $record->id;
2031 return new coursecat($record, true);
2036 * Class to store information about one course in a list of courses
2038 * Not all information may be retrieved when object is created but
2039 * it will be retrieved on demand when appropriate property or method is
2042 * Instances of this class are usually returned by functions
2043 * {@link coursecat::search_courses()}
2045 * {@link coursecat::get_courses()}
2047 * @property-read int $id
2048 * @property-read int $category Category ID
2049 * @property-read int $sortorder
2050 * @property-read string $fullname
2051 * @property-read string $shortname
2052 * @property-read string $idnumber
2053 * @property-read string $summary Course summary. Field is present if coursecat::get_courses()
2054 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2055 * @property-read int $summaryformat Summary format. Field is present if coursecat::get_courses()
2056 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2057 * @property-read string $format Course format. Retrieved from DB on first request
2058 * @property-read int $showgrades Retrieved from DB on first request
2059 * @property-read int $newsitems Retrieved from DB on first request
2060 * @property-read int $startdate
2061 * @property-read int $marker Retrieved from DB on first request
2062 * @property-read int $maxbytes Retrieved from DB on first request
2063 * @property-read int $legacyfiles Retrieved from DB on first request
2064 * @property-read int $showreports Retrieved from DB on first request
2065 * @property-read int $visible
2066 * @property-read int $visibleold Retrieved from DB on first request
2067 * @property-read int $groupmode Retrieved from DB on first request
2068 * @property-read int $groupmodeforce Retrieved from DB on first request
2069 * @property-read int $defaultgroupingid Retrieved from DB on first request
2070 * @property-read string $lang Retrieved from DB on first request
2071 * @property-read string $theme Retrieved from DB on first request
2072 * @property-read int $timecreated Retrieved from DB on first request
2073 * @property-read int $timemodified Retrieved from DB on first request
2074 * @property-read int $requested Retrieved from DB on first request
2075 * @property-read int $enablecompletion Retrieved from DB on first request
2076 * @property-read int $completionnotify Retrieved from DB on first request
2077 * @property-read int $cacherev
2080 * @subpackage course
2081 * @copyright 2013 Marina Glancy
2082 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2084 class course_in_list implements IteratorAggregate {
2086 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2089 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2090 protected $coursecontacts;
2093 * Creates an instance of the class from record
2095 * @param stdClass $record except fields from course table it may contain
2096 * field hassummary indicating that summary field is not empty.
2097 * Also it is recommended to have context fields here ready for
2098 * context preloading
2100 public function __construct(stdClass $record) {
2101 context_helper::preload_from_record($record);
2102 $this->record = new stdClass();
2103 foreach ($record as $key => $value) {
2104 $this->record->$key = $value;
2109 * Indicates if the course has non-empty summary field
2113 public function has_summary() {
2114 if (isset($this->record->hassummary)) {
2115 return !empty($this->record->hassummary);
2117 if (!isset($this->record->summary)) {
2118 // we need to retrieve summary
2119 $this->__get('summary');
2121 return !empty($this->record->summary);
2125 * Indicates if the course have course contacts to display
2129 public function has_course_contacts() {
2130 if (!isset($this->record->managers)) {
2131 $courses = array($this->id => &$this->record);
2132 coursecat::preload_course_contacts($courses);
2134 return !empty($this->record->managers);
2138 * Returns list of course contacts (usually teachers) to display in course link
2140 * Roles to display are set up in $CFG->coursecontact
2142 * The result is the list of users where user id is the key and the value
2143 * is an array with elements:
2144 * - 'user' - object containing basic user information
2145 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2146 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2147 * - 'username' => fullname($user, $canviewfullnames)
2151 public function get_course_contacts() {
2153 if (empty($CFG->coursecontact)) {
2154 // no roles are configured to be displayed as course contacts
2157 if ($this->coursecontacts === null) {
2158 $this->coursecontacts = array();
2159 $context = context_course::instance($this->id);
2161 if (!isset($this->record->managers)) {
2162 // preload course contacts from DB
2163 $courses = array($this->id => &$this->record);
2164 coursecat::preload_course_contacts($courses);
2167 // build return array with full roles names (for this course context) and users names
2168 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2169 foreach ($this->record->managers as $ruser) {
2170 if (isset($this->coursecontacts[$ruser->id])) {
2171 // only display a user once with the highest sortorder role
2174 $user = new stdClass();
2175 $user->id = $ruser->id;
2176 $user->username = $ruser->username;
2177 foreach (get_all_user_name_fields() as $addname) {
2178 $user->$addname = $ruser->$addname;
2180 $role = new stdClass();
2181 $role->id = $ruser->roleid;
2182 $role->name = $ruser->rolename;
2183 $role->shortname = $ruser->roleshortname;
2184 $role->coursealias = $ruser->rolecoursealias;
2186 $this->coursecontacts[$user->id] = array(
2189 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2190 'username' => fullname($user, $canviewfullnames)
2194 return $this->coursecontacts;
2198 * Checks if course has any associated overview files
2202 public function has_course_overviewfiles() {
2204 if (empty($CFG->courseoverviewfileslimit)) {
2207 $fs = get_file_storage();
2208 $context = context_course::instance($this->id);
2209 return !$fs->is_area_empty($context->id, 'course', 'overviewfiles');
2213 * Returns all course overview files
2215 * @return array array of stored_file objects
2217 public function get_course_overviewfiles() {
2219 if (empty($CFG->courseoverviewfileslimit)) {
2222 require_once($CFG->libdir. '/filestorage/file_storage.php');
2223 require_once($CFG->dirroot. '/course/lib.php');
2224 $fs = get_file_storage();
2225 $context = context_course::instance($this->id);
2226 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2227 if (count($files)) {
2228 $overviewfilesoptions = course_overviewfiles_options($this->id);
2229 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2230 if ($acceptedtypes !== '*') {
2231 // filter only files with allowed extensions
2232 require_once($CFG->libdir. '/filelib.php');
2233 foreach ($files as $key => $file) {
2234 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2235 unset($files[$key]);
2239 if (count($files) > $CFG->courseoverviewfileslimit) {
2240 // return no more than $CFG->courseoverviewfileslimit files
2241 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
2247 // ====== magic methods =======
2249 public function __isset($name) {
2250 return isset($this->record->$name);
2254 * Magic method to get a course property
2256 * Returns any field from table course (from cache or from DB) and/or special field 'hassummary'
2258 * @param string $name
2261 public function __get($name) {
2263 if (property_exists($this->record, $name)) {
2264 return $this->record->$name;
2265 } else if ($name === 'summary' || $name === 'summaryformat') {
2266 // retrieve fields summary and summaryformat together because they are most likely to be used together
2267 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
2268 $this->record->summary = $record->summary;
2269 $this->record->summaryformat = $record->summaryformat;
2270 return $this->record->$name;
2271 } else if (array_key_exists($name, $DB->get_columns('course'))) {
2272 // another field from table 'course' that was not retrieved
2273 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
2274 return $this->record->$name;
2276 debugging('Invalid course property accessed! '.$name);
2281 * ALl properties are read only, sorry.
2282 * @param string $name
2284 public function __unset($name) {
2285 debugging('Can not unset '.get_class($this).' instance properties!');
2289 * Magic setter method, we do not want anybody to modify properties from the outside
2290 * @param string $name
2291 * @param mixed $value
2293 public function __set($name, $value) {
2294 debugging('Can not change '.get_class($this).' instance properties!');
2297 // ====== implementing method from interface IteratorAggregate ======
2300 * Create an iterator because magic vars can't be seen by 'foreach'.
2301 * Exclude context fields
2303 public function getIterator() {
2304 $ret = array('id' => $this->record->id);
2305 foreach ($this->record as $property => $value) {
2306 $ret[$property] = $value;
2308 return new ArrayIterator($ret);
2313 * An array of records that is sortable by many fields.
2315 * For more info on the ArrayObject class have a look at php.net.
2318 * @subpackage course
2319 * @copyright 2013 Sam Hemelryk
2320 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2322 class coursecat_sortable_records extends ArrayObject {
2325 * An array of sortable fields.
2326 * Gets set temporarily when sort is called.
2329 protected $sortfields = array();
2332 * Sorts this array using the given fields.
2334 * @param array $records
2335 * @param array $fields
2338 public static function sort(array $records, array $fields) {
2339 $records = new coursecat_sortable_records($records);
2340 $records->sortfields = $fields;
2341 $records->uasort(array($records, 'sort_by_many_fields'));
2342 return $records->getArrayCopy();
2346 * Sorts the two records based upon many fields.
2348 * This method should not be called itself, please call $sort instead.
2349 * It has been marked as access private as such.
2352 * @param stdClass $a
2353 * @param stdClass $b
2356 public function sort_by_many_fields($a, $b) {
2357 foreach ($this->sortfields as $field => $mult) {
2359 if (is_null($a->$field) && !is_null($b->$field)) {
2362 if (is_null($b->$field) && !is_null($a->$field)) {
2366 if (is_string($a->$field) || is_string($b->$field)) {
2368 if ($cmp = strcoll($a->$field, $b->$field)) {
2369 return $mult * $cmp;
2373 if ($a->$field > $b->$field) {
2376 if ($a->$field < $b->$field) {