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 /** Do not fetch course contacts more often than once per hour. */
56 const CACHE_COURSE_CONTACTS_TTL
= 3600;
58 /** @var array list of all fields and their short name and default value for caching */
59 protected static $coursecatfields = array(
60 'id' => array('id', 0),
61 'name' => array('na', ''),
62 'idnumber' => array('in', null),
63 'description' => null, // Not cached.
64 'descriptionformat' => null, // Not cached.
65 'parent' => array('pa', 0),
66 'sortorder' => array('so', 0),
67 'coursecount' => array('cc', 0),
68 'visible' => array('vi', 1),
69 'visibleold' => null, // Not cached.
70 'timemodified' => null, // Not cached.
71 'depth' => array('dh', 1),
72 'path' => array('ph', null),
73 'theme' => null, // Not cached.
83 protected $idnumber = null;
86 protected $description = false;
89 protected $descriptionformat = false;
92 protected $parent = 0;
95 protected $sortorder = 0;
98 protected $coursecount = false;
101 protected $visible = 1;
104 protected $visibleold = false;
107 protected $timemodified = false;
110 protected $depth = 0;
113 protected $path = '';
116 protected $theme = false;
119 protected $fromcache;
122 protected $hasmanagecapability = null;
125 * Magic setter method, we do not want anybody to modify properties from the outside
127 * @param string $name
128 * @param mixed $value
130 public function __set($name, $value) {
131 debugging('Can not change coursecat instance properties!', DEBUG_DEVELOPER
);
135 * Magic method getter, redirects to read only values. Queries from DB the fields that were not cached
137 * @param string $name
140 public function __get($name) {
142 if (array_key_exists($name, self
::$coursecatfields)) {
143 if ($this->$name === false) {
144 // Property was not retrieved from DB, retrieve all not retrieved fields.
145 $notretrievedfields = array_diff_key(self
::$coursecatfields, array_filter(self
::$coursecatfields));
146 $record = $DB->get_record('course_categories', array('id' => $this->id
),
147 join(',', array_keys($notretrievedfields)), MUST_EXIST
);
148 foreach ($record as $key => $value) {
149 $this->$key = $value;
154 debugging('Invalid coursecat property accessed! '.$name, DEBUG_DEVELOPER
);
159 * Full support for isset on our magic read only properties.
161 * @param string $name
164 public function __isset($name) {
165 if (array_key_exists($name, self
::$coursecatfields)) {
166 return isset($this->$name);
172 * All properties are read only, sorry.
174 * @param string $name
176 public function __unset($name) {
177 debugging('Can not unset coursecat instance properties!', DEBUG_DEVELOPER
);
181 * Create an iterator because magic vars can't be seen by 'foreach'.
183 * implementing method from interface IteratorAggregate
185 * @return ArrayIterator
187 public function getIterator() {
189 foreach (self
::$coursecatfields as $property => $unused) {
190 if ($this->$property !== false) {
191 $ret[$property] = $this->$property;
194 return new ArrayIterator($ret);
200 * Constructor is protected, use coursecat::get($id) to retrieve category
202 * @param stdClass $record record from DB (may not contain all fields)
203 * @param bool $fromcache whether it is being restored from cache
205 protected function __construct(stdClass
$record, $fromcache = false) {
206 context_helper
::preload_from_record($record);
207 foreach ($record as $key => $val) {
208 if (array_key_exists($key, self
::$coursecatfields)) {
212 $this->fromcache
= $fromcache;
216 * Returns coursecat object for requested category
218 * If category is not visible to user it is treated as non existing
219 * unless $alwaysreturnhidden is set to true
221 * If id is 0, the pseudo object for root category is returned (convenient
222 * for calling other functions such as get_children())
224 * @param int $id category id
225 * @param int $strictness whether to throw an exception (MUST_EXIST) or
226 * return null (IGNORE_MISSING) in case the category is not found or
227 * not visible to current user
228 * @param bool $alwaysreturnhidden set to true if you want an object to be
229 * returned even if this category is not visible to the current user
230 * (category is hidden and user does not have
231 * 'moodle/category:viewhiddencategories' capability). Use with care!
232 * @return null|coursecat
233 * @throws moodle_exception
235 public static function get($id, $strictness = MUST_EXIST
, $alwaysreturnhidden = false) {
237 if (!isset(self
::$coursecat0)) {
238 $record = new stdClass();
240 $record->visible
= 1;
243 self
::$coursecat0 = new coursecat($record);
245 return self
::$coursecat0;
247 $coursecatrecordcache = cache
::make('core', 'coursecatrecords');
248 $coursecat = $coursecatrecordcache->get($id);
249 if ($coursecat === false) {
250 if ($records = self
::get_records('cc.id = :id', array('id' => $id))) {
251 $record = reset($records);
252 $coursecat = new coursecat($record);
254 $coursecatrecordcache->set($id, $coursecat);
257 if ($coursecat && ($alwaysreturnhidden ||
$coursecat->is_uservisible())) {
260 if ($strictness == MUST_EXIST
) {
261 throw new moodle_exception('unknowcategory');
268 * Load many coursecat objects.
270 * @global moodle_database $DB
271 * @param array $ids An array of category ID's to load.
272 * @return coursecat[]
274 public static function get_many(array $ids) {
276 $coursecatrecordcache = cache
::make('core', 'coursecatrecords');
277 $categories = $coursecatrecordcache->get_many($ids);
279 foreach ($categories as $id => $result) {
280 if ($result === false) {
284 if (!empty($toload)) {
285 list($where, $params) = $DB->get_in_or_equal($toload, SQL_PARAMS_NAMED
);
286 $records = self
::get_records('cc.id '.$where, $params);
288 foreach ($records as $record) {
289 $categories[$record->id
] = new coursecat($record);
290 $toset[$record->id
] = $categories[$record->id
];
292 $coursecatrecordcache->set_many($toset);
298 * Returns the first found category
300 * Note that if there are no categories visible to the current user on the first level,
301 * the invisible category may be returned
305 public static function get_default() {
306 if ($visiblechildren = self
::get(0)->get_children()) {
307 $defcategory = reset($visiblechildren);
309 $toplevelcategories = self
::get_tree(0);
310 $defcategoryid = $toplevelcategories[0];
311 $defcategory = self
::get($defcategoryid, MUST_EXIST
, true);
317 * Restores the object after it has been externally modified in DB for example
318 * during {@link fix_course_sortorder()}
320 protected function restore() {
321 // Update all fields in the current object.
322 $newrecord = self
::get($this->id
, MUST_EXIST
, true);
323 foreach (self
::$coursecatfields as $key => $unused) {
324 $this->$key = $newrecord->$key;
329 * Creates a new category either from form data or from raw data
331 * Please note that this function does not verify access control.
333 * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
335 * Category visibility is inherited from parent unless $data->visible = 0 is specified
337 * @param array|stdClass $data
338 * @param array $editoroptions if specified, the data is considered to be
339 * form data and file_postupdate_standard_editor() is being called to
340 * process images in description.
342 * @throws moodle_exception
344 public static function create($data, $editoroptions = null) {
346 $data = (object)$data;
347 $newcategory = new stdClass();
349 $newcategory->descriptionformat
= FORMAT_MOODLE
;
350 $newcategory->description
= '';
351 // Copy all description* fields regardless of whether this is form data or direct field update.
352 foreach ($data as $key => $value) {
353 if (preg_match("/^description/", $key)) {
354 $newcategory->$key = $value;
358 if (empty($data->name
)) {
359 throw new moodle_exception('categorynamerequired');
361 if (core_text
::strlen($data->name
) > 255) {
362 throw new moodle_exception('categorytoolong');
364 $newcategory->name
= $data->name
;
366 // Validate and set idnumber.
367 if (!empty($data->idnumber
)) {
368 if (core_text
::strlen($data->idnumber
) > 100) {
369 throw new moodle_exception('idnumbertoolong');
371 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber
))) {
372 throw new moodle_exception('categoryidnumbertaken');
375 if (isset($data->idnumber
)) {
376 $newcategory->idnumber
= $data->idnumber
;
379 if (isset($data->theme
) && !empty($CFG->allowcategorythemes
)) {
380 $newcategory->theme
= $data->theme
;
383 if (empty($data->parent
)) {
384 $parent = self
::get(0);
386 $parent = self
::get($data->parent
, MUST_EXIST
, true);
388 $newcategory->parent
= $parent->id
;
389 $newcategory->depth
= $parent->depth +
1;
391 // By default category is visible, unless visible = 0 is specified or parent category is hidden.
392 if (isset($data->visible
) && !$data->visible
) {
393 // Create a hidden category.
394 $newcategory->visible
= $newcategory->visibleold
= 0;
396 // Create a category that inherits visibility from parent.
397 $newcategory->visible
= $parent->visible
;
398 // In case parent is hidden, when it changes visibility this new subcategory will automatically become visible too.
399 $newcategory->visibleold
= 1;
402 $newcategory->sortorder
= 0;
403 $newcategory->timemodified
= time();
405 $newcategory->id
= $DB->insert_record('course_categories', $newcategory);
407 // Update path (only possible after we know the category id.
408 $path = $parent->path
. '/' . $newcategory->id
;
409 $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id
));
411 // We should mark the context as dirty.
412 context_coursecat
::instance($newcategory->id
)->mark_dirty();
414 fix_course_sortorder();
416 // If this is data from form results, save embedded files and update description.
417 $categorycontext = context_coursecat
::instance($newcategory->id
);
418 if ($editoroptions) {
419 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
420 'coursecat', 'description', 0);
422 // Update only fields description and descriptionformat.
423 $updatedata = new stdClass();
424 $updatedata->id
= $newcategory->id
;
425 $updatedata->description
= $newcategory->description
;
426 $updatedata->descriptionformat
= $newcategory->descriptionformat
;
427 $DB->update_record('course_categories', $updatedata);
430 add_to_log(SITEID
, "category", 'add', "editcategory.php?id=$newcategory->id", $newcategory->id
);
431 cache_helper
::purge_by_event('changesincoursecat');
433 return self
::get($newcategory->id
, MUST_EXIST
, true);
437 * Updates the record with either form data or raw data
439 * Please note that this function does not verify access control.
441 * This function calls coursecat::change_parent_raw if field 'parent' is updated.
442 * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
443 * Visibility is changed first and then parent is changed. This means that
444 * if parent category is hidden, the current category will become hidden
445 * too and it may overwrite whatever was set in field 'visible'.
447 * Note that fields 'path' and 'depth' can not be updated manually
448 * Also coursecat::update() can not directly update the field 'sortoder'
450 * @param array|stdClass $data
451 * @param array $editoroptions if specified, the data is considered to be
452 * form data and file_postupdate_standard_editor() is being called to
453 * process images in description.
454 * @throws moodle_exception
456 public function update($data, $editoroptions = null) {
459 // There is no actual DB record associated with root category.
463 $data = (object)$data;
464 $newcategory = new stdClass();
465 $newcategory->id
= $this->id
;
467 // Copy all description* fields regardless of whether this is form data or direct field update.
468 foreach ($data as $key => $value) {
469 if (preg_match("/^description/", $key)) {
470 $newcategory->$key = $value;
474 if (isset($data->name
) && empty($data->name
)) {
475 throw new moodle_exception('categorynamerequired');
478 if (!empty($data->name
) && $data->name
!== $this->name
) {
479 if (core_text
::strlen($data->name
) > 255) {
480 throw new moodle_exception('categorytoolong');
482 $newcategory->name
= $data->name
;
485 if (isset($data->idnumber
) && $data->idnumber
!= $this->idnumber
) {
486 if (core_text
::strlen($data->idnumber
) > 100) {
487 throw new moodle_exception('idnumbertoolong');
489 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber
))) {
490 throw new moodle_exception('categoryidnumbertaken');
492 $newcategory->idnumber
= $data->idnumber
;
495 if (isset($data->theme
) && !empty($CFG->allowcategorythemes
)) {
496 $newcategory->theme
= $data->theme
;
500 if (isset($data->visible
)) {
501 if ($data->visible
) {
502 $changes = $this->show_raw();
504 $changes = $this->hide_raw(0);
508 if (isset($data->parent
) && $data->parent
!= $this->parent
) {
510 cache_helper
::purge_by_event('changesincoursecat');
512 $parentcat = self
::get($data->parent
, MUST_EXIST
, true);
513 $this->change_parent_raw($parentcat);
514 fix_course_sortorder();
517 $newcategory->timemodified
= time();
519 if ($editoroptions) {
520 $categorycontext = $this->get_context();
521 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
522 'coursecat', 'description', 0);
524 $DB->update_record('course_categories', $newcategory);
525 add_to_log(SITEID
, "category", 'update', "editcategory.php?id=$this->id", $this->id
);
526 fix_course_sortorder();
527 // Purge cache even if fix_course_sortorder() did not do it.
528 cache_helper
::purge_by_event('changesincoursecat');
530 // Update all fields in the current object.
535 * Checks if this course category is visible to current user
537 * Please note that methods coursecat::get (without 3rd argumet),
538 * coursecat::get_children(), etc. return only visible categories so it is
539 * usually not needed to call this function outside of this class
543 public function is_uservisible() {
544 return !$this->id ||
$this->visible ||
545 has_capability('moodle/category:viewhiddencategories', $this->get_context());
549 * Returns all categories visible to the current user
551 * This is a generic function that returns an array of
552 * (category id => coursecat object) sorted by sortorder
554 * @see coursecat::get_children()
555 * @see coursecat::get_all_parents()
557 * @return cacheable_object_array array of coursecat objects
559 public static function get_all_visible() {
561 $coursecatcache = cache
::make('core', 'coursecat');
562 $ids = $coursecatcache->get('user'. $USER->id
);
563 if ($ids === false) {
564 $all = self
::get_all_ids();
565 $parentvisible = $all[0];
567 foreach ($all as $id => $children) {
568 if ($id && in_array($id, $parentvisible) &&
569 ($coursecat = self
::get($id, IGNORE_MISSING
)) &&
570 (!$coursecat->parent ||
isset($rv[$coursecat->parent
]))) {
571 $rv[$id] = $coursecat;
572 $parentvisible +
= $children;
575 $coursecatcache->set('user'. $USER->id
, array_keys($rv));
578 foreach ($ids as $id) {
579 if ($coursecat = self
::get($id, IGNORE_MISSING
)) {
580 $rv[$id] = $coursecat;
588 * Returns the complete corresponding record from DB table course_categories
590 * Mostly used in deprecated functions
594 public function get_db_record() {
596 if ($record = $DB->get_record('course_categories', array('id' => $this->id
))) {
599 return (object)convert_to_array($this);
604 * Returns the entry from categories tree and makes sure the application-level tree cache is built
606 * The following keys can be requested:
608 * 'countall' - total number of categories in the system (always present)
609 * 0 - array of ids of top-level categories (always present)
610 * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
611 * $id (int) - array of ids of categories that are direct children of category with id $id. If
612 * category with id $id does not exist returns false. If category has no children returns empty array
613 * $id.'i' - array of ids of children categories that have visible=0
615 * @param int|string $id
618 protected static function get_tree($id) {
620 $coursecattreecache = cache
::make('core', 'coursecattree');
621 $rv = $coursecattreecache->get($id);
625 // Re-build the tree.
626 $sql = "SELECT cc.id, cc.parent, cc.visible
627 FROM {course_categories} cc
628 ORDER BY cc.sortorder";
629 $rs = $DB->get_recordset_sql($sql, array());
630 $all = array(0 => array(), '0i' => array());
632 foreach ($rs as $record) {
633 $all[$record->id
] = array();
634 $all[$record->id
. 'i'] = array();
635 if (array_key_exists($record->parent
, $all)) {
636 $all[$record->parent
][] = $record->id
;
637 if (!$record->visible
) {
638 $all[$record->parent
. 'i'][] = $record->id
;
641 // Parent not found. This is data consistency error but next fix_course_sortorder() should fix it.
642 $all[0][] = $record->id
;
643 if (!$record->visible
) {
644 $all['0i'][] = $record->id
;
651 // No categories found.
652 // This may happen after upgrade of a very old moodle version.
653 // In new versions the default category is created on install.
654 $defcoursecat = self
::create(array('name' => get_string('miscellaneous')));
655 set_config('defaultrequestcategory', $defcoursecat->id
);
656 $all[0] = array($defcoursecat->id
);
657 $all[$defcoursecat->id
] = array();
660 // We must add countall to all in case it was the requested ID.
661 $all['countall'] = $count;
662 foreach ($all as $key => $children) {
663 $coursecattreecache->set($key, $children);
665 if (array_key_exists($id, $all)) {
668 // Requested non-existing category.
673 * Returns number of ALL categories in the system regardless if
674 * they are visible to current user or not
678 public static function count_all() {
679 return self
::get_tree('countall');
683 * Retrieves number of records from course_categories table
685 * Only cached fields are retrieved. Records are ready for preloading context
687 * @param string $whereclause
688 * @param array $params
689 * @return array array of stdClass objects
691 protected static function get_records($whereclause, $params) {
693 // Retrieve from DB only the fields that need to be stored in cache.
694 $fields = array_keys(array_filter(self
::$coursecatfields));
695 $ctxselect = context_helper
::get_preload_record_columns_sql('ctx');
696 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
697 FROM {course_categories} cc
698 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
699 WHERE ". $whereclause." ORDER BY cc.sortorder";
700 return $DB->get_records_sql($sql,
701 array('contextcoursecat' => CONTEXT_COURSECAT
) +
$params);
705 * Given list of DB records from table course populates each record with list of users with course contact roles
707 * This function fills the courses with raw information as {@link get_role_users()} would do.
708 * See also {@link course_in_list::get_course_contacts()} for more readable return
710 * $courses[$i]->managers = array(
711 * $roleassignmentid => $roleuser,
715 * where $roleuser is an stdClass with the following properties:
717 * $roleuser->raid - role assignment id
718 * $roleuser->id - user id
719 * $roleuser->username
720 * $roleuser->firstname
721 * $roleuser->lastname
722 * $roleuser->rolecoursealias
723 * $roleuser->rolename
724 * $roleuser->sortorder - role sortorder
726 * $roleuser->roleshortname
728 * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
730 * @param array $courses
732 public static function preload_course_contacts(&$courses) {
734 if (empty($courses) ||
empty($CFG->coursecontact
)) {
737 $managerroles = explode(',', $CFG->coursecontact
);
738 $cache = cache
::make('core', 'coursecontacts');
739 $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
740 // Check if cache was set for the current course contacts and it is not yet expired.
741 if (empty($cacheddata['basic']) ||
$cacheddata['basic']['roles'] !== $CFG->coursecontact ||
742 $cacheddata['basic']['lastreset'] < time() - self
::CACHE_COURSE_CONTACTS_TTL
) {
745 $cache->set('basic', array('roles' => $CFG->coursecontact
, 'lastreset' => time()));
746 $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
748 $courseids = array();
749 foreach (array_keys($courses) as $id) {
750 if ($cacheddata[$id] !== false) {
751 $courses[$id]->managers
= $cacheddata[$id];
757 // Array $courseids now stores list of ids of courses for which we still need to retrieve contacts.
758 if (empty($courseids)) {
762 // First build the array of all context ids of the courses and their categories.
763 $allcontexts = array();
764 foreach ($courseids as $id) {
765 $context = context_course
::instance($id);
766 $courses[$id]->managers
= array();
767 foreach (preg_split('|/|', $context->path
, 0, PREG_SPLIT_NO_EMPTY
) as $ctxid) {
768 if (!isset($allcontexts[$ctxid])) {
769 $allcontexts[$ctxid] = array();
771 $allcontexts[$ctxid][] = $id;
775 // Fetch list of all users with course contact roles in any of the courses contexts or parent contexts.
776 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED
, 'ctxid');
777 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED
, 'rid');
778 list($sort, $sortparams) = users_order_by_sql('u');
779 $notdeleted = array('notdeleted'=>0);
780 $allnames = get_all_user_name_fields(true, 'u');
781 $sql = "SELECT ra.contextid, ra.id AS raid,
782 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
783 rn.name AS rolecoursealias, u.id, u.username, $allnames
784 FROM {role_assignments} ra
785 JOIN {user} u ON ra.userid = u.id
786 JOIN {role} r ON ra.roleid = r.id
787 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
788 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
789 ORDER BY r.sortorder, $sort";
790 $rs = $DB->get_recordset_sql($sql, $params1 +
$params2 +
$notdeleted +
$sortparams);
791 $checkenrolments = array();
792 foreach ($rs as $ra) {
793 foreach ($allcontexts[$ra->contextid
] as $id) {
794 $courses[$id]->managers
[$ra->raid
] = $ra;
795 if (!isset($checkenrolments[$id])) {
796 $checkenrolments[$id] = array();
798 $checkenrolments[$id][] = $ra->id
;
803 // Remove from course contacts users who are not enrolled in the course.
804 $enrolleduserids = self
::ensure_users_enrolled($checkenrolments);
805 foreach ($checkenrolments as $id => $userids) {
806 if (empty($enrolleduserids[$id])) {
807 $courses[$id]->managers
= array();
808 } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
809 foreach ($courses[$id]->managers
as $raid => $ra) {
810 if (in_array($ra->id
, $notenrolled)) {
811 unset($courses[$id]->managers
[$raid]);
819 foreach ($courseids as $id) {
820 $values[$id] = $courses[$id]->managers
;
822 $cache->set_many($values);
826 * Verify user enrollments for multiple course-user combinations
828 * @param array $courseusers array where keys are course ids and values are array
829 * of users in this course whose enrolment we wish to verify
830 * @return array same structure as input array but values list only users from input
831 * who are enrolled in the course
833 protected static function ensure_users_enrolled($courseusers) {
835 // If the input array is too big, split it into chunks.
836 $maxcoursesinquery = 20;
837 if (count($courseusers) > $maxcoursesinquery) {
839 for ($offset = 0; $offset < count($courseusers); $offset +
= $maxcoursesinquery) {
840 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
841 $rv = $rv + self
::ensure_users_enrolled($chunk);
846 // Create a query verifying valid user enrolments for the number of courses.
847 $sql = "SELECT DISTINCT e.courseid, ue.userid
848 FROM {user_enrolments} ue
849 JOIN {enrol} e ON e.id = ue.enrolid
850 WHERE ue.status = :active
851 AND e.status = :enabled
852 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
853 $now = round(time(), -2); // Rounding helps caching in DB.
854 $params = array('enabled' => ENROL_INSTANCE_ENABLED
,
855 'active' => ENROL_USER_ACTIVE
,
856 'now1' => $now, 'now2' => $now);
860 foreach ($courseusers as $id => $userids) {
861 $enrolled[$id] = array();
862 if (count($userids)) {
863 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED
, 'userid'.$cnt.'_');
864 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
865 $params = $params +
array('courseid'.$cnt => $id) +
$params2;
869 if (count($subsqls)) {
870 $sql .= "AND (". join(' OR ', $subsqls).")";
871 $rs = $DB->get_recordset_sql($sql, $params);
872 foreach ($rs as $record) {
873 $enrolled[$record->courseid
][] = $record->userid
;
881 * Retrieves number of records from course table
883 * Not all fields are retrieved. Records are ready for preloading context
885 * @param string $whereclause
886 * @param array $params
887 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
888 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
889 * on not visible courses
890 * @return array array of stdClass objects
892 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
894 $ctxselect = context_helper
::get_preload_record_columns_sql('ctx');
895 $fields = array('c.id', 'c.category', 'c.sortorder',
896 'c.shortname', 'c.fullname', 'c.idnumber',
897 'c.startdate', 'c.visible', 'c.cacherev');
898 if (!empty($options['summary'])) {
899 $fields[] = 'c.summary';
900 $fields[] = 'c.summaryformat';
902 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
904 $sql = "SELECT ". join(',', $fields). ", $ctxselect
906 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
907 WHERE ". $whereclause." ORDER BY c.sortorder";
908 $list = $DB->get_records_sql($sql,
909 array('contextcourse' => CONTEXT_COURSE
) +
$params);
911 if ($checkvisibility) {
912 // Loop through all records and make sure we only return the courses accessible by user.
913 foreach ($list as $course) {
914 if (isset($list[$course->id
]->hassummary
)) {
915 $list[$course->id
]->hassummary
= strlen($list[$course->id
]->hassummary
) > 0;
917 if (empty($course->visible
)) {
918 // Load context only if we need to check capability.
919 context_helper
::preload_from_record($course);
920 if (!has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
921 unset($list[$course->id
]);
927 // Preload course contacts if necessary.
928 if (!empty($options['coursecontacts'])) {
929 self
::preload_course_contacts($list);
935 * Returns array of ids of children categories that current user can not see
937 * This data is cached in user session cache
941 protected function get_not_visible_children_ids() {
943 $coursecatcache = cache
::make('core', 'coursecat');
944 if (($invisibleids = $coursecatcache->get('ic'. $this->id
)) === false) {
945 // We never checked visible children before.
946 $hidden = self
::get_tree($this->id
.'i');
947 $invisibleids = array();
949 // Preload categories contexts.
950 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED
, 'id');
951 $ctxselect = context_helper
::get_preload_record_columns_sql('ctx');
952 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
953 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
954 array('contextcoursecat' => CONTEXT_COURSECAT
) +
$params);
955 foreach ($contexts as $record) {
956 context_helper
::preload_from_record($record);
958 // Check that user has 'viewhiddencategories' capability for each hidden category.
959 foreach ($hidden as $id) {
960 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat
::instance($id))) {
961 $invisibleids[] = $id;
965 $coursecatcache->set('ic'. $this->id
, $invisibleids);
967 return $invisibleids;
971 * Sorts list of records by several fields
973 * @param array $records array of stdClass objects
974 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
977 protected static function sort_records(&$records, $sortfields) {
978 if (empty($records)) {
981 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname).
982 if (array_key_exists('displayname', $sortfields)) {
983 foreach ($records as $key => $record) {
984 if (!isset($record->displayname
)) {
985 $records[$key]->displayname
= get_course_display_name_for_list($record);
989 // Sorting by one field - use core_collator.
990 if (count($sortfields) == 1) {
991 $property = key($sortfields);
992 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
993 $sortflag = core_collator
::SORT_NUMERIC
;
994 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
995 $sortflag = core_collator
::SORT_STRING
;
997 $sortflag = core_collator
::SORT_REGULAR
;
999 core_collator
::asort_objects_by_property($records, $property, $sortflag);
1000 if ($sortfields[$property] < 0) {
1001 $records = array_reverse($records, true);
1005 $records = coursecat_sortable_records
::sort($records, $sortfields);
1009 * Returns array of children categories visible to the current user
1011 * @param array $options options for retrieving children
1012 * - sort - list of fields to sort. Example
1013 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
1014 * will sort by idnumber asc, name asc and id desc.
1015 * Default: array('sortorder' => 1)
1016 * Only cached fields may be used for sorting!
1018 * - limit - maximum number of children to return, 0 or null for no limit
1019 * @return coursecat[] Array of coursecat objects indexed by category id
1021 public function get_children($options = array()) {
1023 $coursecatcache = cache
::make('core', 'coursecat');
1025 // Get default values for options.
1026 if (!empty($options['sort']) && is_array($options['sort'])) {
1027 $sortfields = $options['sort'];
1029 $sortfields = array('sortorder' => 1);
1032 if (!empty($options['limit']) && (int)$options['limit']) {
1033 $limit = (int)$options['limit'];
1036 if (!empty($options['offset']) && (int)$options['offset']) {
1037 $offset = (int)$options['offset'];
1040 // First retrieve list of user-visible and sorted children ids from cache.
1041 $sortedids = $coursecatcache->get('c'. $this->id
. ':'. serialize($sortfields));
1042 if ($sortedids === false) {
1043 $sortfieldskeys = array_keys($sortfields);
1044 if ($sortfieldskeys[0] === 'sortorder') {
1045 // No DB requests required to build the list of ids sorted by sortorder.
1046 // We can easily ignore other sort fields because sortorder is always different.
1047 $sortedids = self
::get_tree($this->id
);
1048 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
1049 $sortedids = array_diff($sortedids, $invisibleids);
1050 if ($sortfields['sortorder'] == -1) {
1051 $sortedids = array_reverse($sortedids, true);
1055 // We need to retrieve and sort all children. Good thing that it is done only on first request.
1056 if ($invisibleids = $this->get_not_visible_children_ids()) {
1057 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED
, 'id', false);
1058 $records = self
::get_records('cc.parent = :parent AND cc.id '. $sql,
1059 array('parent' => $this->id
) +
$params);
1061 $records = self
::get_records('cc.parent = :parent', array('parent' => $this->id
));
1063 self
::sort_records($records, $sortfields);
1064 $sortedids = array_keys($records);
1066 $coursecatcache->set('c'. $this->id
. ':'.serialize($sortfields), $sortedids);
1069 if (empty($sortedids)) {
1073 // Now retrieive and return categories.
1074 if ($offset ||
$limit) {
1075 $sortedids = array_slice($sortedids, $offset, $limit);
1077 if (isset($records)) {
1078 // Easy, we have already retrieved records.
1079 if ($offset ||
$limit) {
1080 $records = array_slice($records, $offset, $limit, true);
1083 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED
, 'id');
1084 $records = self
::get_records('cc.id '. $sql, array('parent' => $this->id
) +
$params);
1088 foreach ($sortedids as $id) {
1089 if (isset($records[$id])) {
1090 $rv[$id] = new coursecat($records[$id]);
1097 * Returns true if the user has the manage capability on any category.
1099 * This method uses the coursecat cache and an entry `has_manage_capability` to speed up
1100 * calls to this method.
1104 public static function has_manage_capability_on_any() {
1105 return self
::has_capability_on_any('moodle/category:manage');
1109 * Checks if the user has at least one of the given capabilities on any category.
1111 * @param array|string $capabilities One or more capabilities to check. Check made is an OR.
1114 public static function has_capability_on_any($capabilities) {
1116 if (!isloggedin() ||
isguestuser()) {
1120 if (!is_array($capabilities)) {
1121 $capabilities = array($capabilities);
1124 foreach ($capabilities as $capability) {
1125 $keys[$capability] = sha1($capability);
1128 /* @var cache_session $cache */
1129 $cache = cache
::make('core', 'coursecat');
1130 $hascapability = $cache->get_many($keys);
1131 $needtoload = false;
1132 foreach ($hascapability as $capability) {
1133 if ($capability === '1') {
1135 } else if ($capability === false) {
1139 if ($needtoload === false) {
1140 // All capabilities were retrieved and the user didn't have any.
1145 $fields = context_helper
::get_preload_record_columns_sql('ctx');
1146 $sql = "SELECT ctx.instanceid AS categoryid, $fields
1148 WHERE contextlevel = :contextlevel
1149 ORDER BY depth ASC";
1150 $params = array('contextlevel' => CONTEXT_COURSECAT
);
1151 $recordset = $DB->get_recordset_sql($sql, $params);
1152 foreach ($recordset as $context) {
1153 context_helper
::preload_from_record($context);
1154 $context = context_coursecat
::instance($context->categoryid
);
1155 foreach ($capabilities as $capability) {
1156 if (has_capability($capability, $context)) {
1157 $haskey = $capability;
1162 $recordset->close();
1163 if ($haskey === null) {
1165 foreach ($keys as $key) {
1168 $cache->set_many($data);
1171 $cache->set($haskey, '1');
1177 * Returns true if the user can resort any category.
1180 public static function can_resort_any() {
1181 return self
::has_manage_capability_on_any();
1185 * Returns true if the user can change the parent of any category.
1188 public static function can_change_parent_any() {
1189 return self
::has_manage_capability_on_any();
1193 * Returns number of subcategories visible to the current user
1197 public function get_children_count() {
1198 $sortedids = self
::get_tree($this->id
);
1199 $invisibleids = $this->get_not_visible_children_ids();
1200 return count($sortedids) - count($invisibleids);
1204 * Returns true if the category has ANY children, including those not visible to the user
1208 public function has_children() {
1209 $allchildren = self
::get_tree($this->id
);
1210 return !empty($allchildren);
1214 * Returns true if the category has courses in it (count does not include courses
1215 * in child categories)
1219 public function has_courses() {
1221 return $DB->record_exists_sql("select 1 from {course} where category = ?",
1228 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1229 * to this when somebody edits courses or categories, however it is very
1230 * difficult to keep track of all possible changes that may affect list of courses.
1232 * @param array $search contains search criterias, such as:
1233 * - search - search string
1234 * - blocklist - id of block (if we are searching for courses containing specific block0
1235 * - modulelist - name of module (if we are searching for courses containing specific module
1236 * - tagid - id of tag
1237 * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
1238 * search is always category-independent
1239 * @return course_in_list[]
1241 public static function search_courses($search, $options = array()) {
1243 $offset = !empty($options['offset']) ?
$options['offset'] : 0;
1244 $limit = !empty($options['limit']) ?
$options['limit'] : null;
1245 $sortfields = !empty($options['sort']) ?
$options['sort'] : array('sortorder' => 1);
1247 $coursecatcache = cache
::make('core', 'coursecat');
1248 $cachekey = 's-'. serialize($search +
array('sort' => $sortfields));
1249 $cntcachekey = 'scnt-'. serialize($search);
1251 $ids = $coursecatcache->get($cachekey);
1252 if ($ids !== false) {
1253 // We already cached last search result.
1254 $ids = array_slice($ids, $offset, $limit);
1257 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED
, 'id');
1258 $records = self
::get_course_records("c.id ". $sql, $params, $options);
1259 foreach ($ids as $id) {
1260 $courses[$id] = new course_in_list($records[$id]);
1266 $preloadcoursecontacts = !empty($options['coursecontacts']);
1267 unset($options['coursecontacts']);
1269 if (!empty($search['search'])) {
1270 // Search courses that have specified words in their names/summaries.
1271 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY
);
1272 $searchterms = array_filter($searchterms, create_function('$v', 'return strlen($v) > 1;'));
1273 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount);
1274 self
::sort_records($courselist, $sortfields);
1275 $coursecatcache->set($cachekey, array_keys($courselist));
1276 $coursecatcache->set($cntcachekey, $totalcount);
1277 $records = array_slice($courselist, $offset, $limit, true);
1279 if (!empty($search['blocklist'])) {
1280 // Search courses that have block with specified id.
1281 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1282 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1283 WHERE bi.blockname = :blockname)';
1284 $params = array('blockname' => $blockname);
1285 } else if (!empty($search['modulelist'])) {
1286 // Search courses that have module with specified name.
1287 $where = "c.id IN (SELECT DISTINCT module.course ".
1288 "FROM {".$search['modulelist']."} module)";
1290 } else if (!empty($search['tagid'])) {
1291 // Search courses that are tagged with the specified tag.
1292 $where = "c.id IN (SELECT t.itemid ".
1293 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype)";
1294 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course');
1296 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER
);
1299 $courselist = self
::get_course_records($where, $params, $options, true);
1300 self
::sort_records($courselist, $sortfields);
1301 $coursecatcache->set($cachekey, array_keys($courselist));
1302 $coursecatcache->set($cntcachekey, count($courselist));
1303 $records = array_slice($courselist, $offset, $limit, true);
1306 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1307 if (!empty($preloadcoursecontacts)) {
1308 self
::preload_course_contacts($records);
1311 foreach ($records as $record) {
1312 $courses[$record->id
] = new course_in_list($record);
1318 * Returns number of courses in the search results
1320 * It is recommended to call this function after {@link coursecat::search_courses()}
1321 * and not before because only course ids are cached. Otherwise search_courses() may
1322 * perform extra DB queries.
1324 * @param array $search search criteria, see method search_courses() for more details
1325 * @param array $options display options. They do not affect the result but
1326 * the 'sort' property is used in cache key for storing list of course ids
1329 public static function search_courses_count($search, $options = array()) {
1330 $coursecatcache = cache
::make('core', 'coursecat');
1331 $cntcachekey = 'scnt-'. serialize($search);
1332 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1333 // Cached value not found. Retrieve ALL courses and return their count.
1334 unset($options['offset']);
1335 unset($options['limit']);
1336 unset($options['summary']);
1337 unset($options['coursecontacts']);
1338 $courses = self
::search_courses($search, $options);
1339 $cnt = count($courses);
1345 * Retrieves the list of courses accessible by user
1347 * Not all information is cached, try to avoid calling this method
1348 * twice in the same request.
1350 * The following fields are always retrieved:
1351 * - id, visible, fullname, shortname, idnumber, category, sortorder
1353 * If you plan to use properties/methods course_in_list::$summary and/or
1354 * course_in_list::get_course_contacts()
1355 * you can preload this information using appropriate 'options'. Otherwise
1356 * they will be retrieved from DB on demand and it may end with bigger DB load.
1358 * Note that method course_in_list::has_summary() will not perform additional
1359 * DB queries even if $options['summary'] is not specified
1361 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1362 * to this when somebody edits courses or categories, however it is very
1363 * difficult to keep track of all possible changes that may affect list of courses.
1365 * @param array $options options for retrieving children
1366 * - recursive - return courses from subcategories as well. Use with care,
1367 * this may be a huge list!
1368 * - summary - preloads fields 'summary' and 'summaryformat'
1369 * - coursecontacts - preloads course contacts
1370 * - sort - list of fields to sort. Example
1371 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1372 * will sort by idnumber asc, shortname asc and id desc.
1373 * Default: array('sortorder' => 1)
1374 * Only cached fields may be used for sorting!
1376 * - limit - maximum number of children to return, 0 or null for no limit
1377 * @return course_in_list[]
1379 public function get_courses($options = array()) {
1381 $recursive = !empty($options['recursive']);
1382 $offset = !empty($options['offset']) ?
$options['offset'] : 0;
1383 $limit = !empty($options['limit']) ?
$options['limit'] : null;
1384 $sortfields = !empty($options['sort']) ?
$options['sort'] : array('sortorder' => 1);
1386 // Check if this category is hidden.
1387 // Also 0-category never has courses unless this is recursive call.
1388 if (!$this->is_uservisible() ||
(!$this->id
&& !$recursive)) {
1392 $coursecatcache = cache
::make('core', 'coursecat');
1393 $cachekey = 'l-'. $this->id
. '-'. (!empty($options['recursive']) ?
'r' : '').
1394 '-'. serialize($sortfields);
1395 $cntcachekey = 'lcnt-'. $this->id
. '-'. (!empty($options['recursive']) ?
'r' : '');
1397 // Check if we have already cached results.
1398 $ids = $coursecatcache->get($cachekey);
1399 if ($ids !== false) {
1400 // We already cached last search result and it did not expire yet.
1401 $ids = array_slice($ids, $offset, $limit);
1404 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED
, 'id');
1405 $records = self
::get_course_records("c.id ". $sql, $params, $options);
1406 foreach ($ids as $id) {
1407 $courses[$id] = new course_in_list($records[$id]);
1413 // Retrieve list of courses in category.
1414 $where = 'c.id <> :siteid';
1415 $params = array('siteid' => SITEID
);
1418 $context = context_coursecat
::instance($this->id
);
1419 $where .= ' AND ctx.path like :path';
1420 $params['path'] = $context->path
. '/%';
1423 $where .= ' AND c.category = :categoryid';
1424 $params['categoryid'] = $this->id
;
1426 // Get list of courses without preloaded coursecontacts because we don't need them for every course.
1427 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1429 // Sort and cache list.
1430 self
::sort_records($list, $sortfields);
1431 $coursecatcache->set($cachekey, array_keys($list));
1432 $coursecatcache->set($cntcachekey, count($list));
1434 // Apply offset/limit, convert to course_in_list and return.
1437 if ($offset ||
$limit) {
1438 $list = array_slice($list, $offset, $limit, true);
1440 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1441 if (!empty($options['coursecontacts'])) {
1442 self
::preload_course_contacts($list);
1444 foreach ($list as $record) {
1445 $courses[$record->id
] = new course_in_list($record);
1452 * Returns number of courses visible to the user
1454 * @param array $options similar to get_courses() except some options do not affect
1455 * number of courses (i.e. sort, summary, offset, limit etc.)
1458 public function get_courses_count($options = array()) {
1459 $cntcachekey = 'lcnt-'. $this->id
. '-'. (!empty($options['recursive']) ?
'r' : '');
1460 $coursecatcache = cache
::make('core', 'coursecat');
1461 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1462 // Cached value not found. Retrieve ALL courses and return their count.
1463 unset($options['offset']);
1464 unset($options['limit']);
1465 unset($options['summary']);
1466 unset($options['coursecontacts']);
1467 $courses = $this->get_courses($options);
1468 $cnt = count($courses);
1474 * Returns true if the user is able to delete this category.
1476 * Note if this category contains any courses this isn't a full check, it will need to be accompanied by a call to either
1477 * {@link coursecat::can_delete_full()} or {@link coursecat::can_move_content_to()} depending upon what the user wished to do.
1481 public function can_delete() {
1482 if (!$this->has_manage_capability()) {
1485 return $this->parent_has_manage_capability();
1489 * Returns true if user can delete current category and all its contents
1491 * To be able to delete course category the user must have permission
1492 * 'moodle/category:manage' in ALL child course categories AND
1493 * be able to delete all courses
1497 public function can_delete_full() {
1504 $context = $this->get_context();
1505 if (!$this->is_uservisible() ||
1506 !has_capability('moodle/category:manage', $context)) {
1510 // Check all child categories (not only direct children).
1511 $sql = context_helper
::get_preload_record_columns_sql('ctx');
1512 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1513 ' FROM {context} ctx '.
1514 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1515 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1516 array($context->path
. '/%', CONTEXT_COURSECAT
));
1517 foreach ($childcategories as $childcat) {
1518 context_helper
::preload_from_record($childcat);
1519 $childcontext = context_coursecat
::instance($childcat->id
);
1520 if ((!$childcat->visible
&& !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1521 !has_capability('moodle/category:manage', $childcontext)) {
1527 $sql = context_helper
::get_preload_record_columns_sql('ctx');
1528 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1529 $sql. ' FROM {context} ctx '.
1530 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1531 array('pathmask' => $context->path
. '/%',
1532 'courselevel' => CONTEXT_COURSE
));
1533 foreach ($coursescontexts as $ctxrecord) {
1534 context_helper
::preload_from_record($ctxrecord);
1535 if (!can_delete_course($ctxrecord->courseid
)) {
1544 * Recursively delete category including all subcategories and courses
1546 * Function {@link coursecat::can_delete_full()} MUST be called prior
1547 * to calling this function because there is no capability check
1548 * inside this function
1550 * @param boolean $showfeedback display some notices
1551 * @return array return deleted courses
1552 * @throws moodle_exception
1554 public function delete_full($showfeedback = true) {
1557 require_once($CFG->libdir
.'/gradelib.php');
1558 require_once($CFG->libdir
.'/questionlib.php');
1559 require_once($CFG->dirroot
.'/cohort/lib.php');
1561 $deletedcourses = array();
1563 // Get children. Note, we don't want to use cache here because it would be rebuilt too often.
1564 $children = $DB->get_records('course_categories', array('parent' => $this->id
), 'sortorder ASC');
1565 foreach ($children as $record) {
1566 $coursecat = new coursecat($record);
1567 $deletedcourses +
= $coursecat->delete_full($showfeedback);
1570 if ($courses = $DB->get_records('course', array('category' => $this->id
), 'sortorder ASC')) {
1571 foreach ($courses as $course) {
1572 if (!delete_course($course, false)) {
1573 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname
);
1575 $deletedcourses[] = $course;
1579 // Move or delete cohorts in this context.
1580 cohort_delete_category($this);
1582 // Now delete anything that may depend on course category context.
1583 grade_course_category_delete($this->id
, 0, $showfeedback);
1584 if (!question_delete_course_category($this, 0, $showfeedback)) {
1585 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1588 // Finally delete the category and it's context.
1589 $DB->delete_records('course_categories', array('id' => $this->id
));
1591 $coursecatcontext = context_coursecat
::instance($this->id
);
1592 $coursecatcontext->delete();
1594 cache_helper
::purge_by_event('changesincoursecat');
1596 // Trigger a course category deleted event.
1597 /* @var \core\event\course_category_deleted $event */
1598 $event = \core\event\course_category_deleted
::create(array(
1599 'objectid' => $this->id
,
1600 'context' => $coursecatcontext,
1601 'other' => array('name' => $this->name
)
1603 $event->set_legacy_eventdata($this);
1606 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1607 if ($this->id
== $CFG->defaultrequestcategory
) {
1608 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1610 return $deletedcourses;
1614 * Checks if user can delete this category and move content (courses, subcategories and questions)
1615 * to another category. If yes returns the array of possible target categories names
1617 * If user can not manage this category or it is completely empty - empty array will be returned
1621 public function move_content_targets_list() {
1623 require_once($CFG->libdir
. '/questionlib.php');
1624 $context = $this->get_context();
1625 if (!$this->is_uservisible() ||
1626 !has_capability('moodle/category:manage', $context)) {
1627 // User is not able to manage current category, he is not able to delete it.
1628 // No possible target categories.
1632 $testcaps = array();
1633 // If this category has courses in it, user must have 'course:create' capability in target category.
1634 if ($this->has_courses()) {
1635 $testcaps[] = 'moodle/course:create';
1637 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1638 if ($this->has_children() ||
question_context_has_any_questions($context)) {
1639 $testcaps[] = 'moodle/category:manage';
1641 if (!empty($testcaps)) {
1642 // Return list of categories excluding this one and it's children.
1643 return self
::make_categories_list($testcaps, $this->id
);
1646 // Category is completely empty, no need in target for contents.
1651 * Checks if user has capability to move all category content to the new parent before
1652 * removing this category
1654 * @param int $newcatid
1657 public function can_move_content_to($newcatid) {
1659 require_once($CFG->libdir
. '/questionlib.php');
1660 $context = $this->get_context();
1661 if (!$this->is_uservisible() ||
1662 !has_capability('moodle/category:manage', $context)) {
1665 $testcaps = array();
1666 // If this category has courses in it, user must have 'course:create' capability in target category.
1667 if ($this->has_courses()) {
1668 $testcaps[] = 'moodle/course:create';
1670 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1671 if ($this->has_children() ||
question_context_has_any_questions($context)) {
1672 $testcaps[] = 'moodle/category:manage';
1674 if (!empty($testcaps)) {
1675 return has_all_capabilities($testcaps, context_coursecat
::instance($newcatid));
1678 // There is no content but still return true.
1683 * Deletes a category and moves all content (children, courses and questions) to the new parent
1685 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1686 * must be called prior
1688 * @param int $newparentid
1689 * @param bool $showfeedback
1692 public function delete_move($newparentid, $showfeedback = false) {
1693 global $CFG, $DB, $OUTPUT;
1695 require_once($CFG->libdir
.'/gradelib.php');
1696 require_once($CFG->libdir
.'/questionlib.php');
1697 require_once($CFG->dirroot
.'/cohort/lib.php');
1699 // Get all objects and lists because later the caches will be reset so.
1700 // We don't need to make extra queries.
1701 $newparentcat = self
::get($newparentid, MUST_EXIST
, true);
1702 $catname = $this->get_formatted_name();
1703 $children = $this->get_children();
1704 $params = array('category' => $this->id
);
1705 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', $params);
1706 $context = $this->get_context();
1709 foreach ($children as $childcat) {
1710 $childcat->change_parent_raw($newparentcat);
1712 add_to_log(SITEID
, "category", "move", "editcategory.php?id=$childcat->id", $childcat->id
);
1714 fix_course_sortorder();
1718 if (!move_courses($coursesids, $newparentid)) {
1719 if ($showfeedback) {
1720 echo $OUTPUT->notification("Error moving courses");
1724 if ($showfeedback) {
1725 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1729 // Move or delete cohorts in this context.
1730 cohort_delete_category($this);
1732 // Now delete anything that may depend on course category context.
1733 grade_course_category_delete($this->id
, $newparentid, $showfeedback);
1734 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1735 if ($showfeedback) {
1736 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1741 // Finally delete the category and it's context.
1742 $DB->delete_records('course_categories', array('id' => $this->id
));
1745 // Trigger a course category deleted event.
1746 /* @var \core\event\course_category_deleted $event */
1747 $event = \core\event\course_category_deleted
::create(array(
1748 'objectid' => $this->id
,
1749 'context' => $context,
1750 'other' => array('name' => $this->name
)
1752 $event->set_legacy_eventdata($this);
1755 cache_helper
::purge_by_event('changesincoursecat');
1757 if ($showfeedback) {
1758 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1761 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1762 if ($this->id
== $CFG->defaultrequestcategory
) {
1763 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1769 * Checks if user can move current category to the new parent
1771 * This checks if new parent category exists, user has manage cap there
1772 * and new parent is not a child of this category
1774 * @param int|stdClass|coursecat $newparentcat
1777 public function can_change_parent($newparentcat) {
1778 if (!has_capability('moodle/category:manage', $this->get_context())) {
1781 if (is_object($newparentcat)) {
1782 $newparentcat = self
::get($newparentcat->id
, IGNORE_MISSING
);
1784 $newparentcat = self
::get((int)$newparentcat, IGNORE_MISSING
);
1786 if (!$newparentcat) {
1789 if ($newparentcat->id
== $this->id ||
in_array($this->id
, $newparentcat->get_parents())) {
1790 // Can not move to itself or it's own child.
1793 if ($newparentcat->id
) {
1794 return has_capability('moodle/category:manage', context_coursecat
::instance($newparentcat->id
));
1796 return has_capability('moodle/category:manage', context_system
::instance());
1801 * Moves the category under another parent category. All associated contexts are moved as well
1803 * This is protected function, use change_parent() or update() from outside of this class
1805 * @see coursecat::change_parent()
1806 * @see coursecat::update()
1808 * @param coursecat $newparentcat
1809 * @throws moodle_exception
1811 protected function change_parent_raw(coursecat
$newparentcat) {
1814 $context = $this->get_context();
1817 if (empty($newparentcat->id
)) {
1818 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id
));
1819 $newparent = context_system
::instance();
1821 if ($newparentcat->id
== $this->id ||
in_array($this->id
, $newparentcat->get_parents())) {
1822 // Can not move to itself or it's own child.
1823 throw new moodle_exception('cannotmovecategory');
1825 $DB->set_field('course_categories', 'parent', $newparentcat->id
, array('id' => $this->id
));
1826 $newparent = context_coursecat
::instance($newparentcat->id
);
1828 if (!$newparentcat->visible
and $this->visible
) {
1829 // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children
1830 // will be restored properly.
1834 $this->parent
= $newparentcat->id
;
1836 $context->update_moved($newparent);
1838 // Now make it last in new category.
1839 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY
*MAX_COURSE_CATEGORIES
, array('id' => $this->id
));
1842 fix_course_sortorder();
1844 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must
1845 // become visible again.
1851 * Efficiently moves a category - NOTE that this can have
1852 * a huge impact access-control-wise...
1854 * Note that this function does not check capabilities.
1857 * $coursecat = coursecat::get($categoryid);
1858 * if ($coursecat->can_change_parent($newparentcatid)) {
1859 * $coursecat->change_parent($newparentcatid);
1862 * This function does not update field course_categories.timemodified
1863 * If you want to update timemodified, use
1864 * $coursecat->update(array('parent' => $newparentcat));
1866 * @param int|stdClass|coursecat $newparentcat
1868 public function change_parent($newparentcat) {
1869 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1870 if (is_object($newparentcat)) {
1871 $newparentcat = self
::get($newparentcat->id
, MUST_EXIST
, true);
1873 $newparentcat = self
::get((int)$newparentcat, MUST_EXIST
, true);
1875 if ($newparentcat->id
!= $this->parent
) {
1876 $this->change_parent_raw($newparentcat);
1877 fix_course_sortorder();
1878 cache_helper
::purge_by_event('changesincoursecat');
1880 add_to_log(SITEID
, "category", "move", "editcategory.php?id=$this->id", $this->id
);
1885 * Hide course category and child course and subcategories
1887 * If this category has changed the parent and is moved under hidden
1888 * category we will want to store it's current visibility state in
1889 * the field 'visibleold'. If admin clicked 'hide' for this particular
1890 * category, the field 'visibleold' should become 0.
1892 * All subcategories and courses will have their current visibility in the field visibleold
1894 * This is protected function, use hide() or update() from outside of this class
1896 * @see coursecat::hide()
1897 * @see coursecat::update()
1899 * @param int $visibleold value to set in field $visibleold for this category
1900 * @return bool whether changes have been made and caches need to be purged afterwards
1902 protected function hide_raw($visibleold = 0) {
1906 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing.
1907 if ($this->id
&& $this->__get('visibleold') != $visibleold) {
1908 $this->visibleold
= $visibleold;
1909 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id
));
1912 if (!$this->visible ||
!$this->id
) {
1913 // Already hidden or can not be hidden.
1918 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id
));
1919 // Store visible flag so that we can return to it if we immediately unhide.
1920 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id
));
1921 $DB->set_field('course', 'visible', 0, array('category' => $this->id
));
1922 // Get all child categories and hide too.
1923 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
1924 foreach ($subcats as $cat) {
1925 $DB->set_field('course_categories', 'visibleold', $cat->visible
, array('id' => $cat->id
));
1926 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id
));
1927 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id
));
1928 $DB->set_field('course', 'visible', 0, array('category' => $cat->id
));
1935 * Hide course category and child course and subcategories
1937 * Note that there is no capability check inside this function
1939 * This function does not update field course_categories.timemodified
1940 * If you want to update timemodified, use
1941 * $coursecat->update(array('visible' => 0));
1943 public function hide() {
1944 if ($this->hide_raw(0)) {
1945 cache_helper
::purge_by_event('changesincoursecat');
1946 add_to_log(SITEID
, "category", "hide", "editcategory.php?id=$this->id", $this->id
);
1951 * Show course category and restores visibility for child course and subcategories
1953 * Note that there is no capability check inside this function
1955 * This is protected function, use show() or update() from outside of this class
1957 * @see coursecat::show()
1958 * @see coursecat::update()
1960 * @return bool whether changes have been made and caches need to be purged afterwards
1962 protected function show_raw() {
1965 if ($this->visible
) {
1971 $this->visibleold
= 1;
1972 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id
));
1973 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id
));
1974 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id
));
1975 // Get all child categories and unhide too.
1976 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
1977 foreach ($subcats as $cat) {
1978 if ($cat->visibleold
) {
1979 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id
));
1981 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id
));
1988 * Show course category and restores visibility for child course and subcategories
1990 * Note that there is no capability check inside this function
1992 * This function does not update field course_categories.timemodified
1993 * If you want to update timemodified, use
1994 * $coursecat->update(array('visible' => 1));
1996 public function show() {
1997 if ($this->show_raw()) {
1998 cache_helper
::purge_by_event('changesincoursecat');
1999 add_to_log(SITEID
, "category", "show", "editcategory.php?id=$this->id", $this->id
);
2004 * Returns name of the category formatted as a string
2006 * @param array $options formatting options other than context
2009 public function get_formatted_name($options = array()) {
2011 $context = $this->get_context();
2012 return format_string($this->name
, true, array('context' => $context) +
$options);
2014 return ''; // TODO 'Top'?.
2019 * Returns ids of all parents of the category. Last element in the return array is the direct parent
2021 * For example, if you have a tree of categories like:
2022 * Miscellaneous (id = 1)
2023 * Subcategory (id = 2)
2024 * Sub-subcategory (id = 4)
2025 * Other category (id = 3)
2027 * coursecat::get(1)->get_parents() == array()
2028 * coursecat::get(2)->get_parents() == array(1)
2029 * coursecat::get(4)->get_parents() == array(1, 2);
2031 * Note that this method does not check if all parents are accessible by current user
2033 * @return array of category ids
2035 public function get_parents() {
2036 $parents = preg_split('|/|', $this->path
, 0, PREG_SPLIT_NO_EMPTY
);
2037 array_pop($parents);
2042 * This function returns a nice list representing category tree
2043 * for display or to use in a form <select> element
2045 * List is cached for 10 minutes
2047 * For example, if you have a tree of categories like:
2048 * Miscellaneous (id = 1)
2049 * Subcategory (id = 2)
2050 * Sub-subcategory (id = 4)
2051 * Other category (id = 3)
2052 * Then after calling this function you will have
2053 * array(1 => 'Miscellaneous',
2054 * 2 => 'Miscellaneous / Subcategory',
2055 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2056 * 3 => 'Other category');
2058 * If you specify $requiredcapability, then only categories where the current
2059 * user has that capability will be added to $list.
2060 * If you only have $requiredcapability in a child category, not the parent,
2061 * then the child catgegory will still be included.
2063 * If you specify the option $excludeid, then that category, and all its children,
2064 * are omitted from the tree. This is useful when you are doing something like
2065 * moving categories, where you do not want to allow people to move a category
2066 * to be the child of itself.
2068 * See also {@link make_categories_options()}
2070 * @param string/array $requiredcapability if given, only categories where the current
2071 * user has this capability will be returned. Can also be an array of capabilities,
2072 * in which case they are all required.
2073 * @param integer $excludeid Exclude this category and its children from the lists built.
2074 * @param string $separator string to use as a separator between parent and child category. Default ' / '
2075 * @return array of strings
2077 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
2079 $coursecatcache = cache
::make('core', 'coursecat');
2081 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids
2082 // with requried cap ($thislist).
2083 $basecachekey = 'catlist';
2084 $baselist = $coursecatcache->get($basecachekey);
2086 $thiscachekey = null;
2087 if (!empty($requiredcapability)) {
2088 $requiredcapability = (array)$requiredcapability;
2089 $thiscachekey = 'catlist:'. serialize($requiredcapability);
2090 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
2091 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY
);
2093 } else if ($baselist !== false) {
2094 $thislist = array_keys($baselist);
2097 if ($baselist === false) {
2098 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
2099 $ctxselect = context_helper
::get_preload_record_columns_sql('ctx');
2100 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
2101 FROM {course_categories} cc
2102 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
2103 ORDER BY cc.sortorder";
2104 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT
));
2105 $baselist = array();
2106 $thislist = array();
2107 foreach ($rs as $record) {
2108 // If the category's parent is not visible to the user, it is not visible as well.
2109 if (!$record->parent ||
isset($baselist[$record->parent
])) {
2110 context_helper
::preload_from_record($record);
2111 $context = context_coursecat
::instance($record->id
);
2112 if (!$record->visible
&& !has_capability('moodle/category:viewhiddencategories', $context)) {
2113 // No cap to view category, added to neither $baselist nor $thislist.
2116 $baselist[$record->id
] = array(
2117 'name' => format_string($record->name
, true, array('context' => $context)),
2118 'path' => $record->path
2120 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
2121 // No required capability, added to $baselist but not to $thislist.
2124 $thislist[] = $record->id
;
2128 $coursecatcache->set($basecachekey, $baselist);
2129 if (!empty($requiredcapability)) {
2130 $coursecatcache->set($thiscachekey, join(',', $thislist));
2132 } else if ($thislist === false) {
2133 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
2134 $ctxselect = context_helper
::get_preload_record_columns_sql('ctx');
2135 $sql = "SELECT ctx.instanceid AS id, $ctxselect
2136 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
2137 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT
));
2138 $thislist = array();
2139 foreach (array_keys($baselist) as $id) {
2140 context_helper
::preload_from_record($contexts[$id]);
2141 if (has_all_capabilities($requiredcapability, context_coursecat
::instance($id))) {
2145 $coursecatcache->set($thiscachekey, join(',', $thislist));
2148 // Now build the array of strings to return, mind $separator and $excludeid.
2150 foreach ($thislist as $id) {
2151 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY
);
2152 if (!$excludeid ||
!in_array($excludeid, $path)) {
2153 $namechunks = array();
2154 foreach ($path as $parentid) {
2155 $namechunks[] = $baselist[$parentid]['name'];
2157 $names[$id] = join($separator, $namechunks);
2164 * Prepares the object for caching. Works like the __sleep method.
2166 * implementing method from interface cacheable_object
2168 * @return array ready to be cached
2170 public function prepare_to_cache() {
2172 foreach (self
::$coursecatfields as $property => $cachedirectives) {
2173 if ($cachedirectives !== null) {
2174 list($shortname, $defaultvalue) = $cachedirectives;
2175 if ($this->$property !== $defaultvalue) {
2176 $a[$shortname] = $this->$property;
2180 $context = $this->get_context();
2181 $a['xi'] = $context->id
;
2182 $a['xp'] = $context->path
;
2187 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2189 * implementing method from interface cacheable_object
2194 public static function wake_from_cache($a) {
2195 $record = new stdClass
;
2196 foreach (self
::$coursecatfields as $property => $cachedirectives) {
2197 if ($cachedirectives !== null) {
2198 list($shortname, $defaultvalue) = $cachedirectives;
2199 if (array_key_exists($shortname, $a)) {
2200 $record->$property = $a[$shortname];
2202 $record->$property = $defaultvalue;
2206 $record->ctxid
= $a['xi'];
2207 $record->ctxpath
= $a['xp'];
2208 $record->ctxdepth
= $record->depth +
1;
2209 $record->ctxlevel
= CONTEXT_COURSECAT
;
2210 $record->ctxinstance
= $record->id
;
2211 return new coursecat($record, true);
2215 * Returns true if the user is able to create a top level category.
2218 public static function can_create_top_level_category() {
2219 return has_capability('moodle/category:manage', context_system
::instance());
2223 * Returns the category context.
2224 * @return context_coursecat
2226 public function get_context() {
2227 if ($this->id
=== 0) {
2228 // This is the special top level category object.
2229 return context_system
::instance();
2231 return context_coursecat
::instance($this->id
);
2236 * Returns true if the user is able to manage this category.
2239 public function has_manage_capability() {
2240 if ($this->hasmanagecapability
=== null) {
2241 $this->hasmanagecapability
= has_capability('moodle/category:manage', $this->get_context());
2243 return $this->hasmanagecapability
;
2247 * Returns true if the user has the manage capability on the parent category.
2250 public function parent_has_manage_capability() {
2251 return has_capability('moodle/category:manage', get_category_or_system_context($this->parent
));
2255 * Returns true if the current user can create subcategories of this category.
2258 public function can_create_subcategory() {
2259 return $this->has_manage_capability();
2263 * Returns true if the user can resort this categories sub categories and courses.
2266 public function can_resort_subcategories() {
2267 return $this->has_manage_capability();
2271 * Returns true if the user can resort the courses within this category.
2274 public function can_resort_courses() {
2275 return $this->has_manage_capability();
2279 * Returns true of the user can change the sortorder of this category (resort the parent category)
2282 public function can_change_sortorder() {
2283 return $this->parent_has_manage_capability();
2287 * Returns true if the current user can create a course within this category.
2290 public function can_create_course() {
2291 return has_capability('moodle/course:create', $this->get_context());
2295 * Returns true if the current user can edit this categories settings.
2298 public function can_edit() {
2299 return $this->has_manage_capability();
2303 * Returns true if the current user can review role assignments for this category.
2306 public function can_review_roles() {
2307 return has_capability('moodle/role:assign', $this->get_context());
2311 * Returns true if the current user can review permissions for this category.
2314 public function can_review_permissions() {
2315 return has_any_capability(array(
2316 'moodle/role:assign',
2317 'moodle/role:safeoverride',
2318 'moodle/role:override',
2319 'moodle/role:assign'
2320 ), $this->get_context());
2324 * Returns true if the current user can review cohorts for this category.
2327 public function can_review_cohorts() {
2328 return has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->get_context());
2332 * Returns true if the current user can review filter settings for this category.
2335 public function can_review_filters() {
2336 return has_capability('moodle/filter:manage', $this->get_context()) &&
2337 count(filter_get_available_in_context($this->get_context()))>0;
2341 * Returns true if the current user is able to change the visbility of this category.
2344 public function can_change_visibility() {
2345 return $this->parent_has_manage_capability();
2349 * Returns true if the user can move courses out of this category.
2352 public function can_move_courses_out_of() {
2353 return $this->has_manage_capability();
2357 * Returns true if the user can move courses into this category.
2360 public function can_move_courses_into() {
2361 return $this->has_manage_capability();
2365 * Resorts the sub categories of this category by the given field.
2367 * @param string $field
2368 * @param bool $cleanup If true cleanup will be done, if false you will need to do it manually later.
2369 * @return bool True on success.
2370 * @throws coding_exception
2372 public function resort_subcategories($field, $cleanup = true) {
2374 if ($field !== 'name' && $field !== 'idnumber') {
2375 throw new coding_exception('Invalid field requested');
2377 $children = $this->get_children();
2378 core_collator
::asort_objects_by_property($children, $field, core_collator
::SORT_NATURAL
);
2380 foreach ($children as $cat) {
2382 $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id
));
2383 $i +
= $cat->coursecount
;
2386 self
::resort_categories_cleanup();
2392 * Cleans things up after categories have been resorted.
2394 public static function resort_categories_cleanup() {
2395 // This should not be needed but we do it just to be safe.
2396 fix_course_sortorder();
2397 cache_helper
::purge_by_event('changesincoursecat');
2401 * Resort the courses within this category by the given field.
2403 * @param string $field One of fullname, shortname or idnumber
2404 * @param bool $cleanup
2405 * @return bool True for success.
2406 * @throws coding_exception
2408 public function resort_courses($field, $cleanup = true) {
2410 if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber') {
2411 // This is ultra important as we use $field in an SQL statement below this.
2412 throw new coding_exception('Invalid field requested');
2414 $ctxfields = context_helper
::get_preload_record_columns_sql('ctx');
2415 $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields
2417 LEFT JOIN {context} ctx ON ctx.instanceid = c.id
2418 WHERE ctx.contextlevel = :ctxlevel AND
2419 c.category = :categoryid
2420 ORDER BY c.{$field}, c.sortorder";
2422 'ctxlevel' => CONTEXT_COURSE
,
2423 'categoryid' => $this->id
2425 $courses = $DB->get_records_sql($sql, $params);
2426 if (count($courses) > 0) {
2427 foreach ($courses as $courseid => $course) {
2428 context_helper
::preload_from_record($course);
2429 if ($field === 'idnumber') {
2430 $course->sortby
= $course->idnumber
;
2432 // It'll require formatting.
2434 'context' => context_course
::instance($course->id
)
2436 // We format the string first so that it appears as the user would see it.
2437 // This ensures the sorting makes sense to them. However it won't necessarily make
2438 // sense to everyone if things like multilang filters are enabled.
2439 // We then strip any tags as we don't want things such as image tags skewing the
2441 $course->sortby
= strip_tags(format_string($course->$field, true, $options));
2443 // We set it back here rather than using references as there is a bug with using
2444 // references in a foreach before passing as an arg by reference.
2445 $courses[$courseid] = $course;
2447 // Sort the courses.
2448 core_collator
::asort_objects_by_property($courses, 'sortby', core_collator
::SORT_NATURAL
);
2450 foreach ($courses as $course) {
2451 $DB->set_field('course', 'sortorder', $this->sortorder +
$i, array('id' => $course->id
));
2455 // This should not be needed but we do it just to be safe.
2456 fix_course_sortorder();
2457 cache_helper
::purge_by_event('changesincourse');
2464 * Changes the sort order of this categories parent shifting this category up or down one.
2466 * @global \moodle_database $DB
2467 * @param bool $up If set to true the category is shifted up one spot, else its moved down.
2468 * @return bool True on success, false otherwise.
2470 public function change_sortorder_by_one($up) {
2472 $params = array($this->sortorder
, $this->parent
);
2474 $select = 'sortorder < ? AND parent = ?';
2475 $sort = 'sortorder DESC';
2477 $select = 'sortorder > ? AND parent = ?';
2478 $sort = 'sortorder ASC';
2480 fix_course_sortorder();
2481 $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1);
2482 $swapcategory = reset($swapcategory);
2483 if ($swapcategory) {
2484 $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder
, array('id' => $this->id
));
2485 $DB->set_field('course_categories', 'sortorder', $this->sortorder
, array('id' => $swapcategory->id
));
2486 $this->sortorder
= $swapcategory->sortorder
;
2487 add_to_log(SITEID
, "category", "move", "management.php?categoryid={$this->id}", $this->id
);
2488 // Finally reorder courses.
2489 fix_course_sortorder();
2490 cache_helper
::purge_by_event('changesincoursecat');
2497 * Returns the parent coursecat object for this category.
2501 public function get_parent_coursecat() {
2502 return self
::get($this->parent
);
2507 * Returns true if the user is able to request a new course be created.
2510 public function can_request_course() {
2512 if (empty($CFG->enablecourserequests
) ||
$this->id
!= $CFG->defaultrequestcategory
) {
2515 return !$this->can_create_course() && has_capability('moodle/course:request', $this->get_context());
2519 * Returns true if the user can approve course requests.
2522 public static function can_approve_course_requests() {
2524 if (empty($CFG->enablecourserequests
)) {
2527 $context = context_system
::instance();
2528 if (!has_capability('moodle/site:approvecourse', $context)) {
2531 if (!$DB->record_exists('course_request', array())) {
2539 * Class to store information about one course in a list of courses
2541 * Not all information may be retrieved when object is created but
2542 * it will be retrieved on demand when appropriate property or method is
2545 * Instances of this class are usually returned by functions
2546 * {@link coursecat::search_courses()}
2548 * {@link coursecat::get_courses()}
2550 * @property-read int $id
2551 * @property-read int $category Category ID
2552 * @property-read int $sortorder
2553 * @property-read string $fullname
2554 * @property-read string $shortname
2555 * @property-read string $idnumber
2556 * @property-read string $summary Course summary. Field is present if coursecat::get_courses()
2557 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2558 * @property-read int $summaryformat Summary format. Field is present if coursecat::get_courses()
2559 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2560 * @property-read string $format Course format. Retrieved from DB on first request
2561 * @property-read int $showgrades Retrieved from DB on first request
2562 * @property-read int $newsitems Retrieved from DB on first request
2563 * @property-read int $startdate
2564 * @property-read int $marker Retrieved from DB on first request
2565 * @property-read int $maxbytes Retrieved from DB on first request
2566 * @property-read int $legacyfiles Retrieved from DB on first request
2567 * @property-read int $showreports Retrieved from DB on first request
2568 * @property-read int $visible
2569 * @property-read int $visibleold Retrieved from DB on first request
2570 * @property-read int $groupmode Retrieved from DB on first request
2571 * @property-read int $groupmodeforce Retrieved from DB on first request
2572 * @property-read int $defaultgroupingid Retrieved from DB on first request
2573 * @property-read string $lang Retrieved from DB on first request
2574 * @property-read string $theme Retrieved from DB on first request
2575 * @property-read int $timecreated Retrieved from DB on first request
2576 * @property-read int $timemodified Retrieved from DB on first request
2577 * @property-read int $requested Retrieved from DB on first request
2578 * @property-read int $enablecompletion Retrieved from DB on first request
2579 * @property-read int $completionnotify Retrieved from DB on first request
2580 * @property-read int $cacherev
2583 * @subpackage course
2584 * @copyright 2013 Marina Glancy
2585 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2587 class course_in_list
implements IteratorAggregate
{
2589 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2592 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2593 protected $coursecontacts;
2595 /** @var bool true if the current user can access the course, false otherwise. */
2596 protected $canaccess = null;
2599 * Creates an instance of the class from record
2601 * @param stdClass $record except fields from course table it may contain
2602 * field hassummary indicating that summary field is not empty.
2603 * Also it is recommended to have context fields here ready for
2604 * context preloading
2606 public function __construct(stdClass
$record) {
2607 context_helper
::preload_from_record($record);
2608 $this->record
= new stdClass();
2609 foreach ($record as $key => $value) {
2610 $this->record
->$key = $value;
2615 * Indicates if the course has non-empty summary field
2619 public function has_summary() {
2620 if (isset($this->record
->hassummary
)) {
2621 return !empty($this->record
->hassummary
);
2623 if (!isset($this->record
->summary
)) {
2624 // We need to retrieve summary.
2625 $this->__get('summary');
2627 return !empty($this->record
->summary
);
2631 * Indicates if the course have course contacts to display
2635 public function has_course_contacts() {
2636 if (!isset($this->record
->managers
)) {
2637 $courses = array($this->id
=> &$this->record
);
2638 coursecat
::preload_course_contacts($courses);
2640 return !empty($this->record
->managers
);
2644 * Returns list of course contacts (usually teachers) to display in course link
2646 * Roles to display are set up in $CFG->coursecontact
2648 * The result is the list of users where user id is the key and the value
2649 * is an array with elements:
2650 * - 'user' - object containing basic user information
2651 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2652 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2653 * - 'username' => fullname($user, $canviewfullnames)
2657 public function get_course_contacts() {
2659 if (empty($CFG->coursecontact
)) {
2660 // No roles are configured to be displayed as course contacts.
2663 if ($this->coursecontacts
=== null) {
2664 $this->coursecontacts
= array();
2665 $context = context_course
::instance($this->id
);
2667 if (!isset($this->record
->managers
)) {
2668 // Preload course contacts from DB.
2669 $courses = array($this->id
=> &$this->record
);
2670 coursecat
::preload_course_contacts($courses);
2673 // Build return array with full roles names (for this course context) and users names.
2674 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2675 foreach ($this->record
->managers
as $ruser) {
2676 if (isset($this->coursecontacts
[$ruser->id
])) {
2677 // Only display a user once with the highest sortorder role.
2680 $user = new stdClass();
2681 $user->id
= $ruser->id
;
2682 $user->username
= $ruser->username
;
2683 foreach (get_all_user_name_fields() as $addname) {
2684 $user->$addname = $ruser->$addname;
2686 $role = new stdClass();
2687 $role->id
= $ruser->roleid
;
2688 $role->name
= $ruser->rolename
;
2689 $role->shortname
= $ruser->roleshortname
;
2690 $role->coursealias
= $ruser->rolecoursealias
;
2692 $this->coursecontacts
[$user->id
] = array(
2695 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS
),
2696 'username' => fullname($user, $canviewfullnames)
2700 return $this->coursecontacts
;
2704 * Checks if course has any associated overview files
2708 public function has_course_overviewfiles() {
2710 if (empty($CFG->courseoverviewfileslimit
)) {
2713 $fs = get_file_storage();
2714 $context = context_course
::instance($this->id
);
2715 return !$fs->is_area_empty($context->id
, 'course', 'overviewfiles');
2719 * Returns all course overview files
2721 * @return array array of stored_file objects
2723 public function get_course_overviewfiles() {
2725 if (empty($CFG->courseoverviewfileslimit
)) {
2728 require_once($CFG->libdir
. '/filestorage/file_storage.php');
2729 require_once($CFG->dirroot
. '/course/lib.php');
2730 $fs = get_file_storage();
2731 $context = context_course
::instance($this->id
);
2732 $files = $fs->get_area_files($context->id
, 'course', 'overviewfiles', false, 'filename', false);
2733 if (count($files)) {
2734 $overviewfilesoptions = course_overviewfiles_options($this->id
);
2735 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2736 if ($acceptedtypes !== '*') {
2737 // Filter only files with allowed extensions.
2738 require_once($CFG->libdir
. '/filelib.php');
2739 foreach ($files as $key => $file) {
2740 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2741 unset($files[$key]);
2745 if (count($files) > $CFG->courseoverviewfileslimit
) {
2746 // Return no more than $CFG->courseoverviewfileslimit files.
2747 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit
, true);
2754 * Magic method to check if property is set
2756 * @param string $name
2759 public function __isset($name) {
2760 return isset($this->record
->$name);
2764 * Magic method to get a course property
2766 * Returns any field from table course (retrieves it from DB if it was not retrieved before)
2768 * @param string $name
2771 public function __get($name) {
2773 if (property_exists($this->record
, $name)) {
2774 return $this->record
->$name;
2775 } else if ($name === 'summary' ||
$name === 'summaryformat') {
2776 // Retrieve fields summary and summaryformat together because they are most likely to be used together.
2777 $record = $DB->get_record('course', array('id' => $this->record
->id
), 'summary, summaryformat', MUST_EXIST
);
2778 $this->record
->summary
= $record->summary
;
2779 $this->record
->summaryformat
= $record->summaryformat
;
2780 return $this->record
->$name;
2781 } else if (array_key_exists($name, $DB->get_columns('course'))) {
2782 // Another field from table 'course' that was not retrieved.
2783 $this->record
->$name = $DB->get_field('course', $name, array('id' => $this->record
->id
), MUST_EXIST
);
2784 return $this->record
->$name;
2786 debugging('Invalid course property accessed! '.$name);
2791 * All properties are read only, sorry.
2793 * @param string $name
2795 public function __unset($name) {
2796 debugging('Can not unset '.get_class($this).' instance properties!');
2800 * Magic setter method, we do not want anybody to modify properties from the outside
2802 * @param string $name
2803 * @param mixed $value
2805 public function __set($name, $value) {
2806 debugging('Can not change '.get_class($this).' instance properties!');
2810 * Create an iterator because magic vars can't be seen by 'foreach'.
2811 * Exclude context fields
2813 * Implementing method from interface IteratorAggregate
2815 * @return ArrayIterator
2817 public function getIterator() {
2818 $ret = array('id' => $this->record
->id
);
2819 foreach ($this->record
as $property => $value) {
2820 $ret[$property] = $value;
2822 return new ArrayIterator($ret);
2826 * Returns the name of this course as it should be displayed within a list.
2829 public function get_formatted_name() {
2830 return format_string(get_course_display_name_for_list($this), true, $this->get_context());
2834 * Returns the formatted fullname for this course.
2837 public function get_formatted_fullname() {
2838 return format_string($this->__get('fullname'), true, $this->get_context());
2842 * Returns the formatted shortname for this course.
2845 public function get_formatted_shortname() {
2846 return format_string($this->__get('shortname'), true, $this->get_context());
2850 * Returns true if the current user can access this course.
2853 public function can_access() {
2854 if ($this->canaccess
=== null) {
2855 $this->canaccess
= can_access_course($this->record
);
2857 return $this->canaccess
;
2861 * Returns true if the user can edit this courses settings.
2863 * Note: this function does not check that the current user can access the course.
2864 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2868 public function can_edit() {
2869 return has_capability('moodle/course:update', $this->get_context());
2873 * Returns true if the user can change the visibility of this course.
2875 * Note: this function does not check that the current user can access the course.
2876 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2880 public function can_change_visibility() {
2881 // You must be able to both hide a course and view the hidden course.
2882 return has_all_capabilities(array('moodle/course:visibility', 'moodle/course:viewhiddencourses'), $this->get_context());
2886 * Returns the context for this course.
2887 * @return context_course
2889 public function get_context() {
2890 return context_course
::instance($this->__get('id'));
2894 * Returns true if this course is visible to the current user.
2897 public function is_uservisible() {
2898 return $this->visible ||
has_capability('moodle/course:viewhiddencourses', $this->get_context());
2902 * Returns true if the current user can review enrolments for this course.
2904 * Note: this function does not check that the current user can access the course.
2905 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2909 public function can_review_enrolments() {
2910 return has_capability('moodle/course:enrolreview', $this->get_context());
2914 * Returns true if the current user can delete this course.
2916 * Note: this function does not check that the current user can access the course.
2917 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2921 public function can_delete() {
2922 return can_delete_course($this->id
);
2926 * Returns true if the current user can backup this course.
2928 * Note: this function does not check that the current user can access the course.
2929 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2933 public function can_backup() {
2934 return has_capability('moodle/backup:backupcourse', $this->get_context());
2938 * Returns true if the current user can restore this course.
2940 * Note: this function does not check that the current user can access the course.
2941 * To do that please call require_login with the course, or if not possible call {@see course_in_list::can_access()}
2945 public function can_restore() {
2946 return has_capability('moodle/restore:restorecourse', $this->get_context());
2951 * An array of records that is sortable by many fields.
2953 * For more info on the ArrayObject class have a look at php.net.
2956 * @subpackage course
2957 * @copyright 2013 Sam Hemelryk
2958 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2960 class coursecat_sortable_records
extends ArrayObject
{
2963 * An array of sortable fields.
2964 * Gets set temporarily when sort is called.
2967 protected $sortfields = array();
2970 * Sorts this array using the given fields.
2972 * @param array $records
2973 * @param array $fields
2976 public static function sort(array $records, array $fields) {
2977 $records = new coursecat_sortable_records($records);
2978 $records->sortfields
= $fields;
2979 $records->uasort(array($records, 'sort_by_many_fields'));
2980 return $records->getArrayCopy();
2984 * Sorts the two records based upon many fields.
2986 * This method should not be called itself, please call $sort instead.
2987 * It has been marked as access private as such.
2990 * @param stdClass $a
2991 * @param stdClass $b
2994 public function sort_by_many_fields($a, $b) {
2995 foreach ($this->sortfields
as $field => $mult) {
2997 if (is_null($a->$field) && !is_null($b->$field)) {
3000 if (is_null($b->$field) && !is_null($a->$field)) {
3004 if (is_string($a->$field) ||
is_string($b->$field)) {
3006 if ($cmp = strcoll($a->$field, $b->$field)) {
3007 return $mult * $cmp;
3011 if ($a->$field > $b->$field) {
3014 if ($a->$field < $b->$field) {