2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Contains class coursecat reponsible for course category operations
22 * @copyright 2013 Marina Glancy
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') ||
die();
29 * Class to store, cache, render and manage course category
33 * @copyright 2013 Marina Glancy
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 class coursecat
implements renderable
, cacheable_object
, IteratorAggregate
{
37 /** @var coursecat stores pseudo category with id=0. Use coursecat::get(0) to retrieve */
38 protected static $coursecat0;
40 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
67 protected $idnumber = null;
70 protected $description = false;
73 protected $descriptionformat = false;
76 protected $parent = 0;
79 protected $sortorder = 0;
82 protected $coursecount = false;
85 protected $visible = 1;
88 protected $visibleold = false;
91 protected $timemodified = false;
100 protected $theme = false;
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
123 public function __get($name) {
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;
137 debugging('Invalid coursecat property accessed! '.$name, DEBUG_DEVELOPER
);
142 * Full support for isset on our magic read only properties.
144 * @param string $name
147 public function __isset($name) {
148 if (array_key_exists($name, self
::$coursecatfields)) {
149 return isset($this->$name);
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() {
172 foreach (self
::$coursecatfields as $property => $unused) {
173 if ($this->$property !== false) {
174 $ret[$property] = $this->$property;
177 return new ArrayIterator($ret);
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)) {
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) {
219 if (!isset(self
::$coursecat0)) {
220 $record = new stdClass();
222 $record->visible
= 1;
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);
236 $coursecatrecordcache->set($id, $coursecat);
239 if ($coursecat && ($alwaysreturnhidden ||
$coursecat->is_uservisible())) {
242 if ($strictness == MUST_EXIST
) {
243 throw new moodle_exception('unknowcategory');
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
257 public static function get_default() {
258 if ($visiblechildren = self
::get(0)->get_children()) {
259 $defcategory = reset($visiblechildren);
261 $toplevelcategories = self
::get_tree(0);
262 $defcategoryid = $toplevelcategories[0];
263 $defcategory = self
::get($defcategoryid, MUST_EXIST
, true);
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.
294 * @throws moodle_exception
296 public static function create($data, $editoroptions = null) {
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);
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;
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) {
410 // there is no actual DB record associated with root category
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
;
451 if (isset($data->visible
)) {
452 if ($data->visible
) {
453 $changes = $this->show_raw();
455 $changes = $this->hide_raw(0);
459 if (isset($data->parent
) && $data->parent
!= $this->parent
) {
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
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
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() {
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];
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));
529 foreach ($ids as $id) {
530 if ($coursecat = self
::get($id, IGNORE_MISSING
)) {
531 $rv[$id] = $coursecat;
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
553 protected static function get_tree($id) {
555 $coursecattreecache = cache
::make('core', 'coursecattree');
556 $rv = $coursecattreecache->get($id);
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.
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());
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
;
582 // parent not found. This is data consistency error but next fix_course_sortorder() should fix it
583 $all[0][] = $record->id
;
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();
597 $all['countall'] = $count;
598 foreach ($all as $key => $children) {
599 $coursecattreecache->set($key, $children);
601 if (array_key_exists($id, $all)) {
608 * Returns number of ALL categories in the system regardless if
609 * they are visible to current user or not
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) {
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,
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
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) {
669 if (empty($courses) ||
empty($CFG->coursecontact
)) {
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
) {
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];
692 // $courseids now stores list of ids of courses for which we still need to retrieve contacts
693 if (empty($courseids)) {
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 $notdeleted = array('notdeleted'=>0);
715 $sql = "SELECT ra.contextid, ra.id AS raid,
716 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
717 rn.name AS rolecoursealias, u.id, u.username, u.firstname, u.lastname
718 FROM {role_assignments} ra
719 JOIN {user} u ON ra.userid = u.id
720 JOIN {role} r ON ra.roleid = r.id
721 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
722 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
723 ORDER BY r.sortorder, $sort";
724 $rs = $DB->get_recordset_sql($sql, $params1 +
$params2 +
$notdeleted +
$sortparams);
725 $checkenrolments = array();
726 foreach($rs as $ra) {
727 foreach ($allcontexts[$ra->contextid
] as $id) {
728 $courses[$id]->managers
[$ra->raid
] = $ra;
729 if (!isset($checkenrolments[$id])) {
730 $checkenrolments[$id] = array();
732 $checkenrolments[$id][] = $ra->id
;
737 // remove from course contacts users who are not enrolled in the course
738 $enrolleduserids = self
::ensure_users_enrolled($checkenrolments);
739 foreach ($checkenrolments as $id => $userids) {
740 if (empty($enrolleduserids[$id])) {
741 $courses[$id]->managers
= array();
742 } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
743 foreach ($courses[$id]->managers
as $raid => $ra) {
744 if (in_array($ra->id
, $notenrolled)) {
745 unset($courses[$id]->managers
[$raid]);
753 foreach ($courseids as $id) {
754 $values[$id] = $courses[$id]->managers
;
756 $cache->set_many($values);
760 * Verify user enrollments for multiple course-user combinations
762 * @param array $courseusers array where keys are course ids and values are array
763 * of users in this course whose enrolment we wish to verify
764 * @return array same structure as input array but values list only users from input
765 * who are enrolled in the course
767 protected static function ensure_users_enrolled($courseusers) {
769 // If the input array is too big, split it into chunks
770 $maxcoursesinquery = 20;
771 if (count($courseusers) > $maxcoursesinquery) {
773 for ($offset = 0; $offset < count($courseusers); $offset +
= $maxcoursesinquery) {
774 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
775 $rv = $rv + self
::ensure_users_enrolled($chunk);
780 // create a query verifying valid user enrolments for the number of courses
781 $sql = "SELECT DISTINCT e.courseid, ue.userid
782 FROM {user_enrolments} ue
783 JOIN {enrol} e ON e.id = ue.enrolid
784 WHERE ue.status = :active
785 AND e.status = :enabled
786 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
787 $now = round(time(), -2); // rounding helps caching in DB
788 $params = array('enabled' => ENROL_INSTANCE_ENABLED
,
789 'active' => ENROL_USER_ACTIVE
,
790 'now1' => $now, 'now2' => $now);
794 foreach ($courseusers as $id => $userids) {
795 $enrolled[$id] = array();
796 if (count($userids)) {
797 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED
, 'userid'.$cnt.'_');
798 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
799 $params = $params +
array('courseid'.$cnt => $id) +
$params2;
803 if (count($subsqls)) {
804 $sql .= "AND (". join(' OR ', $subsqls).")";
805 $rs = $DB->get_recordset_sql($sql, $params);
806 foreach ($rs as $record) {
807 $enrolled[$record->courseid
][] = $record->userid
;
815 * Retrieves number of records from course table
817 * Not all fields are retrieved. Records are ready for preloading context
819 * @param string $whereclause
820 * @param array $params
821 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
822 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
823 * on not visible courses
824 * @return array array of stdClass objects
826 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
828 $ctxselect = context_helper
::get_preload_record_columns_sql('ctx');
829 $fields = array('c.id', 'c.category', 'c.sortorder',
830 'c.shortname', 'c.fullname', 'c.idnumber',
831 'c.startdate', 'c.visible');
832 if (!empty($options['summary'])) {
833 $fields[] = 'c.summary';
834 $fields[] = 'c.summaryformat';
836 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
838 $sql = "SELECT ". join(',', $fields). ", $ctxselect
840 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
841 WHERE ". $whereclause." ORDER BY c.sortorder";
842 $list = $DB->get_records_sql($sql,
843 array('contextcourse' => CONTEXT_COURSE
) +
$params);
845 if ($checkvisibility) {
846 // Loop through all records and make sure we only return the courses accessible by user.
847 foreach ($list as $course) {
848 if (isset($list[$course->id
]->hassummary
)) {
849 $list[$course->id
]->hassummary
= strlen($list[$course->id
]->hassummary
) > 0;
851 if (empty($course->visible
)) {
852 // load context only if we need to check capability
853 context_helper
::preload_from_record($course);
854 if (!has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
855 unset($list[$course->id
]);
861 // preload course contacts if necessary
862 if (!empty($options['coursecontacts'])) {
863 self
::preload_course_contacts($list);
869 * Returns array of ids of children categories that current user can not see
871 * This data is cached in user session cache
875 protected function get_not_visible_children_ids() {
877 $coursecatcache = cache
::make('core', 'coursecat');
878 if (($invisibleids = $coursecatcache->get('ic'. $this->id
)) === false) {
879 // we never checked visible children before
880 $hidden = self
::get_tree($this->id
.'i');
881 $invisibleids = array();
883 // preload categories contexts
884 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED
, 'id');
885 $ctxselect = context_helper
::get_preload_record_columns_sql('ctx');
886 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
887 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
888 array('contextcoursecat' => CONTEXT_COURSECAT
) +
$params);
889 foreach ($contexts as $record) {
890 context_helper
::preload_from_record($record);
892 // check that user has 'viewhiddencategories' capability for each hidden category
893 foreach ($hidden as $id) {
894 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat
::instance($id))) {
895 $invisibleids[] = $id;
899 $coursecatcache->set('ic'. $this->id
, $invisibleids);
901 return $invisibleids;
905 * Sorts list of records by several fields
907 * @param array $records array of stdClass objects
908 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
911 protected static function sort_records(&$records, $sortfields) {
912 if (empty($records)) {
915 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname)
916 if (array_key_exists('displayname', $sortfields)) {
917 foreach ($records as $key => $record) {
918 if (!isset($record->displayname
)) {
919 $records[$key]->displayname
= get_course_display_name_for_list($record);
923 // sorting by one field - use collatorlib
924 if (count($sortfields) == 1) {
925 $property = key($sortfields);
926 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
927 $sortflag = collatorlib
::SORT_NUMERIC
;
928 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
929 $sortflag = collatorlib
::SORT_STRING
;
931 $sortflag = collatorlib
::SORT_REGULAR
;
933 collatorlib
::asort_objects_by_property($records, $property, $sortflag);
934 if ($sortfields[$property] < 0) {
935 $records = array_reverse($records, true);
939 $records = coursecat_sortable_records
::sort($records, $sortfields);
943 * Returns array of children categories visible to the current user
945 * @param array $options options for retrieving children
946 * - sort - list of fields to sort. Example
947 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
948 * will sort by idnumber asc, name asc and id desc.
949 * Default: array('sortorder' => 1)
950 * Only cached fields may be used for sorting!
952 * - limit - maximum number of children to return, 0 or null for no limit
953 * @return array of coursecat objects indexed by category id
955 public function get_children($options = array()) {
957 $coursecatcache = cache
::make('core', 'coursecat');
959 // get default values for options
960 if (!empty($options['sort']) && is_array($options['sort'])) {
961 $sortfields = $options['sort'];
963 $sortfields = array('sortorder' => 1);
966 if (!empty($options['limit']) && (int)$options['limit']) {
967 $limit = (int)$options['limit'];
970 if (!empty($options['offset']) && (int)$options['offset']) {
971 $offset = (int)$options['offset'];
974 // first retrieve list of user-visible and sorted children ids from cache
975 $sortedids = $coursecatcache->get('c'. $this->id
. ':'. serialize($sortfields));
976 if ($sortedids === false) {
977 $sortfieldskeys = array_keys($sortfields);
978 if ($sortfieldskeys[0] === 'sortorder') {
979 // no DB requests required to build the list of ids sorted by sortorder.
980 // We can easily ignore other sort fields because sortorder is always different
981 $sortedids = self
::get_tree($this->id
);
982 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
983 $sortedids = array_diff($sortedids, $invisibleids);
984 if ($sortfields['sortorder'] == -1) {
985 $sortedids = array_reverse($sortedids, true);
989 // we need to retrieve and sort all children. Good thing that it is done only on first request
990 if ($invisibleids = $this->get_not_visible_children_ids()) {
991 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED
, 'id', false);
992 $records = self
::get_records('cc.parent = :parent AND cc.id '. $sql,
993 array('parent' => $this->id
) +
$params);
995 $records = self
::get_records('cc.parent = :parent', array('parent' => $this->id
));
997 self
::sort_records($records, $sortfields);
998 $sortedids = array_keys($records);
1000 $coursecatcache->set('c'. $this->id
. ':'.serialize($sortfields), $sortedids);
1003 if (empty($sortedids)) {
1007 // now retrieive and return categories
1008 if ($offset ||
$limit) {
1009 $sortedids = array_slice($sortedids, $offset, $limit);
1011 if (isset($records)) {
1012 // easy, we have already retrieved records
1013 if ($offset ||
$limit) {
1014 $records = array_slice($records, $offset, $limit, true);
1017 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED
, 'id');
1018 $records = self
::get_records('cc.id '. $sql,
1019 array('parent' => $this->id
) +
$params);
1023 foreach ($sortedids as $id) {
1024 if (isset($records[$id])) {
1025 $rv[$id] = new coursecat($records[$id]);
1032 * Returns number of subcategories visible to the current user
1036 public function get_children_count() {
1037 $sortedids = self
::get_tree($this->id
);
1038 $invisibleids = $this->get_not_visible_children_ids();
1039 return count($sortedids) - count($invisibleids);
1043 * Returns true if the category has ANY children, including those not visible to the user
1047 public function has_children() {
1048 $allchildren = self
::get_tree($this->id
);
1049 return !empty($allchildren);
1053 * Returns true if the category has courses in it (count does not include courses
1054 * in child categories)
1058 public function has_courses() {
1060 return $DB->record_exists_sql("select 1 from {course} where category = ?",
1067 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1068 * to this when somebody edits courses or categories, however it is very
1069 * difficult to keep track of all possible changes that may affect list of courses.
1071 * @param array $search contains search criterias, such as:
1072 * - search - search string
1073 * - blocklist - id of block (if we are searching for courses containing specific block0
1074 * - modulelist - name of module (if we are searching for courses containing specific module
1075 * - tagid - id of tag
1076 * @param array $options display options, same as in get_courses() except 'recursive' is ignored - search is always category-independent
1079 public static function search_courses($search, $options = array()) {
1081 $offset = !empty($options['offset']) ?
$options['offset'] : 0;
1082 $limit = !empty($options['limit']) ?
$options['limit'] : null;
1083 $sortfields = !empty($options['sort']) ?
$options['sort'] : array('sortorder' => 1);
1085 $coursecatcache = cache
::make('core', 'coursecat');
1086 $cachekey = 's-'. serialize($search +
array('sort' => $sortfields));
1087 $cntcachekey = 'scnt-'. serialize($search);
1089 $ids = $coursecatcache->get($cachekey);
1090 if ($ids !== false) {
1091 // we already cached last search result
1092 $ids = array_slice($ids, $offset, $limit);
1095 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED
, 'id');
1096 $records = self
::get_course_records("c.id ". $sql, $params, $options);
1097 foreach ($ids as $id) {
1098 $courses[$id] = new course_in_list($records[$id]);
1104 $preloadcoursecontacts = !empty($options['coursecontacts']);
1105 unset($options['coursecontacts']);
1107 if (!empty($search['search'])) {
1108 // search courses that have specified words in their names/summaries
1109 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY
);
1110 $searchterms = array_filter($searchterms, create_function('$v', 'return strlen($v) > 1;'));
1111 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount);
1112 self
::sort_records($courselist, $sortfields);
1113 $coursecatcache->set($cachekey, array_keys($courselist));
1114 $coursecatcache->set($cntcachekey, $totalcount);
1115 $records = array_slice($courselist, $offset, $limit, true);
1117 if (!empty($search['blocklist'])) {
1118 // search courses that have block with specified id
1119 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1120 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1121 WHERE bi.blockname = :blockname)';
1122 $params = array('blockname' => $blockname);
1123 } else if (!empty($search['modulelist'])) {
1124 // search courses that have module with specified name
1125 $where = "c.id IN (SELECT DISTINCT module.course ".
1126 "FROM {".$search['modulelist']."} module)";
1128 } else if (!empty($search['tagid'])) {
1129 // search courses that are tagged with the specified tag
1130 $where = "c.id IN (SELECT t.itemid ".
1131 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype)";
1132 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course');
1134 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER
);
1137 $courselist = self
::get_course_records($where, $params, $options, true);
1138 self
::sort_records($courselist, $sortfields);
1139 $coursecatcache->set($cachekey, array_keys($courselist));
1140 $coursecatcache->set($cntcachekey, count($courselist));
1141 $records = array_slice($courselist, $offset, $limit, true);
1144 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1145 if (!empty($preloadcoursecontacts)) {
1146 self
::preload_course_contacts($records);
1149 foreach ($records as $record) {
1150 $courses[$record->id
] = new course_in_list($record);
1156 * Returns number of courses in the search results
1158 * It is recommended to call this function after {@link coursecat::search_courses()}
1159 * and not before because only course ids are cached. Otherwise search_courses() may
1160 * perform extra DB queries.
1162 * @param array $search search criteria, see method search_courses() for more details
1163 * @param array $options display options. They do not affect the result but
1164 * the 'sort' property is used in cache key for storing list of course ids
1167 public static function search_courses_count($search, $options = array()) {
1168 $coursecatcache = cache
::make('core', 'coursecat');
1169 $cntcachekey = 'scnt-'. serialize($search);
1170 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1171 self
::search_courses($search, $options);
1172 $cnt = $coursecatcache->get($cntcachekey);
1178 * Retrieves the list of courses accessible by user
1180 * Not all information is cached, try to avoid calling this method
1181 * twice in the same request.
1183 * The following fields are always retrieved:
1184 * - id, visible, fullname, shortname, idnumber, category, sortorder
1186 * If you plan to use properties/methods course_in_list::$summary and/or
1187 * course_in_list::get_course_contacts()
1188 * you can preload this information using appropriate 'options'. Otherwise
1189 * they will be retrieved from DB on demand and it may end with bigger DB load.
1191 * Note that method course_in_list::has_summary() will not perform additional
1192 * DB queries even if $options['summary'] is not specified
1194 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1195 * to this when somebody edits courses or categories, however it is very
1196 * difficult to keep track of all possible changes that may affect list of courses.
1198 * @param array $options options for retrieving children
1199 * - recursive - return courses from subcategories as well. Use with care,
1200 * this may be a huge list!
1201 * - summary - preloads fields 'summary' and 'summaryformat'
1202 * - coursecontacts - preloads course contacts
1203 * - sort - list of fields to sort. Example
1204 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1205 * will sort by idnumber asc, shortname asc and id desc.
1206 * Default: array('sortorder' => 1)
1207 * Only cached fields may be used for sorting!
1209 * - limit - maximum number of children to return, 0 or null for no limit
1210 * @return array array of instances of course_in_list
1212 public function get_courses($options = array()) {
1214 $recursive = !empty($options['recursive']);
1215 $offset = !empty($options['offset']) ?
$options['offset'] : 0;
1216 $limit = !empty($options['limit']) ?
$options['limit'] : null;
1217 $sortfields = !empty($options['sort']) ?
$options['sort'] : array('sortorder' => 1);
1219 // Check if this category is hidden.
1220 // Also 0-category never has courses unless this is recursive call.
1221 if (!$this->is_uservisible() ||
(!$this->id
&& !$recursive)) {
1225 $coursecatcache = cache
::make('core', 'coursecat');
1226 $cachekey = 'l-'. $this->id
. '-'. (!empty($options['recursive']) ?
'r' : '').
1227 '-'. serialize($sortfields);
1228 $cntcachekey = 'lcnt-'. $this->id
. '-'. (!empty($options['recursive']) ?
'r' : '');
1230 // check if we have already cached results
1231 $ids = $coursecatcache->get($cachekey);
1232 if ($ids !== false) {
1233 // we already cached last search result and it did not expire yet
1234 $ids = array_slice($ids, $offset, $limit);
1237 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED
, 'id');
1238 $records = self
::get_course_records("c.id ". $sql, $params, $options);
1239 foreach ($ids as $id) {
1240 $courses[$id] = new course_in_list($records[$id]);
1246 // retrieve list of courses in category
1247 $where = 'c.id <> :siteid';
1248 $params = array('siteid' => SITEID
);
1251 $context = context_coursecat
::instance($this->id
);
1252 $where .= ' AND ctx.path like :path';
1253 $params['path'] = $context->path
. '/%';
1256 $where .= ' AND c.category = :categoryid';
1257 $params['categoryid'] = $this->id
;
1259 // get list of courses without preloaded coursecontacts because we don't need them for every course
1260 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1262 // sort and cache list
1263 self
::sort_records($list, $sortfields);
1264 $coursecatcache->set($cachekey, array_keys($list));
1265 $coursecatcache->set($cntcachekey, count($list));
1267 // Apply offset/limit, convert to course_in_list and return.
1270 if ($offset ||
$limit) {
1271 $list = array_slice($list, $offset, $limit, true);
1273 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1274 if (!empty($options['coursecontacts'])) {
1275 self
::preload_course_contacts($list);
1277 foreach ($list as $record) {
1278 $courses[$record->id
] = new course_in_list($record);
1285 * Returns number of courses visible to the user
1287 * @param array $options similar to get_courses() except some options do not affect
1288 * number of courses (i.e. sort, summary, offset, limit etc.)
1291 public function get_courses_count($options = array()) {
1292 $cntcachekey = 'lcnt-'. $this->id
. '-'. (!empty($options['recursive']) ?
'r' : '');
1293 $coursecatcache = cache
::make('core', 'coursecat');
1294 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1295 $this->get_courses($options);
1296 $cnt = $coursecatcache->get($cntcachekey);
1302 * Returns true if user can delete current category and all its contents
1304 * To be able to delete course category the user must have permission
1305 * 'moodle/category:manage' in ALL child course categories AND
1306 * be able to delete all courses
1310 public function can_delete_full() {
1317 $context = context_coursecat
::instance($this->id
);
1318 if (!$this->is_uservisible() ||
1319 !has_capability('moodle/category:manage', $context)) {
1323 // Check all child categories (not only direct children)
1324 $sql = context_helper
::get_preload_record_columns_sql('ctx');
1325 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1326 ' FROM {context} ctx '.
1327 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1328 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1329 array($context->path
. '/%', CONTEXT_COURSECAT
));
1330 foreach ($childcategories as $childcat) {
1331 context_helper
::preload_from_record($childcat);
1332 $childcontext = context_coursecat
::instance($childcat->id
);
1333 if ((!$childcat->visible
&& !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1334 !has_capability('moodle/category:manage', $childcontext)) {
1340 $sql = context_helper
::get_preload_record_columns_sql('ctx');
1341 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1342 $sql. ' FROM {context} ctx '.
1343 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1344 array('pathmask' => $context->path
. '/%',
1345 'courselevel' => CONTEXT_COURSE
));
1346 foreach ($coursescontexts as $ctxrecord) {
1347 context_helper
::preload_from_record($ctxrecord);
1348 if (!can_delete_course($ctxrecord->courseid
)) {
1357 * Recursively delete category including all subcategories and courses
1359 * Function {@link coursecat::can_delete_full()} MUST be called prior
1360 * to calling this function because there is no capability check
1361 * inside this function
1363 * @param boolean $showfeedback display some notices
1364 * @return array return deleted courses
1366 public function delete_full($showfeedback = true) {
1368 require_once($CFG->libdir
.'/gradelib.php');
1369 require_once($CFG->libdir
.'/questionlib.php');
1370 require_once($CFG->dirroot
.'/cohort/lib.php');
1372 $deletedcourses = array();
1374 // Get children. Note, we don't want to use cache here because
1375 // it would be rebuilt too often
1376 $children = $DB->get_records('course_categories', array('parent' => $this->id
), 'sortorder ASC');
1377 foreach ($children as $record) {
1378 $coursecat = new coursecat($record);
1379 $deletedcourses +
= $coursecat->delete_full($showfeedback);
1382 if ($courses = $DB->get_records('course', array('category' => $this->id
), 'sortorder ASC')) {
1383 foreach ($courses as $course) {
1384 if (!delete_course($course, false)) {
1385 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname
);
1387 $deletedcourses[] = $course;
1391 // move or delete cohorts in this context
1392 cohort_delete_category($this);
1394 // now delete anything that may depend on course category context
1395 grade_course_category_delete($this->id
, 0, $showfeedback);
1396 if (!question_delete_course_category($this, 0, $showfeedback)) {
1397 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1400 // finally delete the category and it's context
1401 $DB->delete_records('course_categories', array('id' => $this->id
));
1402 delete_context(CONTEXT_COURSECAT
, $this->id
);
1403 add_to_log(SITEID
, "category", "delete", "index.php", "$this->name (ID $this->id)");
1405 cache_helper
::purge_by_event('changesincoursecat');
1407 events_trigger('course_category_deleted', $this);
1409 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1410 if ($this->id
== $CFG->defaultrequestcategory
) {
1411 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1413 return $deletedcourses;
1417 * Checks if user can delete this category and move content (courses, subcategories and questions)
1418 * to another category. If yes returns the array of possible target categories names
1420 * If user can not manage this category or it is completely empty - empty array will be returned
1424 public function move_content_targets_list() {
1426 require_once($CFG->libdir
. '/questionlib.php');
1427 $context = context_coursecat
::instance($this->id
);
1428 if (!$this->is_uservisible() ||
1429 !has_capability('moodle/category:manage', $context)) {
1430 // User is not able to manage current category, he is not able to delete it.
1431 // No possible target categories.
1435 $testcaps = array();
1436 // If this category has courses in it, user must have 'course:create' capability in target category.
1437 if ($this->has_courses()) {
1438 $testcaps[] = 'moodle/course:create';
1440 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1441 if ($this->has_children() ||
question_context_has_any_questions($context)) {
1442 $testcaps[] = 'moodle/category:manage';
1444 if (!empty($testcaps)) {
1445 // return list of categories excluding this one and it's children
1446 return self
::make_categories_list($testcaps, $this->id
);
1449 // Category is completely empty, no need in target for contents.
1454 * Checks if user has capability to move all category content to the new parent before
1455 * removing this category
1457 * @param int $newcatid
1460 public function can_move_content_to($newcatid) {
1462 require_once($CFG->libdir
. '/questionlib.php');
1463 $context = context_coursecat
::instance($this->id
);
1464 if (!$this->is_uservisible() ||
1465 !has_capability('moodle/category:manage', $context)) {
1468 $testcaps = array();
1469 // If this category has courses in it, user must have 'course:create' capability in target category.
1470 if ($this->has_courses()) {
1471 $testcaps[] = 'moodle/course:create';
1473 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1474 if ($this->has_children() ||
question_context_has_any_questions($context)) {
1475 $testcaps[] = 'moodle/category:manage';
1477 if (!empty($testcaps)) {
1478 return has_all_capabilities($testcaps, context_coursecat
::instance($newcatid));
1481 // there is no content but still return true
1486 * Deletes a category and moves all content (children, courses and questions) to the new parent
1488 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1489 * must be called prior
1491 * @param int $newparentid
1492 * @param bool $showfeedback
1495 public function delete_move($newparentid, $showfeedback = false) {
1496 global $CFG, $DB, $OUTPUT;
1497 require_once($CFG->libdir
.'/gradelib.php');
1498 require_once($CFG->libdir
.'/questionlib.php');
1499 require_once($CFG->dirroot
.'/cohort/lib.php');
1501 // get all objects and lists because later the caches will be reset so
1502 // we don't need to make extra queries
1503 $newparentcat = self
::get($newparentid, MUST_EXIST
, true);
1504 $catname = $this->get_formatted_name();
1505 $children = $this->get_children();
1506 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', array('category' => $this->id
));
1507 $context = context_coursecat
::instance($this->id
);
1510 foreach ($children as $childcat) {
1511 $childcat->change_parent_raw($newparentcat);
1513 add_to_log(SITEID
, "category", "move", "editcategory.php?id=$childcat->id", $childcat->id
);
1515 fix_course_sortorder();
1519 if (!move_courses($coursesids, $newparentid)) {
1520 if ($showfeedback) {
1521 echo $OUTPUT->notification("Error moving courses");
1525 if ($showfeedback) {
1526 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1530 // move or delete cohorts in this context
1531 cohort_delete_category($this);
1533 // now delete anything that may depend on course category context
1534 grade_course_category_delete($this->id
, $newparentid, $showfeedback);
1535 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1536 if ($showfeedback) {
1537 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1542 // finally delete the category and it's context
1543 $DB->delete_records('course_categories', array('id' => $this->id
));
1545 add_to_log(SITEID
, "category", "delete", "index.php", "$this->name (ID $this->id)");
1547 events_trigger('course_category_deleted', $this);
1549 cache_helper
::purge_by_event('changesincoursecat');
1551 if ($showfeedback) {
1552 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1555 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1556 if ($this->id
== $CFG->defaultrequestcategory
) {
1557 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1563 * Checks if user can move current category to the new parent
1565 * This checks if new parent category exists, user has manage cap there
1566 * and new parent is not a child of this category
1568 * @param int|stdClass|coursecat $newparentcat
1571 public function can_change_parent($newparentcat) {
1572 if (!has_capability('moodle/category:manage', context_coursecat
::instance($this->id
))) {
1575 if (is_object($newparentcat)) {
1576 $newparentcat = self
::get($newparentcat->id
, IGNORE_MISSING
);
1578 $newparentcat = self
::get((int)$newparentcat, IGNORE_MISSING
);
1580 if (!$newparentcat) {
1583 if ($newparentcat->id
== $this->id ||
in_array($this->id
, $newparentcat->get_parents())) {
1584 // can not move to itself or it's own child
1587 if ($newparentcat->id
) {
1588 return has_capability('moodle/category:manage', context_coursecat
::instance($newparentcat->id
));
1590 return has_capability('moodle/category:manage', context_system
::instance());
1595 * Moves the category under another parent category. All associated contexts are moved as well
1597 * This is protected function, use change_parent() or update() from outside of this class
1599 * @see coursecat::change_parent()
1600 * @see coursecat::update()
1602 * @param coursecat $newparentcat
1604 protected function change_parent_raw(coursecat
$newparentcat) {
1607 $context = context_coursecat
::instance($this->id
);
1610 if (empty($newparentcat->id
)) {
1611 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id
));
1612 $newparent = context_system
::instance();
1614 if ($newparentcat->id
== $this->id ||
in_array($this->id
, $newparentcat->get_parents())) {
1615 // can not move to itself or it's own child
1616 throw new moodle_exception('cannotmovecategory');
1618 $DB->set_field('course_categories', 'parent', $newparentcat->id
, array('id' => $this->id
));
1619 $newparent = context_coursecat
::instance($newparentcat->id
);
1621 if (!$newparentcat->visible
and $this->visible
) {
1622 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
1626 $this->parent
= $newparentcat->id
;
1628 $context->update_moved($newparent);
1630 // now make it last in new category
1631 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY
*MAX_COURSE_CATEGORIES
, array('id' => $this->id
));
1634 fix_course_sortorder();
1636 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must become visible again.
1642 * Efficiently moves a category - NOTE that this can have
1643 * a huge impact access-control-wise...
1645 * Note that this function does not check capabilities.
1648 * $coursecat = coursecat::get($categoryid);
1649 * if ($coursecat->can_change_parent($newparentcatid)) {
1650 * $coursecat->change_parent($newparentcatid);
1653 * This function does not update field course_categories.timemodified
1654 * If you want to update timemodified, use
1655 * $coursecat->update(array('parent' => $newparentcat));
1657 * @param int|stdClass|coursecat $newparentcat
1659 public function change_parent($newparentcat) {
1660 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1661 if (is_object($newparentcat)) {
1662 $newparentcat = self
::get($newparentcat->id
, MUST_EXIST
, true);
1664 $newparentcat = self
::get((int)$newparentcat, MUST_EXIST
, true);
1666 if ($newparentcat->id
!= $this->parent
) {
1667 $this->change_parent_raw($newparentcat);
1668 fix_course_sortorder();
1669 cache_helper
::purge_by_event('changesincoursecat');
1671 add_to_log(SITEID
, "category", "move", "editcategory.php?id=$this->id", $this->id
);
1676 * Hide course category and child course and subcategories
1678 * If this category has changed the parent and is moved under hidden
1679 * category we will want to store it's current visibility state in
1680 * the field 'visibleold'. If admin clicked 'hide' for this particular
1681 * category, the field 'visibleold' should become 0.
1683 * All subcategories and courses will have their current visibility in the field visibleold
1685 * This is protected function, use hide() or update() from outside of this class
1687 * @see coursecat::hide()
1688 * @see coursecat::update()
1690 * @param int $visibleold value to set in field $visibleold for this category
1691 * @return bool whether changes have been made and caches need to be purged afterwards
1693 protected function hide_raw($visibleold = 0) {
1697 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing
1698 if ($this->id
&& $this->__get('visibleold') != $visibleold) {
1699 $this->visibleold
= $visibleold;
1700 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id
));
1703 if (!$this->visible ||
!$this->id
) {
1704 // already hidden or can not be hidden
1709 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id
));
1710 $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
1711 $DB->set_field('course', 'visible', 0, array('category' => $this->id
));
1712 // get all child categories and hide too
1713 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
1714 foreach ($subcats as $cat) {
1715 $DB->set_field('course_categories', 'visibleold', $cat->visible
, array('id' => $cat->id
));
1716 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id
));
1717 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id
));
1718 $DB->set_field('course', 'visible', 0, array('category' => $cat->id
));
1725 * Hide course category and child course and subcategories
1727 * Note that there is no capability check inside this function
1729 * This function does not update field course_categories.timemodified
1730 * If you want to update timemodified, use
1731 * $coursecat->update(array('visible' => 0));
1733 public function hide() {
1734 if ($this->hide_raw(0)) {
1735 cache_helper
::purge_by_event('changesincoursecat');
1736 add_to_log(SITEID
, "category", "hide", "editcategory.php?id=$this->id", $this->id
);
1741 * Show course category and restores visibility for child course and subcategories
1743 * Note that there is no capability check inside this function
1745 * This is protected function, use show() or update() from outside of this class
1747 * @see coursecat::show()
1748 * @see coursecat::update()
1750 * @return bool whether changes have been made and caches need to be purged afterwards
1752 protected function show_raw() {
1755 if ($this->visible
) {
1761 $this->visibleold
= 1;
1762 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id
));
1763 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id
));
1764 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id
));
1765 // get all child categories and unhide too
1766 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
1767 foreach ($subcats as $cat) {
1768 if ($cat->visibleold
) {
1769 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id
));
1771 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id
));
1778 * Show course category and restores visibility for child course and subcategories
1780 * Note that there is no capability check inside this function
1782 * This function does not update field course_categories.timemodified
1783 * If you want to update timemodified, use
1784 * $coursecat->update(array('visible' => 1));
1786 public function show() {
1787 if ($this->show_raw()) {
1788 cache_helper
::purge_by_event('changesincoursecat');
1789 add_to_log(SITEID
, "category", "show", "editcategory.php?id=$this->id", $this->id
);
1794 * Returns name of the category formatted as a string
1796 * @param array $options formatting options other than context
1799 public function get_formatted_name($options = array()) {
1801 $context = context_coursecat
::instance($this->id
);
1802 return format_string($this->name
, true, array('context' => $context) +
$options);
1804 return ''; // TODO 'Top'?
1809 * Returns ids of all parents of the category. Last element in the return array is the direct parent
1811 * For example, if you have a tree of categories like:
1812 * Miscellaneous (id = 1)
1813 * Subcategory (id = 2)
1814 * Sub-subcategory (id = 4)
1815 * Other category (id = 3)
1817 * coursecat::get(1)->get_parents() == array()
1818 * coursecat::get(2)->get_parents() == array(1)
1819 * coursecat::get(4)->get_parents() == array(1, 2);
1821 * Note that this method does not check if all parents are accessible by current user
1823 * @return array of category ids
1825 public function get_parents() {
1826 $parents = preg_split('|/|', $this->path
, 0, PREG_SPLIT_NO_EMPTY
);
1827 array_pop($parents);
1832 * This function returns a nice list representing category tree
1833 * for display or to use in a form <select> element
1835 * List is cached for 10 minutes
1837 * For example, if you have a tree of categories like:
1838 * Miscellaneous (id = 1)
1839 * Subcategory (id = 2)
1840 * Sub-subcategory (id = 4)
1841 * Other category (id = 3)
1842 * Then after calling this function you will have
1843 * array(1 => 'Miscellaneous',
1844 * 2 => 'Miscellaneous / Subcategory',
1845 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1846 * 3 => 'Other category');
1848 * If you specify $requiredcapability, then only categories where the current
1849 * user has that capability will be added to $list.
1850 * If you only have $requiredcapability in a child category, not the parent,
1851 * then the child catgegory will still be included.
1853 * If you specify the option $excludeid, then that category, and all its children,
1854 * are omitted from the tree. This is useful when you are doing something like
1855 * moving categories, where you do not want to allow people to move a category
1856 * to be the child of itself.
1858 * See also {@link make_categories_options()}
1860 * @param string/array $requiredcapability if given, only categories where the current
1861 * user has this capability will be returned. Can also be an array of capabilities,
1862 * in which case they are all required.
1863 * @param integer $excludeid Exclude this category and its children from the lists built.
1864 * @param string $separator string to use as a separator between parent and child category. Default ' / '
1865 * @return array of strings
1867 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
1869 $coursecatcache = cache
::make('core', 'coursecat');
1871 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids with requried cap ($thislist).
1872 $basecachekey = 'catlist';
1873 $baselist = $coursecatcache->get($basecachekey);
1875 if (!empty($requiredcapability)) {
1876 $requiredcapability = (array)$requiredcapability;
1877 $thiscachekey = 'catlist:'. serialize($requiredcapability);
1878 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
1879 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY
);
1881 } else if ($baselist !== false) {
1882 $thislist = array_keys($baselist);
1885 if ($baselist === false) {
1886 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
1887 $ctxselect = context_helper
::get_preload_record_columns_sql('ctx');
1888 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
1889 FROM {course_categories} cc
1890 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
1891 ORDER BY cc.sortorder";
1892 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT
));
1893 $baselist = array();
1894 $thislist = array();
1895 foreach ($rs as $record) {
1896 // If the category's parent is not visible to the user, it is not visible as well.
1897 if (!$record->parent ||
isset($baselist[$record->parent
])) {
1898 $context = context_coursecat
::instance($record->id
);
1899 if (!$record->visible
&& !has_capability('moodle/category:viewhiddencategories', $context)) {
1900 // No cap to view category, added to neither $baselist nor $thislist
1903 $baselist[$record->id
] = array(
1904 'name' => format_string($record->name
, true, array('context' => $context)),
1905 'path' => $record->path
1907 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
1908 // No required capability, added to $baselist but not to $thislist.
1911 $thislist[] = $record->id
;
1915 $coursecatcache->set($basecachekey, $baselist);
1916 if (!empty($requiredcapability)) {
1917 $coursecatcache->set($thiscachekey, join(',', $thislist));
1919 } else if ($thislist === false) {
1920 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
1921 $ctxselect = context_helper
::get_preload_record_columns_sql('ctx');
1922 $sql = "SELECT ctx.instanceid id, $ctxselect
1923 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
1924 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT
));
1925 $thislist = array();
1926 foreach (array_keys($baselist) as $id) {
1927 context_helper
::preload_from_record($contexts[$id]);
1928 if (has_all_capabilities($requiredcapability, context_coursecat
::instance($id))) {
1932 $coursecatcache->set($thiscachekey, join(',', $thislist));
1935 // Now build the array of strings to return, mind $separator and $excludeid.
1937 foreach ($thislist as $id) {
1938 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY
);
1939 if (!$excludeid ||
!in_array($excludeid, $path)) {
1940 $namechunks = array();
1941 foreach ($path as $parentid) {
1942 $namechunks[] = $baselist[$parentid]['name'];
1944 $names[$id] = join($separator, $namechunks);
1951 * Prepares the object for caching. Works like the __sleep method.
1953 * implementing method from interface cacheable_object
1955 * @return array ready to be cached
1957 public function prepare_to_cache() {
1959 foreach (self
::$coursecatfields as $property => $cachedirectives) {
1960 if ($cachedirectives !== null) {
1961 list($shortname, $defaultvalue) = $cachedirectives;
1962 if ($this->$property !== $defaultvalue) {
1963 $a[$shortname] = $this->$property;
1967 $context = context_coursecat
::instance($this->id
);
1968 $a['xi'] = $context->id
;
1969 $a['xp'] = $context->path
;
1974 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
1976 * implementing method from interface cacheable_object
1981 public static function wake_from_cache($a) {
1982 $record = new stdClass
;
1983 foreach (self
::$coursecatfields as $property => $cachedirectives) {
1984 if ($cachedirectives !== null) {
1985 list($shortname, $defaultvalue) = $cachedirectives;
1986 if (array_key_exists($shortname, $a)) {
1987 $record->$property = $a[$shortname];
1989 $record->$property = $defaultvalue;
1993 $record->ctxid
= $a['xi'];
1994 $record->ctxpath
= $a['xp'];
1995 $record->ctxdepth
= $record->depth +
1;
1996 $record->ctxlevel
= CONTEXT_COURSECAT
;
1997 $record->ctxinstance
= $record->id
;
1998 return new coursecat($record, true);
2003 * Class to store information about one course in a list of courses
2005 * Not all information may be retrieved when object is created but
2006 * it will be retrieved on demand when appropriate property or method is
2009 * Instances of this class are usually returned by functions
2010 * {@link coursecat::search_courses()}
2012 * {@link coursecat::get_courses()}
2015 * @subpackage course
2016 * @copyright 2013 Marina Glancy
2017 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2019 class course_in_list
implements IteratorAggregate
{
2021 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2024 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2025 protected $coursecontacts;
2028 * Creates an instance of the class from record
2030 * @param stdClass $record except fields from course table it may contain
2031 * field hassummary indicating that summary field is not empty.
2032 * Also it is recommended to have context fields here ready for
2033 * context preloading
2035 public function __construct(stdClass
$record) {
2036 context_instance_preload($record);
2037 $this->record
= new stdClass();
2038 foreach ($record as $key => $value) {
2039 $this->record
->$key = $value;
2044 * Indicates if the course has non-empty summary field
2048 public function has_summary() {
2049 if (isset($this->record
->hassummary
)) {
2050 return !empty($this->record
->hassummary
);
2052 if (!isset($this->record
->summary
)) {
2053 // we need to retrieve summary
2054 $this->__get('summary');
2056 return !empty($this->record
->summary
);
2060 * Indicates if the course have course contacts to display
2064 public function has_course_contacts() {
2065 if (!isset($this->record
->managers
)) {
2066 $courses = array($this->id
=> &$this->record
);
2067 coursecat
::preload_course_contacts($courses);
2069 return !empty($this->record
->managers
);
2073 * Returns list of course contacts (usually teachers) to display in course link
2075 * Roles to display are set up in $CFG->coursecontact
2077 * The result is the list of users where user id is the key and the value
2078 * is an array with elements:
2079 * - 'user' - object containing basic user information
2080 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2081 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2082 * - 'username' => fullname($user, $canviewfullnames)
2086 public function get_course_contacts() {
2088 if (empty($CFG->coursecontact
)) {
2089 // no roles are configured to be displayed as course contacts
2092 if ($this->coursecontacts
=== null) {
2093 $this->coursecontacts
= array();
2094 $context = context_course
::instance($this->id
);
2096 if (!isset($this->record
->managers
)) {
2097 // preload course contacts from DB
2098 $courses = array($this->id
=> &$this->record
);
2099 coursecat
::preload_course_contacts($courses);
2102 // build return array with full roles names (for this course context) and users names
2103 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2104 foreach ($this->record
->managers
as $ruser) {
2105 if (isset($this->coursecontacts
[$ruser->id
])) {
2106 // only display a user once with the highest sortorder role
2109 $user = new stdClass();
2110 $user->id
= $ruser->id
;
2111 $user->username
= $ruser->username
;
2112 $user->firstname
= $ruser->firstname
;
2113 $user->lastname
= $ruser->lastname
;
2114 $role = new stdClass();
2115 $role->id
= $ruser->roleid
;
2116 $role->name
= $ruser->rolename
;
2117 $role->shortname
= $ruser->roleshortname
;
2118 $role->coursealias
= $ruser->rolecoursealias
;
2120 $this->coursecontacts
[$user->id
] = array(
2123 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS
),
2124 'username' => fullname($user, $canviewfullnames)
2128 return $this->coursecontacts
;
2132 * Checks if course has any associated overview files
2136 public function has_course_overviewfiles() {
2138 if (empty($CFG->courseoverviewfileslimit
)) {
2141 require_once($CFG->libdir
. '/filestorage/file_storage.php');
2142 $fs = get_file_storage();
2143 $context = context_course
::instance($this->id
);
2144 return $fs->is_area_empty($context->id
, 'course', 'overviewfiles');
2148 * Returns all course overview files
2150 * @return array array of stored_file objects
2152 public function get_course_overviewfiles() {
2154 if (empty($CFG->courseoverviewfileslimit
)) {
2157 require_once($CFG->libdir
. '/filestorage/file_storage.php');
2158 require_once($CFG->dirroot
. '/course/lib.php');
2159 $fs = get_file_storage();
2160 $context = context_course
::instance($this->id
);
2161 $files = $fs->get_area_files($context->id
, 'course', 'overviewfiles', false, 'filename', false);
2162 if (count($files)) {
2163 $overviewfilesoptions = course_overviewfiles_options($this->id
);
2164 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2165 if ($acceptedtypes !== '*') {
2166 // filter only files with allowed extensions
2167 require_once($CFG->libdir
. '/filelib.php');
2168 foreach ($files as $key => $file) {
2169 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2170 unset($files[$key]);
2174 if (count($files) > $CFG->courseoverviewfileslimit
) {
2175 // return no more than $CFG->courseoverviewfileslimit files
2176 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit
, true);
2182 // ====== magic methods =======
2184 public function __isset($name) {
2185 return isset($this->record
->$name);
2189 * Magic method to get a course property
2191 * Returns any field from table course (from cache or from DB) and/or special field 'hassummary'
2193 * @param string $name
2196 public function __get($name) {
2198 if (property_exists($this->record
, $name)) {
2199 return $this->record
->$name;
2200 } else if ($name === 'summary' ||
$name === 'summaryformat') {
2201 // retrieve fields summary and summaryformat together because they are most likely to be used together
2202 $record = $DB->get_record('course', array('id' => $this->record
->id
), 'summary, summaryformat', MUST_EXIST
);
2203 $this->record
->summary
= $record->summary
;
2204 $this->record
->summaryformat
= $record->summaryformat
;
2205 return $this->record
->$name;
2206 } else if (array_key_exists($name, $DB->get_columns('course'))) {
2207 // another field from table 'course' that was not retrieved
2208 $this->record
->$name = $DB->get_field('course', $name, array('id' => $this->record
->id
), MUST_EXIST
);
2209 return $this->record
->$name;
2211 debugging('Invalid course property accessed! '.$name);
2216 * ALl properties are read only, sorry.
2217 * @param string $name
2219 public function __unset($name) {
2220 debugging('Can not unset '.get_class($this).' instance properties!');
2224 * Magic setter method, we do not want anybody to modify properties from the outside
2225 * @param string $name
2226 * @param mixed $value
2228 public function __set($name, $value) {
2229 debugging('Can not change '.get_class($this).' instance properties!');
2232 // ====== implementing method from interface IteratorAggregate ======
2235 * Create an iterator because magic vars can't be seen by 'foreach'.
2236 * Exclude context fields
2238 public function getIterator() {
2239 $ret = array('id' => $this->record
->id
);
2240 foreach ($this->record
as $property => $value) {
2241 $ret[$property] = $value;
2243 return new ArrayIterator($ret);
2248 * An array of records that is sortable by many fields.
2250 * For more info on the ArrayObject class have a look at php.net.
2253 * @subpackage course
2254 * @copyright 2013 Sam Hemelryk
2255 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2257 class coursecat_sortable_records
extends ArrayObject
{
2260 * An array of sortable fields.
2261 * Gets set temporarily when sort is called.
2264 protected $sortfields = array();
2267 * Sorts this array using the given fields.
2269 * @param array $records
2270 * @param array $fields
2273 public static function sort(array $records, array $fields) {
2274 $records = new coursecat_sortable_records($records);
2275 $records->sortfields
= $fields;
2276 $records->uasort(array($records, 'sort_by_many_fields'));
2277 return $records->getArrayCopy();
2281 * Sorts the two records based upon many fields.
2283 * This method should not be called itself, please call $sort instead.
2284 * It has been marked as access private as such.
2287 * @param stdClass $a
2288 * @param stdClass $b
2291 public function sort_by_many_fields($a, $b) {
2292 foreach ($this->sortfields
as $field => $mult) {
2294 if (is_null($a->$field) && !is_null($b->$field)) {
2297 if (is_null($b->$field) && !is_null($a->$field)) {
2301 if (is_string($a->$field) ||
is_string($b->$field)) {
2303 if ($cmp = strcoll($a->$field, $b->$field)) {
2304 return $mult * $cmp;
2308 if ($a->$field > $b->$field) {
2311 if ($a->$field < $b->$field) {