MDL-38596 Added caching to the list of course contacts
[moodle.git] / lib / coursecatlib.php
blob607342d7db3e5a8e063365b3115fbc353fe57a6e
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Contains class coursecat reponsible for course category operations
20 * @package core
21 * @subpackage course
22 * @copyright 2013 Marina Glancy
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /**
29 * Class to store, cache, render and manage course category
31 * @package core
32 * @subpackage course
33 * @copyright 2013 Marina Glancy
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 class coursecat implements renderable, cacheable_object, IteratorAggregate {
37 /** @var coursecat stores pseudo category with id=0. Use coursecat::get(0) to retrieve */
38 protected static $coursecat0;
40 const CACHE_COURSE_CONTACTS_TTL = 3600; // do not fetch course contacts more often than once per hour
42 /** @var array list of all fields and their short name and default value for caching */
43 protected static $coursecatfields = array(
44 'id' => array('id', 0),
45 'name' => array('na', ''),
46 'idnumber' => array('in', null),
47 'description' => null, // not cached
48 'descriptionformat' => null, // not cached
49 'parent' => array('pa', 0),
50 'sortorder' => array('so', 0),
51 'coursecount' => null, // not cached
52 'visible' => array('vi', 1),
53 'visibleold' => null, // not cached
54 'timemodified' => null, // not cached
55 'depth' => array('dh', 1),
56 'path' => array('ph', null),
57 'theme' => null, // not cached
60 /** @var int */
61 protected $id;
63 /** @var string */
64 protected $name = '';
66 /** @var string */
67 protected $idnumber = null;
69 /** @var string */
70 protected $description = false;
72 /** @var int */
73 protected $descriptionformat = false;
75 /** @var int */
76 protected $parent = 0;
78 /** @var int */
79 protected $sortorder = 0;
81 /** @var int */
82 protected $coursecount = false;
84 /** @var int */
85 protected $visible = 1;
87 /** @var int */
88 protected $visibleold = false;
90 /** @var int */
91 protected $timemodified = false;
93 /** @var int */
94 protected $depth = 0;
96 /** @var string */
97 protected $path = '';
99 /** @var string */
100 protected $theme = false;
102 /** @var bool */
103 protected $fromcache;
105 // ====== magic methods =======
108 * Magic setter method, we do not want anybody to modify properties from the outside
110 * @param string $name
111 * @param mixed $value
113 public function __set($name, $value) {
114 debugging('Can not change coursecat instance properties!', DEBUG_DEVELOPER);
118 * Magic method getter, redirects to read only values. Queries from DB the fields that were not cached
120 * @param string $name
121 * @return mixed
123 public function __get($name) {
124 global $DB;
125 if (array_key_exists($name, self::$coursecatfields)) {
126 if ($this->$name === false) {
127 // property was not retrieved from DB, retrieve all not retrieved fields
128 $notretrievedfields = array_diff_key(self::$coursecatfields, array_filter(self::$coursecatfields));
129 $record = $DB->get_record('course_categories', array('id' => $this->id),
130 join(',', array_keys($notretrievedfields)), MUST_EXIST);
131 foreach ($record as $key => $value) {
132 $this->$key = $value;
135 return $this->$name;
137 debugging('Invalid coursecat property accessed! '.$name, DEBUG_DEVELOPER);
138 return null;
142 * Full support for isset on our magic read only properties.
144 * @param string $name
145 * @return bool
147 public function __isset($name) {
148 if (array_key_exists($name, self::$coursecatfields)) {
149 return isset($this->$name);
151 return false;
155 * All properties are read only, sorry.
157 * @param string $name
159 public function __unset($name) {
160 debugging('Can not unset coursecat instance properties!', DEBUG_DEVELOPER);
164 * Create an iterator because magic vars can't be seen by 'foreach'.
166 * implementing method from interface IteratorAggregate
168 * @return ArrayIterator
170 public function getIterator() {
171 $ret = array();
172 foreach (self::$coursecatfields as $property => $unused) {
173 if ($this->$property !== false) {
174 $ret[$property] = $this->$property;
177 return new ArrayIterator($ret);
181 * Constructor
183 * Constructor is protected, use coursecat::get($id) to retrieve category
185 * @param stdClass $record record from DB (may not contain all fields)
186 * @param bool $fromcache whether it is being restored from cache
188 protected function __construct(stdClass $record, $fromcache = false) {
189 context_helper::preload_from_record($record);
190 foreach ($record as $key => $val) {
191 if (array_key_exists($key, self::$coursecatfields)) {
192 $this->$key = $val;
195 $this->fromcache = $fromcache;
199 * Returns coursecat object for requested category
201 * If category is not visible to user it is treated as non existing
202 * unless $alwaysreturnhidden is set to true
204 * If id is 0, the pseudo object for root category is returned (convenient
205 * for calling other functions such as get_children())
207 * @param int $id category id
208 * @param int $strictness whether to throw an exception (MUST_EXIST) or
209 * return null (IGNORE_MISSING) in case the category is not found or
210 * not visible to current user
211 * @param bool $alwaysreturnhidden set to true if you want an object to be
212 * returned even if this category is not visible to the current user
213 * (category is hidden and user does not have
214 * 'moodle/category:viewhiddencategories' capability). Use with care!
215 * @return null|coursecat
217 public static function get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false) {
218 if (!$id) {
219 if (!isset(self::$coursecat0)) {
220 $record = new stdClass();
221 $record->id = 0;
222 $record->visible = 1;
223 $record->depth = 0;
224 $record->path = '';
225 self::$coursecat0 = new coursecat($record);
227 return self::$coursecat0;
229 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
230 $coursecat = $coursecatrecordcache->get($id);
231 if ($coursecat === false) {
232 if ($records = self::get_records('cc.id = :id', array('id' => $id))) {
233 $record = reset($records);
234 $coursecat = new coursecat($record);
235 // Store in cache
236 $coursecatrecordcache->set($id, $coursecat);
239 if ($coursecat && ($alwaysreturnhidden || $coursecat->is_uservisible())) {
240 return $coursecat;
241 } else {
242 if ($strictness == MUST_EXIST) {
243 throw new moodle_exception('unknowcategory');
246 return null;
250 * Returns the first found category
252 * Note that if there are no categories visible to the current user on the first level,
253 * the invisible category may be returned
255 * @return coursecat
257 public static function get_default() {
258 if ($visiblechildren = self::get(0)->get_children()) {
259 $defcategory = reset($visiblechildren);
260 } else {
261 $toplevelcategories = self::get_tree(0);
262 $defcategoryid = $toplevelcategories[0];
263 $defcategory = self::get($defcategoryid, MUST_EXIST, true);
265 return $defcategory;
269 * Restores the object after it has been externally modified in DB for example
270 * during {@link fix_course_sortorder()}
272 protected function restore() {
273 // update all fields in the current object
274 $newrecord = self::get($this->id, MUST_EXIST, true);
275 foreach (self::$coursecatfields as $key => $unused) {
276 $this->$key = $newrecord->$key;
281 * Creates a new category either from form data or from raw data
283 * Please note that this function does not verify access control.
285 * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
287 * Category visibility is inherited from parent unless $data->visible = 0 is specified
289 * @param array|stdClass $data
290 * @param array $editoroptions if specified, the data is considered to be
291 * form data and file_postupdate_standard_editor() is being called to
292 * process images in description.
293 * @return coursecat
294 * @throws moodle_exception
296 public static function create($data, $editoroptions = null) {
297 global $DB, $CFG;
298 $data = (object)$data;
299 $newcategory = new stdClass();
301 $newcategory->descriptionformat = FORMAT_MOODLE;
302 $newcategory->description = '';
303 // copy all description* fields regardless of whether this is form data or direct field update
304 foreach ($data as $key => $value) {
305 if (preg_match("/^description/", $key)) {
306 $newcategory->$key = $value;
310 if (empty($data->name)) {
311 throw new moodle_exception('categorynamerequired');
313 if (textlib::strlen($data->name) > 255) {
314 throw new moodle_exception('categorytoolong');
316 $newcategory->name = $data->name;
318 // validate and set idnumber
319 if (!empty($data->idnumber)) {
320 if (textlib::strlen($data->idnumber) > 100) {
321 throw new moodle_exception('idnumbertoolong');
323 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
324 throw new moodle_exception('categoryidnumbertaken');
327 if (isset($data->idnumber)) {
328 $newcategory->idnumber = $data->idnumber;
331 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
332 $newcategory->theme = $data->theme;
335 if (empty($data->parent)) {
336 $parent = self::get(0);
337 } else {
338 $parent = self::get($data->parent, MUST_EXIST, true);
340 $newcategory->parent = $parent->id;
341 $newcategory->depth = $parent->depth + 1;
343 // By default category is visible, unless visible = 0 is specified or parent category is hidden
344 if (isset($data->visible) && !$data->visible) {
345 // create a hidden category
346 $newcategory->visible = $newcategory->visibleold = 0;
347 } else {
348 // create a category that inherits visibility from parent
349 $newcategory->visible = $parent->visible;
350 // in case parent is hidden, when it changes visibility this new subcategory will automatically become visible too
351 $newcategory->visibleold = 1;
354 $newcategory->sortorder = 0;
355 $newcategory->timemodified = time();
357 $newcategory->id = $DB->insert_record('course_categories', $newcategory);
359 // update path (only possible after we know the category id
360 $path = $parent->path . '/' . $newcategory->id;
361 $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));
363 // We should mark the context as dirty
364 context_coursecat::instance($newcategory->id)->mark_dirty();
366 fix_course_sortorder();
368 // if this is data from form results, save embedded files and update description
369 $categorycontext = context_coursecat::instance($newcategory->id);
370 if ($editoroptions) {
371 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext, 'coursecat', 'description', 0);
373 // update only fields description and descriptionformat
374 $updatedata = new stdClass();
375 $updatedata->id = $newcategory->id;
376 $updatedata->description = $newcategory->description;
377 $updatedata->descriptionformat = $newcategory->descriptionformat;
378 $DB->update_record('course_categories', $updatedata);
381 add_to_log(SITEID, "category", 'add', "editcategory.php?id=$newcategory->id", $newcategory->id);
382 cache_helper::purge_by_event('changesincoursecat');
384 return self::get($newcategory->id, MUST_EXIST, true);
388 * Updates the record with either form data or raw data
390 * Please note that this function does not verify access control.
392 * This function calls coursecat::change_parent_raw if field 'parent' is updated.
393 * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
394 * Visibility is changed first and then parent is changed. This means that
395 * if parent category is hidden, the current category will become hidden
396 * too and it may overwrite whatever was set in field 'visible'.
398 * Note that fields 'path' and 'depth' can not be updated manually
399 * Also coursecat::update() can not directly update the field 'sortoder'
401 * @param array|stdClass $data
402 * @param array $editoroptions if specified, the data is considered to be
403 * form data and file_postupdate_standard_editor() is being called to
404 * process images in description.
405 * @throws moodle_exception
407 public function update($data, $editoroptions = null) {
408 global $DB, $CFG;
409 if (!$this->id) {
410 // there is no actual DB record associated with root category
411 return;
414 $data = (object)$data;
415 $newcategory = new stdClass();
416 $newcategory->id = $this->id;
418 // copy all description* fields regardless of whether this is form data or direct field update
419 foreach ($data as $key => $value) {
420 if (preg_match("/^description/", $key)) {
421 $newcategory->$key = $value;
425 if (isset($data->name) && empty($data->name)) {
426 throw new moodle_exception('categorynamerequired');
429 if (!empty($data->name) && $data->name !== $this->name) {
430 if (textlib::strlen($data->name) > 255) {
431 throw new moodle_exception('categorytoolong');
433 $newcategory->name = $data->name;
436 if (isset($data->idnumber) && $data->idnumber != $this->idnumber) {
437 if (textlib::strlen($data->idnumber) > 100) {
438 throw new moodle_exception('idnumbertoolong');
440 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
441 throw new moodle_exception('categoryidnumbertaken');
443 $newcategory->idnumber = $data->idnumber;
446 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
447 $newcategory->theme = $data->theme;
450 $changes = false;
451 if (isset($data->visible)) {
452 if ($data->visible) {
453 $changes = $this->show_raw();
454 } else {
455 $changes = $this->hide_raw(0);
459 if (isset($data->parent) && $data->parent != $this->parent) {
460 if ($changes) {
461 cache_helper::purge_by_event('changesincoursecat');
463 $parentcat = self::get($data->parent, MUST_EXIST, true);
464 $this->change_parent_raw($parentcat);
465 fix_course_sortorder();
468 $newcategory->timemodified = time();
470 if ($editoroptions) {
471 $categorycontext = context_coursecat::instance($this->id);
472 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext, 'coursecat', 'description', 0);
474 $DB->update_record('course_categories', $newcategory);
475 add_to_log(SITEID, "category", 'update', "editcategory.php?id=$this->id", $this->id);
476 fix_course_sortorder();
477 // purge cache even if fix_course_sortorder() did not do it
478 cache_helper::purge_by_event('changesincoursecat');
480 // update all fields in the current object
481 $this->restore();
485 * Checks if this course category is visible to current user
487 * Please note that methods coursecat::get (without 3rd argumet),
488 * coursecat::get_children(), etc. return only visible categories so it is
489 * usually not needed to call this function outside of this class
491 * @return bool
493 public function is_uservisible() {
494 return !$this->id || $this->visible ||
495 has_capability('moodle/category:viewhiddencategories',
496 context_coursecat::instance($this->id));
500 * Returns all categories visible to the current user
502 * This is a generic function that returns an array of
503 * (category id => coursecat object) sorted by sortorder
505 * @see coursecat::get_children()
506 * @see coursecat::get_all_parents()
508 * @return cacheable_object_array array of coursecat objects
510 public static function get_all_visible() {
511 global $USER;
512 $coursecatcache = cache::make('core', 'coursecat');
513 $ids = $coursecatcache->get('user'. $USER->id);
514 if ($ids === false) {
515 $all = self::get_all_ids();
516 $parentvisible = $all[0];
517 $rv = array();
518 foreach ($all as $id => $children) {
519 if ($id && in_array($id, $parentvisible) &&
520 ($coursecat = self::get($id, IGNORE_MISSING)) &&
521 (!$coursecat->parent || isset($rv[$coursecat->parent]))) {
522 $rv[$id] = $coursecat;
523 $parentvisible += $children;
526 $coursecatcache->set('user'. $USER->id, array_keys($rv));
527 } else {
528 $rv = array();
529 foreach ($ids as $id) {
530 if ($coursecat = self::get($id, IGNORE_MISSING)) {
531 $rv[$id] = $coursecat;
535 return $rv;
539 * Returns the entry from categories tree and makes sure the application-level tree cache is built
541 * The following keys can be requested:
543 * 'countall' - total number of categories in the system (always present)
544 * 0 - array of ids of top-level categories (always present)
545 * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
546 * $id (int) - array of ids of categories that are direct children of category with id $id. If
547 * category with id $id does not exist returns false. If category has no children returns empty array
548 * $id.'i' - array of ids of children categories that have visible=0
550 * @param int|string $id
551 * @return mixed
553 protected static function get_tree($id) {
554 global $DB;
555 $coursecattreecache = cache::make('core', 'coursecattree');
556 $rv = $coursecattreecache->get($id);
557 if ($rv !== false) {
558 return $rv;
560 // We did not find the entry in cache but it also can mean that tree is not built.
561 // The keys 0 and 'countall' must always be present if tree is built.
562 if ($id !== 0 && $id !== 'countall' && $coursecattreecache->has('countall')) {
563 // Tree was built, it means the non-existing $id was requested.
564 return false;
566 // Re-build the tree.
567 $sql = "SELECT cc.id, cc.parent, cc.visible
568 FROM {course_categories} cc
569 ORDER BY cc.sortorder";
570 $rs = $DB->get_recordset_sql($sql, array());
571 $all = array(0 => array(), '0i' => array());
572 $count = 0;
573 foreach ($rs as $record) {
574 $all[$record->id] = array();
575 $all[$record->id. 'i'] = array();
576 if (array_key_exists($record->parent, $all)) {
577 $all[$record->parent][] = $record->id;
578 if (!$record->visible) {
579 $all[$record->parent. 'i'][] = $record->id;
581 } else {
582 // parent not found. This is data consistency error but next fix_course_sortorder() should fix it
583 $all[0][] = $record->id;
585 $count++;
587 $rs->close();
588 if (!$count) {
589 // No categories found.
590 // This may happen after upgrade from very old moodle version. In new versions the default category is created on install.
591 $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
592 set_config('defaultrequestcategory', $defcoursecat->id);
593 $all[0] = array($defcoursecat->id);
594 $all[$defcoursecat->id] = array();
595 $count++;
597 $all['countall'] = $count;
598 foreach ($all as $key => $children) {
599 $coursecattreecache->set($key, $children);
601 if (array_key_exists($id, $all)) {
602 return $all[$id];
604 return false;
608 * Returns number of ALL categories in the system regardless if
609 * they are visible to current user or not
611 * @return int
613 public static function count_all() {
614 return self::get_tree('countall');
618 * Retrieves number of records from course_categories table
620 * Only cached fields are retrieved. Records are ready for preloading context
622 * @param string $whereclause
623 * @param array $params
624 * @return array array of stdClass objects
626 protected static function get_records($whereclause, $params) {
627 global $DB;
628 // Retrieve from DB only the fields that need to be stored in cache
629 $fields = array_keys(array_filter(self::$coursecatfields));
630 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
631 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
632 FROM {course_categories} cc
633 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
634 WHERE ". $whereclause." ORDER BY cc.sortorder";
635 return $DB->get_records_sql($sql,
636 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
640 * Given list of DB records from table course populates each record with list of users with course contact roles
642 * This function fills the courses with raw information as {@link get_role_users()} would do.
643 * See also {@link course_in_list::get_course_contacts()} for more readable return
645 * $courses[$i]->managers = array(
646 * $roleassignmentid => $roleuser,
647 * ...
648 * );
650 * where $roleuser is an stdClass with the following properties:
652 * $roleuser->raid - role assignment id
653 * $roleuser->id - user id
654 * $roleuser->username
655 * $roleuser->firstname
656 * $roleuser->lastname
657 * $roleuser->rolecoursealias
658 * $roleuser->rolename
659 * $roleuser->sortorder - role sortorder
660 * $roleuser->roleid
661 * $roleuser->roleshortname
663 * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
665 * @param array $courses
667 public static function preload_course_contacts(&$courses) {
668 global $CFG, $DB;
669 if (empty($courses) || empty($CFG->coursecontact)) {
670 return;
672 $managerroles = explode(',', $CFG->coursecontact);
673 $cache = cache::make('core', 'coursecontacts');
674 $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
675 // check if cache was set for the current course contacts and it is not yet expired
676 if (empty($cacheddata['basic']) || $cacheddata['basic']['roles'] !== $CFG->coursecontact ||
677 $cacheddata['basic']['lastreset'] < time() - self::CACHE_COURSE_CONTACTS_TTL) {
678 // reset cache
679 $cache->purge();
680 $cache->set('basic', array('roles' => $CFG->coursecontact, 'lastreset' => time()));
681 $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
683 $courseids = array();
684 foreach (array_keys($courses) as $id) {
685 if ($cacheddata[$id] !== false) {
686 $courses[$id]->managers = $cacheddata[$id];
687 } else {
688 $courseids[] = $id;
692 // $courseids now stores list of ids of courses for which we still need to retrieve contacts
693 if (empty($courseids)) {
694 return;
697 // first build the array of all context ids of the courses and their categories
698 $allcontexts = array();
699 foreach ($courseids as $id) {
700 $context = context_course::instance($id);
701 $courses[$id]->managers = array();
702 foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
703 if (!isset($allcontexts[$ctxid])) {
704 $allcontexts[$ctxid] = array();
706 $allcontexts[$ctxid][] = $id;
710 // fetch list of all users with course contact roles in any of the courses contexts or parent contexts
711 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
712 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
713 list($sort, $sortparams) = users_order_by_sql('u');
714 $sql = "SELECT ra.contextid, ra.id AS raid,
715 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
716 rn.name AS rolecoursealias, u.id, u.username, u.firstname, u.lastname
717 FROM {role_assignments} ra
718 JOIN {user} u ON ra.userid = u.id
719 JOIN {role} r ON ra.roleid = r.id
720 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
721 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2."
722 ORDER BY r.sortorder, $sort";
723 $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $sortparams);
724 $checkenrolments = array();
725 foreach($rs as $ra) {
726 foreach ($allcontexts[$ra->contextid] as $id) {
727 $courses[$id]->managers[$ra->raid] = $ra;
728 if (!isset($checkenrolments[$id])) {
729 $checkenrolments[$id] = array();
731 $checkenrolments[$id][] = $ra->id;
734 $rs->close();
736 // remove from course contacts users who are not enrolled in the course
737 $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
738 foreach ($checkenrolments as $id => $userids) {
739 if (empty($enrolleduserids[$id])) {
740 $courses[$id]->managers = array();
741 } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
742 foreach ($courses[$id]->managers as $raid => $ra) {
743 if (in_array($ra->id, $notenrolled)) {
744 unset($courses[$id]->managers[$raid]);
750 // set the cache
751 $values = array();
752 foreach ($courseids as $id) {
753 $values[$id] = $courses[$id]->managers;
755 $cache->set_many($values);
759 * Verify user enrollments for multiple course-user combinations
761 * @param array $courseusers array where keys are course ids and values are array
762 * of users in this course whose enrolment we wish to verify
763 * @return array same structure as input array but values list only users from input
764 * who are enrolled in the course
766 protected static function ensure_users_enrolled($courseusers) {
767 global $DB;
768 // If the input array is too big, split it into chunks
769 $maxcoursesinquery = 20;
770 if (count($courseusers) > $maxcoursesinquery) {
771 $rv = array();
772 for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
773 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
774 $rv = $rv + self::ensure_users_enrolled($chunk);
776 return $rv;
779 // create a query verifying valid user enrolments for the number of courses
780 $sql = "SELECT DISTINCT e.courseid, ue.userid
781 FROM {user_enrolments} ue
782 JOIN {enrol} e ON e.id = ue.enrolid
783 WHERE ue.status = :active
784 AND e.status = :enabled
785 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
786 $now = round(time(), -2); // rounding helps caching in DB
787 $params = array('enabled' => ENROL_INSTANCE_ENABLED,
788 'active' => ENROL_USER_ACTIVE,
789 'now1' => $now, 'now2' => $now);
790 $cnt = 0;
791 $subsqls = array();
792 $enrolled = array();
793 foreach ($courseusers as $id => $userids) {
794 $enrolled[$id] = array();
795 if (count($userids)) {
796 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
797 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
798 $params = $params + array('courseid'.$cnt => $id) + $params2;
799 $cnt++;
802 if (count($subsqls)) {
803 $sql .= "AND (". join(' OR ', $subsqls).")";
804 $rs = $DB->get_recordset_sql($sql, $params);
805 foreach ($rs as $record) {
806 $enrolled[$record->courseid][] = $record->userid;
808 $rs->close();
810 return $enrolled;
814 * Retrieves number of records from course table
816 * Not all fields are retrieved. Records are ready for preloading context
818 * @param string $whereclause
819 * @param array $params
820 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
821 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
822 * on not visible courses
823 * @return array array of stdClass objects
825 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
826 global $DB;
827 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
828 $fields = array('c.id', 'c.category', 'c.sortorder',
829 'c.shortname', 'c.fullname', 'c.idnumber',
830 'c.startdate', 'c.visible');
831 if (!empty($options['summary'])) {
832 $fields[] = 'c.summary';
833 $fields[] = 'c.summaryformat';
834 } else {
835 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' hassummary';
837 $sql = "SELECT ". join(',', $fields). ", $ctxselect
838 FROM {course} c
839 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
840 WHERE ". $whereclause." ORDER BY c.sortorder";
841 $list = $DB->get_records_sql($sql,
842 array('contextcourse' => CONTEXT_COURSE) + $params);
844 if ($checkvisibility) {
845 // Loop through all records and make sure we only return the courses accessible by user.
846 foreach ($list as $course) {
847 if (isset($list[$course->id]->hassummary)) {
848 $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
850 if (empty($course->visible)) {
851 // load context only if we need to check capability
852 context_helper::preload_from_record($course);
853 if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
854 unset($list[$course->id]);
860 // preload course contacts if necessary
861 if (!empty($options['coursecontacts'])) {
862 self::preload_course_contacts($list);
864 return $list;
868 * Returns array of ids of children categories that current user can not see
870 * This data is cached in user session cache
872 * @return array
874 protected function get_not_visible_children_ids() {
875 global $DB;
876 $coursecatcache = cache::make('core', 'coursecat');
877 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
878 // we never checked visible children before
879 $hidden = self::get_tree($this->id.'i');
880 $invisibleids = array();
881 if ($hidden) {
882 // preload categories contexts
883 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
884 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
885 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
886 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
887 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
888 foreach ($contexts as $record) {
889 context_helper::preload_from_record($record);
891 // check that user has 'viewhiddencategories' capability for each hidden category
892 foreach ($hidden as $id) {
893 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
894 $invisibleids[] = $id;
898 $coursecatcache->set('ic'. $this->id, $invisibleids);
900 return $invisibleids;
904 * Sorts list of records by several fields
906 * @param array $records array of stdClass objects
907 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
908 * @return int
910 protected static function sort_records(&$records, $sortfields) {
911 if (empty($records)) {
912 return;
914 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname)
915 if (array_key_exists('displayname', $sortfields)) {
916 foreach ($records as $key => $record) {
917 if (!isset($record->displayname)) {
918 $records[$key]->displayname = get_course_display_name_for_list($record);
922 // sorting by one field - use collatorlib
923 if (count($sortfields) == 1) {
924 $property = key($sortfields);
925 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
926 $sortflag = collatorlib::SORT_NUMERIC;
927 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
928 $sortflag = collatorlib::SORT_STRING;
929 } else {
930 $sortflag = collatorlib::SORT_REGULAR;
932 collatorlib::asort_objects_by_property($records, $property, $sortflag);
933 if ($sortfields[$property] < 0) {
934 $records = array_reverse($records, true);
936 return;
938 $records = coursecat_sortable_records::sort($records, $sortfields);
942 * Returns array of children categories visible to the current user
944 * @param array $options options for retrieving children
945 * - sort - list of fields to sort. Example
946 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
947 * will sort by idnumber asc, name asc and id desc.
948 * Default: array('sortorder' => 1)
949 * Only cached fields may be used for sorting!
950 * - offset
951 * - limit - maximum number of children to return, 0 or null for no limit
952 * @return array of coursecat objects indexed by category id
954 public function get_children($options = array()) {
955 global $DB;
956 $coursecatcache = cache::make('core', 'coursecat');
958 // get default values for options
959 if (!empty($options['sort']) && is_array($options['sort'])) {
960 $sortfields = $options['sort'];
961 } else {
962 $sortfields = array('sortorder' => 1);
964 $limit = null;
965 if (!empty($options['limit']) && (int)$options['limit']) {
966 $limit = (int)$options['limit'];
968 $offset = 0;
969 if (!empty($options['offset']) && (int)$options['offset']) {
970 $offset = (int)$options['offset'];
973 // first retrieve list of user-visible and sorted children ids from cache
974 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
975 if ($sortedids === false) {
976 $sortfieldskeys = array_keys($sortfields);
977 if ($sortfieldskeys[0] === 'sortorder') {
978 // no DB requests required to build the list of ids sorted by sortorder.
979 // We can easily ignore other sort fields because sortorder is always different
980 $sortedids = self::get_tree($this->id);
981 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
982 $sortedids = array_diff($sortedids, $invisibleids);
983 if ($sortfields['sortorder'] == -1) {
984 $sortedids = array_reverse($sortedids, true);
987 } else {
988 // we need to retrieve and sort all children. Good thing that it is done only on first request
989 if ($invisibleids = $this->get_not_visible_children_ids()) {
990 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
991 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
992 array('parent' => $this->id) + $params);
993 } else {
994 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
996 self::sort_records($records, $sortfields);
997 $sortedids = array_keys($records);
999 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
1002 if (empty($sortedids)) {
1003 return array();
1006 // now retrieive and return categories
1007 if ($offset || $limit) {
1008 $sortedids = array_slice($sortedids, $offset, $limit);
1010 if (isset($records)) {
1011 // easy, we have already retrieved records
1012 if ($offset || $limit) {
1013 $records = array_slice($records, $offset, $limit, true);
1015 } else {
1016 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
1017 $records = self::get_records('cc.id '. $sql,
1018 array('parent' => $this->id) + $params);
1021 $rv = array();
1022 foreach ($sortedids as $id) {
1023 if (isset($records[$id])) {
1024 $rv[$id] = new coursecat($records[$id]);
1027 return $rv;
1031 * Returns number of subcategories visible to the current user
1033 * @return int
1035 public function get_children_count() {
1036 $sortedids = self::get_tree($this->id);
1037 $invisibleids = $this->get_not_visible_children_ids();
1038 return count($sortedids) - count($invisibleids);
1042 * Returns true if the category has ANY children, including those not visible to the user
1044 * @return boolean
1046 public function has_children() {
1047 $allchildren = self::get_tree($this->id);
1048 return !empty($allchildren);
1052 * Returns true if the category has courses in it (count does not include courses
1053 * in child categories)
1055 * @return bool
1057 public function has_courses() {
1058 global $DB;
1059 return $DB->record_exists_sql("select 1 from {course} where category = ?",
1060 array($this->id));
1064 * Searches courses
1066 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1067 * to this when somebody edits courses or categories, however it is very
1068 * difficult to keep track of all possible changes that may affect list of courses.
1070 * @param array $search contains search criterias, such as:
1071 * - search - search string
1072 * - blocklist - id of block (if we are searching for courses containing specific block0
1073 * - modulelist - name of module (if we are searching for courses containing specific module
1074 * - tagid - id of tag
1075 * @param array $options display options, same as in get_courses() except 'recursive' is ignored - search is always category-independent
1076 * @return array
1078 public static function search_courses($search, $options = array()) {
1079 global $DB;
1080 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1081 $limit = !empty($options['limit']) ? $options['limit'] : null;
1082 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1084 $coursecatcache = cache::make('core', 'coursecat');
1085 $cachekey = 's-'. serialize($search + array('sort' => $sortfields));
1086 $cntcachekey = 'scnt-'. serialize($search);
1088 $ids = $coursecatcache->get($cachekey);
1089 if ($ids !== false) {
1090 // we already cached last search result
1091 $ids = array_slice($ids, $offset, $limit);
1092 $courses = array();
1093 if (!empty($ids)) {
1094 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1095 $records = self::get_course_records("c.id ". $sql, $params, $options);
1096 foreach ($ids as $id) {
1097 $courses[$id] = new course_in_list($records[$id]);
1100 return $courses;
1103 $preloadcoursecontacts = !empty($options['coursecontacts']);
1104 unset($options['coursecontacts']);
1106 if (!empty($search['search'])) {
1107 // search courses that have specified words in their names/summaries
1108 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1109 $searchterms = array_filter($searchterms, create_function('$v', 'return strlen($v) > 1;'));
1110 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount);
1111 self::sort_records($courselist, $sortfields);
1112 $coursecatcache->set($cachekey, array_keys($courselist));
1113 $coursecatcache->set($cntcachekey, $totalcount);
1114 $records = array_slice($courselist, $offset, $limit, true);
1115 } else {
1116 if (!empty($search['blocklist'])) {
1117 // search courses that have block with specified id
1118 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1119 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1120 WHERE bi.blockname = :blockname)';
1121 $params = array('blockname' => $blockname);
1122 } else if (!empty($search['modulelist'])) {
1123 // search courses that have module with specified name
1124 $where = "c.id IN (SELECT DISTINCT module.course ".
1125 "FROM {".$search['modulelist']."} module)";
1126 $params = array();
1127 } else if (!empty($search['tagid'])) {
1128 // search courses that are tagged with the specified tag
1129 $where = "c.id IN (SELECT t.itemid ".
1130 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype)";
1131 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course');
1132 } else {
1133 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1134 return array();
1136 $courselist = self::get_course_records($where, $params, $options, true);
1137 self::sort_records($courselist, $sortfields);
1138 $coursecatcache->set($cachekey, array_keys($courselist));
1139 $coursecatcache->set($cntcachekey, count($courselist));
1140 $records = array_slice($courselist, $offset, $limit, true);
1143 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1144 if (!empty($preloadcoursecontacts)) {
1145 self::preload_course_contacts($records);
1147 $courses = array();
1148 foreach ($records as $record) {
1149 $courses[$record->id] = new course_in_list($record);
1151 return $courses;
1155 * Returns number of courses in the search results
1157 * It is recommended to call this function after {@link coursecat::search_courses()}
1158 * and not before because only course ids are cached. Otherwise search_courses() may
1159 * perform extra DB queries.
1161 * @param array $search search criteria, see method search_courses() for more details
1162 * @param array $options display options. They do not affect the result but
1163 * the 'sort' property is used in cache key for storing list of course ids
1164 * @return int
1166 public static function search_courses_count($search, $options = array()) {
1167 $coursecatcache = cache::make('core', 'coursecat');
1168 $cntcachekey = 'scnt-'. serialize($search);
1169 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1170 self::search_courses($search, $options);
1171 $cnt = $coursecatcache->get($cntcachekey);
1173 return $cnt;
1177 * Retrieves the list of courses accessible by user
1179 * Not all information is cached, try to avoid calling this method
1180 * twice in the same request.
1182 * The following fields are always retrieved:
1183 * - id, visible, fullname, shortname, idnumber, category, sortorder
1185 * If you plan to use properties/methods course_in_list::$summary and/or
1186 * course_in_list::get_course_contacts()
1187 * you can preload this information using appropriate 'options'. Otherwise
1188 * they will be retrieved from DB on demand and it may end with bigger DB load.
1190 * Note that method course_in_list::has_summary() will not perform additional
1191 * DB queries even if $options['summary'] is not specified
1193 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1194 * to this when somebody edits courses or categories, however it is very
1195 * difficult to keep track of all possible changes that may affect list of courses.
1197 * @param array $options options for retrieving children
1198 * - recursive - return courses from subcategories as well. Use with care,
1199 * this may be a huge list!
1200 * - summary - preloads fields 'summary' and 'summaryformat'
1201 * - coursecontacts - preloads course contacts
1202 * - sort - list of fields to sort. Example
1203 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1204 * will sort by idnumber asc, shortname asc and id desc.
1205 * Default: array('sortorder' => 1)
1206 * Only cached fields may be used for sorting!
1207 * - offset
1208 * - limit - maximum number of children to return, 0 or null for no limit
1209 * @return array array of instances of course_in_list
1211 public function get_courses($options = array()) {
1212 global $DB;
1213 $recursive = !empty($options['recursive']);
1214 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1215 $limit = !empty($options['limit']) ? $options['limit'] : null;
1216 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1218 // Check if this category is hidden.
1219 // Also 0-category never has courses unless this is recursive call.
1220 if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1221 return array();
1224 $coursecatcache = cache::make('core', 'coursecat');
1225 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1226 '-'. serialize($sortfields);
1227 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1229 // check if we have already cached results
1230 $ids = $coursecatcache->get($cachekey);
1231 if ($ids !== false) {
1232 // we already cached last search result and it did not expire yet
1233 $ids = array_slice($ids, $offset, $limit);
1234 $courses = array();
1235 if (!empty($ids)) {
1236 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1237 $records = self::get_course_records("c.id ". $sql, $params, $options);
1238 foreach ($ids as $id) {
1239 $courses[$id] = new course_in_list($records[$id]);
1242 return $courses;
1245 // retrieve list of courses in category
1246 $where = 'c.id <> :siteid';
1247 $params = array('siteid' => SITEID);
1248 if ($recursive) {
1249 if ($this->id) {
1250 $context = context_coursecat::instance($this->id);
1251 $where .= ' AND ctx.path like :path';
1252 $params['path'] = $context->path. '/%';
1254 } else {
1255 $where .= ' AND c.category = :categoryid';
1256 $params['categoryid'] = $this->id;
1258 // get list of courses without preloaded coursecontacts because we don't need them for every course
1259 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1261 // sort and cache list
1262 self::sort_records($list, $sortfields);
1263 $coursecatcache->set($cachekey, array_keys($list));
1264 $coursecatcache->set($cntcachekey, count($list));
1266 // Apply offset/limit, convert to course_in_list and return.
1267 $courses = array();
1268 if (isset($list)) {
1269 if ($offset || $limit) {
1270 $list = array_slice($list, $offset, $limit, true);
1272 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1273 if (!empty($options['coursecontacts'])) {
1274 self::preload_course_contacts($list);
1276 foreach ($list as $record) {
1277 $courses[$record->id] = new course_in_list($record);
1280 return $courses;
1284 * Returns number of courses visible to the user
1286 * @param array $options similar to get_courses() except some options do not affect
1287 * number of courses (i.e. sort, summary, offset, limit etc.)
1288 * @return int
1290 public function get_courses_count($options = array()) {
1291 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1292 $coursecatcache = cache::make('core', 'coursecat');
1293 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1294 $this->get_courses($options);
1295 $cnt = $coursecatcache->get($cntcachekey);
1297 return $cnt;
1301 * Returns true if user can delete current category and all its contents
1303 * To be able to delete course category the user must have permission
1304 * 'moodle/category:manage' in ALL child course categories AND
1305 * be able to delete all courses
1307 * @return bool
1309 public function can_delete_full() {
1310 global $DB;
1311 if (!$this->id) {
1312 // fool-proof
1313 return false;
1316 $context = context_coursecat::instance($this->id);
1317 if (!$this->is_uservisible() ||
1318 !has_capability('moodle/category:manage', $context)) {
1319 return false;
1322 // Check all child categories (not only direct children)
1323 $sql = context_helper::get_preload_record_columns_sql('ctx');
1324 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1325 ' FROM {context} ctx '.
1326 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1327 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1328 array($context->path. '/%', CONTEXT_COURSECAT));
1329 foreach ($childcategories as $childcat) {
1330 context_helper::preload_from_record($childcat);
1331 $childcontext = context_coursecat::instance($childcat->id);
1332 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1333 !has_capability('moodle/category:manage', $childcontext)) {
1334 return false;
1338 // Check courses
1339 $sql = context_helper::get_preload_record_columns_sql('ctx');
1340 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1341 $sql. ' FROM {context} ctx '.
1342 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1343 array('pathmask' => $context->path. '/%',
1344 'courselevel' => CONTEXT_COURSE));
1345 foreach ($coursescontexts as $ctxrecord) {
1346 context_helper::preload_from_record($ctxrecord);
1347 if (!can_delete_course($ctxrecord->courseid)) {
1348 return false;
1352 return true;
1356 * Recursively delete category including all subcategories and courses
1358 * Function {@link coursecat::can_delete_full()} MUST be called prior
1359 * to calling this function because there is no capability check
1360 * inside this function
1362 * @param boolean $showfeedback display some notices
1363 * @return array return deleted courses
1365 public function delete_full($showfeedback = true) {
1366 global $CFG, $DB;
1367 require_once($CFG->libdir.'/gradelib.php');
1368 require_once($CFG->libdir.'/questionlib.php');
1369 require_once($CFG->dirroot.'/cohort/lib.php');
1371 $deletedcourses = array();
1373 // Get children. Note, we don't want to use cache here because
1374 // it would be rebuilt too often
1375 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1376 foreach ($children as $record) {
1377 $coursecat = new coursecat($record);
1378 $deletedcourses += $coursecat->delete_full($showfeedback);
1381 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1382 foreach ($courses as $course) {
1383 if (!delete_course($course, false)) {
1384 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1386 $deletedcourses[] = $course;
1390 // move or delete cohorts in this context
1391 cohort_delete_category($this);
1393 // now delete anything that may depend on course category context
1394 grade_course_category_delete($this->id, 0, $showfeedback);
1395 if (!question_delete_course_category($this, 0, $showfeedback)) {
1396 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1399 // finally delete the category and it's context
1400 $DB->delete_records('course_categories', array('id' => $this->id));
1401 delete_context(CONTEXT_COURSECAT, $this->id);
1402 add_to_log(SITEID, "category", "delete", "index.php", "$this->name (ID $this->id)");
1404 cache_helper::purge_by_event('changesincoursecat');
1406 events_trigger('course_category_deleted', $this);
1408 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1409 if ($this->id == $CFG->defaultrequestcategory) {
1410 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1412 return $deletedcourses;
1416 * Checks if user can delete this category and move content (courses, subcategories and questions)
1417 * to another category. If yes returns the array of possible target categories names
1419 * If user can not manage this category or it is completely empty - empty array will be returned
1421 * @return array
1423 public function move_content_targets_list() {
1424 global $CFG;
1425 require_once($CFG->libdir . '/questionlib.php');
1426 $context = context_coursecat::instance($this->id);
1427 if (!$this->is_uservisible() ||
1428 !has_capability('moodle/category:manage', $context)) {
1429 // User is not able to manage current category, he is not able to delete it.
1430 // No possible target categories.
1431 return array();
1434 $testcaps = array();
1435 // If this category has courses in it, user must have 'course:create' capability in target category.
1436 if ($this->has_courses()) {
1437 $testcaps[] = 'moodle/course:create';
1439 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1440 if ($this->has_children() || question_context_has_any_questions($context)) {
1441 $testcaps[] = 'moodle/category:manage';
1443 if (!empty($testcaps)) {
1444 // return list of categories excluding this one and it's children
1445 return self::make_categories_list($testcaps, $this->id);
1448 // Category is completely empty, no need in target for contents.
1449 return array();
1453 * Checks if user has capability to move all category content to the new parent before
1454 * removing this category
1456 * @param int $newcatid
1457 * @return bool
1459 public function can_move_content_to($newcatid) {
1460 global $CFG;
1461 require_once($CFG->libdir . '/questionlib.php');
1462 $context = context_coursecat::instance($this->id);
1463 if (!$this->is_uservisible() ||
1464 !has_capability('moodle/category:manage', $context)) {
1465 return false;
1467 $testcaps = array();
1468 // If this category has courses in it, user must have 'course:create' capability in target category.
1469 if ($this->has_courses()) {
1470 $testcaps[] = 'moodle/course:create';
1472 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1473 if ($this->has_children() || question_context_has_any_questions($context)) {
1474 $testcaps[] = 'moodle/category:manage';
1476 if (!empty($testcaps)) {
1477 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1480 // there is no content but still return true
1481 return true;
1485 * Deletes a category and moves all content (children, courses and questions) to the new parent
1487 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1488 * must be called prior
1490 * @param int $newparentid
1491 * @param bool $showfeedback
1492 * @return bool
1494 public function delete_move($newparentid, $showfeedback = false) {
1495 global $CFG, $DB, $OUTPUT;
1496 require_once($CFG->libdir.'/gradelib.php');
1497 require_once($CFG->libdir.'/questionlib.php');
1498 require_once($CFG->dirroot.'/cohort/lib.php');
1500 // get all objects and lists because later the caches will be reset so
1501 // we don't need to make extra queries
1502 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1503 $catname = $this->get_formatted_name();
1504 $children = $this->get_children();
1505 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', array('category' => $this->id));
1506 $context = context_coursecat::instance($this->id);
1508 if ($children) {
1509 foreach ($children as $childcat) {
1510 $childcat->change_parent_raw($newparentcat);
1511 // Log action.
1512 add_to_log(SITEID, "category", "move", "editcategory.php?id=$childcat->id", $childcat->id);
1514 fix_course_sortorder();
1517 if ($coursesids) {
1518 if (!move_courses($coursesids, $newparentid)) {
1519 if ($showfeedback) {
1520 echo $OUTPUT->notification("Error moving courses");
1522 return false;
1524 if ($showfeedback) {
1525 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1529 // move or delete cohorts in this context
1530 cohort_delete_category($this);
1532 // now delete anything that may depend on course category context
1533 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1534 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1535 if ($showfeedback) {
1536 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1538 return false;
1541 // finally delete the category and it's context
1542 $DB->delete_records('course_categories', array('id' => $this->id));
1543 $context->delete();
1544 add_to_log(SITEID, "category", "delete", "index.php", "$this->name (ID $this->id)");
1546 events_trigger('course_category_deleted', $this);
1548 cache_helper::purge_by_event('changesincoursecat');
1550 if ($showfeedback) {
1551 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1554 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1555 if ($this->id == $CFG->defaultrequestcategory) {
1556 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1558 return true;
1562 * Checks if user can move current category to the new parent
1564 * This checks if new parent category exists, user has manage cap there
1565 * and new parent is not a child of this category
1567 * @param int|stdClass|coursecat $newparentcat
1568 * @return bool
1570 public function can_change_parent($newparentcat) {
1571 if (!has_capability('moodle/category:manage', context_coursecat::instance($this->id))) {
1572 return false;
1574 if (is_object($newparentcat)) {
1575 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1576 } else {
1577 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1579 if (!$newparentcat) {
1580 return false;
1582 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1583 // can not move to itself or it's own child
1584 return false;
1586 if ($newparentcat->id) {
1587 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
1588 } else {
1589 return has_capability('moodle/category:manage', context_system::instance());
1594 * Moves the category under another parent category. All associated contexts are moved as well
1596 * This is protected function, use change_parent() or update() from outside of this class
1598 * @see coursecat::change_parent()
1599 * @see coursecat::update()
1601 * @param coursecat $newparentcat
1603 protected function change_parent_raw(coursecat $newparentcat) {
1604 global $DB;
1606 $context = context_coursecat::instance($this->id);
1608 $hidecat = false;
1609 if (empty($newparentcat->id)) {
1610 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1611 $newparent = context_system::instance();
1612 } else {
1613 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
1614 // can not move to itself or it's own child
1615 throw new moodle_exception('cannotmovecategory');
1617 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
1618 $newparent = context_coursecat::instance($newparentcat->id);
1620 if (!$newparentcat->visible and $this->visible) {
1621 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
1622 $hidecat = true;
1625 $this->parent = $newparentcat->id;
1627 $context->update_moved($newparent);
1629 // now make it last in new category
1630 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
1632 if ($hidecat) {
1633 fix_course_sortorder();
1634 $this->restore();
1635 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must become visible again.
1636 $this->hide_raw(1);
1641 * Efficiently moves a category - NOTE that this can have
1642 * a huge impact access-control-wise...
1644 * Note that this function does not check capabilities.
1646 * Example of usage:
1647 * $coursecat = coursecat::get($categoryid);
1648 * if ($coursecat->can_change_parent($newparentcatid)) {
1649 * $coursecat->change_parent($newparentcatid);
1652 * This function does not update field course_categories.timemodified
1653 * If you want to update timemodified, use
1654 * $coursecat->update(array('parent' => $newparentcat));
1656 * @param int|stdClass|coursecat $newparentcat
1658 public function change_parent($newparentcat) {
1659 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1660 if (is_object($newparentcat)) {
1661 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
1662 } else {
1663 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
1665 if ($newparentcat->id != $this->parent) {
1666 $this->change_parent_raw($newparentcat);
1667 fix_course_sortorder();
1668 cache_helper::purge_by_event('changesincoursecat');
1669 $this->restore();
1670 add_to_log(SITEID, "category", "move", "editcategory.php?id=$this->id", $this->id);
1675 * Hide course category and child course and subcategories
1677 * If this category has changed the parent and is moved under hidden
1678 * category we will want to store it's current visibility state in
1679 * the field 'visibleold'. If admin clicked 'hide' for this particular
1680 * category, the field 'visibleold' should become 0.
1682 * All subcategories and courses will have their current visibility in the field visibleold
1684 * This is protected function, use hide() or update() from outside of this class
1686 * @see coursecat::hide()
1687 * @see coursecat::update()
1689 * @param int $visibleold value to set in field $visibleold for this category
1690 * @return bool whether changes have been made and caches need to be purged afterwards
1692 protected function hide_raw($visibleold = 0) {
1693 global $DB;
1694 $changes = false;
1696 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing
1697 if ($this->id && $this->__get('visibleold') != $visibleold) {
1698 $this->visibleold = $visibleold;
1699 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
1700 $changes = true;
1702 if (!$this->visible || !$this->id) {
1703 // already hidden or can not be hidden
1704 return $changes;
1707 $this->visible = 0;
1708 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
1709 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id)); // store visible flag so that we can return to it if we immediately unhide
1710 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
1711 // get all child categories and hide too
1712 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
1713 foreach ($subcats as $cat) {
1714 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
1715 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
1716 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
1717 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
1720 return true;
1724 * Hide course category and child course and subcategories
1726 * Note that there is no capability check inside this function
1728 * This function does not update field course_categories.timemodified
1729 * If you want to update timemodified, use
1730 * $coursecat->update(array('visible' => 0));
1732 public function hide() {
1733 if ($this->hide_raw(0)) {
1734 cache_helper::purge_by_event('changesincoursecat');
1735 add_to_log(SITEID, "category", "hide", "editcategory.php?id=$this->id", $this->id);
1740 * Show course category and restores visibility for child course and subcategories
1742 * Note that there is no capability check inside this function
1744 * This is protected function, use show() or update() from outside of this class
1746 * @see coursecat::show()
1747 * @see coursecat::update()
1749 * @return bool whether changes have been made and caches need to be purged afterwards
1751 protected function show_raw() {
1752 global $DB;
1754 if ($this->visible) {
1755 // already visible
1756 return false;
1759 $this->visible = 1;
1760 $this->visibleold = 1;
1761 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
1762 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
1763 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
1764 // get all child categories and unhide too
1765 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
1766 foreach ($subcats as $cat) {
1767 if ($cat->visibleold) {
1768 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
1770 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
1773 return true;
1777 * Show course category and restores visibility for child course and subcategories
1779 * Note that there is no capability check inside this function
1781 * This function does not update field course_categories.timemodified
1782 * If you want to update timemodified, use
1783 * $coursecat->update(array('visible' => 1));
1785 public function show() {
1786 if ($this->show_raw()) {
1787 cache_helper::purge_by_event('changesincoursecat');
1788 add_to_log(SITEID, "category", "show", "editcategory.php?id=$this->id", $this->id);
1793 * Returns name of the category formatted as a string
1795 * @param array $options formatting options other than context
1796 * @return string
1798 public function get_formatted_name($options = array()) {
1799 if ($this->id) {
1800 $context = context_coursecat::instance($this->id);
1801 return format_string($this->name, true, array('context' => $context) + $options);
1802 } else {
1803 return ''; // TODO 'Top'?
1808 * Returns ids of all parents of the category. Last element in the return array is the direct parent
1810 * For example, if you have a tree of categories like:
1811 * Miscellaneous (id = 1)
1812 * Subcategory (id = 2)
1813 * Sub-subcategory (id = 4)
1814 * Other category (id = 3)
1816 * coursecat::get(1)->get_parents() == array()
1817 * coursecat::get(2)->get_parents() == array(1)
1818 * coursecat::get(4)->get_parents() == array(1, 2);
1820 * Note that this method does not check if all parents are accessible by current user
1822 * @return array of category ids
1824 public function get_parents() {
1825 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
1826 array_pop($parents);
1827 return $parents;
1831 * This function returns a nice list representing category tree
1832 * for display or to use in a form <select> element
1834 * List is cached for 10 minutes
1836 * For example, if you have a tree of categories like:
1837 * Miscellaneous (id = 1)
1838 * Subcategory (id = 2)
1839 * Sub-subcategory (id = 4)
1840 * Other category (id = 3)
1841 * Then after calling this function you will have
1842 * array(1 => 'Miscellaneous',
1843 * 2 => 'Miscellaneous / Subcategory',
1844 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1845 * 3 => 'Other category');
1847 * If you specify $requiredcapability, then only categories where the current
1848 * user has that capability will be added to $list.
1849 * If you only have $requiredcapability in a child category, not the parent,
1850 * then the child catgegory will still be included.
1852 * If you specify the option $excludeid, then that category, and all its children,
1853 * are omitted from the tree. This is useful when you are doing something like
1854 * moving categories, where you do not want to allow people to move a category
1855 * to be the child of itself.
1857 * See also {@link make_categories_options()}
1859 * @param string/array $requiredcapability if given, only categories where the current
1860 * user has this capability will be returned. Can also be an array of capabilities,
1861 * in which case they are all required.
1862 * @param integer $excludeid Exclude this category and its children from the lists built.
1863 * @param string $separator string to use as a separator between parent and child category. Default ' / '
1864 * @return array of strings
1866 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
1867 global $DB;
1868 $coursecatcache = cache::make('core', 'coursecat');
1870 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids with requried cap ($thislist).
1871 $basecachekey = 'catlist';
1872 $baselist = $coursecatcache->get($basecachekey);
1873 if ($baselist !== false) {
1874 $baselist = false;
1876 $thislist = false;
1877 if (!empty($requiredcapability)) {
1878 $requiredcapability = (array)$requiredcapability;
1879 $thiscachekey = 'catlist:'. serialize($requiredcapability);
1880 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
1881 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
1883 } else if ($baselist !== false) {
1884 $thislist = array_keys($baselist);
1887 if ($baselist === false) {
1888 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
1889 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1890 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
1891 FROM {course_categories} cc
1892 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
1893 ORDER BY cc.sortorder";
1894 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
1895 $baselist = array();
1896 $thislist = array();
1897 foreach ($rs as $record) {
1898 // If the category's parent is not visible to the user, it is not visible as well.
1899 if (!$record->parent || isset($baselist[$record->parent])) {
1900 $context = context_coursecat::instance($record->id);
1901 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
1902 // No cap to view category, added to neither $baselist nor $thislist
1903 continue;
1905 $baselist[$record->id] = array(
1906 'name' => format_string($record->name, true, array('context' => $context)),
1907 'path' => $record->path
1909 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
1910 // No required capability, added to $baselist but not to $thislist.
1911 continue;
1913 $thislist[] = $record->id;
1916 $rs->close();
1917 $coursecatcache->set($basecachekey, $baselist);
1918 if (!empty($requiredcapability)) {
1919 $coursecatcache->set($thiscachekey, join(',', $thislist));
1921 } else if ($thislist === false) {
1922 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
1923 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1924 $sql = "SELECT ctx.instanceid id, $ctxselect
1925 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
1926 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
1927 $thislist = array();
1928 foreach (array_keys($baselist) as $id) {
1929 context_helper::preload_from_record($contexts[$id]);
1930 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
1931 $thislist[] = $id;
1934 $coursecatcache->set($thiscachekey, join(',', $thislist));
1937 // Now build the array of strings to return, mind $separator and $excludeid.
1938 $names = array();
1939 foreach ($thislist as $id) {
1940 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
1941 if (!$excludeid || !in_array($excludeid, $path)) {
1942 $namechunks = array();
1943 foreach ($path as $parentid) {
1944 $namechunks[] = $baselist[$parentid]['name'];
1946 $names[$id] = join($separator, $namechunks);
1949 return $names;
1953 * Prepares the object for caching. Works like the __sleep method.
1955 * implementing method from interface cacheable_object
1957 * @return array ready to be cached
1959 public function prepare_to_cache() {
1960 $a = array();
1961 foreach (self::$coursecatfields as $property => $cachedirectives) {
1962 if ($cachedirectives !== null) {
1963 list($shortname, $defaultvalue) = $cachedirectives;
1964 if ($this->$property !== $defaultvalue) {
1965 $a[$shortname] = $this->$property;
1969 $context = context_coursecat::instance($this->id);
1970 $a['xi'] = $context->id;
1971 $a['xp'] = $context->path;
1972 return $a;
1976 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
1978 * implementing method from interface cacheable_object
1980 * @param array $a
1981 * @return coursecat
1983 public static function wake_from_cache($a) {
1984 $record = new stdClass;
1985 foreach (self::$coursecatfields as $property => $cachedirectives) {
1986 if ($cachedirectives !== null) {
1987 list($shortname, $defaultvalue) = $cachedirectives;
1988 if (array_key_exists($shortname, $a)) {
1989 $record->$property = $a[$shortname];
1990 } else {
1991 $record->$property = $defaultvalue;
1995 $record->ctxid = $a['xi'];
1996 $record->ctxpath = $a['xp'];
1997 $record->ctxdepth = $record->depth + 1;
1998 $record->ctxlevel = CONTEXT_COURSECAT;
1999 $record->ctxinstance = $record->id;
2000 return new coursecat($record, true);
2005 * Class to store information about one course in a list of courses
2007 * Not all information may be retrieved when object is created but
2008 * it will be retrieved on demand when appropriate property or method is
2009 * called.
2011 * Instances of this class are usually returned by functions
2012 * {@link coursecat::search_courses()}
2013 * and
2014 * {@link coursecat::get_courses()}
2016 * @package core
2017 * @subpackage course
2018 * @copyright 2013 Marina Glancy
2019 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2021 class course_in_list implements IteratorAggregate {
2023 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2024 protected $record;
2026 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2027 protected $coursecontacts;
2030 * Creates an instance of the class from record
2032 * @param stdClass $record except fields from course table it may contain
2033 * field hassummary indicating that summary field is not empty.
2034 * Also it is recommended to have context fields here ready for
2035 * context preloading
2037 public function __construct(stdClass $record) {
2038 context_instance_preload($record);
2039 $this->record = new stdClass();
2040 foreach ($record as $key => $value) {
2041 $this->record->$key = $value;
2046 * Indicates if the course has non-empty summary field
2048 * @return bool
2050 public function has_summary() {
2051 if (isset($this->record->hassummary)) {
2052 return !empty($this->record->hassummary);
2054 if (!isset($this->record->summary)) {
2055 // we need to retrieve summary
2056 $this->__get('summary');
2058 return !empty($this->record->summary);
2062 * Indicates if the course have course contacts to display
2064 * @return bool
2066 public function has_course_contacts() {
2067 if (!isset($this->record->managers)) {
2068 $courses = array($this->id => &$this->record);
2069 coursecat::preload_course_contacts($courses);
2071 return !empty($this->record->managers);
2075 * Returns list of course contacts (usually teachers) to display in course link
2077 * Roles to display are set up in $CFG->coursecontact
2079 * The result is the list of users where user id is the key and the value
2080 * is an array with elements:
2081 * - 'user' - object containing basic user information
2082 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2083 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2084 * - 'username' => fullname($user, $canviewfullnames)
2086 * @return array
2088 public function get_course_contacts() {
2089 global $CFG;
2090 if (empty($CFG->coursecontact)) {
2091 // no roles are configured to be displayed as course contacts
2092 return array();
2094 if ($this->coursecontacts === null) {
2095 $this->coursecontacts = array();
2096 $context = context_course::instance($this->id);
2098 if (!isset($this->record->managers)) {
2099 // preload course contacts from DB
2100 $courses = array($this->id => &$this->record);
2101 coursecat::preload_course_contacts($courses);
2104 // build return array with full roles names (for this course context) and users names
2105 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2106 foreach ($this->record->managers as $ruser) {
2107 if (isset($this->coursecontacts[$ruser->id])) {
2108 // only display a user once with the highest sortorder role
2109 continue;
2111 $user = new stdClass();
2112 $user->id = $ruser->id;
2113 $user->username = $ruser->username;
2114 $user->firstname = $ruser->firstname;
2115 $user->lastname = $ruser->lastname;
2116 $role = new stdClass();
2117 $role->id = $ruser->roleid;
2118 $role->name = $ruser->rolename;
2119 $role->shortname = $ruser->roleshortname;
2120 $role->coursealias = $ruser->rolecoursealias;
2122 $this->coursecontacts[$user->id] = array(
2123 'user' => $user,
2124 'role' => $role,
2125 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2126 'username' => fullname($user, $canviewfullnames)
2130 return $this->coursecontacts;
2134 * Checks if course has any associated overview files
2136 * @return bool
2138 public function has_course_overviewfiles() {
2139 global $CFG;
2140 if (empty($CFG->courseoverviewfileslimit)) {
2141 return 0;
2143 require_once($CFG->libdir. '/filestorage/file_storage.php');
2144 $fs = get_file_storage();
2145 $context = context_course::instance($this->id);
2146 return $fs->is_area_empty($context->id, 'course', 'overviewfiles');
2150 * Returns all course overview files
2152 * @return array array of stored_file objects
2154 public function get_course_overviewfiles() {
2155 global $CFG;
2156 if (empty($CFG->courseoverviewfileslimit)) {
2157 return array();
2159 require_once($CFG->libdir. '/filestorage/file_storage.php');
2160 require_once($CFG->dirroot. '/course/lib.php');
2161 $fs = get_file_storage();
2162 $context = context_course::instance($this->id);
2163 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2164 if (count($files)) {
2165 $overviewfilesoptions = course_overviewfiles_options($this->id);
2166 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2167 if ($acceptedtypes !== '*') {
2168 // filter only files with allowed extensions
2169 require_once($CFG->libdir. '/filelib.php');
2170 foreach ($files as $key => $file) {
2171 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2172 unset($files[$key]);
2176 if (count($files) > $CFG->courseoverviewfileslimit) {
2177 // return no more than $CFG->courseoverviewfileslimit files
2178 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
2181 return $files;
2184 // ====== magic methods =======
2186 public function __isset($name) {
2187 return isset($this->record->$name);
2191 * Magic method to get a course property
2193 * Returns any field from table course (from cache or from DB) and/or special field 'hassummary'
2195 * @param string $name
2196 * @return mixed
2198 public function __get($name) {
2199 global $DB;
2200 if (property_exists($this->record, $name)) {
2201 return $this->record->$name;
2202 } else if ($name === 'summary' || $name === 'summaryformat') {
2203 // retrieve fields summary and summaryformat together because they are most likely to be used together
2204 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
2205 $this->record->summary = $record->summary;
2206 $this->record->summaryformat = $record->summaryformat;
2207 return $this->record->$name;
2208 } else if (array_key_exists($name, $DB->get_columns('course'))) {
2209 // another field from table 'course' that was not retrieved
2210 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
2211 return $this->record->$name;
2213 debugging('Invalid course property accessed! '.$name);
2214 return null;
2218 * ALl properties are read only, sorry.
2219 * @param string $name
2221 public function __unset($name) {
2222 debugging('Can not unset '.get_class($this).' instance properties!');
2226 * Magic setter method, we do not want anybody to modify properties from the outside
2227 * @param string $name
2228 * @param mixed $value
2230 public function __set($name, $value) {
2231 debugging('Can not change '.get_class($this).' instance properties!');
2234 // ====== implementing method from interface IteratorAggregate ======
2237 * Create an iterator because magic vars can't be seen by 'foreach'.
2238 * Exclude context fields
2240 public function getIterator() {
2241 $ret = array('id' => $this->record->id);
2242 foreach ($this->record as $property => $value) {
2243 $ret[$property] = $value;
2245 return new ArrayIterator($ret);
2250 * An array of records that is sortable by many fields.
2252 * For more info on the ArrayObject class have a look at php.net.
2254 * @package core
2255 * @subpackage course
2256 * @copyright 2013 Sam Hemelryk
2257 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2259 class coursecat_sortable_records extends ArrayObject {
2262 * An array of sortable fields.
2263 * Gets set temporarily when sort is called.
2264 * @var array
2266 protected $sortfields = array();
2269 * Sorts this array using the given fields.
2271 * @param array $records
2272 * @param array $fields
2273 * @return array
2275 public static function sort(array $records, array $fields) {
2276 $records = new coursecat_sortable_records($records);
2277 $records->sortfields = $fields;
2278 $records->uasort(array($records, 'sort_by_many_fields'));
2279 return $records->getArrayCopy();
2283 * Sorts the two records based upon many fields.
2285 * This method should not be called itself, please call $sort instead.
2286 * It has been marked as access private as such.
2288 * @access private
2289 * @param stdClass $a
2290 * @param stdClass $b
2291 * @return int
2293 public function sort_by_many_fields($a, $b) {
2294 foreach ($this->sortfields as $field => $mult) {
2295 // nulls first
2296 if (is_null($a->$field) && !is_null($b->$field)) {
2297 return -$mult;
2299 if (is_null($b->$field) && !is_null($a->$field)) {
2300 return $mult;
2303 if (is_string($a->$field) || is_string($b->$field)) {
2304 // string fields
2305 if ($cmp = strcoll($a->$field, $b->$field)) {
2306 return $mult * $cmp;
2308 } else {
2309 // int fields
2310 if ($a->$field > $b->$field) {
2311 return $mult;
2313 if ($a->$field < $b->$field) {
2314 return -$mult;
2318 return 0;