3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * This file contains functions for managing user access
21 * <b>Public API vs internals</b>
23 * General users probably only care about
26 * - get_context_instance()
27 * - get_context_instance_by_id()
28 * - get_parent_contexts()
29 * - get_child_contexts()
31 * Whether the user can do something...
33 * - has_any_capability()
34 * - has_all_capabilities()
35 * - require_capability()
36 * - require_login() (from moodlelib)
38 * What courses has this user access to?
39 * - get_user_courses_bycap()
41 * What users can do X in this context?
42 * - get_users_by_capability()
45 * - enrol_into_course()
46 * - role_assign()/role_unassign()
50 * - load_all_capabilities()
51 * - reload_all_capabilities()
52 * - has_capability_in_accessdata()
54 * - get_user_access_sitewide()
56 * - get_role_access_bycontext()
58 * <b>Name conventions</b>
64 * Access control data is held in the "accessdata" array
65 * which - for the logged-in user, will be in $USER->access
67 * For other users can be generated and passed around (but may also be cached
68 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser.
70 * $accessdata is a multidimensional array, holding
71 * role assignments (RAs), role-capabilities-perm sets
72 * (role defs) and a list of courses we have loaded
75 * Things are keyed on "contextpaths" (the path field of
76 * the context table) for fast walking up/down the tree.
78 * $accessdata[ra][$contextpath]= array($roleid)
79 * [$contextpath]= array($roleid)
80 * [$contextpath]= array($roleid)
83 * Role definitions are stored like this
84 * (no cap merge is done - so it's compact)
87 * $accessdata[rdef][$contextpath:$roleid][mod/forum:viewpost] = 1
88 * [mod/forum:editallpost] = -1
89 * [mod/forum:startdiscussion] = -1000
92 * See how has_capability_in_accessdata() walks up/down the tree.
94 * Normally - specially for the logged-in user, we only load
95 * rdef and ra down to the course level, but not below. This
96 * keeps accessdata small and compact. Below-the-course ra/rdef
97 * are loaded as needed. We keep track of which courses we
98 * have loaded ra/rdef in
100 * $accessdata[loaded] = array($contextpath, $contextpath)
103 * <b>Stale accessdata</b>
105 * For the logged-in user, accessdata is long-lived.
107 * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
108 * context paths affected by changes. Any check at-or-below
109 * a dirty context will trigger a transparent reload of accessdata.
111 * Changes at the system level will force the reload for everyone.
113 * <b>Default role caps</b>
114 * The default role assignment is not in the DB, so we
115 * add it manually to accessdata.
117 * This means that functions that work directly off the
118 * DB need to ensure that the default role caps
119 * are dealt with appropriately.
123 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
124 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
127 defined('MOODLE_INTERNAL') || die();
129 /** permission definitions */
130 define('CAP_INHERIT', 0);
131 /** permission definitions */
132 define('CAP_ALLOW', 1);
133 /** permission definitions */
134 define('CAP_PREVENT', -1);
135 /** permission definitions */
136 define('CAP_PROHIBIT', -1000);
138 /** context definitions */
139 define('CONTEXT_SYSTEM', 10);
140 /** context definitions */
141 define('CONTEXT_USER', 30);
142 /** context definitions */
143 define('CONTEXT_COURSECAT', 40);
144 /** context definitions */
145 define('CONTEXT_COURSE', 50);
146 /** context definitions */
147 define('CONTEXT_MODULE', 70);
148 /** context definitions */
149 define('CONTEXT_BLOCK', 80);
151 /** capability risks - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
152 define('RISK_MANAGETRUST', 0x0001);
153 /** capability risks - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
154 define('RISK_CONFIG', 0x0002);
155 /** capability risks - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
156 define('RISK_XSS', 0x0004);
157 /** capability risks - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
158 define('RISK_PERSONAL', 0x0008);
159 /** capability risks - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
160 define('RISK_SPAM', 0x0010);
161 /** capability risks - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
162 define('RISK_DATALOSS', 0x0020);
164 /** rolename displays - the name as defined in the role definition */
165 define('ROLENAME_ORIGINAL', 0);
166 /** rolename displays - the name as defined by a role alias */
167 define('ROLENAME_ALIAS', 1);
168 /** rolename displays - Both, like this: Role alias (Original)*/
169 define('ROLENAME_BOTH', 2);
170 /** rolename displays - the name as defined in the role definition and the shortname in brackets*/
171 define('ROLENAME_ORIGINALANDSHORT', 3);
172 /** rolename displays - the name as defined by a role alias, in raw form suitable for editing*/
173 define('ROLENAME_ALIAS_RAW', 4);
174 /** rolename displays - the name is simply short role name*/
175 define('ROLENAME_SHORT', 5);
178 * Internal class provides a cache of context information. The cache is
179 * restricted in size.
181 * This cache should NOT be used outside accesslib.php!
184 * @author Sam Marshall
186 class context_cache {
187 private $contextsbyid;
192 * @var int Maximum number of contexts that will be cached.
194 const MAX_SIZE = 2500;
196 * @var int Once contexts reach maximum number, this many will be removed from cache.
198 const REDUCE_SIZE = 1000;
201 * Initialises (empty)
203 public function __construct() {
208 * Resets the cache to remove all data.
210 public function reset() {
211 $this->contexts = array();
212 $this->contextsbyid = array();
217 * Adds a context to the cache. If the cache is full, discards a batch of
219 * @param stdClass $context New context to add
221 public function add(stdClass $context) {
222 if ($this->count >= self::MAX_SIZE) {
223 for ($i=0; $i<self::REDUCE_SIZE; $i++) {
224 if ($first = reset($this->contextsbyid)) {
225 unset($this->contextsbyid[$first->id]);
226 unset($this->contexts[$first->contextlevel][$first->instanceid]);
229 $this->count -= self::REDUCE_SIZE;
230 if ($this->count < 0) {
231 // most probably caused by the drift, the reset() above
232 // might have returned false because there might not be any more elements
237 $this->contexts[$context->contextlevel][$context->instanceid] = $context;
238 $this->contextsbyid[$context->id] = $context;
240 // Note the count may get out of synch slightly if you cache a context
241 // that is already cached, but it doesn't really matter much and I
242 // didn't think it was worth the performance hit.
247 * Removes a context from the cache.
248 * @param stdClass $context Context object to remove (must include fields
249 * ->id, ->contextlevel, ->instanceid at least)
251 public function remove(stdClass $context) {
252 unset($this->contexts[$context->contextlevel][$context->instanceid]);
253 unset($this->contextsbyid[$context->id]);
255 // Again the count may get a bit out of synch if you remove things
259 if ($this->count < 0) {
265 * Gets a context from the cache.
266 * @param int $contextlevel Context level
267 * @param int $instance Instance ID
268 * @return stdClass|bool Context or false if not in cache
270 public function get($contextlevel, $instance) {
271 if (isset($this->contexts[$contextlevel][$instance])) {
272 return $this->contexts[$contextlevel][$instance];
278 * Gets a context from the cache based on its id.
279 * @param int $id Context ID
280 * @return stdClass|bool Context or false if not in cache
282 public function get_by_id($id) {
283 if (isset($this->contextsbyid[$id])) {
284 return $this->contextsbyid[$id];
290 * @return int Count of contexts in cache (approximately)
292 public function get_approx_count() {
298 * Although this looks like a global variable, it isn't really.
300 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
301 * It is used to cache various bits of data between function calls for performance reasons.
302 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
303 * as methods of a class, instead of functions.
305 * @global stdClass $ACCESSLIB_PRIVATE
306 * @name $ACCESSLIB_PRIVATE
308 global $ACCESSLIB_PRIVATE;
309 $ACCESSLIB_PRIVATE = new stdClass();
310 $ACCESSLIB_PRIVATE->contexcache = new context_cache();
311 $ACCESSLIB_PRIVATE->systemcontext = null; // Used in get_system_context
312 $ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache
313 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the $accessdata structure for users other than $USER
314 $ACCESSLIB_PRIVATE->roledefinitions = array(); // role definitions cache - helps a lot with mem usage in cron
315 $ACCESSLIB_PRIVATE->croncache = array(); // Used in get_role_access
316 $ACCESSLIB_PRIVATE->preloadedcourses = array(); // Used in preload_course_contexts.
317 $ACCESSLIB_PRIVATE->capabilities = null; // detailed information about the capabilities
320 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
322 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
323 * accesslib's private caches. You need to do this before setting up test data,
324 * and also at the end of the tests.
326 function accesslib_clear_all_caches_for_unit_testing() {
327 global $UNITTEST, $USER, $ACCESSLIB_PRIVATE;
328 if (empty($UNITTEST->running)) {
329 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
331 $ACCESSLIB_PRIVATE->contexcache = new context_cache();
332 $ACCESSLIB_PRIVATE->systemcontext = null;
333 $ACCESSLIB_PRIVATE->dirtycontexts = null;
334 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
335 $ACCESSLIB_PRIVATE->roledefinitions = array();
336 $ACCESSLIB_PRIVATE->croncache = array();
337 $ACCESSLIB_PRIVATE->preloadedcourses = array();
338 $ACCESSLIB_PRIVATE->capabilities = null;
340 unset($USER->access);
344 * This is really slow!!! do not use above course context level
347 * @param object $context
350 function get_role_context_caps($roleid, $context) {
353 //this is really slow!!!! - do not use above course context level!
355 $result[$context->id] = array();
357 // first emulate the parent context capabilities merging into context
358 $searchcontexts = array_reverse(get_parent_contexts($context));
359 array_push($searchcontexts, $context->id);
360 foreach ($searchcontexts as $cid) {
361 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
362 foreach ($capabilities as $cap) {
363 if (!array_key_exists($cap->capability, $result[$context->id])) {
364 $result[$context->id][$cap->capability] = 0;
366 $result[$context->id][$cap->capability] += $cap->permission;
371 // now go through the contexts bellow given context
372 $searchcontexts = array_keys(get_child_contexts($context));
373 foreach ($searchcontexts as $cid) {
374 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
375 foreach ($capabilities as $cap) {
376 if (!array_key_exists($cap->contextid, $result)) {
377 $result[$cap->contextid] = array();
379 $result[$cap->contextid][$cap->capability] = $cap->permission;
388 * Gets the accessdata for role "sitewide" (system down to course)
391 * @param array $accessdata defaults to null
394 function get_role_access($roleid, $accessdata = null) {
397 /* Get it in 1 cheap DB query...
398 * - relevant role caps at the root and down
399 * to the course level - but not below
401 if (is_null($accessdata)) {
402 $accessdata = array(); // named list
403 $accessdata['ra'] = array();
404 $accessdata['rdef'] = array();
405 $accessdata['loaded'] = array();
409 // Overrides for the role IN ANY CONTEXTS
410 // down to COURSE - not below -
412 $sql = "SELECT ctx.path,
413 rc.capability, rc.permission
415 JOIN {role_capabilities} rc
416 ON rc.contextid=ctx.id
418 AND ctx.contextlevel <= ".CONTEXT_COURSE."
419 ORDER BY ctx.depth, ctx.path";
420 $params = array($roleid);
422 // we need extra caching in CLI scripts and cron
424 global $ACCESSLIB_PRIVATE;
426 if (!isset($ACCESSLIB_PRIVATE->croncache[$roleid])) {
427 $ACCESSLIB_PRIVATE->croncache[$roleid] = array();
428 $rs = $DB->get_recordset_sql($sql, $params);
429 foreach ($rs as $rd) {
430 $ACCESSLIB_PRIVATE->croncache[$roleid][] = $rd;
435 foreach ($ACCESSLIB_PRIVATE->croncache[$roleid] as $rd) {
436 $k = "{$rd->path}:{$roleid}";
437 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
441 $rs = $DB->get_recordset_sql($sql, $params);
443 foreach ($rs as $rd) {
444 $k = "{$rd->path}:{$roleid}";
445 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
456 * Gets the accessdata for role "sitewide" (system down to course)
459 * @param array $accessdata defaults to null
462 function get_default_frontpage_role_access($roleid, $accessdata = null) {
466 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
467 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
470 // Overrides for the role in any contexts related to the course
472 $sql = "SELECT ctx.path,
473 rc.capability, rc.permission
475 JOIN {role_capabilities} rc
476 ON rc.contextid=ctx.id
478 AND (ctx.id = ".SYSCONTEXTID." OR ctx.path LIKE ?)
479 AND ctx.contextlevel <= ".CONTEXT_COURSE."
480 ORDER BY ctx.depth, ctx.path";
481 $params = array($roleid, "$base/%");
483 $rs = $DB->get_recordset_sql($sql, $params);
485 foreach ($rs as $rd) {
486 $k = "{$rd->path}:{$roleid}";
487 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
498 * Get the default guest role
500 * @return stdClass role
502 function get_guest_role() {
505 if (empty($CFG->guestroleid)) {
506 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
507 $guestrole = array_shift($roles); // Pick the first one
508 set_config('guestroleid', $guestrole->id);
511 debugging('Can not find any guest role!');
515 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
518 //somebody is messing with guest roles, remove incorrect setting and try to find a new one
519 set_config('guestroleid', '');
520 return get_guest_role();
526 * Check whether a user has a particular capability in a given context.
529 * $context = get_context_instance(CONTEXT_MODULE, $cm->id);
530 * has_capability('mod/forum:replypost',$context)
532 * By default checks the capabilities of the current user, but you can pass a
533 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
535 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
536 * or capabilities with XSS, config or data loss risks.
538 * @param string $capability the name of the capability to check. For example mod/forum:view
539 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
540 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
541 * @param boolean $doanything If false, ignores effect of admin role assignment
542 * @return boolean true if the user has this capability. Otherwise false.
544 function has_capability($capability, $context, $user = null, $doanything = true) {
545 global $USER, $CFG, $DB, $SCRIPT, $ACCESSLIB_PRIVATE;
547 if (during_initial_install()) {
548 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cliupgrade.php") {
549 // we are in an installer - roles can not work yet
556 if (strpos($capability, 'moodle/legacy:') === 0) {
557 throw new coding_exception('Legacy capabilities can not be used any more!');
560 // the original $CONTEXT here was hiding serious errors
561 // for security reasons do not reuse previous context
562 if (empty($context)) {
563 debugging('Incorrect context specified');
566 if (!is_bool($doanything)) {
567 throw new coding_exception('Capability parameter "doanything" is wierd ("'.$doanything.'"). This has to be fixed in code.');
570 // make sure there is a real user specified
571 if ($user === null) {
572 $userid = isset($USER->id) ? $USER->id : 0;
574 $userid = is_object($user) ? $user->id : $user;
577 // capability must exist
578 if (!$capinfo = get_capability_info($capability)) {
579 debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
582 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
583 if (($capinfo->captype === 'write') or ((int)$capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
584 if (isguestuser($userid) or $userid == 0) {
589 if (is_null($context->path) or $context->depth == 0) {
590 //this should not happen
591 $contexts = array(SYSCONTEXTID, $context->id);
592 $context->path = '/'.SYSCONTEXTID.'/'.$context->id;
593 debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()', DEBUG_DEVELOPER);
596 $contexts = explode('/', $context->path);
597 array_shift($contexts);
600 if (CLI_SCRIPT && !isset($USER->access)) {
601 // In cron, some modules setup a 'fake' $USER,
602 // ensure we load the appropriate accessdata.
603 if (isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
604 $ACCESSLIB_PRIVATE->dirtycontexts = null; //load fresh dirty contexts
606 load_user_accessdata($userid);
607 $ACCESSLIB_PRIVATE->dirtycontexts = array();
609 $USER->access = $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
611 } else if (isset($USER->id) && ($USER->id == $userid) && !isset($USER->access)) {
612 // caps not loaded yet - better to load them to keep BC with 1.8
613 // not-logged-in user or $USER object set up manually first time here
614 load_all_capabilities();
615 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // reset the cache for other users too, the dirty contexts are empty now
616 $ACCESSLIB_PRIVATE->roledefinitions = array();
619 // Load dirty contexts list if needed
620 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
621 if (isset($USER->access['time'])) {
622 $ACCESSLIB_PRIVATE->dirtycontexts = get_dirty_contexts($USER->access['time']);
625 $ACCESSLIB_PRIVATE->dirtycontexts = array();
629 // Careful check for staleness...
630 if (count($ACCESSLIB_PRIVATE->dirtycontexts) !== 0 and is_contextpath_dirty($contexts, $ACCESSLIB_PRIVATE->dirtycontexts)) {
631 // reload all capabilities - preserving loginas, roleswitches, etc
632 // and then cleanup any marks of dirtyness... at least from our short
634 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
635 $ACCESSLIB_PRIVATE->roledefinitions = array();
638 load_user_accessdata($userid);
639 $USER->access = $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
640 $ACCESSLIB_PRIVATE->dirtycontexts = array();
643 reload_all_capabilities();
647 // Find out if user is admin - it is not possible to override the doanything in any way
648 // and it is not possible to switch to admin role either.
650 if (is_siteadmin($userid)) {
651 if ($userid != $USER->id) {
654 // make sure switchrole is not used in this context
655 if (empty($USER->access['rsw'])) {
658 $parts = explode('/', trim($context->path, '/'));
661 foreach ($parts as $part) {
662 $path .= '/' . $part;
663 if (!empty($USER->access['rsw'][$path])) {
671 //ok, admin switched role in this context, let's use normal access control rules
675 // divulge how many times we are called
676 //// error_log("has_capability: id:{$context->id} path:{$context->path} userid:$userid cap:$capability");
678 if (isset($USER->id) && ($USER->id == $userid)) { // we must accept strings and integers in $userid
680 // For the logged in user, we have $USER->access
681 // which will have all RAs and caps preloaded for
682 // course and above contexts.
684 // Contexts below courses && contexts that do not
685 // hang from courses are loaded into $USER->access
686 // on demand, and listed in $USER->access[loaded]
688 if ($context->contextlevel <= CONTEXT_COURSE) {
689 // Course and above are always preloaded
690 return has_capability_in_accessdata($capability, $context, $USER->access);
692 // Load accessdata for below-the-course contexts
693 if (!path_inaccessdata($context->path,$USER->access)) {
694 // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
695 // $bt = debug_backtrace();
696 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
697 load_subcontext($USER->id, $context, $USER->access);
699 return has_capability_in_accessdata($capability, $context, $USER->access);
702 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
703 load_user_accessdata($userid);
706 if ($context->contextlevel <= CONTEXT_COURSE) {
707 // Course and above are always preloaded
708 return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
710 // Load accessdata for below-the-course contexts as needed
711 if (!path_inaccessdata($context->path, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
712 // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
713 // $bt = debug_backtrace();
714 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
715 load_subcontext($userid, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
717 return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
721 * Check if the user has any one of several capabilities from a list.
723 * This is just a utility method that calls has_capability in a loop. Try to put
724 * the capabilities that most users are likely to have first in the list for best
727 * There are probably tricks that could be done to improve the performance here, for example,
728 * check the capabilities that are already cached first.
730 * @see has_capability()
731 * @param array $capabilities an array of capability names.
732 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
733 * @param integer $userid A user id. By default (null) checks the permissions of the current user.
734 * @param boolean $doanything If false, ignore effect of admin role assignment
735 * @return boolean true if the user has any of these capabilities. Otherwise false.
737 function has_any_capability($capabilities, $context, $userid = null, $doanything = true) {
738 if (!is_array($capabilities)) {
739 debugging('Incorrect $capabilities parameter in has_any_capabilities() call - must be an array');
742 foreach ($capabilities as $capability) {
743 if (has_capability($capability, $context, $userid, $doanything)) {
751 * Check if the user has all the capabilities in a list.
753 * This is just a utility method that calls has_capability in a loop. Try to put
754 * the capabilities that fewest users are likely to have first in the list for best
757 * There are probably tricks that could be done to improve the performance here, for example,
758 * check the capabilities that are already cached first.
760 * @see has_capability()
761 * @param array $capabilities an array of capability names.
762 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
763 * @param integer $userid A user id. By default (null) checks the permissions of the current user.
764 * @param boolean $doanything If false, ignore effect of admin role assignment
765 * @return boolean true if the user has all of these capabilities. Otherwise false.
767 function has_all_capabilities($capabilities, $context, $userid = null, $doanything = true) {
768 if (!is_array($capabilities)) {
769 debugging('Incorrect $capabilities parameter in has_all_capabilities() call - must be an array');
772 foreach ($capabilities as $capability) {
773 if (!has_capability($capability, $context, $userid, $doanything)) {
781 * Check if the user is an admin at the site level.
783 * Please note that use of proper capabilities is always encouraged,
784 * this function is supposed to be used from core or for temporary hacks.
786 * @param int|object $user_or_id user id or user object
787 * @returns bool true if user is one of the administrators, false otherwise
789 function is_siteadmin($user_or_id = null) {
792 if ($user_or_id === null) {
796 if (empty($user_or_id)) {
799 if (!empty($user_or_id->id)) {
801 $userid = $user_or_id->id;
803 $userid = $user_or_id;
806 $siteadmins = explode(',', $CFG->siteadmins);
807 return in_array($userid, $siteadmins);
811 * Returns true if user has at least one role assign
812 * of 'coursecontact' role (is potentially listed in some course descriptions).
817 function has_coursecontact_role($userid) {
820 if (empty($CFG->coursecontact)) {
824 FROM {role_assignments}
825 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
826 return $DB->record_exists_sql($sql, array('userid'=>$userid));
830 * @param string $path
833 function get_course_from_path($path) {
834 // assume that nothing is more than 1 course deep
835 if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
842 * @param string $path
843 * @param array $accessdata
846 function path_inaccessdata($path, $accessdata) {
847 if (empty($accessdata['loaded'])) {
851 // assume that contexts hang from sys or from a course
852 // this will only work well with stuff that hangs from a course
853 if (in_array($path, $accessdata['loaded'], true)) {
854 // error_log("found it!");
857 $base = '/' . SYSCONTEXTID;
858 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
860 if ($path === $base) {
863 if (in_array($path, $accessdata['loaded'], true)) {
871 * Does the user have a capability to do something?
873 * Walk the accessdata array and return true/false.
874 * Deals with prohibits, roleswitching, aggregating
877 * The main feature of here is being FAST and with no
882 * Switch Roles exits early
883 * ------------------------
884 * cap checks within a switchrole need to exit early
885 * in our bottom up processing so they don't "see" that
886 * there are real RAs that can do all sorts of things.
888 * Switch Role merges with default role
889 * ------------------------------------
890 * If you are a teacher in course X, you have at least
891 * teacher-in-X + defaultloggedinuser-sitewide. So in the
892 * course you'll have techer+defaultloggedinuser.
893 * We try to mimic that in switchrole.
895 * Permission evaluation
896 * ---------------------
897 * Originally there was an extremely complicated way
898 * to determine the user access that dealt with
899 * "locality" or role assignments and role overrides.
900 * Now we simply evaluate access for each role separately
901 * and then verify if user has at least one role with allow
902 * and at the same time no role with prohibit.
904 * @param string $capability
905 * @param object $context
906 * @param array $accessdata
909 function has_capability_in_accessdata($capability, $context, array $accessdata) {
912 if (empty($context->id)) {
913 throw new coding_exception('Invalid context specified');
916 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
917 $contextids = explode('/', trim($context->path, '/'));
918 $paths = array($context->path);
919 while ($contextids) {
920 array_pop($contextids);
921 $paths[] = '/' . implode('/', $contextids);
926 $switchedrole = false;
928 // Find out if role switched
929 if (!empty($accessdata['rsw'])) {
930 // From the bottom up...
931 foreach ($paths as $path) {
932 if (isset($accessdata['rsw'][$path])) {
933 // Found a switchrole assignment - check for that role _plus_ the default user role
934 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
935 $switchedrole = true;
941 if (!$switchedrole) {
942 // get all users roles in this context and above
943 foreach ($paths as $path) {
944 if (isset($accessdata['ra'][$path])) {
945 foreach ($accessdata['ra'][$path] as $roleid) {
946 $roles[$roleid] = null;
952 // Now find out what access is given to each role, going bottom-->up direction
953 foreach ($roles as $roleid => $ignored) {
954 foreach ($paths as $path) {
955 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
956 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
957 if ($perm === CAP_PROHIBIT or is_null($roles[$roleid])) {
958 $roles[$roleid] = $perm;
963 // any CAP_PROHIBIT found means no permission for the user
964 if (array_search(CAP_PROHIBIT, $roles) !== false) {
968 // at least one CAP_ALLOW means the user has a permission
969 return (array_search(CAP_ALLOW, $roles) !== false);
973 * @param object $context
974 * @param array $accessdata
977 function aggregate_roles_from_accessdata($context, $accessdata) {
979 $path = $context->path;
981 // build $contexts as a list of "paths" of the current
982 // contexts and parents with the order top-to-bottom
983 $contexts = array($path);
984 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
986 array_unshift($contexts, $path);
989 $cc = count($contexts);
992 // From the bottom up...
993 for ($n=$cc-1; $n>=0; $n--) {
994 $ctxp = $contexts[$n];
995 if (isset($accessdata['ra'][$ctxp]) && count($accessdata['ra'][$ctxp])) {
996 // Found assignments on this leaf
997 $addroles = $accessdata['ra'][$ctxp];
998 $roles = array_merge($roles, $addroles);
1002 return array_unique($roles);
1006 * A convenience function that tests has_capability, and displays an error if
1007 * the user does not have that capability.
1009 * NOTE before Moodle 2.0, this function attempted to make an appropriate
1010 * require_login call before checking the capability. This is no longer the case.
1011 * You must call require_login (or one of its variants) if you want to check the
1012 * user is logged in, before you call this function.
1014 * @see has_capability()
1016 * @param string $capability the name of the capability to check. For example mod/forum:view
1017 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
1018 * @param integer $userid A user id. By default (null) checks the permissions of the current user.
1019 * @param bool $doanything If false, ignore effect of admin role assignment
1020 * @param string $errorstring The error string to to user. Defaults to 'nopermissions'.
1021 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
1022 * @return void terminates with an error if the user does not have the given capability.
1024 function require_capability($capability, $context, $userid = null, $doanything = true,
1025 $errormessage = 'nopermissions', $stringfile = '') {
1026 if (!has_capability($capability, $context, $userid, $doanything)) {
1027 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
1032 * Get an array of courses where cap requested is available
1033 * and user is enrolled, this can be relatively slow.
1035 * @param string $capability - name of the capability
1036 * @param array $accessdata_ignored
1037 * @param bool $doanything_ignored
1038 * @param string $sort - sorting fields - prefix each fieldname with "c."
1039 * @param array $fields - additional fields you are interested in...
1040 * @param int $limit_ignored
1041 * @return array $courses - ordered array of course objects - see notes above
1043 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
1045 //TODO: this should be most probably deprecated
1047 $courses = enrol_get_users_courses($userid, true, $fields, $sort);
1048 foreach ($courses as $id=>$course) {
1049 $context = get_context_instance(CONTEXT_COURSE, $id);
1050 if (!has_capability($cap, $context, $userid)) {
1051 unset($courses[$id]);
1060 * Return a nested array showing role assignments
1061 * all relevant role capabilities for the user at
1062 * site/course_category/course levels
1064 * We do _not_ delve deeper than courses because the number of
1065 * overrides at the module/block levels is HUGE.
1067 * [ra] => [/path/][]=roleid
1068 * [rdef] => [/path/:roleid][capability]=permission
1069 * [loaded] => array('/path', '/path')
1071 * @param int $userid - the id of the user
1074 function get_user_access_sitewide($userid) {
1077 /* Get in 3 cheap DB queries...
1078 * - role assignments
1079 * - relevant role caps
1080 * - above and within this user's RAs
1081 * - below this user's RAs - limited to course level
1084 $accessdata = array(); // named list
1085 $accessdata['ra'] = array();
1086 $accessdata['rdef'] = array();
1087 $accessdata['loaded'] = array();
1092 $sql = "SELECT ctx.path, ra.roleid
1093 FROM {role_assignments} ra
1094 JOIN {context} ctx ON ctx.id=ra.contextid
1095 WHERE ra.userid = ? AND ctx.contextlevel <= ".CONTEXT_COURSE;
1096 $params = array($userid);
1097 $rs = $DB->get_recordset_sql($sql, $params);
1100 // raparents collects paths & roles we need to walk up
1101 // the parenthood to build the rdef
1103 $raparents = array();
1105 foreach ($rs as $ra) {
1106 // RAs leafs are arrays to support multi
1107 // role assignments...
1108 if (!isset($accessdata['ra'][$ra->path])) {
1109 $accessdata['ra'][$ra->path] = array();
1111 $accessdata['ra'][$ra->path][$ra->roleid] = $ra->roleid;
1113 // Concatenate as string the whole path (all related context)
1114 // for this role. This is damn faster than using array_merge()
1115 // Will unique them later
1116 if (isset($raparents[$ra->roleid])) {
1117 $raparents[$ra->roleid] .= $ra->path;
1119 $raparents[$ra->roleid] = $ra->path;
1126 // Walk up the tree to grab all the roledefs
1127 // of interest to our user...
1129 // NOTE: we use a series of IN clauses here - which
1130 // might explode on huge sites with very convoluted nesting of
1131 // categories... - extremely unlikely that the number of categories
1132 // and roletypes is so large that we hit the limits of IN()
1135 foreach ($raparents as $roleid=>$strcontexts) {
1136 $contexts = implode(',', array_unique(explode('/', trim($strcontexts, '/'))));
1137 if ($contexts ==! '') {
1141 $clauses .= "(roleid=? AND contextid IN ($contexts))";
1142 $cparams[] = $roleid;
1146 if ($clauses !== '') {
1147 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1148 FROM {role_capabilities} rc
1149 JOIN {context} ctx ON rc.contextid=ctx.id
1153 $rs = $DB->get_recordset_sql($sql, $cparams);
1156 foreach ($rs as $rd) {
1157 $k = "{$rd->path}:{$rd->roleid}";
1158 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1166 // Overrides for the role assignments IN SUBCONTEXTS
1167 // (though we still do _not_ go below the course level.
1169 // NOTE that the JOIN w sctx is with 3-way triangulation to
1170 // catch overrides to the applicable role in any subcontext, based
1171 // on the path field of the parent.
1173 $sql = "SELECT sctx.path, ra.roleid,
1174 ctx.path AS parentpath,
1175 rco.capability, rco.permission
1176 FROM {role_assignments} ra
1178 ON ra.contextid=ctx.id
1180 ON (sctx.path LIKE " . $DB->sql_concat('ctx.path',"'/%'"). " )
1181 JOIN {role_capabilities} rco
1182 ON (rco.roleid=ra.roleid AND rco.contextid=sctx.id)
1184 AND ctx.contextlevel <= ".CONTEXT_COURSECAT."
1185 AND sctx.contextlevel <= ".CONTEXT_COURSE."
1186 ORDER BY sctx.depth, sctx.path, ra.roleid";
1187 $params = array($userid);
1188 $rs = $DB->get_recordset_sql($sql, $params);
1190 foreach ($rs as $rd) {
1191 $k = "{$rd->path}:{$rd->roleid}";
1192 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1201 * Add to the access ctrl array the data needed by a user for a given context
1203 * @param integer $userid the id of the user
1204 * @param object $context needs path!
1205 * @param array $accessdata accessdata array
1208 function load_subcontext($userid, $context, &$accessdata) {
1211 /* Get the additional RAs and relevant rolecaps
1212 * - role assignments - with role_caps
1213 * - relevant role caps
1214 * - above this user's RAs
1215 * - below this user's RAs - limited to course level
1218 $base = "/" . SYSCONTEXTID;
1221 // Replace $context with the target context we will
1222 // load. Normally, this will be a course context, but
1223 // may be a different top-level context.
1228 // - BLOCK/PERSON/USER/COURSE(sitecourse) hanging from SYSTEM
1229 // - BLOCK/MODULE/GROUP hanging from a course
1231 // For course contexts, we _already_ have the RAs
1232 // but the cost of re-fetching is minimal so we don't care.
1234 if ($context->contextlevel !== CONTEXT_COURSE
1235 && $context->path !== "$base/{$context->id}") {
1236 // Case BLOCK/MODULE/GROUP hanging from a course
1237 // Assumption: the course _must_ be our parent
1238 // If we ever see stuff nested further this needs to
1239 // change to do 1 query over the exploded path to
1240 // find out which one is the course
1241 $courses = explode('/',get_course_from_path($context->path));
1242 $targetid = array_pop($courses);
1243 $context = get_context_instance_by_id($targetid);
1248 // Role assignments in the context and below
1250 $sql = "SELECT ctx.path, ra.roleid
1251 FROM {role_assignments} ra
1253 ON ra.contextid=ctx.id
1255 AND (ctx.path = ? OR ctx.path LIKE ?)
1256 ORDER BY ctx.depth, ctx.path, ra.roleid";
1257 $params = array($userid, $context->path, $context->path."/%");
1258 $rs = $DB->get_recordset_sql($sql, $params);
1261 // Read in the RAs, preventing duplicates
1264 $localroles = array();
1266 foreach ($rs as $ra) {
1267 if (!isset($accessdata['ra'][$ra->path])) {
1268 $accessdata['ra'][$ra->path] = array();
1270 // only add if is not a repeat caused
1271 // by capability join...
1272 // (this check is cheaper than in_array())
1273 if ($lastseen !== $ra->path.':'.$ra->roleid) {
1274 $lastseen = $ra->path.':'.$ra->roleid;
1275 $accessdata['ra'][$ra->path][$ra->roleid] = $ra->roleid;
1276 array_push($localroles, $ra->roleid);
1283 // Walk up and down the tree to grab all the roledefs
1284 // of interest to our user...
1287 // - we use IN() but the number of roles is very limited.
1289 $courseroles = aggregate_roles_from_accessdata($context, $accessdata);
1291 // Do we have any interesting "local" roles?
1292 $localroles = array_diff($localroles,$courseroles); // only "new" local roles
1293 $wherelocalroles='';
1294 if (count($localroles)) {
1295 // Role defs for local roles in 'higher' contexts...
1296 $contexts = substr($context->path, 1); // kill leading slash
1297 $contexts = str_replace('/', ',', $contexts);
1298 $localroleids = implode(',',$localroles);
1299 $wherelocalroles="OR (rc.roleid IN ({$localroleids})
1300 AND ctx.id IN ($contexts))" ;
1303 // We will want overrides for all of them
1305 if ($roleids = implode(',',array_merge($courseroles,$localroles))) {
1306 $whereroles = "rc.roleid IN ($roleids) AND";
1308 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1309 FROM {role_capabilities} rc
1311 ON rc.contextid=ctx.id
1313 (ctx.id=? OR ctx.path LIKE ?))
1315 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1316 $params = array($context->id, $context->path."/%");
1318 $newrdefs = array();
1319 $rs = $DB->get_recordset_sql($sql, $params);
1320 foreach ($rs as $rd) {
1321 $k = "{$rd->path}:{$rd->roleid}";
1322 if (!array_key_exists($k, $newrdefs)) {
1323 $newrdefs[$k] = array();
1325 $newrdefs[$k][$rd->capability] = $rd->permission;
1329 compact_rdefs($newrdefs);
1330 foreach ($newrdefs as $key=>$value) {
1331 $accessdata['rdef'][$key] =& $newrdefs[$key];
1334 // error_log("loaded {$context->path}");
1335 $accessdata['loaded'][] = $context->path;
1339 * Add to the access ctrl array the data needed by a role for a given context.
1341 * The data is added in the rdef key.
1343 * This role-centric function is useful for role_switching
1344 * and to get an overview of what a role gets under a
1345 * given context and below...
1347 * @param integer $roleid the id of the user
1348 * @param object $context needs path!
1349 * @param array $accessdata accessdata array null by default
1352 function get_role_access_bycontext($roleid, $context, $accessdata = null) {
1355 /* Get the relevant rolecaps into rdef
1356 * - relevant role caps
1357 * - at ctx and above
1361 if (is_null($accessdata)) {
1362 $accessdata = array(); // named list
1363 $accessdata['ra'] = array();
1364 $accessdata['rdef'] = array();
1365 $accessdata['loaded'] = array();
1368 $contexts = substr($context->path, 1); // kill leading slash
1369 $contexts = str_replace('/', ',', $contexts);
1372 // Walk up and down the tree to grab all the roledefs
1373 // of interest to our role...
1375 // NOTE: we use an IN clauses here - which
1376 // might explode on huge sites with very convoluted nesting of
1377 // categories... - extremely unlikely that the number of nested
1378 // categories is so large that we hit the limits of IN()
1380 $sql = "SELECT ctx.path, rc.capability, rc.permission
1381 FROM {role_capabilities} rc
1383 ON rc.contextid=ctx.id
1384 WHERE rc.roleid=? AND
1385 ( ctx.id IN ($contexts) OR
1387 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1388 $params = array($roleid, $context->path."/%");
1390 $rs = $DB->get_recordset_sql($sql, $params);
1391 foreach ($rs as $rd) {
1392 $k = "{$rd->path}:{$roleid}";
1393 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1401 * Load accessdata for a user into the $ACCESSLIB_PRIVATE->accessdatabyuser global
1403 * Used by has_capability() - but feel free
1404 * to call it if you are about to run a BIG
1405 * cron run across a bazillion users.
1407 * @param int $userid
1408 * @return array returns ACCESSLIB_PRIVATE->accessdatabyuser[userid]
1410 function load_user_accessdata($userid) {
1411 global $CFG, $ACCESSLIB_PRIVATE;
1413 $base = '/'.SYSCONTEXTID;
1415 $accessdata = get_user_access_sitewide($userid);
1416 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
1418 // provide "default role" & set 'dr'
1420 if (!empty($CFG->defaultuserroleid)) {
1421 $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1422 if (!isset($accessdata['ra'][$base])) {
1423 $accessdata['ra'][$base] = array();
1425 $accessdata['ra'][$base][$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
1426 $accessdata['dr'] = $CFG->defaultuserroleid;
1430 // provide "default frontpage role"
1432 if (!empty($CFG->defaultfrontpageroleid)) {
1433 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
1434 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
1435 if (!isset($accessdata['ra'][$base])) {
1436 $accessdata['ra'][$base] = array();
1438 $accessdata['ra'][$base][$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
1440 // for dirty timestamps in cron
1441 $accessdata['time'] = time();
1443 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1444 compact_rdefs($ACCESSLIB_PRIVATE->accessdatabyuser[$userid]['rdef']);
1446 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1450 * Use shared copy of role definitions stored in ACCESSLIB_PRIVATE->roledefinitions;
1452 * @param array $rdefs array of role definitions in contexts
1454 function compact_rdefs(&$rdefs) {
1455 global $ACCESSLIB_PRIVATE;
1458 * This is a basic sharing only, we could also
1459 * use md5 sums of values. The main purpose is to
1460 * reduce mem in cron jobs - many users in $ACCESSLIB_PRIVATE->accessdatabyuser array.
1463 foreach ($rdefs as $key => $value) {
1464 if (!array_key_exists($key, $ACCESSLIB_PRIVATE->roledefinitions)) {
1465 $ACCESSLIB_PRIVATE->roledefinitions[$key] = $rdefs[$key];
1467 $rdefs[$key] =& $ACCESSLIB_PRIVATE->roledefinitions[$key];
1472 * A convenience function to completely load all the capabilities
1473 * for the current user. This is what gets called from complete_user_login()
1474 * for example. Call it only _after_ you've setup $USER and called
1475 * check_enrolment_plugins();
1476 * @see check_enrolment_plugins()
1480 function load_all_capabilities() {
1481 global $CFG, $ACCESSLIB_PRIVATE;
1483 //NOTE: we can not use $USER here because it may no be linked to $_SESSION['USER'] yet!
1485 // roles not installed yet - we are in the middle of installation
1486 if (during_initial_install()) {
1490 $base = '/'.SYSCONTEXTID;
1492 if (isguestuser($_SESSION['USER'])) {
1493 $guest = get_guest_role();
1496 $_SESSION['USER']->access = get_role_access($guest->id);
1497 // Put the ghost enrolment in place...
1498 $_SESSION['USER']->access['ra'][$base] = array($guest->id => $guest->id);
1501 } else if (!empty($_SESSION['USER']->id)) { // can not use isloggedin() yet
1503 $accessdata = get_user_access_sitewide($_SESSION['USER']->id);
1506 // provide "default role" & set 'dr'
1508 if (!empty($CFG->defaultuserroleid)) {
1509 $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1510 if (!isset($accessdata['ra'][$base])) {
1511 $accessdata['ra'][$base] = array();
1513 $accessdata['ra'][$base][$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
1514 $accessdata['dr'] = $CFG->defaultuserroleid;
1517 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
1520 // provide "default frontpage role"
1522 if (!empty($CFG->defaultfrontpageroleid)) {
1523 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
1524 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
1525 if (!isset($accessdata['ra'][$base])) {
1526 $accessdata['ra'][$base] = array();
1528 $accessdata['ra'][$base][$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
1530 $_SESSION['USER']->access = $accessdata;
1532 } else if (!empty($CFG->notloggedinroleid)) {
1533 $_SESSION['USER']->access = get_role_access($CFG->notloggedinroleid);
1534 $_SESSION['USER']->access['ra'][$base] = array($CFG->notloggedinroleid => $CFG->notloggedinroleid);
1537 // Timestamp to read dirty context timestamps later
1538 $_SESSION['USER']->access['time'] = time();
1539 $ACCESSLIB_PRIVATE->dirtycontexts = array();
1541 // Clear to force a refresh
1542 unset($_SESSION['USER']->mycourses);
1546 * A convenience function to completely reload all the capabilities
1547 * for the current user when roles have been updated in a relevant
1548 * context -- but PRESERVING switchroles and loginas.
1550 * That is - completely transparent to the user.
1552 * Note: rewrites $USER->access completely.
1556 function reload_all_capabilities() {
1559 // error_log("reloading");
1562 if (isset($USER->access['rsw'])) {
1563 $sw = $USER->access['rsw'];
1564 // error_log(print_r($sw,1));
1567 unset($USER->access);
1568 unset($USER->mycourses);
1570 load_all_capabilities();
1572 foreach ($sw as $path => $roleid) {
1573 $context = $DB->get_record('context', array('path'=>$path));
1574 role_switch($roleid, $context);
1580 * Adds a temp role to an accessdata array.
1582 * Useful for the "temporary guest" access
1583 * we grant to logged-in users.
1585 * Note - assumes a course context!
1587 * @param object $content
1588 * @param int $roleid
1589 * @param array $accessdata
1590 * @return array Returns access data
1592 function load_temp_role($context, $roleid, array $accessdata) {
1596 // Load rdefs for the role in -
1598 // - all the parents
1599 // - and below - IOWs overrides...
1602 // turn the path into a list of context ids
1603 $contexts = substr($context->path, 1); // kill leading slash
1604 $contexts = str_replace('/', ',', $contexts);
1606 $sql = "SELECT ctx.path, rc.capability, rc.permission
1608 JOIN {role_capabilities} rc
1609 ON rc.contextid=ctx.id
1610 WHERE (ctx.id IN ($contexts)
1613 ORDER BY ctx.depth, ctx.path";
1614 $params = array($context->path."/%", $roleid);
1615 $rs = $DB->get_recordset_sql($sql, $params);
1616 foreach ($rs as $rd) {
1617 $k = "{$rd->path}:{$roleid}";
1618 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1623 // Say we loaded everything for the course context
1624 // - which we just did - if the user gets a proper
1625 // RA in this session, this data will need to be reloaded,
1626 // but that is handled by the complete accessdata reload
1628 array_push($accessdata['loaded'], $context->path);
1633 if (!isset($accessdata['ra'][$context->path])) {
1634 $accessdata['ra'][$context->path] = array();
1636 $accessdata['ra'][$context->path][$roleid] = $roleid;
1642 * Removes any extra guest roles from accessdata
1643 * @param object $context
1644 * @param array $accessdata
1645 * @return array access data
1647 function remove_temp_roles($context, array $accessdata) {
1649 $sql = "SELECT DISTINCT ra.roleid AS id
1650 FROM {role_assignments} ra
1651 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1652 $ras = $DB->get_records_sql($sql, array('contextid'=>$context->id, 'userid'=>$USER->id));
1655 $accessdata['ra'][$context->path] = array_combine(array_keys($ras), array_keys($ras));
1657 $accessdata['ra'][$context->path] = array();
1664 * Returns array of all role archetypes.
1668 function get_role_archetypes() {
1670 'manager' => 'manager',
1671 'coursecreator' => 'coursecreator',
1672 'editingteacher' => 'editingteacher',
1673 'teacher' => 'teacher',
1674 'student' => 'student',
1677 'frontpage' => 'frontpage'
1682 * Assign the defaults found in this capability definition to roles that have
1683 * the corresponding legacy capabilities assigned to them.
1685 * @param string $capability
1686 * @param array $legacyperms an array in the format (example):
1687 * 'guest' => CAP_PREVENT,
1688 * 'student' => CAP_ALLOW,
1689 * 'teacher' => CAP_ALLOW,
1690 * 'editingteacher' => CAP_ALLOW,
1691 * 'coursecreator' => CAP_ALLOW,
1692 * 'manager' => CAP_ALLOW
1693 * @return boolean success or failure.
1695 function assign_legacy_capabilities($capability, $legacyperms) {
1697 $archetypes = get_role_archetypes();
1699 foreach ($legacyperms as $type => $perm) {
1701 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1702 if ($type === 'admin') {
1703 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1707 if (!array_key_exists($type, $archetypes)) {
1708 print_error('invalidlegacy', '', '', $type);
1711 if ($roles = get_archetype_roles($type)) {
1712 foreach ($roles as $role) {
1713 // Assign a site level capability.
1714 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1724 * @param object $capability a capability - a row from the capabilities table.
1725 * @return boolean whether this capability is safe - that is, whether people with the
1726 * safeoverrides capability should be allowed to change it.
1728 function is_safe_capability($capability) {
1729 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1732 /**********************************
1733 * Context Manipulation functions *
1734 **********************************/
1737 * Context creation - internal implementation.
1739 * Create a new context record for use by all roles-related stuff
1740 * assumes that the caller has done the homework.
1742 * DO NOT CALL THIS DIRECTLY, instead use {@link get_context_instance}!
1744 * @param int $contextlevel
1745 * @param int $instanceid
1746 * @param int $strictness
1747 * @return object newly created context
1749 function create_context($contextlevel, $instanceid, $strictness = IGNORE_MISSING) {
1752 if ($contextlevel == CONTEXT_SYSTEM) {
1753 return get_system_context();
1756 $context = new stdClass();
1757 $context->contextlevel = $contextlevel;
1758 $context->instanceid = $instanceid;
1760 // Define $context->path based on the parent
1761 // context. In other words... Who is your daddy?
1762 $basepath = '/' . SYSCONTEXTID;
1766 $error_message = null;
1768 switch ($contextlevel) {
1769 case CONTEXT_COURSECAT:
1770 $sql = "SELECT ctx.path, ctx.depth
1772 JOIN {course_categories} cc
1773 ON (cc.parent=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
1775 $params = array($instanceid);
1776 if ($p = $DB->get_record_sql($sql, $params)) {
1777 $basepath = $p->path;
1778 $basedepth = $p->depth;
1779 } else if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), '*', $strictness)) {
1780 if (empty($category->parent)) {
1781 // ok - this is a top category
1782 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $category->parent)) {
1783 $basepath = $parent->path;
1784 $basedepth = $parent->depth;
1786 // wrong parent category - no big deal, this can be fixed later
1791 // incorrect category id
1792 $error_message = "incorrect course category id ($instanceid)";
1797 case CONTEXT_COURSE:
1798 $sql = "SELECT ctx.path, ctx.depth
1801 ON (c.category=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
1802 WHERE c.id=? AND c.id !=" . SITEID;
1803 $params = array($instanceid);
1804 if ($p = $DB->get_record_sql($sql, $params)) {
1805 $basepath = $p->path;
1806 $basedepth = $p->depth;
1807 } else if ($course = $DB->get_record('course', array('id'=>$instanceid), '*', $strictness)) {
1808 if ($course->id == SITEID) {
1809 //ok - no parent category
1810 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
1811 $basepath = $parent->path;
1812 $basedepth = $parent->depth;
1814 // wrong parent category of course - no big deal, this can be fixed later
1818 } else if ($instanceid == SITEID) {
1819 // no errors for missing site course during installation
1822 // incorrect course id
1823 $error_message = "incorrect course id ($instanceid)";
1828 case CONTEXT_MODULE:
1829 $sql = "SELECT ctx.path, ctx.depth
1831 JOIN {course_modules} cm
1832 ON (cm.course=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
1834 $params = array($instanceid);
1835 if ($p = $DB->get_record_sql($sql, $params)) {
1836 $basepath = $p->path;
1837 $basedepth = $p->depth;
1838 } else if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), '*', $strictness)) {
1839 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course, $strictness)) {
1840 $basepath = $parent->path;
1841 $basedepth = $parent->depth;
1843 // course does not exist - modules can not exist without a course
1844 $error_message = "course does not exist ($cm->course) - modules can not exist without a course";
1848 // cm does not exist
1849 $error_message = "cm with id $instanceid does not exist";
1855 $sql = "SELECT ctx.path, ctx.depth
1857 JOIN {block_instances} bi ON (bi.parentcontextid=ctx.id)
1859 $params = array($instanceid, CONTEXT_COURSE);
1860 if ($p = $DB->get_record_sql($sql, $params, '*', $strictness)) {
1861 $basepath = $p->path;
1862 $basedepth = $p->depth;
1864 // block does not exist
1865 $error_message = 'block or parent context does not exist';
1870 // default to basepath
1874 // if grandparents unknown, maybe rebuild_context_path() will solve it later
1875 if ($basedepth != 0) {
1876 $context->depth = $basedepth+1;
1880 debugging('Error: could not insert new context level "'.
1881 s($contextlevel).'", instance "'.
1882 s($instanceid).'". ' . $error_message);
1887 $id = $DB->insert_record('context', $context);
1888 // can't set the full path till we know the id!
1889 if ($basedepth != 0 and !empty($basepath)) {
1890 $DB->set_field('context', 'path', $basepath.'/'. $id, array('id'=>$id));
1892 return get_context_instance_by_id($id);
1896 * Returns system context or null if can not be created yet.
1898 * @param bool $cache use caching
1899 * @return mixed system context or null
1901 function get_system_context($cache = true) {
1902 global $DB, $ACCESSLIB_PRIVATE;
1903 if ($cache and defined('SYSCONTEXTID')) {
1904 if (is_null($ACCESSLIB_PRIVATE->systemcontext)) {
1905 $ACCESSLIB_PRIVATE->systemcontext = new stdClass();
1906 $ACCESSLIB_PRIVATE->systemcontext->id = SYSCONTEXTID;
1907 $ACCESSLIB_PRIVATE->systemcontext->contextlevel = CONTEXT_SYSTEM;
1908 $ACCESSLIB_PRIVATE->systemcontext->instanceid = 0;
1909 $ACCESSLIB_PRIVATE->systemcontext->path = '/'.SYSCONTEXTID;
1910 $ACCESSLIB_PRIVATE->systemcontext->depth = 1;
1912 return $ACCESSLIB_PRIVATE->systemcontext;
1915 $context = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM));
1916 } catch (dml_exception $e) {
1917 //table does not exist yet, sorry
1922 $context = new stdClass();
1923 $context->contextlevel = CONTEXT_SYSTEM;
1924 $context->instanceid = 0;
1925 $context->depth = 1;
1926 $context->path = null; //not known before insert
1929 $context->id = $DB->insert_record('context', $context);
1930 } catch (dml_exception $e) {
1931 // can not create context yet, sorry
1936 if (!isset($context->depth) or $context->depth != 1 or $context->instanceid != 0 or $context->path != '/'.$context->id) {
1937 $context->instanceid = 0;
1938 $context->path = '/'.$context->id;
1939 $context->depth = 1;
1940 $DB->update_record('context', $context);
1943 if (!defined('SYSCONTEXTID')) {
1944 define('SYSCONTEXTID', $context->id);
1947 $ACCESSLIB_PRIVATE->systemcontext = $context;
1948 return $ACCESSLIB_PRIVATE->systemcontext;
1952 * Remove a context record and any dependent entries,
1953 * removes context from static context cache too
1956 * @param int $instanceid
1957 * @param bool $deleterecord false means keep record for now
1958 * @return bool returns true or throws an exception
1960 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
1961 global $DB, $ACCESSLIB_PRIVATE, $CFG;
1963 // do not use get_context_instance(), because the related object might not exist,
1964 // or the context does not exist yet and it would be created now
1965 if ($context = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
1966 // delete these first because they might fetch the context and try to recreate it!
1967 blocks_delete_all_for_context($context->id);
1968 filter_delete_all_for_context($context->id);
1970 require_once($CFG->dirroot . '/comment/lib.php');
1971 comment::delete_comments(array('contextid'=>$context->id));
1973 require_once($CFG->dirroot.'/rating/lib.php');
1974 $delopt = new stdclass();
1975 $delopt->contextid = $context->id;
1976 $rm = new rating_manager();
1977 $rm->delete_ratings($delopt);
1979 // delete all files attached to this context
1980 $fs = get_file_storage();
1981 $fs->delete_area_files($context->id);
1983 // now delete stuff from role related tables, role_unassign_all
1984 // and unenrol should be called earlier to do proper cleanup
1985 $DB->delete_records('role_assignments', array('contextid'=>$context->id));
1986 $DB->delete_records('role_capabilities', array('contextid'=>$context->id));
1987 $DB->delete_records('role_names', array('contextid'=>$context->id));
1989 // and finally it is time to delete the context record if requested
1990 if ($deleterecord) {
1991 $DB->delete_records('context', array('id'=>$context->id));
1992 // purge static context cache if entry present
1993 $ACCESSLIB_PRIVATE->contexcache->remove($context);
1996 // do not mark dirty contexts if parents unknown
1997 if (!is_null($context->path) and $context->depth > 0) {
1998 mark_context_dirty($context->path);
2006 * Precreates all contexts including all parents
2008 * @param int $contextlevel empty means all
2009 * @param bool $buildpaths update paths and depths
2012 function create_contexts($contextlevel = null, $buildpaths = true) {
2015 //make sure system context exists
2016 $syscontext = get_system_context(false);
2018 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSECAT
2019 or $contextlevel == CONTEXT_COURSE
2020 or $contextlevel == CONTEXT_MODULE
2021 or $contextlevel == CONTEXT_BLOCK) {
2022 $sql = "INSERT INTO {context} (contextlevel, instanceid)
2023 SELECT ".CONTEXT_COURSECAT.", cc.id
2024 FROM {course}_categories cc
2025 WHERE NOT EXISTS (SELECT 'x'
2027 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
2032 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSE
2033 or $contextlevel == CONTEXT_MODULE
2034 or $contextlevel == CONTEXT_BLOCK) {
2035 $sql = "INSERT INTO {context} (contextlevel, instanceid)
2036 SELECT ".CONTEXT_COURSE.", c.id
2038 WHERE NOT EXISTS (SELECT 'x'
2040 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
2045 if (empty($contextlevel) or $contextlevel == CONTEXT_MODULE
2046 or $contextlevel == CONTEXT_BLOCK) {
2047 $sql = "INSERT INTO {context} (contextlevel, instanceid)
2048 SELECT ".CONTEXT_MODULE.", cm.id
2049 FROM {course}_modules cm
2050 WHERE NOT EXISTS (SELECT 'x'
2052 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
2056 if (empty($contextlevel) or $contextlevel == CONTEXT_USER
2057 or $contextlevel == CONTEXT_BLOCK) {
2058 $sql = "INSERT INTO {context} (contextlevel, instanceid)
2059 SELECT ".CONTEXT_USER.", u.id
2062 AND NOT EXISTS (SELECT 'x'
2064 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
2069 if (empty($contextlevel) or $contextlevel == CONTEXT_BLOCK) {
2070 $sql = "INSERT INTO {context} (contextlevel, instanceid)
2071 SELECT ".CONTEXT_BLOCK.", bi.id
2072 FROM {block_instances} bi
2073 WHERE NOT EXISTS (SELECT 'x'
2075 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
2080 build_context_path(false);
2085 * Remove stale context records
2089 function cleanup_contexts() {
2092 $sql = " SELECT c.contextlevel,
2093 c.instanceid AS instanceid
2095 LEFT OUTER JOIN {course}_categories t
2096 ON c.instanceid = t.id
2097 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
2099 SELECT c.contextlevel,
2102 LEFT OUTER JOIN {course} t
2103 ON c.instanceid = t.id
2104 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
2106 SELECT c.contextlevel,
2109 LEFT OUTER JOIN {course}_modules t
2110 ON c.instanceid = t.id
2111 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
2113 SELECT c.contextlevel,
2116 LEFT OUTER JOIN {user} t
2117 ON c.instanceid = t.id
2118 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
2120 SELECT c.contextlevel,
2123 LEFT OUTER JOIN {block_instances} t
2124 ON c.instanceid = t.id
2125 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
2128 // transactions used only for performance reasons here
2129 $transaction = $DB->start_delegated_transaction();
2131 $rs = $DB->get_recordset_sql($sql);
2132 foreach ($rs as $ctx) {
2133 delete_context($ctx->contextlevel, $ctx->instanceid);
2137 $transaction->allow_commit();
2142 * Preloads all contexts relating to a course: course, modules. Block contexts
2143 * are no longer loaded here. The contexts for all the blocks on the current
2144 * page are now efficiently loaded by {@link block_manager::load_blocks()}.
2146 * @param int $courseid Course ID
2149 function preload_course_contexts($courseid) {
2150 global $DB, $ACCESSLIB_PRIVATE;
2152 // Users can call this multiple times without doing any harm
2153 global $ACCESSLIB_PRIVATE;
2154 if (array_key_exists($courseid, $ACCESSLIB_PRIVATE->preloadedcourses)) {
2158 $params = array($courseid, $courseid, $courseid);
2159 $sql = "SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth
2160 FROM {course_modules} cm
2161 JOIN {context} x ON x.instanceid=cm.id
2162 WHERE cm.course=? AND x.contextlevel=".CONTEXT_MODULE."
2166 SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth
2168 WHERE x.instanceid=? AND x.contextlevel=".CONTEXT_COURSE."";
2170 $rs = $DB->get_recordset_sql($sql, $params);
2171 foreach($rs as $context) {
2172 $ACCESSLIB_PRIVATE->contexcache->add($context);
2175 $ACCESSLIB_PRIVATE->preloadedcourses[$courseid] = true;
2179 * Get the context instance as an object. This function will create the
2180 * context instance if it does not exist yet.
2182 * @todo Remove code branch from previous fix MDL-9016 which is no longer needed
2184 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
2185 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
2186 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
2187 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
2188 * MUST_EXIST means throw exception if no record or multiple records found
2189 * @return object The context object.
2191 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
2192 global $DB, $ACCESSLIB_PRIVATE;
2193 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK);
2195 /// System context has special cache
2196 if ($contextlevel == CONTEXT_SYSTEM) {
2197 return get_system_context();
2200 /// check allowed context levels
2201 if (!in_array($contextlevel, $allowed_contexts)) {
2202 // fatal error, code must be fixed - probably typo or switched parameters
2203 print_error('invalidcourselevel');
2206 // Various operations rely on context cache
2207 $cache = $ACCESSLIB_PRIVATE->contexcache;
2209 if (!is_array($instance)) {
2211 $context = $cache->get($contextlevel, $instance);
2216 /// Get it from the database, or create it
2217 if (!$context = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instance))) {
2218 $context = create_context($contextlevel, $instance, $strictness);
2221 /// Only add to cache if context isn't empty.
2222 if (!empty($context)) {
2223 $cache->add($context);
2230 /// ok, somebody wants to load several contexts to save some db queries ;-)
2231 $instances = $instance;
2234 foreach ($instances as $key=>$instance) {
2235 /// Check the cache first
2236 if ($context = $cache->get($contextlevel, $instance)) { // Already cached
2237 $result[$instance] = $context;
2238 unset($instances[$key]);
2244 list($instanceids, $params) = $DB->get_in_or_equal($instances, SQL_PARAMS_QM);
2245 array_unshift($params, $contextlevel);
2246 $sql = "SELECT instanceid, id, contextlevel, path, depth
2248 WHERE contextlevel=? AND instanceid $instanceids";
2250 if (!$contexts = $DB->get_records_sql($sql, $params)) {
2251 $contexts = array();
2254 foreach ($instances as $instance) {
2255 if (isset($contexts[$instance])) {
2256 $context = $contexts[$instance];
2258 $context = create_context($contextlevel, $instance);
2261 if (!empty($context)) {
2262 $cache->add($context);
2265 $result[$instance] = $context;
2274 * Get a context instance as an object, from a given context id.
2276 * @param int $id context id
2277 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
2278 * MUST_EXIST means throw exception if no record or multiple records found
2279 * @return stdClass|bool the context object or false if not found.
2281 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
2282 global $DB, $ACCESSLIB_PRIVATE;
2284 if ($id == SYSCONTEXTID) {
2285 return get_system_context();
2288 $cache = $ACCESSLIB_PRIVATE->contexcache;
2289 if ($context = $cache->get_by_id($id)) {
2293 if ($context = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
2294 $cache->add($context);
2303 * Get the local override (if any) for a given capability in a role in a context
2305 * @param int $roleid
2306 * @param int $contextid
2307 * @param string $capability
2309 function get_local_override($roleid, $contextid, $capability) {
2311 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
2315 * Returns context instance plus related course and cm instances
2316 * @param int $contextid
2317 * @return array of ($context, $course, $cm)
2319 function get_context_info_array($contextid) {
2322 $context = get_context_instance_by_id($contextid, MUST_EXIST);
2326 if ($context->contextlevel == CONTEXT_COURSE) {
2327 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
2329 } else if ($context->contextlevel == CONTEXT_MODULE) {
2330 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
2331 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
2333 } else if ($context->contextlevel == CONTEXT_BLOCK) {
2334 $parentcontexts = get_parent_contexts($context, false);
2335 $parent = reset($parentcontexts);
2336 $parent = get_context_instance_by_id($parent);
2338 if ($parent->contextlevel == CONTEXT_COURSE) {
2339 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
2340 } else if ($parent->contextlevel == CONTEXT_MODULE) {
2341 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
2342 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
2346 return array($context, $course, $cm);
2350 * Returns current course id or null if outside of course based on context parameter.
2351 * @param object $context
2352 * @return int|bool related course id or false
2354 function get_courseid_from_context($context) {
2355 if (empty($context->contextlevel)) {
2356 debugging('Invalid context object specified in get_courseid_from_context() call');
2359 if ($context->contextlevel == CONTEXT_COURSE) {
2360 return $context->instanceid;
2363 if ($context->contextlevel < CONTEXT_COURSE) {
2367 if ($context->contextlevel == CONTEXT_MODULE) {
2368 $parentcontexts = get_parent_contexts($context, false);
2369 $parent = reset($parentcontexts);
2370 $parent = get_context_instance_by_id($parent);
2371 return $parent->instanceid;
2374 if ($context->contextlevel == CONTEXT_BLOCK) {
2375 $parentcontexts = get_parent_contexts($context, false);
2376 $parent = reset($parentcontexts);
2377 return get_courseid_from_context(get_context_instance_by_id($parent));
2384 //////////////////////////////////////
2385 // DB TABLE RELATED FUNCTIONS //
2386 //////////////////////////////////////
2389 * function that creates a role
2391 * @param string $name role name
2392 * @param string $shortname role short name
2393 * @param string $description role description
2394 * @param string $archetype
2395 * @return int id or dml_exception
2397 function create_role($name, $shortname, $description, $archetype = '') {
2400 if (strpos($archetype, 'moodle/legacy:') !== false) {
2401 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
2404 // verify role archetype actually exists
2405 $archetypes = get_role_archetypes();
2406 if (empty($archetypes[$archetype])) {
2410 // Get the system context.
2411 $context = get_context_instance(CONTEXT_SYSTEM);
2413 // Insert the role record.
2414 $role = new stdClass();
2415 $role->name = $name;
2416 $role->shortname = $shortname;
2417 $role->description = $description;
2418 $role->archetype = $archetype;
2420 //find free sortorder number
2421 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
2422 if (empty($role->sortorder)) {
2423 $role->sortorder = 1;
2425 $id = $DB->insert_record('role', $role);
2431 * Function that deletes a role and cleanups up after it
2433 * @param int $roleid id of role to delete
2434 * @return bool always true
2436 function delete_role($roleid) {
2439 // first unssign all users
2440 role_unassign_all(array('roleid'=>$roleid));
2442 // cleanup all references to this role, ignore errors
2443 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2444 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
2445 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
2446 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
2447 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
2448 $DB->delete_records('role_names', array('roleid'=>$roleid));
2449 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
2451 // finally delete the role itself
2452 // get this before the name is gone for logging
2453 $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
2455 $DB->delete_records('role', array('id'=>$roleid));
2457 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
2463 * Function to write context specific overrides, or default capabilities.
2465 * @param string $capability string name
2466 * @param int $permission CAP_ constants
2467 * @param int $roleid role id
2468 * @param int $contextid context id
2469 * @param bool $overwrite
2470 * @return bool always true or exception
2472 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
2475 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
2476 unassign_capability($capability, $roleid, $contextid);
2480 $existing = $DB->get_record('role_capabilities', array('contextid'=>$contextid, 'roleid'=>$roleid, 'capability'=>$capability));
2482 if ($existing and !$overwrite) { // We want to keep whatever is there already
2486 $cap = new stdClass();
2487 $cap->contextid = $contextid;
2488 $cap->roleid = $roleid;
2489 $cap->capability = $capability;
2490 $cap->permission = $permission;
2491 $cap->timemodified = time();
2492 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
2495 $cap->id = $existing->id;
2496 $DB->update_record('role_capabilities', $cap);
2498 $c = $DB->get_record('context', array('id'=>$contextid));
2499 $DB->insert_record('role_capabilities', $cap);
2505 * Unassign a capability from a role.
2507 * @param string $capability the name of the capability
2508 * @param int $roleid the role id
2509 * @param int $contextid null means all contexts
2510 * @return boolean success or failure
2512 function unassign_capability($capability, $roleid, $contextid = null) {
2515 if (!empty($contextid)) {
2516 // delete from context rel, if this is the last override in this context
2517 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$contextid));
2519 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
2526 * Get the roles that have a given capability assigned to it
2528 * This function does not resolve the actual permission of the capability.
2529 * It just checks for permissions and overrides.
2530 * Use get_roles_with_cap_in_context() if resolution is required.
2532 * @param string $capability - capability name (string)
2533 * @param string $permission - optional, the permission defined for this capability
2534 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
2535 * @param stdClass $context, null means any
2536 * @return array of role objects
2538 function get_roles_with_capability($capability, $permission = null, $context = null) {
2542 $contexts = get_parent_contexts($context, true);
2543 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
2544 $contextsql = "AND rc.contextid $insql";
2551 $permissionsql = " AND rc.permission = :permission";
2552 $params['permission'] = $permission;
2554 $permissionsql = '';
2559 WHERE r.id IN (SELECT rc.roleid
2560 FROM {role_capabilities} rc
2561 WHERE rc.capability = :capname
2564 $params['capname'] = $capability;
2567 return $DB->get_records_sql($sql, $params);
2572 * This function makes a role-assignment (a role for a user in a particular context)
2574 * @param int $roleid the role of the id
2575 * @param int $userid userid
2576 * @param int $contextid id of the context
2577 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
2578 * @prama int $itemid id of enrolment/auth plugin
2579 * @param string $timemodified defaults to current time
2580 * @return int new/existing id of the assignment
2582 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
2583 global $USER, $CFG, $DB;
2585 // first of all detect if somebody is using old style parameters
2586 if ($contextid === 0 or is_numeric($component)) {
2587 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
2590 // now validate all parameters
2591 if (empty($roleid)) {
2592 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
2595 if (empty($userid)) {
2596 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
2600 if (strpos($component, '_') === false) {
2601 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
2605 if ($component !== '' and strpos($component, '_') === false) {
2606 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
2610 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
2611 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
2614 $context = get_context_instance_by_id($contextid, MUST_EXIST);
2616 if (!$timemodified) {
2617 $timemodified = time();
2620 /// Check for existing entry
2621 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
2624 // role already assigned - this should not happen
2625 if (count($ras) > 1) {
2626 //very weird - remove all duplicates!
2627 $ra = array_shift($ras);
2628 foreach ($ras as $r) {
2629 $DB->delete_records('role_assignments', array('id'=>$r->id));
2635 // actually there is no need to update, reset anything or trigger any event, so just return
2639 // Create a new entry
2640 $ra = new stdClass();
2641 $ra->roleid = $roleid;
2642 $ra->contextid = $context->id;
2643 $ra->userid = $userid;
2644 $ra->component = $component;
2645 $ra->itemid = $itemid;
2646 $ra->timemodified = $timemodified;
2647 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
2649 $ra->id = $DB->insert_record('role_assignments', $ra);
2651 // mark context as dirty - again expensive, but needed
2652 mark_context_dirty($context->path);
2654 if (!empty($USER->id) && $USER->id == $userid) {
2655 // If the user is the current user, then do full reload of capabilities too.
2656 load_all_capabilities();
2659 events_trigger('role_assigned', $ra);
2665 * Removes one role assignment
2667 * @param int $roleid
2668 * @param int $userid
2669 * @param int $contextid
2670 * @param string $component
2671 * @param int $itemid
2674 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
2675 global $USER, $CFG, $DB;
2677 // first make sure the params make sense
2678 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
2679 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
2683 if (strpos($component, '_') === false) {
2684 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
2688 if ($component !== '' and strpos($component, '_') === false) {
2689 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
2693 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
2697 * Removes multiple role assignments, parameters may contain:
2698 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
2700 * @param array $params role assignment parameters
2701 * @param bool $subcontexts unassign in subcontexts too
2702 * @param bool $includmanual include manual role assignments too
2705 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
2706 global $USER, $CFG, $DB;
2709 throw new coding_exception('Missing parameters in role_unsassign_all() call');
2712 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
2713 foreach ($params as $key=>$value) {
2714 if (!in_array($key, $allowed)) {
2715 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
2719 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
2720 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
2723 if ($includemanual) {
2724 if (!isset($params['component']) or $params['component'] === '') {
2725 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
2730 if (empty($params['contextid'])) {
2731 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
2735 $ras = $DB->get_records('role_assignments', $params);
2736 foreach($ras as $ra) {
2737 $DB->delete_records('role_assignments', array('id'=>$ra->id));
2738 if ($context = get_context_instance_by_id($ra->contextid)) {
2739 // this is a bit expensive but necessary
2740 mark_context_dirty($context->path);
2741 /// If the user is the current user, then do full reload of capabilities too.
2742 if (!empty($USER->id) && $USER->id == $ra->userid) {
2743 load_all_capabilities();
2746 events_trigger('role_unassigned', $ra);
2750 // process subcontexts
2751 if ($subcontexts and $context = get_context_instance_by_id($params['contextid'])) {
2752 $contexts = get_child_contexts($context);
2754 foreach($contexts as $context) {
2755 $mparams['contextid'] = $context->id;
2756 $ras = $DB->get_records('role_assignments', $mparams);
2757 foreach($ras as $ra) {
2758 $DB->delete_records('role_assignments', array('id'=>$ra->id));
2759 // this is a bit expensive but necessary
2760 mark_context_dirty($context->path);
2761 /// If the user is the current user, then do full reload of capabilities too.
2762 if (!empty($USER->id) && $USER->id == $ra->userid) {
2763 load_all_capabilities();
2765 events_trigger('role_unassigned', $ra);
2770 // do this once more for all manual role assignments
2771 if ($includemanual) {
2772 $params['component'] = '';
2773 role_unassign_all($params, $subcontexts, false);
2779 * Determines if a user is currently logged in
2783 function isloggedin() {
2786 return (!empty($USER->id));
2790 * Determines if a user is logged in as real guest user with username 'guest'.
2792 * @param int|object $user mixed user object or id, $USER if not specified
2793 * @return bool true if user is the real guest user, false if not logged in or other user
2795 function isguestuser($user = null) {
2796 global $USER, $DB, $CFG;
2798 // make sure we have the user id cached in config table, because we are going to use it a lot
2799 if (empty($CFG->siteguest)) {
2800 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
2801 // guest does not exist yet, weird
2804 set_config('siteguest', $guestid);
2806 if ($user === null) {
2810 if ($user === null) {
2811 // happens when setting the $USER
2814 } else if (is_numeric($user)) {
2815 return ($CFG->siteguest == $user);
2817 } else if (is_object($user)) {
2818 if (empty($user->id)) {
2819 return false; // not logged in means is not be guest
2821 return ($CFG->siteguest == $user->id);
2825 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
2830 * Does user have a (temporary or real) guest access to course?
2832 * @param stdClass $context
2833 * @param stdClass|int $user
2836 function is_guest($context, $user = null) {
2839 // first find the course context
2840 $coursecontext = get_course_context($context);
2842 // make sure there is a real user specified
2843 if ($user === null) {
2844 $userid = isset($USER->id) ? $USER->id : 0;
2846 $userid = is_object($user) ? $user->id : $user;
2849 if (isguestuser($userid)) {
2850 // can not inspect or be enrolled
2854 if (has_capability('moodle/course:view', $coursecontext, $user)) {
2855 // viewing users appear out of nowhere, they are neither guests nor participants
2859 // consider only real active enrolments here
2860 if (is_enrolled($coursecontext, $user, '', true)) {
2869 * Returns true if the user has moodle/course:view capability in the course,
2870 * this is intended for admins, managers (aka small admins), inspectors, etc.
2872 * @param stdClass $context
2873 * @param int|object $user, if null $USER is used
2874 * @param string $withcapability extra capability name
2877 function is_viewing($context, $user = null, $withcapability = '') {
2878 // first find the course context
2879 $coursecontext = get_course_context($context);
2881 if (isguestuser($user)) {
2886 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
2887 // admins are allowed to inspect courses
2891 if ($withcapability and !has_capability($withcapability, $context, $user)) {
2892 // site admins always have the capability, but the enrolment above blocks
2900 * Returns true if user is enrolled (is participating) in course
2901 * this is intended for students and teachers.
2903 * @param object $context
2904 * @param int|object $user, if null $USER is used, otherwise user object or id expected
2905 * @param string $withcapability extra capability name
2906 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2909 function is_enrolled($context, $user = null, $withcapability = '', $onlyactive = false) {
2912 // first find the course context
2913 $coursecontext = get_course_context($context);
2915 // make sure there is a real user specified
2916 if ($user === null) {
2917 $userid = isset($USER->id) ? $USER->id : 0;
2919 $userid = is_object($user) ? $user->id : $user;
2922 if (empty($userid)) {
2925 } else if (isguestuser($userid)) {
2926 // guest account can not be enrolled anywhere
2930 if ($coursecontext->instanceid == SITEID) {
2931 // everybody participates on frontpage
2935 FROM {user_enrolments} ue
2936 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2937 JOIN {user} u ON u.id = ue.userid
2938 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
2939 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2940 // this result should be very small, better not do the complex time checks in sql for now ;-)
2941 $enrolments = $DB->get_records_sql($sql, $params);
2943 // make sure the enrol period is ok
2945 foreach ($enrolments as $e) {
2946 if ($e->timestart > $now) {
2949 if ($e->timeend and $e->timeend < $now) {
2960 // any enrolment is good for us here, even outdated, disabled or inactive
2962 FROM {user_enrolments} ue
2963 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2964 JOIN {user} u ON u.id = ue.userid
2965 WHERE ue.userid = :userid AND u.deleted = 0";
2966 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2967 if (!$DB->record_exists_sql($sql, $params)) {
2973 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2981 * Returns true if the user is able to access the course.
2983 * This function is in no way, shape, or form a substitute for require_login.
2984 * It should only be used in circumstances where it is not possible to call require_login
2985 * such as the navigation.
2987 * This function checks many of the methods of access to a course such as the view
2988 * capability, enrollments, and guest access. It also makes use of the cache
2989 * generated by require_login for guest access.
2991 * The flags within the $USER object that are used here should NEVER be used outside
2992 * of this function can_access_course and require_login. Doing so WILL break future
2995 * @global moodle_database $DB
2996 * @param stdClass $context
2997 * @param stdClass|null $user
2998 * @param string $withcapability Check for this capability as well.
2999 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
3000 * @param boolean $trustcache If set to false guest access will always be checked
3001 * against the enrolment plugins from the course, rather
3002 * than the cache generated by require_login.
3003 * @return boolean Returns true if the user is able to access the course
3005 function can_access_course($context, $user = null, $withcapability = '', $onlyactive = false, $trustcache = true) {
3008 $coursecontext = get_course_context($context);
3009 $courseid = $coursecontext->instanceid;
3011 // First check the obvious, is the user viewing or is the user enrolled.
3012 if (is_viewing($coursecontext, $user, $withcapability) || is_enrolled($coursecontext, $user, $withcapability, $onlyactive)) {
3013 // How easy was that!
3018 if (!isset($USER->enrol)) {
3019 // Cache hasn't been generated yet so we can't trust it
3020 $trustcache = false;
3022 * These flags within the $USER object should NEVER be used outside of this
3023 * function can_access_course and the function require_login.
3024 * Doing so WILL break future versions!!!!
3026 $USER->enrol = array();
3027 $USER->enrol['enrolled'] = array();
3028 $USER->enrol['tempguest'] = array();
3031 // If we don't trust the cache we need to check with the courses enrolment
3032 // plugin instances to see if the user can access the course as a guest.
3034 // Ok, off to the database we go!
3035 $instances = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
3036 $enrols = enrol_get_plugins(true);
3037 foreach($instances as $instance) {
3038 if (!isset($enrols[$instance->enrol])) {
3041 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3042 if ($until !== false) {
3043 // Never use me anywhere but here and require_login
3044 $USER->enrol['tempguest'][$courseid] = $until;
3051 // If we don't already have access (from above) check the cache and see whether
3052 // there is record of it in there.
3053 if (!$access && isset($USER->enrol['tempguest'][$courseid])) {
3054 // Never use me anywhere but here and require_login
3055 if ($USER->enrol['tempguest'][$courseid] == 0) {
3057 } else if ($USER->enrol['tempguest'][$courseid] > time()) {
3061 unset($USER->enrol['tempguest'][$courseid]);
3068 * Returns array with sql code and parameters returning all ids
3069 * of users enrolled into course.
3071 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
3073 * @param object $context
3074 * @param string $withcapability
3075 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
3076 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
3077 * @return array list($sql, $params)
3079 function get_enrolled_sql($context, $withcapability = '', $groupid = 0, $onlyactive = false) {
3082 // use unique prefix just in case somebody makes some SQL magic with the result
3085 $prefix = 'eu'.$i.'_';
3087 // first find the course context
3088 $coursecontext = get_course_context($context);
3090 $isfrontpage = ($coursecontext->instanceid == SITEID);
3096 list($contextids, $contextpaths) = get_context_info_list($context);
3098 // get all relevant capability info for all roles
3099 if ($withcapability) {
3100 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
3101 $cparams['cap'] = $withcapability;
3104 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
3105 FROM {role_capabilities} rc
3106 JOIN {context} ctx on rc.contextid = ctx.id
3107 WHERE rc.contextid $incontexts AND rc.capability = :cap";
3108 $rcs = $DB->get_records_sql($sql, $cparams);
3109 foreach ($rcs as $rc) {
3110 $defs[$rc->path][$rc->roleid] = $rc->permission;
3114 if (!empty($defs)) {
3115 foreach ($contextpaths as $path) {
3116 if (empty($defs[$path])) {
3119 foreach($defs[$path] as $roleid => $perm) {
3120 if ($perm == CAP_PROHIBIT) {
3121 $access[$roleid] = CAP_PROHIBIT;
3124 if (!isset($access[$roleid])) {
3125 $access[$roleid] = (int)$perm;
3133 // make lists of roles that are needed and prohibited
3134 $needed = array(); // one of these is enough
3135 $prohibited = array(); // must not have any of these
3136 foreach ($access as $roleid => $perm) {
3137 if ($perm == CAP_PROHIBIT) {
3138 unset($needed[$roleid]);
3139 $prohibited[$roleid] = true;
3140 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
3141 $needed[$roleid] = true;
3145 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3146 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3151 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
3153 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
3154 // everybody not having prohibit has the capability
3156 } else if (empty($needed)) {
3160 if (!empty($prohibited[$defaultuserroleid])) {
3162 } else if (!empty($needed[$defaultuserroleid])) {
3163 // everybody not having prohibit has the capability
3165 } else if (empty($needed)) {
3171 // nobody can match so return some SQL that does not return any results
3172 $wheres[] = "1 = 2";
3177 $ctxids = implode(',', $contextids);
3178 $roleids = implode(',', array_keys($needed));
3179 $joins[] = "JOIN {role_assignments} {$prefix}ra3 ON ({$prefix}ra3.userid = {$prefix}u.id AND {$prefix}ra3.roleid IN ($roleids) AND {$prefix}ra3.contextid IN ($ctxids))";
3183 $ctxids = implode(',', $contextids);
3184 $roleids = implode(',', array_keys($prohibited));
3185 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4 ON ({$prefix}ra4.userid = {$prefix}u.id AND {$prefix}ra4.roleid IN ($roleids) AND {$prefix}ra4.contextid IN ($ctxids))";
3186 $wheres[] = "{$prefix}ra4.id IS NULL";
3190 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
3191 $params["{$prefix}gmid"] = $groupid;
3197 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
3198 $params["{$prefix}gmid"] = $groupid;
3202 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
3203 $params["{$prefix}guestid"] = $CFG->siteguest;
3206 // all users are "enrolled" on the frontpage
3208 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
3209 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
3210 $params[$prefix.'courseid'] = $coursecontext->instanceid;
3213 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
3214 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
3215 $now = round(time(), -2); // rounding helps caching in DB
3216 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
3217 $prefix.'active'=>ENROL_USER_ACTIVE,
3218 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
3222 $joins = implode("\n", $joins);
3223 $wheres = "WHERE ".implode(" AND ", $wheres);
3225 $sql = "SELECT DISTINCT {$prefix}u.id
3226 FROM {user} {$prefix}u
3230 return array($sql, $params);
3234 * Returns list of users enrolled into course.
3235 * @param object $context
3236 * @param string $withcapability
3237 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
3238 * @param string $userfields requested user record fields
3239 * @param string $orderby
3240 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
3241 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
3242 * @return array of user records
3244 function get_enrolled_users($context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = '', $limitfrom = 0, $limitnum = 0) {
3247 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
3248 $sql = "SELECT $userfields
3250 JOIN ($esql) je ON je.id = u.id
3251 WHERE u.deleted = 0";
3254 $sql = "$sql ORDER BY $orderby";
3256 $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
3259 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3263 * Counts list of users enrolled into course (as per above function)
3264 * @param object $context
3265 * @param string $withcapability
3266 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
3267 * @return array of user records
3269 function count_enrolled_users($context, $withcapability = '', $groupid = 0) {
3272 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
3273 $sql = "SELECT count(u.id)
3275 JOIN ($esql) je ON je.id = u.id
3276 WHERE u.deleted = 0";
3278 return $DB->count_records_sql($sql, $params);
3283 * Loads the capability definitions for the component (from file).
3285 * Loads the capability definitions for the component (from file). If no
3286 * capabilities are defined for the component, we simply return an empty array.
3288 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
3289 * @return array array of capabilities
3291 function load_capability_def($component) {
3292 $defpath = get_component_directory($component).'/db/access.php';
3294 $capabilities = array();
3295 if (file_exists($defpath)) {
3297 if (!empty(${$component.'_capabilities'})) {
3298 // BC capability array name
3299 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
3300 debugging('componentname_capabilities array is deprecated, please use capabilities array only in access.php files');
3301 $capabilities = ${$component.'_capabilities'};
3305 return $capabilities;
3310 * Gets the capabilities that have been cached in the database for this component.
3311 * @param string $component - examples: 'moodle', 'mod_forum'
3312 * @return array array of capabilities
3314 function get_cached_capabilities($component = 'moodle') {
3316 return $DB->get_records('capabilities', array('component'=>$component));
3320 * Returns default capabilities for given role archetype.
3321 * @param string $archetype role archetype
3324 function get_default_capabilities($archetype) {
3332 $defaults = array();
3333 $components = array();
3334 $allcaps = $DB->get_records('capabilities');
3336 foreach ($allcaps as $cap) {
3337 if (!in_array($cap->component, $components)) {
3338 $components[] = $cap->component;
3339 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
3342 foreach($alldefs as $name=>$def) {
3343 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
3344 if (isset($def['archetypes'])) {
3345 if (isset($def['archetypes'][$archetype])) {
3346 $defaults[$name] = $def['archetypes'][$archetype];
3348 // 'legacy' is for backward compatibility with 1.9 access.php
3350 if (isset($def['legacy'][$archetype])) {
3351 $defaults[$name] = $def['legacy'][$archetype];
3360 * Reset role capabilities to default according to selected role archetype.
3361 * If no archetype selected, removes all capabilities.
3362 * @param int $roleid
3365 function reset_role_capabilities($roleid) {
3368 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
3369 $defaultcaps = get_default_capabilities($role->archetype);
3371 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
3373 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
3375 foreach($defaultcaps as $cap=>$permission) {
3376 assign_capability($cap, $permission, $roleid, $sitecontext->id);
3381 * Updates the capabilities table with the component capability definitions.
3382 * If no parameters are given, the function updates the core moodle
3385 * Note that the absence of the db/access.php capabilities definition file
3386 * will cause any stored capabilities for the component to be removed from
3389 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
3390 * @return boolean true if success, exception in case of any problems
3392 function update_capabilities($component = 'moodle') {
3393 global $DB, $OUTPUT, $ACCESSLIB_PRIVATE;
3395 $storedcaps = array();
3397 $filecaps = load_capability_def($component);
3398 foreach($filecaps as $capname=>$unused) {
3399 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
3400 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
3404 $cachedcaps = get_cached_capabilities($component);
3406 foreach ($cachedcaps as $cachedcap) {
3407 array_push($storedcaps, $cachedcap->name);
3408 // update risk bitmasks and context levels in existing capabilities if needed
3409 if (array_key_exists($cachedcap->name, $filecaps)) {
3410 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
3411 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
3413 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
3414 $updatecap = new stdClass();
3415 $updatecap->id = $cachedcap->id;
3416 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
3417 $DB->update_record('capabilities', $updatecap);
3419 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
3420 $updatecap = new stdClass();
3421 $updatecap->id = $cachedcap->id;
3422 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
3423 $DB->update_record('capabilities', $updatecap);
3426 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
3427 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
3429 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
3430 $updatecap = new stdClass();
3431 $updatecap->id = $cachedcap->id;
3432 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
3433 $DB->update_record('capabilities', $updatecap);
3439 // Are there new capabilities in the file definition?
3442 foreach ($filecaps as $filecap => $def) {
3444 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
3445 if (!array_key_exists('riskbitmask', $def)) {
3446 $def['riskbitmask'] = 0; // no risk if not specified
3448 $newcaps[$filecap] = $def;
3451 // Add new capabilities to the stored definition.
3452 foreach ($newcaps as $capname => $capdef) {
3453 $capability = new stdClass();
3454 $capability->name = $capname;
3455 $capability->captype = $capdef['captype'];
3456 $capability->contextlevel = $capdef['contextlevel'];
3457 $capability->component = $component;
3458 $capability->riskbitmask = $capdef['riskbitmask'];
3460 $DB->insert_record('capabilities', $capability, false);
3462 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
3463 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
3464 foreach ($rolecapabilities as $rolecapability){
3465 //assign_capability will update rather than insert if capability exists
3466 if (!assign_capability($capname, $rolecapability->permission,
3467 $rolecapability->roleid, $rolecapability->contextid, true)){
3468 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
3472 // we ignore archetype key if we have cloned permissions
3473 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
3474 assign_legacy_capabilities($capname, $capdef['archetypes']);
3475 // 'legacy' is for backward compatibility with 1.9 access.php
3476 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
3477 assign_legacy_capabilities($capname, $capdef['legacy']);
3480 // Are there any capabilities that have been removed from the file
3481 // definition that we need to delete from the stored capabilities and
3482 // role assignments?
3483 capabilities_cleanup($component, $filecaps);
3485 // reset static caches
3486 $ACCESSLIB_PRIVATE->capabilities = null;
3493 * Deletes cached capabilities that are no longer needed by the component.
3494 * Also unassigns these capabilities from any roles that have them.
3496 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
3497 * @param array $newcapdef array of the new capability definitions that will be
3498 * compared with the cached capabilities
3499 * @return int number of deprecated capabilities that have been removed
3501 function capabilities_cleanup($component, $newcapdef = null) {
3506 if ($cachedcaps = get_cached_capabilities($component)) {
3507 foreach ($cachedcaps as $cachedcap) {
3508 if (empty($newcapdef) ||
3509 array_key_exists($cachedcap->name, $newcapdef) === false) {
3511 // Remove from capabilities cache.
3512 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
3514 // Delete from roles.
3515 if ($roles = get_roles_with_capability($cachedcap->name)) {
3516 foreach($roles as $role) {
3517 if (!unassign_capability($cachedcap->name, $role->id)) {
3518 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
3525 return $removedcount;
3535 * @param integer $contextlevel $context->context level. One of the CONTEXT_... constants.
3536 * @return string the name for this type of context.
3538 function get_contextlevel_name($contextlevel) {
3539 static $strcontextlevels = null;
3540 if (is_null($strcontextlevels)) {
3541 $strcontextlevels = array(
3542 CONTEXT_SYSTEM => get_string('coresystem'),
3543 CONTEXT_USER => get_string('user'),
3544 CONTEXT_COURSECAT => get_string('category'),
3545 CONTEXT_COURSE => get_string('course'),
3546 CONTEXT_MODULE => get_string('activitymodule'),
3547 CONTEXT_BLOCK => get_string('block')
3550 return $strcontextlevels[$contextlevel];
3554 * Prints human readable context identifier.
3556 * @param object $context the context.
3557 * @param boolean $withprefix whether to prefix the name of the context with the
3558 * type of context, e.g. User, Course, Forum, etc.
3559 * @param boolean $short whether to user the short name of the thing. Only applies
3560 * to course contexts
3561 * @return string the human readable context name.
3563 function print_context_name($context, $withprefix = true, $short = false) {
3567 switch ($context->contextlevel) {
3569 case CONTEXT_SYSTEM:
3570 $name = get_string('coresystem');
3574 if ($user = $DB->get_record('user', array('id'=>$context->instanceid))) {
3576 $name = get_string('user').': ';
3578 $name .= fullname($user);
3582 case CONTEXT_COURSECAT:
3583 if ($category = $DB->get_record('course_categories', array('id'=>$context->instanceid))) {
3585 $name = get_string('category').': ';
3587 $name .= format_string($category->name, true, array('context' => $context));
3591 case CONTEXT_COURSE:
3592 if ($context->instanceid == SITEID) {
3593 $name = get_string('frontpage', 'admin');
3595 if ($course = $DB->get_record('course', array('id'=>$context->instanceid))) {
3597 $name = get_string('course').': ';
3600 $name .= format_string($course->shortname, true, array('context' => $context));
3602 $name .= format_string($course->fullname);
3608 case CONTEXT_MODULE:
3609 if ($cm = $DB->get_record_sql('SELECT cm.*, md.name AS modname FROM {course_modules} cm ' .
3610 'JOIN {modules} md ON md.id = cm.module WHERE cm.id = ?', array($context->instanceid))) {
3611 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
3613 $name = get_string('modulename', $cm->modname).': ';
3615 $name .= $mod->name;
3621 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$context->instanceid))) {
3623 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
3624 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
3625 $blockname = "block_$blockinstance->blockname";
3626 if ($blockobject = new $blockname()) {
3628 $name = get_string('block').': ';
3630 $name .= $blockobject->title;
3636 print_error('unknowncontext');
3644 * Get a URL for a context, if there is a natural one. For example, for
3645 * CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
3646 * user profile page.
3648 * @param object $context the context.
3649 * @return moodle_url
3651 function get_context_url($context) {
3652 global $COURSE, $DB;
3654 switch ($context->contextlevel) {
3656 if ($COURSE->id == SITEID) {
3657 $url = new moodle_url('/user/profile.php', array('id'=>$context->instanceid));
3659 $url = new moodle_url('/user/view.php', array('id'=>$context->instanceid, 'courseid'=>$COURSE->id));
3663 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
3664 return new moodle_url('/course/category.php', array('id'=>$context->instanceid));
3666 case CONTEXT_COURSE: // 1 to 1 to course cat
3667 if ($context->instanceid != SITEID) {
3668 return new moodle_url('/course/view.php', array('id'=>$context->instanceid));
3672 case CONTEXT_MODULE: // 1 to 1 to course
3673 if ($modname = $DB->get_field_sql('SELECT md.name AS modname FROM {course_modules} cm ' .
3674 'JOIN {modules} md ON md.id = cm.module WHERE cm.id = ?', array($context->instanceid))) {
3675 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$context->instanceid));
3680 $parentcontexts = get_parent_contexts($context, false);
3681 $parent = reset($parentcontexts);
3682 $parent = get_context_instance_by_id($parent);
3683 return get_context_url($parent);
3686 return new moodle_url('/');
3690 * Returns an array of all the known types of risk
3691 * The array keys can be used, for example as CSS class names, or in calls to
3692 * print_risk_icon. The values are the corresponding RISK_ constants.
3694 * @return array all the known types of risk.
3696 function get_all_risks() {
3698 'riskmanagetrust' => RISK_MANAGETRUST,
3699 'riskconfig' => RISK_CONFIG,
3700 'riskxss' => RISK_XSS,
3701 'riskpersonal' => RISK_PERSONAL,
3702 'riskspam' => RISK_SPAM,
3703 'riskdataloss' => RISK_DATALOSS,
3708 * Return a link to moodle docs for a given capability name
3710 * @param object $capability a capability - a row from the mdl_capabilities table.
3711 * @return string the human-readable capability name as a link to Moodle Docs.
3713 function get_capability_docs_link($capability) {
3715 $url = get_docs_url('Capabilities/' . $capability->name);
3716 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
3720 * Extracts the relevant capabilities given a contextid.
3721 * All case based, example an instance of forum context.
3722 * Will fetch all forum related capabilities, while course contexts
3723 * Will fetch all capabilities
3726 * `name` varchar(150) NOT NULL,
3727 * `captype` varchar(50) NOT NULL,
3728 * `contextlevel` int(10) NOT NULL,
3729 * `component` varchar(100) NOT NULL,
3731 * @param object context
3734 function fetch_context_capabilities($context) {
3737 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
3741 switch ($context->contextlevel) {
3743 case CONTEXT_SYSTEM: // all
3745 FROM {capabilities}";
3749 $extracaps = array('moodle/grade:viewall');
3750 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
3753 WHERE contextlevel = ".CONTEXT_USER."
3757 case CONTEXT_COURSECAT: // course category context and bellow
3760 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
3763 case CONTEXT_COURSE: // course context and bellow
3766 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
3769 case CONTEXT_MODULE: // mod caps
3770 $cm = $DB->get_record('course_modules', array('id'=>$context->instanceid));
3771 $module = $DB->get_record('modules', array('id'=>$cm->module));
3774 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
3775 if (file_exists($subpluginsfile)) {
3776 $subplugins = array(); // should be redefined in the file
3777 include($subpluginsfile);
3778 if (!empty($subplugins)) {
3779 foreach (array_keys($subplugins) as $subplugintype) {
3780 foreach (array_keys(get_plugin_list($subplugintype)) as $subpluginname) {
3781 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
3787 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
3788 if (file_exists($modfile)) {
3789 include_once($modfile);
3790 $modfunction = $module->name.'_get_extra_capabilities';
3791 if (function_exists($modfunction)) {
3792 $extracaps = $modfunction();
3795 if (empty($extracaps)) {
3796 $extracaps = array();
3799 $extracaps = array_merge($subcaps, $extracaps);
3801 // All modules allow viewhiddenactivities. This is so you can hide
3802 // the module then override to allow specific roles to see it.
3803 // The actual check is in course page so not module-specific
3804 $extracaps[]="moodle/course:viewhiddenactivities";
3805 list($extra, $params) = $DB->get_in_or_equal(
3806 $extracaps, SQL_PARAMS_NAMED, 'cap0');
3807 $extra = "OR name $extra";
3811 WHERE (contextlevel = ".CONTEXT_MODULE."
3812 AND component = :component)
3814 $params['component'] = "mod_$module->name";
3817 case CONTEXT_BLOCK: // block caps
3818 $bi = $DB->get_record('block_instances', array('id' => $context->instanceid));
3821 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
3823 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
3824 $extra = "OR name $extra";
3829 WHERE (contextlevel = ".CONTEXT_BLOCK."
3830 AND component = :component)
3832 $params['component'] = 'block_' . $bi->blockname;
3839 if (!$records = $DB->get_records_sql($SQL.' '.$sort, $params)) {
3848 * This function pulls out all the resolved capabilities (overrides and
3849 * defaults) of a role used in capability overrides in contexts at a given
3852 * @param obj $context
3853 * @param int $roleid
3854 * @param string $cap capability, optional, defaults to ''
3855 * @return array of capabilities
3857 function role_context_capabilities($roleid, $context, $cap = '') {
3860 $contexts = get_parent_contexts($context);
3861 $contexts[] = $context->id;
3862 $contexts = '('.implode(',', $contexts).')';
3864 $params = array($roleid);
3867 $search = " AND rc.capability = ? ";
3874 FROM {role_capabilities} rc, {context} c
3875 WHERE rc.contextid in $contexts
3877 AND rc.contextid = c.id $search
3878 ORDER BY c.contextlevel DESC, rc.capability DESC";
3880 $capabilities = array();
3882 if ($records = $DB->get_records_sql($sql, $params)) {
3883 // We are traversing via reverse order.
3884 foreach ($records as $record) {
3885 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
3886 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
3887 $capabilities[$record->capability] = $record->permission;
3891 return $capabilities;
3895 * Recursive function which, given a context, find all parent context ids,
3896 * and return the array in reverse order, i.e. parent first, then grand
3899 * @param object $context
3900 * @param bool $capability optional, defaults to false
3903 function get_parent_contexts($context, $includeself = false) {
3905 if ($context->path == '') {
3909 $parentcontexts = substr($context->path, 1); // kill leading slash
3910 $parentcontexts = explode('/', $parentcontexts);
3911 if (!$includeself) {
3912 array_pop($parentcontexts); // and remove its own id
3915 return array_reverse($parentcontexts);
3919 * Return the id of the parent of this context, or false if there is no parent (only happens if this
3920 * is the site context.)
3922 * @param object $context
3923 * @return integer the id of the parent context.
3925 function get_parent_contextid($context) {
3926 $parentcontexts = get_parent_contexts($context);
3927 if (count($parentcontexts) == 0) {
3930 return array_shift($parentcontexts);
3934 * Constructs array with contextids as first parameter and context paths,
3935 * in both cases bottom top including self.
3937 * @param object $context
3940 function get_context_info_list($context) {
3941 $contextids = explode('/', ltrim($context->path, '/'));
3942 $contextpaths = array();
3943 $contextids2 = $contextids;
3944 while ($contextids2) {
3945 $contextpaths[] = '/' . implode('/', $contextids2);
3946 array_pop($contextids2);
3948 return array($contextids, $contextpaths);
3952 * Find course context
3953 * @param object $context - course or lower context
3954 * @return object context of the enclosing course, throws exception when related course context can not be found
3956 function get_course_context($context) {
3957 if (empty($context->contextlevel)) {
3958 throw new coding_exception('Invalid context parameter.');
3960 } if ($context->contextlevel == CONTEXT_COURSE) {
3963 } else if ($context->contextlevel == CONTEXT_MODULE) {
3964 return get_context_instance_by_id(get_parent_contextid($context, MUST_EXIST));
3966 } else if ($context->contextlevel == CONTEXT_BLOCK) {
3967 $parentcontext = get_context_instance_by_id(get_parent_contextid($context, MUST_EXIST));
3968 if ($parentcontext->contextlevel == CONTEXT_COURSE) {
3969 return $parentcontext;
3970 } else if ($parentcontext->contextlevel == CONTEXT_MODULE) {
3971 return get_context_instance_by_id(get_parent_contextid($parentcontext, MUST_EXIST));
3973 throw new coding_exception('Invalid level of block context parameter.');
3977 throw new coding_exception('Invalid context level of parameter.');
3981 * Check if context is the front page context or a context inside it
3983 * Returns true if this context is the front page context, or a context inside it,
3986 * @param object $context a context object.
3989 function is_inside_frontpage($context) {
3990 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
3991 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
3995 * Runs get_records select on context table and returns the result
3996 * Does get_records_select on the context table, and returns the results ordered
3997 * by contextlevel, and then the natural sort order within each level.
3998 * for the purpose of $select, you need to know that the context table has been
3999 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
4001 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
4002 * @param array $params any parameters required by $select.
4003 * @return array the requested context records.
4005 function get_sorted_contexts($select, $params = array()) {
4008 $select = 'WHERE ' . $select;
4010 return $DB->get_records_sql("
4013 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
4014 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
4015 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
4016 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
4017 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
4019 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
4024 * Recursive function which, given a context, find all its children context ids.
4026 * When called for a course context, it will return the modules and blocks
4027 * displayed in the course page.
4029 * For course category contexts it will return categories and courses. It will
4030 * NOT recurse into courses, nor return blocks on the category pages. If you
4031 * want to do that, call it on the returned courses.
4033 * If called on a course context it _will_ populate the cache with the appropriate
4036 * @param object $context.
4037 * @return array Array of child records
4039 function get_child_contexts($context) {
4041 global $DB, $ACCESSLIB_PRIVATE;
4043 // We *MUST* populate the context_cache as the callers
4044 // will probably ask for the full record anyway soon after
4045 // soon after calling us ;-)
4048 $cache = $ACCESSLIB_PRIVATE->contexcache;
4050 switch ($context->contextlevel) {
4056 case CONTEXT_MODULE:
4058 // - blocks under this context path.
4059 $sql = " SELECT ctx.*
4061 WHERE ctx.path LIKE ?
4062 AND ctx.contextlevel = ".CONTEXT_BLOCK;
4063 $params = array("{$context->path}/%", $context->instanceid);
4064 $records = $DB->get_recordset_sql($sql, $params);
4065 foreach ($records as $rec) {
4067 $array[$rec->id] = $rec;
4071 case CONTEXT_COURSE:
4073 // - modules and blocks under this context path.
4074 $sql = " SELECT ctx.*
4076 WHERE ctx.path LIKE ?
4077 AND ctx.contextlevel IN (".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
4078 $params = array("{$context->path}/%", $context->instanceid);
4079 $records = $DB->get_recordset_sql($sql, $params);
4080 foreach ($records as $rec) {
4082 $array[$rec->id] = $rec;
4086 case CONTEXT_COURSECAT:
4090 $sql = " SELECT ctx.*
4092 WHERE ctx.path LIKE ?
4093 AND ctx.contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.")";
4094 $params = array("{$context->path}/%");
4095 $records = $DB->get_recordset_sql($sql, $params);
4096 foreach ($records as $rec) {
4098 $array[$rec->id] = $rec;
4104 // - blocks under this context path.
4105 $sql = " SELECT ctx.*
4107 WHERE ctx.path LIKE ?
4108 AND ctx.contextlevel = ".CONTEXT_BLOCK;
4109 $params = array("{$context->path}/%", $context->instanceid);
4110 $records = $DB->get_recordset_sql($sql, $params);
4111 foreach ($records as $rec) {
4113 $array[$rec->id] = $rec;
4117 case CONTEXT_SYSTEM:
4118 // Just get all the contexts except for CONTEXT_SYSTEM level
4119 // and hope we don't OOM in the process - don't cache
4122 WHERE contextlevel != ".CONTEXT_SYSTEM;
4124 $records = $DB->get_records_sql($sql);
4125 foreach ($records as $rec) {
4126 $array[$rec->id] = $rec;
4131 print_error('unknowcontext', '', '', $context->contextlevel);
4139 * Gets a string for sql calls, searching for stuff in this context or above
4141 * @param object $context
4144 function get_related_contexts_string($context) {
4145 if ($parents = get_parent_contexts($context)) {
4146 return (' IN ('.$context->id.','.implode(',', $parents).')');
4148 return (' ='.$context->id);
4153 * Returns capability information (cached)
4155 * @param string $capabilityname
4156 * @return object or null if capability not found
4158 function get_capability_info($capabilityname) {
4159 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
4161 // TODO: cache this in shared memory if available, use new $CFG->roledefrev for version check
4163 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
4164 $ACCESSLIB_PRIVATE->capabilities = array();
4165 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
4166 foreach ($caps as $cap) {
4167 $capname = $cap->name;
4170 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
4174 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
4178 * Returns the human-readable, translated version of the capability.
4179 * Basically a big switch statement.
4181 * @param string $capabilityname e.g. mod/choice:readresponses
4184 function get_capability_string($capabilityname) {
4186 // Typical capability name is 'plugintype/pluginname:capabilityname'
4187 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
4189 if ($type === 'moodle') {
4190 $component = 'core_role';
4191 } else if ($type === 'quizreport') {
4193 $component = 'quiz_'.$name;
4195 $component = $type.'_'.$name;
4198 $stringname = $name.':'.$capname;
4200 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
4201 return get_string($stringname, $component);
4204 $dir = get_component_directory($component);
4205 if (!file_exists($dir)) {
4206 // plugin broken or does not exist, do not bother with printing of debug message
4207 return $capabilityname.' ???';
4210 // something is wrong in plugin, better print debug
4211 return get_string($stringname, $component);
4216 * This gets the mod/block/course/core etc strings.
4218 * @param string $component
4219 * @param int $contextlevel
4220 * @return string|bool String is success, false if failed
4222 function get_component_string($component, $contextlevel) {
4224 if ($component === 'moodle' or $component === 'core') {
4225 switch ($contextlevel) {
4226 case CONTEXT_SYSTEM: return get_string('coresystem');
4227 case CONTEXT_USER: return get_string('users');
4228 case CONTEXT_COURSECAT: return get_string('categories');
4229 case CONTEXT_COURSE: return get_string('course');
4230 case CONTEXT_MODULE: return get_string('activities');
4231 case CONTEXT_BLOCK: return get_string('block');
4232 default: print_error('unknowncontext');
4236 list($type, $name) = normalize_component($component);
4237 $dir = get_plugin_directory($type, $name);
4238 if (!file_exists($dir)) {
4239 // plugin not installed, bad luck, there is no way to find the name
4240 return $component.' ???';
4244 // TODO this is really hacky
4245 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
4246 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
4247 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
4248 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
4249 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
4250 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
4251 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
4253 if (get_string_manager()->string_exists('pluginname', $component)) {
4254 return get_string('activity').': '.get_string('pluginname', $component);
4256 return get_string('activity').': '.get_string('modulename', $component);
4258 default: return get_string('pluginname', $component);
4263 * Gets the list of roles assigned to this context and up (parents)
4264 * from the list of roles that are visible on user profile page
4265 * and participants page.
4267 * @param object $context
4270 function get_profile_roles($context) {
4273 if (empty($CFG->profileroles)) {
4277 $allowed = explode(',', $CFG->profileroles);
4278 list($rallowed, $params) = $DB->get_in_or_equal($allowed, SQL_PARAMS_NAMED);
4280 $contextlist = get_related_contexts_string($context);
4282 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder