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
33 * @copyright 2013 Marina Glancy
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 class coursecat implements renderable, cacheable_object, IteratorAggregate {
37 /** @var coursecat stores pseudo category with id=0. Use coursecat::get(0) to retrieve */
38 protected static $coursecat0;
40 /** @var array list of all fields and their short name and default value for caching */
41 protected static $coursecatfields = array(
42 'id' => array('id', 0),
43 'name' => array('na', ''),
44 'idnumber' => array('in', null),
45 'description' => null, // not cached
46 'descriptionformat' => null, // not cached
47 'parent' => array('pa', 0),
48 'sortorder' => array('so', 0),
49 'coursecount' => null, // not cached
50 'visible' => array('vi', 1),
51 'visibleold' => null, // not cached
52 'timemodified' => null, // not cached
53 'depth' => array('dh', 1),
54 'path' => array('ph', null),
55 'theme' => null, // not cached
65 protected $idnumber = null;
68 protected $description = false;
71 protected $descriptionformat = false;
74 protected $parent = 0;
77 protected $sortorder = 0;
80 protected $coursecount = false;
83 protected $visible = 1;
86 protected $visibleold = false;
89 protected $timemodified = false;
98 protected $theme = false;
101 protected $fromcache;
103 // ====== magic methods =======
106 * Magic setter method, we do not want anybody to modify properties from the outside
108 * @param string $name
109 * @param mixed $value
111 public function __set($name, $value) {
112 debugging('Can not change coursecat instance properties!', DEBUG_DEVELOPER);
116 * Magic method getter, redirects to read only values. Queries from DB the fields that were not cached
118 * @param string $name
121 public function __get($name) {
123 if (array_key_exists($name, self::$coursecatfields)) {
124 if ($this->$name === false) {
125 // property was not retrieved from DB, retrieve all not retrieved fields
126 $notretrievedfields = array_diff_key(self::$coursecatfields, array_filter(self::$coursecatfields));
127 $record = $DB->get_record('course_categories', array('id' => $this->id),
128 join(',', array_keys($notretrievedfields)), MUST_EXIST);
129 foreach ($record as $key => $value) {
130 $this->$key = $value;
135 debugging('Invalid coursecat property accessed! '.$name, DEBUG_DEVELOPER);
140 * Full support for isset on our magic read only properties.
142 * @param string $name
145 public function __isset($name) {
146 if (array_key_exists($name, self::$coursecatfields)) {
147 return isset($this->$name);
153 * All properties are read only, sorry.
155 * @param string $name
157 public function __unset($name) {
158 debugging('Can not unset coursecat instance properties!', DEBUG_DEVELOPER);
162 * Create an iterator because magic vars can't be seen by 'foreach'.
164 * implementing method from interface IteratorAggregate
166 * @return ArrayIterator
168 public function getIterator() {
170 foreach (self::$coursecatfields as $property => $unused) {
171 if ($this->$property !== false) {
172 $ret[$property] = $this->$property;
175 return new ArrayIterator($ret);
181 * Constructor is protected, use coursecat::get($id) to retrieve category
183 * @param stdClass $record record from DB (may not contain all fields)
184 * @param bool $fromcache whether it is being restored from cache
186 protected function __construct(stdClass $record, $fromcache = false) {
187 context_helper::preload_from_record($record);
188 foreach ($record as $key => $val) {
189 if (array_key_exists($key, self::$coursecatfields)) {
193 $this->fromcache = $fromcache;
197 * Returns coursecat object for requested category
199 * If category is not visible to user it is treated as non existing
200 * unless $alwaysreturnhidden is set to true
202 * If id is 0, the pseudo object for root category is returned (convenient
203 * for calling other functions such as get_children())
205 * @param int $id category id
206 * @param int $strictness whether to throw an exception (MUST_EXIST) or
207 * return null (IGNORE_MISSING) in case the category is not found or
208 * not visible to current user
209 * @param bool $alwaysreturnhidden set to true if you want an object to be
210 * returned even if this category is not visible to the current user
211 * (category is hidden and user does not have
212 * 'moodle/category:viewhiddencategories' capability). Use with care!
213 * @return null|coursecat
215 public static function get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false) {
217 if (!isset(self::$coursecat0)) {
218 $record = new stdClass();
220 $record->visible = 1;
223 self::$coursecat0 = new coursecat($record);
225 return self::$coursecat0;
227 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
228 $coursecat = $coursecatrecordcache->get($id);
229 if ($coursecat === false) {
230 if ($records = self::get_records('cc.id = :id', array('id' => $id))) {
231 $record = reset($records);
232 $coursecat = new coursecat($record);
234 $coursecatrecordcache->set($id, $coursecat);
237 if ($coursecat && ($alwaysreturnhidden || $coursecat->is_uservisible())) {
240 if ($strictness == MUST_EXIST) {
241 throw new moodle_exception('unknowcategory');
248 * Returns the first found category
250 * Note that if there are no categories visible to the current user on the first level,
251 * the invisible category may be returned
255 public static function get_default() {
256 if ($visiblechildren = self::get(0)->get_children()) {
257 $defcategory = reset($visiblechildren);
259 $toplevelcategories = self::get_tree(0);
260 $defcategoryid = $toplevelcategories[0];
261 $defcategory = self::get($defcategoryid, MUST_EXIST, true);
267 * Restores the object after it has been externally modified in DB for example
268 * during {@link fix_course_sortorder()}
270 protected function restore() {
271 // update all fields in the current object
272 $newrecord = self::get($this->id, MUST_EXIST, true);
273 foreach (self::$coursecatfields as $key => $unused) {
274 $this->$key = $newrecord->$key;
279 * Creates a new category either from form data or from raw data
281 * Please note that this function does not verify access control.
283 * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
285 * Category visibility is inherited from parent unless $data->visible = 0 is specified
287 * @param array|stdClass $data
288 * @param array $editoroptions if specified, the data is considered to be
289 * form data and file_postupdate_standard_editor() is being called to
290 * process images in description.
292 * @throws moodle_exception
294 public static function create($data, $editoroptions = null) {
296 $data = (object)$data;
297 $newcategory = new stdClass();
299 $newcategory->descriptionformat = FORMAT_MOODLE;
300 $newcategory->description = '';
301 // copy all description* fields regardless of whether this is form data or direct field update
302 foreach ($data as $key => $value) {
303 if (preg_match("/^description/", $key)) {
304 $newcategory->$key = $value;
308 if (empty($data->name)) {
309 throw new moodle_exception('categorynamerequired');
311 if (textlib::strlen($data->name) > 255) {
312 throw new moodle_exception('categorytoolong');
314 $newcategory->name = $data->name;
316 // validate and set idnumber
317 if (!empty($data->idnumber)) {
318 if (textlib::strlen($data->idnumber) > 100) {
319 throw new moodle_exception('idnumbertoolong');
321 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
322 throw new moodle_exception('categoryidnumbertaken');
325 if (isset($data->idnumber)) {
326 $newcategory->idnumber = $data->idnumber;
329 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
330 $newcategory->theme = $data->theme;
333 if (empty($data->parent)) {
334 $parent = self::get(0);
336 $parent = self::get($data->parent, MUST_EXIST, true);
338 $newcategory->parent = $parent->id;
339 $newcategory->depth = $parent->depth + 1;
341 // By default category is visible, unless visible = 0 is specified or parent category is hidden
342 if (isset($data->visible) && !$data->visible) {
343 // create a hidden category
344 $newcategory->visible = $newcategory->visibleold = 0;
346 // create a category that inherits visibility from parent
347 $newcategory->visible = $parent->visible;
348 // in case parent is hidden, when it changes visibility this new subcategory will automatically become visible too
349 $newcategory->visibleold = 1;
352 $newcategory->sortorder = 0;
353 $newcategory->timemodified = time();
355 $newcategory->id = $DB->insert_record('course_categories', $newcategory);
357 // update path (only possible after we know the category id
358 $path = $parent->path . '/' . $newcategory->id;
359 $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));
361 // We should mark the context as dirty
362 context_coursecat::instance($newcategory->id)->mark_dirty();
364 fix_course_sortorder();
366 // if this is data from form results, save embedded files and update description
367 $categorycontext = context_coursecat::instance($newcategory->id);
368 if ($editoroptions) {
369 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext, 'coursecat', 'description', 0);
371 // update only fields description and descriptionformat
372 $updatedata = new stdClass();
373 $updatedata->id = $newcategory->id;
374 $updatedata->description = $newcategory->description;
375 $updatedata->descriptionformat = $newcategory->descriptionformat;
376 $DB->update_record('course_categories', $updatedata);
379 add_to_log(SITEID, "category", 'add', "editcategory.php?id=$newcategory->id", $newcategory->id);
380 cache_helper::purge_by_event('changesincoursecat');
382 return self::get($newcategory->id, MUST_EXIST, true);
386 * Updates the record with either form data or raw data
388 * Please note that this function does not verify access control.
390 * This function calls coursecat::change_parent_raw if field 'parent' is updated.
391 * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
392 * Visibility is changed first and then parent is changed. This means that
393 * if parent category is hidden, the current category will become hidden
394 * too and it may overwrite whatever was set in field 'visible'.
396 * Note that fields 'path' and 'depth' can not be updated manually
397 * Also coursecat::update() can not directly update the field 'sortoder'
399 * @param array|stdClass $data
400 * @param array $editoroptions if specified, the data is considered to be
401 * form data and file_postupdate_standard_editor() is being called to
402 * process images in description.
403 * @throws moodle_exception
405 public function update($data, $editoroptions = null) {
408 // there is no actual DB record associated with root category
412 $data = (object)$data;
413 $newcategory = new stdClass();
414 $newcategory->id = $this->id;
416 // copy all description* fields regardless of whether this is form data or direct field update
417 foreach ($data as $key => $value) {
418 if (preg_match("/^description/", $key)) {
419 $newcategory->$key = $value;
423 if (isset($data->name) && empty($data->name)) {
424 throw new moodle_exception('categorynamerequired');
427 if (!empty($data->name) && $data->name !== $this->name) {
428 if (textlib::strlen($data->name) > 255) {
429 throw new moodle_exception('categorytoolong');
431 $newcategory->name = $data->name;
434 if (isset($data->idnumber) && $data->idnumber != $this->idnumber) {
435 if (textlib::strlen($data->idnumber) > 100) {
436 throw new moodle_exception('idnumbertoolong');
438 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
439 throw new moodle_exception('categoryidnumbertaken');
441 $newcategory->idnumber = $data->idnumber;
444 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
445 $newcategory->theme = $data->theme;
449 if (isset($data->visible)) {
450 if ($data->visible) {
451 $changes = $this->show_raw();
453 $changes = $this->hide_raw(0);
457 if (isset($data->parent) && $data->parent != $this->parent) {
459 cache_helper::purge_by_event('changesincoursecat');
461 $parentcat = self::get($data->parent, MUST_EXIST, true);
462 $this->change_parent_raw($parentcat);
463 fix_course_sortorder();
466 $newcategory->timemodified = time();
468 if ($editoroptions) {
469 $categorycontext = context_coursecat::instance($this->id);
470 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext, 'coursecat', 'description', 0);
472 $DB->update_record('course_categories', $newcategory);
473 add_to_log(SITEID, "category", 'update', "editcategory.php?id=$this->id", $this->id);
474 fix_course_sortorder();
475 // purge cache even if fix_course_sortorder() did not do it
476 cache_helper::purge_by_event('changesincoursecat');
478 // update all fields in the current object
483 * Checks if this course category is visible to current user
485 * Please note that methods coursecat::get (without 3rd argumet),
486 * coursecat::get_children(), etc. return only visible categories so it is
487 * usually not needed to call this function outside of this class
491 public function is_uservisible() {
492 return !$this->id || $this->visible ||
493 has_capability('moodle/category:viewhiddencategories',
494 context_coursecat::instance($this->id));
498 * Returns all categories visible to the current user
500 * This is a generic function that returns an array of
501 * (category id => coursecat object) sorted by sortorder
503 * @see coursecat::get_children()
504 * @see coursecat::get_all_parents()
506 * @return cacheable_object_array array of coursecat objects
508 public static function get_all_visible() {
510 $coursecatcache = cache::make('core', 'coursecat');
511 $ids = $coursecatcache->get('user'. $USER->id);
512 if ($ids === false) {
513 $all = self::get_all_ids();
514 $parentvisible = $all[0];
516 foreach ($all as $id => $children) {
517 if ($id && in_array($id, $parentvisible) &&
518 ($coursecat = self::get($id, IGNORE_MISSING)) &&
519 (!$coursecat->parent || isset($rv[$coursecat->parent]))) {
520 $rv[$id] = $coursecat;
521 $parentvisible += $children;
524 $coursecatcache->set('user'. $USER->id, array_keys($rv));
527 foreach ($ids as $id) {
528 if ($coursecat = self::get($id, IGNORE_MISSING)) {
529 $rv[$id] = $coursecat;
537 * Returns the entry from categories tree and makes sure the application-level tree cache is built
539 * The following keys can be requested:
541 * 'countall' - total number of categories in the system (always present)
542 * 0 - array of ids of top-level categories (always present)
543 * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
544 * $id (int) - array of ids of categories that are direct children of category with id $id. If
545 * category with id $id does not exist returns false. If category has no children returns empty array
546 * $id.'i' - array of ids of children categories that have visible=0
548 * @param int|string $id
551 protected static function get_tree($id) {
553 $coursecattreecache = cache::make('core', 'coursecattree');
554 $rv = $coursecattreecache->get($id);
558 // We did not find the entry in cache but it also can mean that tree is not built.
559 // The keys 0 and 'countall' must always be present if tree is built.
560 if ($id !== 0 && $id !== 'countall' && $coursecattreecache->has('countall')) {
561 // Tree was built, it means the non-existing $id was requested.
564 // Re-build the tree.
565 $sql = "SELECT cc.id, cc.parent, cc.visible
566 FROM {course_categories} cc
567 ORDER BY cc.sortorder";
568 $rs = $DB->get_recordset_sql($sql, array());
569 $all = array(0 => array(), '0i' => array());
571 foreach ($rs as $record) {
572 $all[$record->id] = array();
573 $all[$record->id. 'i'] = array();
574 if (array_key_exists($record->parent, $all)) {
575 $all[$record->parent][] = $record->id;
576 if (!$record->visible) {
577 $all[$record->parent. 'i'][] = $record->id;
580 // parent not found. This is data consistency error but next fix_course_sortorder() should fix it
581 $all[0][] = $record->id;
587 // No categories found.
588 // This may happen after upgrade from very old moodle version. In new versions the default category is created on install.
589 $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
590 set_config('defaultrequestcategory', $defcoursecat->id);
591 $all[0] = array($defcoursecat->id);
592 $all[$defcoursecat->id] = array();
595 $all['countall'] = $count;
596 foreach ($all as $key => $children) {
597 $coursecattreecache->set($key, $children);
599 if (array_key_exists($id, $all)) {
606 * Returns number of ALL categories in the system regardless if
607 * they are visible to current user or not
611 public static function count_all() {
612 return self::get_tree('countall');
616 * Retrieves number of records from course_categories table
618 * Only cached fields are retrieved. Records are ready for preloading context
620 * @param string $whereclause
621 * @param array $params
622 * @return array array of stdClass objects
624 protected static function get_records($whereclause, $params) {
626 // Retrieve from DB only the fields that need to be stored in cache
627 $fields = array_keys(array_filter(self::$coursecatfields));
628 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
629 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
630 FROM {course_categories} cc
631 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
632 WHERE ". $whereclause." ORDER BY cc.sortorder";
633 return $DB->get_records_sql($sql,
634 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
638 * Given list of DB records from table course populates each record with list of users with course contact roles
640 * This function fills the courses with raw information as {@link get_role_users()} would do.
641 * See also {@link course_in_list::get_course_contacts()} for more readable return
643 * $courses[$i]->managers = array(
644 * $roleassignmentid => $roleuser,
648 * where $roleuser is an stdClass with the following properties:
650 * $roleuser->raid - role assignment id
651 * $roleuser->id - user id
652 * $roleuser->username
653 * $roleuser->firstname
654 * $roleuser->lastname
655 * $roleuser->rolecoursealias
656 * $roleuser->rolename
657 * $roleuser->sortorder - role sortorder
659 * $roleuser->roleshortname
661 * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
663 * @param array $courses
665 public static function preload_course_contacts(&$courses) {
667 if (empty($courses) || empty($CFG->coursecontact)) {
670 $managerroles = explode(',', $CFG->coursecontact);
672 // TODO MDL-38596, this commented code is similar to get_courses_wmanagers()
673 // It bulk-preloads course contacts for all courses BUT it does not check enrolments
675 // first build the array of all context ids of the courses and their categories
676 $allcontexts = array();
677 foreach (array_keys($courses) as $id) {
678 $context = context_course::instance($id);
679 $courses[$id]->managers = array();
680 foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
681 if (!isset($allcontexts[$ctxid])) {
682 $allcontexts[$ctxid] = array();
684 $allcontexts[$ctxid][] = $id;
688 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
689 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
690 list($sort, $sortparams) = users_order_by_sql('u');
691 $sql = "SELECT ra.contextid, ra.id AS raid,
692 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
693 rn.name AS rolecoursealias, u.id, u.username, u.firstname, u.lastname
694 FROM {role_assignments} ra
695 JOIN {user} u ON ra.userid = u.id
696 JOIN {role} r ON ra.roleid = r.id
697 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
698 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2."
699 ORDER BY r.sortorder, $sort";
700 $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $sortparams);
701 foreach($rs as $ra) {
702 foreach ($allcontexts[$ra->contextid] as $id) {
703 $courses[$id]->managers[$ra->raid] = $ra;
708 list($sort, $sortparams) = users_order_by_sql('u');
709 foreach (array_keys($courses) as $id) {
710 $context = context_course::instance($id);
711 $courses[$id]->managers = get_role_users($managerroles, $context, true,
712 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
713 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
714 'r.sortorder ASC, ' . $sort, false, '', '', '', '', $sortparams);
719 * Retrieves number of records from course table
721 * Not all fields are retrieved. Records are ready for preloading context
723 * @param string $whereclause
724 * @param array $params
725 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
726 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
727 * on not visible courses
728 * @return array array of stdClass objects
730 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
732 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
733 $fields = array('c.id', 'c.category', 'c.sortorder',
734 'c.shortname', 'c.fullname', 'c.idnumber',
735 'c.startdate', 'c.visible');
736 if (!empty($options['summary'])) {
737 $fields[] = 'c.summary';
738 $fields[] = 'c.summaryformat';
740 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' hassummary';
742 $sql = "SELECT ". join(',', $fields). ", $ctxselect
744 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
745 WHERE ". $whereclause." ORDER BY c.sortorder";
746 $list = $DB->get_records_sql($sql,
747 array('contextcourse' => CONTEXT_COURSE) + $params);
749 if ($checkvisibility) {
750 // Loop through all records and make sure we only return the courses accessible by user.
751 foreach ($list as $course) {
752 if (isset($list[$course->id]->hassummary)) {
753 $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
755 if (empty($course->visible)) {
756 // load context only if we need to check capability
757 context_helper::preload_from_record($course);
758 if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
759 unset($list[$course->id]);
765 // preload course contacts if necessary
766 if (!empty($options['coursecontacts'])) {
767 self::preload_course_contacts($list);
773 * Returns array of ids of children categories that current user can not see
775 * This data is cached in user session cache
779 protected function get_not_visible_children_ids() {
781 $coursecatcache = cache::make('core', 'coursecat');
782 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
783 // we never checked visible children before
784 $hidden = self::get_tree($this->id.'i');
785 $invisibleids = array();
787 // preload categories contexts
788 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
789 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
790 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
791 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
792 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
793 foreach ($contexts as $record) {
794 context_helper::preload_from_record($record);
796 // check that user has 'viewhiddencategories' capability for each hidden category
797 foreach ($hidden as $id) {
798 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
799 $invisibleids[] = $id;
803 $coursecatcache->set('ic'. $this->id, $invisibleids);
805 return $invisibleids;
809 * Sorts list of records by several fields
811 * @param array $records array of stdClass objects
812 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
815 protected static function sort_records(&$records, $sortfields) {
816 if (empty($records)) {
819 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname)
820 if (array_key_exists('displayname', $sortfields)) {
821 foreach ($records as $key => $record) {
822 if (!isset($record->displayname)) {
823 $records[$key]->displayname = get_course_display_name_for_list($record);
827 // sorting by one field - use collatorlib
828 if (count($sortfields) == 1) {
829 $property = key($sortfields);
830 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
831 $sortflag = collatorlib::SORT_NUMERIC;
832 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
833 $sortflag = collatorlib::SORT_STRING;
835 $sortflag = collatorlib::SORT_REGULAR;
837 collatorlib::asort_objects_by_property($records, $property, $sortflag);
838 if ($sortfields[$property] < 0) {
839 $records = array_reverse($records, true);
843 $records = coursecat_sortable_records::sort($records, $sortfields);
847 * Returns array of children categories visible to the current user
849 * @param array $options options for retrieving children
850 * - sort - list of fields to sort. Example
851 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
852 * will sort by idnumber asc, name asc and id desc.
853 * Default: array('sortorder' => 1)
854 * Only cached fields may be used for sorting!
856 * - limit - maximum number of children to return, 0 or null for no limit
857 * @return array of coursecat objects indexed by category id
859 public function get_children($options = array()) {
861 $coursecatcache = cache::make('core', 'coursecat');
863 // get default values for options
864 if (!empty($options['sort']) && is_array($options['sort'])) {
865 $sortfields = $options['sort'];
867 $sortfields = array('sortorder' => 1);
870 if (!empty($options['limit']) && (int)$options['limit']) {
871 $limit = (int)$options['limit'];
874 if (!empty($options['offset']) && (int)$options['offset']) {
875 $offset = (int)$options['offset'];
878 // first retrieve list of user-visible and sorted children ids from cache
879 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
880 if ($sortedids === false) {
881 $sortfieldskeys = array_keys($sortfields);
882 if ($sortfieldskeys[0] === 'sortorder') {
883 // no DB requests required to build the list of ids sorted by sortorder.
884 // We can easily ignore other sort fields because sortorder is always different
885 $sortedids = self::get_tree($this->id);
886 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
887 $sortedids = array_diff($sortedids, $invisibleids);
888 if ($sortfields['sortorder'] == -1) {
889 $sortedids = array_reverse($sortedids, true);
893 // we need to retrieve and sort all children. Good thing that it is done only on first request
894 if ($invisibleids = $this->get_not_visible_children_ids()) {
895 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
896 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
897 array('parent' => $this->id) + $params);
899 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
901 self::sort_records($records, $sortfields);
902 $sortedids = array_keys($records);
904 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
907 if (empty($sortedids)) {
911 // now retrieive and return categories
912 if ($offset || $limit) {
913 $sortedids = array_slice($sortedids, $offset, $limit);
915 if (isset($records)) {
916 // easy, we have already retrieved records
917 if ($offset || $limit) {
918 $records = array_slice($records, $offset, $limit, true);
921 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
922 $records = self::get_records('cc.id '. $sql,
923 array('parent' => $this->id) + $params);
927 foreach ($sortedids as $id) {
928 if (isset($records[$id])) {
929 $rv[$id] = new coursecat($records[$id]);
936 * Returns number of subcategories visible to the current user
940 public function get_children_count() {
941 $sortedids = self::get_tree($this->id);
942 $invisibleids = $this->get_not_visible_children_ids();
943 return count($sortedids) - count($invisibleids);
947 * Returns true if the category has ANY children, including those not visible to the user
951 public function has_children() {
952 $allchildren = self::get_tree($this->id);
953 return !empty($allchildren);
957 * Returns true if the category has courses in it (count does not include courses
958 * in child categories)
962 public function has_courses() {
964 return $DB->record_exists_sql("select 1 from {course} where category = ?",
971 * List of found course ids is cached for 10 minutes. Cache may be purged prior
972 * to this when somebody edits courses or categories, however it is very
973 * difficult to keep track of all possible changes that may affect list of courses.
975 * @param array $search contains search criterias, such as:
976 * - search - search string
977 * - blocklist - id of block (if we are searching for courses containing specific block0
978 * - modulelist - name of module (if we are searching for courses containing specific module
979 * - tagid - id of tag
980 * @param array $options display options, same as in get_courses() except 'recursive' is ignored - search is always category-independent
983 public static function search_courses($search, $options = array()) {
985 $offset = !empty($options['offset']) ? $options['offset'] : 0;
986 $limit = !empty($options['limit']) ? $options['limit'] : null;
987 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
989 $coursecatcache = cache::make('core', 'coursecat');
990 $cachekey = 's-'. serialize($search + array('sort' => $sortfields));
991 $cntcachekey = 'scnt-'. serialize($search);
993 $ids = $coursecatcache->get($cachekey);
994 if ($ids !== false) {
995 // we already cached last search result
996 $ids = array_slice($ids, $offset, $limit);
999 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1000 $records = self::get_course_records("c.id ". $sql, $params, $options);
1001 foreach ($ids as $id) {
1002 $courses[$id] = new course_in_list($records[$id]);
1008 $preloadcoursecontacts = !empty($options['coursecontacts']);
1009 unset($options['coursecontacts']);
1011 if (!empty($search['search'])) {
1012 // search courses that have specified words in their names/summaries
1013 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1014 $searchterms = array_filter($searchterms, create_function('$v', 'return strlen($v) > 1;'));
1015 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount);
1016 self::sort_records($courselist, $sortfields);
1017 $coursecatcache->set($cachekey, array_keys($courselist));
1018 $coursecatcache->set($cntcachekey, $totalcount);
1019 $records = array_slice($courselist, $offset, $limit, true);
1021 if (!empty($search['blocklist'])) {
1022 // search courses that have block with specified id
1023 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1024 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1025 WHERE bi.blockname = :blockname)';
1026 $params = array('blockname' => $blockname);
1027 } else if (!empty($search['modulelist'])) {
1028 // search courses that have module with specified name
1029 $where = "c.id IN (SELECT DISTINCT module.course ".
1030 "FROM {".$search['modulelist']."} module)";
1032 } else if (!empty($search['tagid'])) {
1033 // search courses that are tagged with the specified tag
1034 $where = "c.id IN (SELECT t.itemid ".
1035 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype)";
1036 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course');
1038 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1041 $courselist = self::get_course_records($where, $params, $options, true);
1042 self::sort_records($courselist, $sortfields);
1043 $coursecatcache->set($cachekey, array_keys($courselist));
1044 $coursecatcache->set($cntcachekey, count($courselist));
1045 $records = array_slice($courselist, $offset, $limit, true);
1048 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1049 if (!empty($preloadcoursecontacts)) {
1050 self::preload_course_contacts($records);
1053 foreach ($records as $record) {
1054 $courses[$record->id] = new course_in_list($record);
1060 * Returns number of courses in the search results
1062 * It is recommended to call this function after {@link coursecat::search_courses()}
1063 * and not before because only course ids are cached. Otherwise search_courses() may
1064 * perform extra DB queries.
1066 * @param array $search search criteria, see method search_courses() for more details
1067 * @param array $options display options. They do not affect the result but
1068 * the 'sort' property is used in cache key for storing list of course ids
1071 public static function search_courses_count($search, $options = array()) {
1072 $coursecatcache = cache::make('core', 'coursecat');
1073 $cntcachekey = 'scnt-'. serialize($search);
1074 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1075 self::search_courses($search, $options);
1076 $cnt = $coursecatcache->get($cntcachekey);
1082 * Retrieves the list of courses accessible by user
1084 * Not all information is cached, try to avoid calling this method
1085 * twice in the same request.
1087 * The following fields are always retrieved:
1088 * - id, visible, fullname, shortname, idnumber, category, sortorder
1090 * If you plan to use properties/methods course_in_list::$summary and/or
1091 * course_in_list::get_course_contacts()
1092 * you can preload this information using appropriate 'options'. Otherwise
1093 * they will be retrieved from DB on demand and it may end with bigger DB load.
1095 * Note that method course_in_list::has_summary() will not perform additional
1096 * DB queries even if $options['summary'] is not specified
1098 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1099 * to this when somebody edits courses or categories, however it is very
1100 * difficult to keep track of all possible changes that may affect list of courses.
1102 * @param array $options options for retrieving children
1103 * - recursive - return courses from subcategories as well. Use with care,
1104 * this may be a huge list!
1105 * - summary - preloads fields 'summary' and 'summaryformat'
1106 * - coursecontacts - preloads course contacts
1107 * - sort - list of fields to sort. Example
1108 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1109 * will sort by idnumber asc, shortname asc and id desc.
1110 * Default: array('sortorder' => 1)
1111 * Only cached fields may be used for sorting!
1113 * - limit - maximum number of children to return, 0 or null for no limit
1114 * @return array array of instances of course_in_list
1116 public function get_courses($options = array()) {
1118 $recursive = !empty($options['recursive']);
1119 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1120 $limit = !empty($options['limit']) ? $options['limit'] : null;
1121 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1123 // Check if this category is hidden.
1124 // Also 0-category never has courses unless this is recursive call.
1125 if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1129 $coursecatcache = cache::make('core', 'coursecat');
1130 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1131 '-'. serialize($sortfields);
1132 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1134 // check if we have already cached results
1135 $ids = $coursecatcache->get($cachekey);
1136 if ($ids !== false) {
1137 // we already cached last search result and it did not expire yet
1138 $ids = array_slice($ids, $offset, $limit);
1141 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1142 $records = self::get_course_records("c.id ". $sql, $params, $options);
1143 foreach ($ids as $id) {
1144 $courses[$id] = new course_in_list($records[$id]);
1150 // retrieve list of courses in category
1151 $where = 'c.id <> :siteid';
1152 $params = array('siteid' => SITEID);
1155 $context = context_coursecat::instance($this->id);
1156 $where .= ' AND ctx.path like :path';
1157 $params['path'] = $context->path. '/%';
1160 $where .= ' AND c.category = :categoryid';
1161 $params['categoryid'] = $this->id;
1163 // get list of courses without preloaded coursecontacts because we don't need them for every course
1164 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1166 // sort and cache list
1167 self::sort_records($list, $sortfields);
1168 $coursecatcache->set($cachekey, array_keys($list));
1169 $coursecatcache->set($cntcachekey, count($list));
1171 // Apply offset/limit, convert to course_in_list and return.
1174 if ($offset || $limit) {
1175 $list = array_slice($list, $offset, $limit, true);
1177 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1178 if (!empty($options['coursecontacts'])) {
1179 self::preload_course_contacts($list);
1181 foreach ($list as $record) {
1182 $courses[$record->id] = new course_in_list($record);
1189 * Returns number of courses visible to the user
1191 * @param array $options similar to get_courses() except some options do not affect
1192 * number of courses (i.e. sort, summary, offset, limit etc.)
1195 public function get_courses_count($options = array()) {
1196 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1197 $coursecatcache = cache::make('core', 'coursecat');
1198 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1199 $this->get_courses($options);
1200 $cnt = $coursecatcache->get($cntcachekey);
1206 * Returns true if user can delete current category and all its contents
1208 * To be able to delete course category the user must have permission
1209 * 'moodle/category:manage' in ALL child course categories AND
1210 * be able to delete all courses
1214 public function can_delete_full() {
1221 $context = context_coursecat::instance($this->id);
1222 if (!$this->is_uservisible() ||
1223 !has_capability('moodle/category:manage', $context)) {
1227 // Check all child categories (not only direct children)
1228 $sql = context_helper::get_preload_record_columns_sql('ctx');
1229 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1230 ' FROM {context} ctx '.
1231 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1232 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1233 array($context->path. '/%', CONTEXT_COURSECAT));
1234 foreach ($childcategories as $childcat) {
1235 context_helper::preload_from_record($childcat);
1236 $childcontext = context_coursecat::instance($childcat->id);
1237 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1238 !has_capability('moodle/category:manage', $childcontext)) {
1244 $sql = context_helper::get_preload_record_columns_sql('ctx');
1245 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1246 $sql. ' FROM {context} ctx '.
1247 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1248 array('pathmask' => $context->path. '/%',
1249 'courselevel' => CONTEXT_COURSE));
1250 foreach ($coursescontexts as $ctxrecord) {
1251 context_helper::preload_from_record($ctxrecord);
1252 if (!can_delete_course($ctxrecord->courseid)) {
1261 * Recursively delete category including all subcategories and courses
1263 * Function {@link coursecat::can_delete_full()} MUST be called prior
1264 * to calling this function because there is no capability check
1265 * inside this function
1267 * @param boolean $showfeedback display some notices
1268 * @return array return deleted courses
1270 public function delete_full($showfeedback = true) {
1272 require_once($CFG->libdir.'/gradelib.php');
1273 require_once($CFG->libdir.'/questionlib.php');
1274 require_once($CFG->dirroot.'/cohort/lib.php');
1276 $deletedcourses = array();
1278 // Get children. Note, we don't want to use cache here because
1279 // it would be rebuilt too often
1280 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1281 foreach ($children as $record) {
1282 $coursecat = new coursecat($record);
1283 $deletedcourses += $coursecat->delete_full($showfeedback);
1286 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1287 foreach ($courses as $course) {
1288 if (!delete_course($course, false)) {
1289 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1291 $deletedcourses[] = $course;
1295 // move or delete cohorts in this context
1296 cohort_delete_category($this);
1298 // now delete anything that may depend on course category context
1299 grade_course_category_delete($this->id, 0, $showfeedback);
1300 if (!question_delete_course_category($this, 0, $showfeedback)) {
1301 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1304 // finally delete the category and it's context
1305 $DB->delete_records('course_categories', array('id' => $this->id));
1306 delete_context(CONTEXT_COURSECAT, $this->id);
1307 add_to_log(SITEID, "category", "delete", "index.php", "$this->name (ID $this->id)");
1309 cache_helper::purge_by_event('changesincoursecat');
1311 events_trigger('course_category_deleted', $this);
1313 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1314 if ($this->id == $CFG->defaultrequestcategory) {
1315 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1317 return $deletedcourses;
1321 * Checks if user can delete this category and move content (courses, subcategories and questions)
1322 * to another category. If yes returns the array of possible target categories names
1324 * If user can not manage this category or it is completely empty - empty array will be returned
1328 public function move_content_targets_list() {
1330 require_once($CFG->libdir . '/questionlib.php');
1331 $context = context_coursecat::instance($this->id);
1332 if (!$this->is_uservisible() ||
1333 !has_capability('moodle/category:manage', $context)) {
1334 // User is not able to manage current category, he is not able to delete it.
1335 // No possible target categories.
1339 $testcaps = array();
1340 // If this category has courses in it, user must have 'course:create' capability in target category.
1341 if ($this->has_courses()) {
1342 $testcaps[] = 'moodle/course:create';
1344 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1345 if ($this->has_children() || question_context_has_any_questions($context)) {
1346 $testcaps[] = 'moodle/category:manage';
1348 if (!empty($testcaps)) {
1349 // return list of categories excluding this one and it's children
1350 return self::make_categories_list($testcaps, $this->id);
1353 // Category is completely empty, no need in target for contents.
1358 * Checks if user has capability to move all category content to the new parent before
1359 * removing this category
1361 * @param int $newcatid
1364 public function can_move_content_to($newcatid) {
1366 require_once($CFG->libdir . '/questionlib.php');
1367 $context = context_coursecat::instance($this->id);
1368 if (!$this->is_uservisible() ||
1369 !has_capability('moodle/category:manage', $context)) {
1372 $testcaps = array();
1373 // If this category has courses in it, user must have 'course:create' capability in target category.
1374 if ($this->has_courses()) {
1375 $testcaps[] = 'moodle/course:create';
1377 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1378 if ($this->has_children() || question_context_has_any_questions($context)) {
1379 $testcaps[] = 'moodle/category:manage';
1381 if (!empty($testcaps)) {
1382 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1385 // there is no content but still return true
1390 * Deletes a category and moves all content (children, courses and questions) to the new parent
1392 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1393 * must be called prior
1395 * @param int $newparentid
1396 * @param bool $showfeedback
1399 public function delete_move($newparentid, $showfeedback = false) {
1400 global $CFG, $DB, $OUTPUT;
1401 require_once($CFG->libdir.'/gradelib.php');
1402 require_once($CFG->libdir.'/questionlib.php');
1403 require_once($CFG->dirroot.'/cohort/lib.php');
1405 // get all objects and lists because later the caches will be reset so
1406 // we don't need to make extra queries
1407 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1408 $catname = $this->get_formatted_name();
1409 $children = $this->get_children();
1410 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', array('category' => $this->id));
1411 $context = context_coursecat::instance($this->id);
1414 foreach ($children as $childcat) {
1415 $childcat->change_parent_raw($newparentcat);
1417 add_to_log(SITEID, "category", "move", "editcategory.php?id=$childcat->id", $childcat->id);
1419 fix_course_sortorder();
1423 if (!move_courses($coursesids, $newparentid)) {
1424 if ($showfeedback) {
1425 echo $OUTPUT->notification("Error moving courses");
1429 if ($showfeedback) {
1430 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1434 // move or delete cohorts in this context
1435 cohort_delete_category($this);
1437 // now delete anything that may depend on course category context
1438 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1439 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1440 if ($showfeedback) {
1441 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1446 // finally delete the category and it's context
1447 $DB->delete_records('course_categories', array('id' => $this->id));
1449 add_to_log(SITEID, "category", "delete", "index.php", "$this->name (ID $this->id)");
1451 events_trigger('course_category_deleted', $this);
1453 cache_helper::purge_by_event('changesincoursecat');
1455 if ($showfeedback) {
1456 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1459 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1460 if ($this->id == $CFG->defaultrequestcategory) {
1461 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1467 * Checks if user can move current category to the new parent
1469 * This checks if new parent category exists, user has manage cap there
1470 * and new parent is not a child of this category
1472 * @param int|stdClass|coursecat $newparentcat
1475 public function can_change_parent($newparentcat) {
1476 if (!has_capability('moodle/category:manage', context_coursecat::instance($this->id))) {
1479 if (is_object($newparentcat)) {
1480 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1482 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1484 if (!$newparentcat) {
1487 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1488 // can not move to itself or it's own child
1491 if ($newparentcat->id) {
1492 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
1494 return has_capability('moodle/category:manage', context_system::instance());
1499 * Moves the category under another parent category. All associated contexts are moved as well
1501 * This is protected function, use change_parent() or update() from outside of this class
1503 * @see coursecat::change_parent()
1504 * @see coursecat::update()
1506 * @param coursecat $newparentcat
1508 protected function change_parent_raw(coursecat $newparentcat) {
1511 $context = context_coursecat::instance($this->id);
1514 if (empty($newparentcat->id)) {
1515 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1516 $newparent = context_system::instance();
1518 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1519 // can not move to itself or it's own child
1520 throw new moodle_exception('cannotmovecategory');
1522 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
1523 $newparent = context_coursecat::instance($newparentcat->id);
1525 if (!$newparentcat->visible and $this->visible) {
1526 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
1530 $this->parent = $newparentcat->id;
1532 $context->update_moved($newparent);
1534 // now make it last in new category
1535 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
1538 fix_course_sortorder();
1540 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must become visible again.
1546 * Efficiently moves a category - NOTE that this can have
1547 * a huge impact access-control-wise...
1549 * Note that this function does not check capabilities.
1552 * $coursecat = coursecat::get($categoryid);
1553 * if ($coursecat->can_change_parent($newparentcatid)) {
1554 * $coursecat->change_parent($newparentcatid);
1557 * This function does not update field course_categories.timemodified
1558 * If you want to update timemodified, use
1559 * $coursecat->update(array('parent' => $newparentcat));
1561 * @param int|stdClass|coursecat $newparentcat
1563 public function change_parent($newparentcat) {
1564 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1565 if (is_object($newparentcat)) {
1566 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
1568 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
1570 if ($newparentcat->id != $this->parent) {
1571 $this->change_parent_raw($newparentcat);
1572 fix_course_sortorder();
1573 cache_helper::purge_by_event('changesincoursecat');
1575 add_to_log(SITEID, "category", "move", "editcategory.php?id=$this->id", $this->id);
1580 * Hide course category and child course and subcategories
1582 * If this category has changed the parent and is moved under hidden
1583 * category we will want to store it's current visibility state in
1584 * the field 'visibleold'. If admin clicked 'hide' for this particular
1585 * category, the field 'visibleold' should become 0.
1587 * All subcategories and courses will have their current visibility in the field visibleold
1589 * This is protected function, use hide() or update() from outside of this class
1591 * @see coursecat::hide()
1592 * @see coursecat::update()
1594 * @param int $visibleold value to set in field $visibleold for this category
1595 * @return bool whether changes have been made and caches need to be purged afterwards
1597 protected function hide_raw($visibleold = 0) {
1601 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing
1602 if ($this->id && $this->__get('visibleold') != $visibleold) {
1603 $this->visibleold = $visibleold;
1604 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
1607 if (!$this->visible || !$this->id) {
1608 // already hidden or can not be hidden
1613 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
1614 $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
1615 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
1616 // get all child categories and hide too
1617 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
1618 foreach ($subcats as $cat) {
1619 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
1620 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
1621 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
1622 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
1629 * Hide course category and child course and subcategories
1631 * Note that there is no capability check inside this function
1633 * This function does not update field course_categories.timemodified
1634 * If you want to update timemodified, use
1635 * $coursecat->update(array('visible' => 0));
1637 public function hide() {
1638 if ($this->hide_raw(0)) {
1639 cache_helper::purge_by_event('changesincoursecat');
1640 add_to_log(SITEID, "category", "hide", "editcategory.php?id=$this->id", $this->id);
1645 * Show course category and restores visibility for child course and subcategories
1647 * Note that there is no capability check inside this function
1649 * This is protected function, use show() or update() from outside of this class
1651 * @see coursecat::show()
1652 * @see coursecat::update()
1654 * @return bool whether changes have been made and caches need to be purged afterwards
1656 protected function show_raw() {
1659 if ($this->visible) {
1665 $this->visibleold = 1;
1666 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
1667 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
1668 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
1669 // get all child categories and unhide too
1670 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
1671 foreach ($subcats as $cat) {
1672 if ($cat->visibleold) {
1673 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
1675 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
1682 * Show course category and restores visibility for child course and subcategories
1684 * Note that there is no capability check inside this function
1686 * This function does not update field course_categories.timemodified
1687 * If you want to update timemodified, use
1688 * $coursecat->update(array('visible' => 1));
1690 public function show() {
1691 if ($this->show_raw()) {
1692 cache_helper::purge_by_event('changesincoursecat');
1693 add_to_log(SITEID, "category", "show", "editcategory.php?id=$this->id", $this->id);
1698 * Returns name of the category formatted as a string
1700 * @param array $options formatting options other than context
1703 public function get_formatted_name($options = array()) {
1705 $context = context_coursecat::instance($this->id);
1706 return format_string($this->name, true, array('context' => $context) + $options);
1708 return ''; // TODO 'Top'?
1713 * Returns ids of all parents of the category. Last element in the return array is the direct parent
1715 * For example, if you have a tree of categories like:
1716 * Miscellaneous (id = 1)
1717 * Subcategory (id = 2)
1718 * Sub-subcategory (id = 4)
1719 * Other category (id = 3)
1721 * coursecat::get(1)->get_parents() == array()
1722 * coursecat::get(2)->get_parents() == array(1)
1723 * coursecat::get(4)->get_parents() == array(1, 2);
1725 * Note that this method does not check if all parents are accessible by current user
1727 * @return array of category ids
1729 public function get_parents() {
1730 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
1731 array_pop($parents);
1736 * This function returns a nice list representing category tree
1737 * for display or to use in a form <select> element
1739 * List is cached for 10 minutes
1741 * For example, if you have a tree of categories like:
1742 * Miscellaneous (id = 1)
1743 * Subcategory (id = 2)
1744 * Sub-subcategory (id = 4)
1745 * Other category (id = 3)
1746 * Then after calling this function you will have
1747 * array(1 => 'Miscellaneous',
1748 * 2 => 'Miscellaneous / Subcategory',
1749 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1750 * 3 => 'Other category');
1752 * If you specify $requiredcapability, then only categories where the current
1753 * user has that capability will be added to $list.
1754 * If you only have $requiredcapability in a child category, not the parent,
1755 * then the child catgegory will still be included.
1757 * If you specify the option $excludeid, then that category, and all its children,
1758 * are omitted from the tree. This is useful when you are doing something like
1759 * moving categories, where you do not want to allow people to move a category
1760 * to be the child of itself.
1762 * See also {@link make_categories_options()}
1764 * @param string/array $requiredcapability if given, only categories where the current
1765 * user has this capability will be returned. Can also be an array of capabilities,
1766 * in which case they are all required.
1767 * @param integer $excludeid Exclude this category and its children from the lists built.
1768 * @param string $separator string to use as a separator between parent and child category. Default ' / '
1769 * @return array of strings
1771 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
1773 $coursecatcache = cache::make('core', 'coursecat');
1775 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids with requried cap ($thislist).
1776 $basecachekey = 'catlist';
1777 $baselist = $coursecatcache->get($basecachekey);
1778 if ($baselist !== false) {
1782 if (!empty($requiredcapability)) {
1783 $requiredcapability = (array)$requiredcapability;
1784 $thiscachekey = 'catlist:'. serialize($requiredcapability);
1785 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
1786 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
1788 } else if ($baselist !== false) {
1789 $thislist = array_keys($baselist);
1792 if ($baselist === false) {
1793 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
1794 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1795 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
1796 FROM {course_categories} cc
1797 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
1798 ORDER BY cc.sortorder";
1799 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
1800 $baselist = array();
1801 $thislist = array();
1802 foreach ($rs as $record) {
1803 // If the category's parent is not visible to the user, it is not visible as well.
1804 if (!$record->parent || isset($baselist[$record->parent])) {
1805 $context = context_coursecat::instance($record->id);
1806 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
1807 // No cap to view category, added to neither $baselist nor $thislist
1810 $baselist[$record->id] = array(
1811 'name' => format_string($record->name, true, array('context' => $context)),
1812 'path' => $record->path
1814 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
1815 // No required capability, added to $baselist but not to $thislist.
1818 $thislist[] = $record->id;
1822 $coursecatcache->set($basecachekey, $baselist);
1823 if (!empty($requiredcapability)) {
1824 $coursecatcache->set($thiscachekey, join(',', $thislist));
1826 } else if ($thislist === false) {
1827 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
1828 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1829 $sql = "SELECT ctx.instanceid id, $ctxselect
1830 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
1831 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
1832 $thislist = array();
1833 foreach (array_keys($baselist) as $id) {
1834 context_helper::preload_from_record($contexts[$id]);
1835 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
1839 $coursecatcache->set($thiscachekey, join(',', $thislist));
1842 // Now build the array of strings to return, mind $separator and $excludeid.
1844 foreach ($thislist as $id) {
1845 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
1846 if (!$excludeid || !in_array($excludeid, $path)) {
1847 $namechunks = array();
1848 foreach ($path as $parentid) {
1849 $namechunks[] = $baselist[$parentid]['name'];
1851 $names[$id] = join($separator, $namechunks);
1858 * Prepares the object for caching. Works like the __sleep method.
1860 * implementing method from interface cacheable_object
1862 * @return array ready to be cached
1864 public function prepare_to_cache() {
1866 foreach (self::$coursecatfields as $property => $cachedirectives) {
1867 if ($cachedirectives !== null) {
1868 list($shortname, $defaultvalue) = $cachedirectives;
1869 if ($this->$property !== $defaultvalue) {
1870 $a[$shortname] = $this->$property;
1874 $context = context_coursecat::instance($this->id);
1875 $a['xi'] = $context->id;
1876 $a['xp'] = $context->path;
1881 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
1883 * implementing method from interface cacheable_object
1888 public static function wake_from_cache($a) {
1889 $record = new stdClass;
1890 foreach (self::$coursecatfields as $property => $cachedirectives) {
1891 if ($cachedirectives !== null) {
1892 list($shortname, $defaultvalue) = $cachedirectives;
1893 if (array_key_exists($shortname, $a)) {
1894 $record->$property = $a[$shortname];
1896 $record->$property = $defaultvalue;
1900 $record->ctxid = $a['xi'];
1901 $record->ctxpath = $a['xp'];
1902 $record->ctxdepth = $record->depth + 1;
1903 $record->ctxlevel = CONTEXT_COURSECAT;
1904 $record->ctxinstance = $record->id;
1905 return new coursecat($record, true);
1910 * Class to store information about one course in a list of courses
1912 * Not all information may be retrieved when object is created but
1913 * it will be retrieved on demand when appropriate property or method is
1916 * Instances of this class are usually returned by functions
1917 * {@link coursecat::search_courses()}
1919 * {@link coursecat::get_courses()}
1922 * @subpackage course
1923 * @copyright 2013 Marina Glancy
1924 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1926 class course_in_list implements IteratorAggregate {
1928 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
1931 /** @var array array of course contacts - stores result of call to get_course_contacts() */
1932 protected $coursecontacts;
1935 * Creates an instance of the class from record
1937 * @param stdClass $record except fields from course table it may contain
1938 * field hassummary indicating that summary field is not empty.
1939 * Also it is recommended to have context fields here ready for
1940 * context preloading
1942 public function __construct(stdClass $record) {
1943 context_instance_preload($record);
1944 $this->record = new stdClass();
1945 foreach ($record as $key => $value) {
1946 $this->record->$key = $value;
1951 * Indicates if the course has non-empty summary field
1955 public function has_summary() {
1956 if (isset($this->record->hassummary)) {
1957 return !empty($this->record->hassummary);
1959 if (!isset($this->record->summary)) {
1960 // we need to retrieve summary
1961 $this->__get('summary');
1963 return !empty($this->record->summary);
1967 * Indicates if the course have course contacts to display
1971 public function has_course_contacts() {
1972 if (!isset($this->record->managers)) {
1973 $courses = array($this->id => &$this->record);
1974 coursecat::preload_course_contacts($courses);
1976 return !empty($this->record->managers);
1980 * Returns list of course contacts (usually teachers) to display in course link
1982 * Roles to display are set up in $CFG->coursecontact
1984 * The result is the list of users where user id is the key and the value
1985 * is an array with elements:
1986 * - 'user' - object containing basic user information
1987 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
1988 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
1989 * - 'username' => fullname($user, $canviewfullnames)
1993 public function get_course_contacts() {
1995 if (empty($CFG->coursecontact)) {
1996 // no roles are configured to be displayed as course contacts
1999 if ($this->coursecontacts === null) {
2000 $this->coursecontacts = array();
2001 $context = context_course::instance($this->id);
2003 if (!isset($this->record->managers)) {
2004 // preload course contacts from DB
2005 $courses = array($this->id => &$this->record);
2006 coursecat::preload_course_contacts($courses);
2009 // build return array with full roles names (for this course context) and users names
2010 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2011 foreach ($this->record->managers as $ruser) {
2012 if (isset($this->coursecontacts[$ruser->id])) {
2013 // only display a user once with the highest sortorder role
2016 $user = new stdClass();
2017 $user->id = $ruser->id;
2018 $user->username = $ruser->username;
2019 $user->firstname = $ruser->firstname;
2020 $user->lastname = $ruser->lastname;
2021 $role = new stdClass();
2022 $role->id = $ruser->roleid;
2023 $role->name = $ruser->rolename;
2024 $role->shortname = $ruser->roleshortname;
2025 $role->coursealias = $ruser->rolecoursealias;
2027 $this->coursecontacts[$user->id] = array(
2030 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2031 'username' => fullname($user, $canviewfullnames)
2035 return $this->coursecontacts;
2039 * Checks if course has any associated overview files
2043 public function has_course_overviewfiles() {
2045 if (empty($CFG->courseoverviewfileslimit)) {
2048 require_once($CFG->libdir. '/filestorage/file_storage.php');
2049 $fs = get_file_storage();
2050 $context = context_course::instance($this->id);
2051 return $fs->is_area_empty($context->id, 'course', 'overviewfiles');
2055 * Returns all course overview files
2057 * @return array array of stored_file objects
2059 public function get_course_overviewfiles() {
2061 if (empty($CFG->courseoverviewfileslimit)) {
2064 require_once($CFG->libdir. '/filestorage/file_storage.php');
2065 require_once($CFG->dirroot. '/course/lib.php');
2066 $fs = get_file_storage();
2067 $context = context_course::instance($this->id);
2068 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2069 if (count($files)) {
2070 $overviewfilesoptions = course_overviewfiles_options($this->id);
2071 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2072 if ($acceptedtypes !== '*') {
2073 // filter only files with allowed extensions
2074 require_once($CFG->libdir. '/filelib.php');
2075 foreach ($files as $key => $file) {
2076 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2077 unset($files[$key]);
2081 if (count($files) > $CFG->courseoverviewfileslimit) {
2082 // return no more than $CFG->courseoverviewfileslimit files
2083 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
2089 // ====== magic methods =======
2091 public function __isset($name) {
2092 return isset($this->record->$name);
2096 * Magic method to get a course property
2098 * Returns any field from table course (from cache or from DB) and/or special field 'hassummary'
2100 * @param string $name
2103 public function __get($name) {
2105 if (property_exists($this->record, $name)) {
2106 return $this->record->$name;
2107 } else if ($name === 'summary' || $name === 'summaryformat') {
2108 // retrieve fields summary and summaryformat together because they are most likely to be used together
2109 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
2110 $this->record->summary = $record->summary;
2111 $this->record->summaryformat = $record->summaryformat;
2112 return $this->record->$name;
2113 } else if (array_key_exists($name, $DB->get_columns('course'))) {
2114 // another field from table 'course' that was not retrieved
2115 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
2116 return $this->record->$name;
2118 debugging('Invalid course property accessed! '.$name);
2123 * ALl properties are read only, sorry.
2124 * @param string $name
2126 public function __unset($name) {
2127 debugging('Can not unset '.get_class($this).' instance properties!');
2131 * Magic setter method, we do not want anybody to modify properties from the outside
2132 * @param string $name
2133 * @param mixed $value
2135 public function __set($name, $value) {
2136 debugging('Can not change '.get_class($this).' instance properties!');
2139 // ====== implementing method from interface IteratorAggregate ======
2142 * Create an iterator because magic vars can't be seen by 'foreach'.
2143 * Exclude context fields
2145 public function getIterator() {
2146 $ret = array('id' => $this->record->id);
2147 foreach ($this->record as $property => $value) {
2148 $ret[$property] = $value;
2150 return new ArrayIterator($ret);
2155 * An array of records that is sortable by many fields.
2157 * For more info on the ArrayObject class have a look at php.net.
2160 * @subpackage course
2161 * @copyright 2013 Sam Hemelryk
2162 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2164 class coursecat_sortable_records extends ArrayObject {
2167 * An array of sortable fields.
2168 * Gets set temporarily when sort is called.
2171 protected $sortfields = array();
2174 * Sorts this array using the given fields.
2176 * @param array $records
2177 * @param array $fields
2180 public static function sort(array $records, array $fields) {
2181 $records = new coursecat_sortable_records($records);
2182 $records->sortfields = $fields;
2183 $records->uasort(array($records, 'sort_by_many_fields'));
2184 return $records->getArrayCopy();
2188 * Sorts the two records based upon many fields.
2190 * This method should not be called itself, please call $sort instead.
2191 * It has been marked as access private as such.
2194 * @param stdClass $a
2195 * @param stdClass $b
2198 public function sort_by_many_fields($a, $b) {
2199 foreach ($this->sortfields as $field => $mult) {
2201 if (is_null($a->$field) && !is_null($b->$field)) {
2204 if (is_null($b->$field) && !is_null($a->$field)) {
2208 if (is_string($a->$field) || is_string($b->$field)) {
2210 if ($cmp = strcoll($a->$field, $b->$field)) {
2211 return $mult * $cmp;
2215 if ($a->$field > $b->$field) {
2218 if ($a->$field < $b->$field) {