2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * This file contains functions for managing user access
20 * <b>Public API vs internals</b>
22 * General users probably only care about
25 * - context_course::instance($courseid), context_module::instance($cm->id), context_coursecat::instance($catid)
26 * - context::instance_by_id($contextid)
27 * - $context->get_parent_contexts();
28 * - $context->get_child_contexts();
30 * Whether the user can do something...
32 * - has_any_capability()
33 * - has_all_capabilities()
34 * - require_capability()
35 * - require_login() (from moodlelib)
43 * What courses has this user access to?
44 * - get_enrolled_users()
46 * What users can do X in this context?
47 * - get_enrolled_users() - at and bellow course context
48 * - get_users_by_capability() - above course context
53 * - role_unassign_all()
55 * Advanced - for internal use only
56 * - load_all_capabilities()
57 * - reload_all_capabilities()
58 * - has_capability_in_accessdata()
59 * - get_user_access_sitewide()
60 * - load_course_context()
61 * - load_role_access_by_context()
64 * <b>Name conventions</b>
70 * Access control data is held in the "accessdata" array
71 * which - for the logged-in user, will be in $USER->access
73 * For other users can be generated and passed around (but may also be cached
74 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser).
76 * $accessdata is a multidimensional array, holding
77 * role assignments (RAs), role-capabilities-perm sets
78 * (role defs) and a list of courses we have loaded
81 * Things are keyed on "contextpaths" (the path field of
82 * the context table) for fast walking up/down the tree.
84 * $accessdata['ra'][$contextpath] = array($roleid=>$roleid)
85 * [$contextpath] = array($roleid=>$roleid)
86 * [$contextpath] = array($roleid=>$roleid)
89 * Role definitions are stored like this
90 * (no cap merge is done - so it's compact)
93 * $accessdata['rdef']["$contextpath:$roleid"]['mod/forum:viewpost'] = 1
94 * ['mod/forum:editallpost'] = -1
95 * ['mod/forum:startdiscussion'] = -1000
98 * See how has_capability_in_accessdata() walks up the tree.
100 * First we only load rdef and ra down to the course level, but not below.
101 * This keeps accessdata small and compact. Below-the-course ra/rdef
102 * are loaded as needed. We keep track of which courses we have loaded ra/rdef in
104 * $accessdata['loaded'] = array($courseid1=>1, $courseid2=>1)
107 * <b>Stale accessdata</b>
109 * For the logged-in user, accessdata is long-lived.
111 * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
112 * context paths affected by changes. Any check at-or-below
113 * a dirty context will trigger a transparent reload of accessdata.
115 * Changes at the system level will force the reload for everyone.
117 * <b>Default role caps</b>
118 * The default role assignment is not in the DB, so we
119 * add it manually to accessdata.
121 * This means that functions that work directly off the
122 * DB need to ensure that the default role caps
123 * are dealt with appropriately.
125 * @package core_access
126 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
127 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
130 defined('MOODLE_INTERNAL') || die();
132 /** No capability change */
133 define('CAP_INHERIT', 0);
134 /** Allow permission, overrides CAP_PREVENT defined in parent contexts */
135 define('CAP_ALLOW', 1);
136 /** Prevent permission, overrides CAP_ALLOW defined in parent contexts */
137 define('CAP_PREVENT', -1);
138 /** Prohibit permission, overrides everything in current and child contexts */
139 define('CAP_PROHIBIT', -1000);
141 /** System context level - only one instance in every system */
142 define('CONTEXT_SYSTEM', 10);
143 /** User context level - one instance for each user describing what others can do to user */
144 define('CONTEXT_USER', 30);
145 /** Course category context level - one instance for each category */
146 define('CONTEXT_COURSECAT', 40);
147 /** Course context level - one instances for each course */
148 define('CONTEXT_COURSE', 50);
149 /** Course module context level - one instance for each course module */
150 define('CONTEXT_MODULE', 70);
152 * Block context level - one instance for each block, sticky blocks are tricky
153 * because ppl think they should be able to override them at lower contexts.
154 * Any other context level instance can be parent of block context.
156 define('CONTEXT_BLOCK', 80);
158 /** Capability allow management of trusts - NOT IMPLEMENTED YET - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
159 define('RISK_MANAGETRUST', 0x0001);
160 /** Capability allows changes in system configuration - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
161 define('RISK_CONFIG', 0x0002);
162 /** Capability allows user to add scripted content - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
163 define('RISK_XSS', 0x0004);
164 /** Capability allows access to personal user information - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
165 define('RISK_PERSONAL', 0x0008);
166 /** Capability allows users to add content others may see - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
167 define('RISK_SPAM', 0x0010);
168 /** capability allows mass delete of data belonging to other users - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
169 define('RISK_DATALOSS', 0x0020);
171 /** rolename displays - the name as defined in the role definition, localised if name empty */
172 define('ROLENAME_ORIGINAL', 0);
173 /** rolename displays - the name as defined by a role alias at the course level, falls back to ROLENAME_ORIGINAL if alias not present */
174 define('ROLENAME_ALIAS', 1);
175 /** rolename displays - Both, like this: Role alias (Original) */
176 define('ROLENAME_BOTH', 2);
177 /** rolename displays - the name as defined in the role definition and the shortname in brackets */
178 define('ROLENAME_ORIGINALANDSHORT', 3);
179 /** rolename displays - the name as defined by a role alias, in raw form suitable for editing */
180 define('ROLENAME_ALIAS_RAW', 4);
181 /** rolename displays - the name is simply short role name */
182 define('ROLENAME_SHORT', 5);
184 if (!defined('CONTEXT_CACHE_MAX_SIZE')) {
185 /** maximum size of context cache - it is possible to tweak this config.php or in any script before inclusion of context.php */
186 define('CONTEXT_CACHE_MAX_SIZE', 2500);
190 * Although this looks like a global variable, it isn't really.
192 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
193 * It is used to cache various bits of data between function calls for performance reasons.
194 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
195 * as methods of a class, instead of functions.
198 * @global stdClass $ACCESSLIB_PRIVATE
199 * @name $ACCESSLIB_PRIVATE
201 global $ACCESSLIB_PRIVATE;
202 $ACCESSLIB_PRIVATE = new stdClass();
203 $ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache, loaded from DB once per page
204 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
205 $ACCESSLIB_PRIVATE->rolepermissions = array(); // role permissions cache - helps a lot with mem usage
206 $ACCESSLIB_PRIVATE->capabilities = null; // detailed information about the capabilities
209 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
211 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
212 * accesslib's private caches. You need to do this before setting up test data,
213 * and also at the end of the tests.
218 function accesslib_clear_all_caches_for_unit_testing() {
221 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
224 accesslib_clear_all_caches(true);
226 unset($USER->access);
230 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
232 * This reset does not touch global $USER.
235 * @param bool $resetcontexts
238 function accesslib_clear_all_caches($resetcontexts) {
239 global $ACCESSLIB_PRIVATE;
241 $ACCESSLIB_PRIVATE->dirtycontexts = null;
242 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
243 $ACCESSLIB_PRIVATE->rolepermissions = array();
244 $ACCESSLIB_PRIVATE->capabilities = null;
246 if ($resetcontexts) {
247 context_helper::reset_caches();
252 * Gets the accessdata for role "sitewide" (system down to course)
258 function get_role_access($roleid) {
259 global $DB, $ACCESSLIB_PRIVATE;
261 /* Get it in 1 DB query...
262 * - relevant role caps at the root and down
263 * to the course level - but not below
266 //TODO: MUC - this could be cached in shared memory to speed up first page loading, web crawlers, etc.
268 $accessdata = get_empty_accessdata();
270 $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
272 // Overrides for the role IN ANY CONTEXTS down to COURSE - not below -.
275 $sql = "SELECT ctx.path,
276 rc.capability, rc.permission
278 JOIN {role_capabilities} rc ON rc.contextid = ctx.id
279 LEFT JOIN {context} cctx
280 ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
281 WHERE rc.roleid = ? AND cctx.id IS NULL";
282 $params = array($roleid);
285 // Note: the commented out query is 100% accurate but slow, so let's cheat instead by hardcoding the blocks mess directly.
287 $sql = "SELECT COALESCE(ctx.path, bctx.path) AS path, rc.capability, rc.permission
288 FROM {role_capabilities} rc
289 LEFT JOIN {context} ctx ON (ctx.id = rc.contextid AND ctx.contextlevel <= ".CONTEXT_COURSE.")
290 LEFT JOIN ({context} bctx
291 JOIN {block_instances} bi ON (bi.id = bctx.instanceid)
292 JOIN {context} pctx ON (pctx.id = bi.parentcontextid AND pctx.contextlevel < ".CONTEXT_COURSE.")
293 ) ON (bctx.id = rc.contextid AND bctx.contextlevel = ".CONTEXT_BLOCK.")
294 WHERE rc.roleid = :roleid AND (ctx.id IS NOT NULL OR bctx.id IS NOT NULL)";
295 $params = array('roleid'=>$roleid);
297 // we need extra caching in CLI scripts and cron
298 $rs = $DB->get_recordset_sql($sql, $params);
299 foreach ($rs as $rd) {
300 $k = "{$rd->path}:{$roleid}";
301 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
305 // share the role definitions
306 foreach ($accessdata['rdef'] as $k=>$unused) {
307 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
308 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
310 $accessdata['rdef_count']++;
311 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
318 * Get the default guest role, this is used for guest account,
319 * search engine spiders, etc.
321 * @return stdClass role record
323 function get_guest_role() {
326 if (empty($CFG->guestroleid)) {
327 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
328 $guestrole = array_shift($roles); // Pick the first one
329 set_config('guestroleid', $guestrole->id);
332 debugging('Can not find any guest role!');
336 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
339 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
340 set_config('guestroleid', '');
341 return get_guest_role();
347 * Check whether a user has a particular capability in a given context.
350 * $context = context_module::instance($cm->id);
351 * has_capability('mod/forum:replypost', $context)
353 * By default checks the capabilities of the current user, but you can pass a
354 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
356 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
357 * or capabilities with XSS, config or data loss risks.
361 * @param string $capability the name of the capability to check. For example mod/forum:view
362 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
363 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
364 * @param boolean $doanything If false, ignores effect of admin role assignment
365 * @return boolean true if the user has this capability. Otherwise false.
367 function has_capability($capability, context $context, $user = null, $doanything = true) {
368 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
370 if (during_initial_install()) {
371 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cli/install.php" or $SCRIPT === "/$CFG->admin/cli/install_database.php") {
372 // we are in an installer - roles can not work yet
379 if (strpos($capability, 'moodle/legacy:') === 0) {
380 throw new coding_exception('Legacy capabilities can not be used any more!');
383 if (!is_bool($doanything)) {
384 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
387 // capability must exist
388 if (!$capinfo = get_capability_info($capability)) {
389 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
393 if (!isset($USER->id)) {
394 // should never happen
396 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER);
399 // make sure there is a real user specified
400 if ($user === null) {
403 $userid = is_object($user) ? $user->id : $user;
406 // make sure forcelogin cuts off not-logged-in users if enabled
407 if (!empty($CFG->forcelogin) and $userid == 0) {
411 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
412 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
413 if (isguestuser($userid) or $userid == 0) {
418 // somehow make sure the user is not deleted and actually exists
420 if ($userid == $USER->id and isset($USER->deleted)) {
421 // this prevents one query per page, it is a bit of cheating,
422 // but hopefully session is terminated properly once user is deleted
423 if ($USER->deleted) {
427 if (!context_user::instance($userid, IGNORE_MISSING)) {
428 // no user context == invalid userid
434 // context path/depth must be valid
435 if (empty($context->path) or $context->depth == 0) {
436 // this should not happen often, each upgrade tries to rebuild the context paths
437 debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()');
438 if (is_siteadmin($userid)) {
445 // Find out if user is admin - it is not possible to override the doanything in any way
446 // and it is not possible to switch to admin role either.
448 if (is_siteadmin($userid)) {
449 if ($userid != $USER->id) {
452 // make sure switchrole is not used in this context
453 if (empty($USER->access['rsw'])) {
456 $parts = explode('/', trim($context->path, '/'));
459 foreach ($parts as $part) {
460 $path .= '/' . $part;
461 if (!empty($USER->access['rsw'][$path])) {
469 //ok, admin switched role in this context, let's use normal access control rules
473 // Careful check for staleness...
474 $context->reload_if_dirty();
476 if ($USER->id == $userid) {
477 if (!isset($USER->access)) {
478 load_all_capabilities();
480 $access =& $USER->access;
483 // make sure user accessdata is really loaded
484 get_user_accessdata($userid, true);
485 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
489 // Load accessdata for below-the-course context if necessary,
490 // all contexts at and above all courses are already loaded
491 if ($context->contextlevel != CONTEXT_COURSE and $coursecontext = $context->get_course_context(false)) {
492 load_course_context($userid, $coursecontext, $access);
495 return has_capability_in_accessdata($capability, $context, $access);
499 * Check if the user has any one of several capabilities from a list.
501 * This is just a utility method that calls has_capability in a loop. Try to put
502 * the capabilities that most users are likely to have first in the list for best
506 * @see has_capability()
508 * @param array $capabilities an array of capability names.
509 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
510 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
511 * @param boolean $doanything If false, ignore effect of admin role assignment
512 * @return boolean true if the user has any of these capabilities. Otherwise false.
514 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
515 foreach ($capabilities as $capability) {
516 if (has_capability($capability, $context, $user, $doanything)) {
524 * Check if the user has all the capabilities in a list.
526 * This is just a utility method that calls has_capability in a loop. Try to put
527 * the capabilities that fewest users are likely to have first in the list for best
531 * @see has_capability()
533 * @param array $capabilities an array of capability names.
534 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
535 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
536 * @param boolean $doanything If false, ignore effect of admin role assignment
537 * @return boolean true if the user has all of these capabilities. Otherwise false.
539 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
540 foreach ($capabilities as $capability) {
541 if (!has_capability($capability, $context, $user, $doanything)) {
549 * Is course creator going to have capability in a new course?
551 * This is intended to be used in enrolment plugins before or during course creation,
552 * do not use after the course is fully created.
556 * @param string $capability the name of the capability to check.
557 * @param context $context course or category context where is course going to be created
558 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
559 * @return boolean true if the user will have this capability.
561 * @throws coding_exception if different type of context submitted
563 function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) {
566 if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) {
567 throw new coding_exception('Only course or course category context expected');
570 if (has_capability($capability, $context, $user)) {
571 // User already has the capability, it could be only removed if CAP_PROHIBIT
572 // was involved here, but we ignore that.
576 if (!has_capability('moodle/course:create', $context, $user)) {
580 if (!enrol_is_enabled('manual')) {
584 if (empty($CFG->creatornewroleid)) {
588 if ($context->contextlevel == CONTEXT_COURSE) {
589 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
593 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
598 // Most likely they will be enrolled after the course creation is finished,
599 // does the new role have the required capability?
600 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
601 return isset($neededroles[$CFG->creatornewroleid]);
605 * Check if the user is an admin at the site level.
607 * Please note that use of proper capabilities is always encouraged,
608 * this function is supposed to be used from core or for temporary hacks.
612 * @param int|stdClass $user_or_id user id or user object
613 * @return bool true if user is one of the administrators, false otherwise
615 function is_siteadmin($user_or_id = null) {
618 if ($user_or_id === null) {
622 if (empty($user_or_id)) {
625 if (!empty($user_or_id->id)) {
626 $userid = $user_or_id->id;
628 $userid = $user_or_id;
631 // Because this script is called many times (150+ for course page) with
632 // the same parameters, it is worth doing minor optimisations. This static
633 // cache stores the value for a single userid, saving about 2ms from course
634 // page load time without using significant memory. As the static cache
635 // also includes the value it depends on, this cannot break unit tests.
636 static $knownid, $knownresult, $knownsiteadmins;
637 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
641 $knownsiteadmins = $CFG->siteadmins;
643 $siteadmins = explode(',', $CFG->siteadmins);
644 $knownresult = in_array($userid, $siteadmins);
649 * Returns true if user has at least one role assign
650 * of 'coursecontact' role (is potentially listed in some course descriptions).
655 function has_coursecontact_role($userid) {
658 if (empty($CFG->coursecontact)) {
662 FROM {role_assignments}
663 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
664 return $DB->record_exists_sql($sql, array('userid'=>$userid));
668 * Does the user have a capability to do something?
670 * Walk the accessdata array and return true/false.
671 * Deals with prohibits, role switching, aggregating
674 * The main feature of here is being FAST and with no
679 * Switch Role merges with default role
680 * ------------------------------------
681 * If you are a teacher in course X, you have at least
682 * teacher-in-X + defaultloggedinuser-sitewide. So in the
683 * course you'll have techer+defaultloggedinuser.
684 * We try to mimic that in switchrole.
686 * Permission evaluation
687 * ---------------------
688 * Originally there was an extremely complicated way
689 * to determine the user access that dealt with
690 * "locality" or role assignments and role overrides.
691 * Now we simply evaluate access for each role separately
692 * and then verify if user has at least one role with allow
693 * and at the same time no role with prohibit.
696 * @param string $capability
697 * @param context $context
698 * @param array $accessdata
701 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
704 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
705 $path = $context->path;
706 $paths = array($path);
707 while($path = rtrim($path, '0123456789')) {
708 $path = rtrim($path, '/');
716 $switchedrole = false;
718 // Find out if role switched
719 if (!empty($accessdata['rsw'])) {
720 // From the bottom up...
721 foreach ($paths as $path) {
722 if (isset($accessdata['rsw'][$path])) {
723 // Found a switchrole assignment - check for that role _plus_ the default user role
724 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
725 $switchedrole = true;
731 if (!$switchedrole) {
732 // get all users roles in this context and above
733 foreach ($paths as $path) {
734 if (isset($accessdata['ra'][$path])) {
735 foreach ($accessdata['ra'][$path] as $roleid) {
736 $roles[$roleid] = null;
742 // Now find out what access is given to each role, going bottom-->up direction
744 foreach ($roles as $roleid => $ignored) {
745 foreach ($paths as $path) {
746 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
747 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
748 if ($perm === CAP_PROHIBIT) {
749 // any CAP_PROHIBIT found means no permission for the user
752 if (is_null($roles[$roleid])) {
753 $roles[$roleid] = $perm;
757 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
758 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
765 * A convenience function that tests has_capability, and displays an error if
766 * the user does not have that capability.
768 * NOTE before Moodle 2.0, this function attempted to make an appropriate
769 * require_login call before checking the capability. This is no longer the case.
770 * You must call require_login (or one of its variants) if you want to check the
771 * user is logged in, before you call this function.
773 * @see has_capability()
775 * @param string $capability the name of the capability to check. For example mod/forum:view
776 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
777 * @param int $userid A user id. By default (null) checks the permissions of the current user.
778 * @param bool $doanything If false, ignore effect of admin role assignment
779 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
780 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
781 * @return void terminates with an error if the user does not have the given capability.
783 function require_capability($capability, context $context, $userid = null, $doanything = true,
784 $errormessage = 'nopermissions', $stringfile = '') {
785 if (!has_capability($capability, $context, $userid, $doanything)) {
786 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
791 * Return a nested array showing role assignments
792 * all relevant role capabilities for the user at
793 * site/course_category/course levels
795 * We do _not_ delve deeper than courses because the number of
796 * overrides at the module/block levels can be HUGE.
798 * [ra] => [/path][roleid]=roleid
799 * [rdef] => [/path:roleid][capability]=permission
802 * @param int $userid - the id of the user
803 * @return array access info array
805 function get_user_access_sitewide($userid) {
806 global $CFG, $DB, $ACCESSLIB_PRIVATE;
808 /* Get in a few cheap DB queries...
810 * - relevant role caps
811 * - above and within this user's RAs
812 * - below this user's RAs - limited to course level
815 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
816 $raparents = array();
817 $accessdata = get_empty_accessdata();
819 // start with the default role
820 if (!empty($CFG->defaultuserroleid)) {
821 $syscontext = context_system::instance();
822 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
823 $raparents[$CFG->defaultuserroleid][$syscontext->id] = $syscontext->id;
826 // load the "default frontpage role"
827 if (!empty($CFG->defaultfrontpageroleid)) {
828 $frontpagecontext = context_course::instance(get_site()->id);
829 if ($frontpagecontext->path) {
830 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
831 $raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->id] = $frontpagecontext->id;
835 // preload every assigned role at and above course context
836 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
837 FROM {role_assignments} ra
839 ON ctx.id = ra.contextid
840 LEFT JOIN {block_instances} bi
841 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
842 LEFT JOIN {context} bpctx
843 ON (bpctx.id = bi.parentcontextid)
844 WHERE ra.userid = :userid
845 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")";
846 $params = array('userid'=>$userid);
847 $rs = $DB->get_recordset_sql($sql, $params);
848 foreach ($rs as $ra) {
849 // RAs leafs are arrays to support multi-role assignments...
850 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
851 $raparents[$ra->roleid][$ra->contextid] = $ra->contextid;
855 if (empty($raparents)) {
859 // now get overrides of interesting roles in all interesting child contexts
860 // hopefully we will not run out of SQL limits here,
861 // users would have to have very many roles at/above course context...
866 foreach ($raparents as $roleid=>$ras) {
868 list($sqlcids, $cids) = $DB->get_in_or_equal($ras, SQL_PARAMS_NAMED, 'c'.$cp.'_');
869 $params = array_merge($params, $cids);
870 $params['r'.$cp] = $roleid;
871 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
872 FROM {role_capabilities} rc
874 ON (ctx.id = rc.contextid)
877 AND (ctx.id = pctx.id
878 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
879 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
880 LEFT JOIN {block_instances} bi
881 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
882 LEFT JOIN {context} bpctx
883 ON (bpctx.id = bi.parentcontextid)
884 WHERE rc.roleid = :r{$cp}
885 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")
889 // fixed capability order is necessary for rdef dedupe
890 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
892 foreach ($rs as $rd) {
893 $k = $rd->path.':'.$rd->roleid;
894 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
898 // share the role definitions
899 foreach ($accessdata['rdef'] as $k=>$unused) {
900 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
901 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
903 $accessdata['rdef_count']++;
904 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
911 * Add to the access ctrl array the data needed by a user for a given course.
913 * This function injects all course related access info into the accessdata array.
916 * @param int $userid the id of the user
917 * @param context_course $coursecontext course context
918 * @param array $accessdata accessdata array (modified)
919 * @return void modifies $accessdata parameter
921 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
922 global $DB, $CFG, $ACCESSLIB_PRIVATE;
924 if (empty($coursecontext->path)) {
925 // weird, this should not happen
929 if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
930 // already loaded, great!
936 if (empty($userid)) {
937 if (!empty($CFG->notloggedinroleid)) {
938 $roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
941 } else if (isguestuser($userid)) {
942 if ($guestrole = get_guest_role()) {
943 $roles[$guestrole->id] = $guestrole->id;
947 // Interesting role assignments at, above and below the course context
948 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
949 $params['userid'] = $userid;
950 $params['children'] = $coursecontext->path."/%";
951 $sql = "SELECT ra.*, ctx.path
952 FROM {role_assignments} ra
953 JOIN {context} ctx ON ra.contextid = ctx.id
954 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
955 $rs = $DB->get_recordset_sql($sql, $params);
957 // add missing role definitions
958 foreach ($rs as $ra) {
959 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
960 $roles[$ra->roleid] = $ra->roleid;
964 // add the "default frontpage role" when on the frontpage
965 if (!empty($CFG->defaultfrontpageroleid)) {
966 $frontpagecontext = context_course::instance(get_site()->id);
967 if ($frontpagecontext->id == $coursecontext->id) {
968 $roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
972 // do not forget the default role
973 if (!empty($CFG->defaultuserroleid)) {
974 $roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
979 // weird, default roles must be missing...
980 $accessdata['loaded'][$coursecontext->instanceid] = 1;
984 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
985 $params = array('c'=>$coursecontext->id);
986 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
987 $params = array_merge($params, $rparams);
988 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
989 $params = array_merge($params, $rparams);
991 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
992 FROM {role_capabilities} rc
994 ON (ctx.id = rc.contextid)
997 AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
998 WHERE rc.roleid $roleids
999 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
1000 $rs = $DB->get_recordset_sql($sql, $params);
1002 $newrdefs = array();
1003 foreach ($rs as $rd) {
1004 $k = $rd->path.':'.$rd->roleid;
1005 if (isset($accessdata['rdef'][$k])) {
1008 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
1012 // share new role definitions
1013 foreach ($newrdefs as $k=>$unused) {
1014 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
1015 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
1017 $accessdata['rdef_count']++;
1018 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1021 $accessdata['loaded'][$coursecontext->instanceid] = 1;
1023 // we want to deduplicate the USER->access from time to time, this looks like a good place,
1024 // because we have to do it before the end of session
1025 dedupe_user_access();
1029 * Add to the access ctrl array the data needed by a role for a given context.
1031 * The data is added in the rdef key.
1032 * This role-centric function is useful for role_switching
1033 * and temporary course roles.
1036 * @param int $roleid the id of the user
1037 * @param context $context needs path!
1038 * @param array $accessdata accessdata array (is modified)
1041 function load_role_access_by_context($roleid, context $context, &$accessdata) {
1042 global $DB, $ACCESSLIB_PRIVATE;
1044 /* Get the relevant rolecaps into rdef
1045 * - relevant role caps
1046 * - at ctx and above
1050 if (empty($context->path)) {
1051 // weird, this should not happen
1055 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
1056 $params['roleid'] = $roleid;
1057 $params['childpath'] = $context->path.'/%';
1059 $sql = "SELECT ctx.path, rc.capability, rc.permission
1060 FROM {role_capabilities} rc
1061 JOIN {context} ctx ON (rc.contextid = ctx.id)
1062 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
1063 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
1064 $rs = $DB->get_recordset_sql($sql, $params);
1066 $newrdefs = array();
1067 foreach ($rs as $rd) {
1068 $k = $rd->path.':'.$roleid;
1069 if (isset($accessdata['rdef'][$k])) {
1072 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
1076 // share new role definitions
1077 foreach ($newrdefs as $k=>$unused) {
1078 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
1079 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
1081 $accessdata['rdef_count']++;
1082 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1087 * Returns empty accessdata structure.
1090 * @return array empt accessdata
1092 function get_empty_accessdata() {
1093 $accessdata = array(); // named list
1094 $accessdata['ra'] = array();
1095 $accessdata['rdef'] = array();
1096 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
1097 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
1098 $accessdata['loaded'] = array(); // loaded course contexts
1099 $accessdata['time'] = time();
1100 $accessdata['rsw'] = array();
1106 * Get accessdata for a given user.
1109 * @param int $userid
1110 * @param bool $preloadonly true means do not return access array
1111 * @return array accessdata
1113 function get_user_accessdata($userid, $preloadonly=false) {
1114 global $CFG, $ACCESSLIB_PRIVATE, $USER;
1116 if (!empty($USER->access['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1117 // share rdef from USER session with rolepermissions cache in order to conserve memory
1118 foreach ($USER->access['rdef'] as $k=>$v) {
1119 $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->access['rdef'][$k];
1121 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->access;
1124 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
1125 if (empty($userid)) {
1126 if (!empty($CFG->notloggedinroleid)) {
1127 $accessdata = get_role_access($CFG->notloggedinroleid);
1130 return get_empty_accessdata();
1133 } else if (isguestuser($userid)) {
1134 if ($guestrole = get_guest_role()) {
1135 $accessdata = get_role_access($guestrole->id);
1138 return get_empty_accessdata();
1142 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1145 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1151 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1156 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1157 * this function looks for contexts with the same overrides and shares them.
1162 function dedupe_user_access() {
1166 // no session in CLI --> no compression necessary
1170 if (empty($USER->access['rdef_count'])) {
1171 // weird, this should not happen
1175 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1176 if ($USER->access['rdef_count'] - $USER->access['rdef_lcc'] > 10) {
1177 // do not compress after each change, wait till there is more stuff to be done
1182 foreach ($USER->access['rdef'] as $k=>$def) {
1183 $hash = sha1(serialize($def));
1184 if (isset($hashmap[$hash])) {
1185 $USER->access['rdef'][$k] =& $hashmap[$hash];
1187 $hashmap[$hash] =& $USER->access['rdef'][$k];
1191 $USER->access['rdef_lcc'] = $USER->access['rdef_count'];
1195 * A convenience function to completely load all the capabilities
1196 * for the current user. It is called from has_capability() and functions change permissions.
1198 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1199 * @see check_enrolment_plugins()
1204 function load_all_capabilities() {
1207 // roles not installed yet - we are in the middle of installation
1208 if (during_initial_install()) {
1212 if (!isset($USER->id)) {
1213 // this should not happen
1217 unset($USER->access);
1218 $USER->access = get_user_accessdata($USER->id);
1220 // deduplicate the overrides to minimize session size
1221 dedupe_user_access();
1223 // Clear to force a refresh
1224 unset($USER->mycourses);
1226 // init/reset internal enrol caches - active course enrolments and temp access
1227 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1231 * A convenience function to completely reload all the capabilities
1232 * for the current user when roles have been updated in a relevant
1233 * context -- but PRESERVING switchroles and loginas.
1234 * This function resets all accesslib and context caches.
1236 * That is - completely transparent to the user.
1238 * Note: reloads $USER->access completely.
1243 function reload_all_capabilities() {
1244 global $USER, $DB, $ACCESSLIB_PRIVATE;
1248 if (!empty($USER->access['rsw'])) {
1249 $sw = $USER->access['rsw'];
1252 accesslib_clear_all_caches(true);
1253 unset($USER->access);
1254 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
1256 load_all_capabilities();
1258 foreach ($sw as $path => $roleid) {
1259 if ($record = $DB->get_record('context', array('path'=>$path))) {
1260 $context = context::instance_by_id($record->id);
1261 role_switch($roleid, $context);
1267 * Adds a temp role to current USER->access array.
1269 * Useful for the "temporary guest" access we grant to logged-in users.
1270 * This is useful for enrol plugins only.
1273 * @param context_course $coursecontext
1274 * @param int $roleid
1277 function load_temp_course_role(context_course $coursecontext, $roleid) {
1278 global $USER, $SITE;
1280 if (empty($roleid)) {
1281 debugging('invalid role specified in load_temp_course_role()');
1285 if ($coursecontext->instanceid == $SITE->id) {
1286 debugging('Can not use temp roles on the frontpage');
1290 if (!isset($USER->access)) {
1291 load_all_capabilities();
1294 $coursecontext->reload_if_dirty();
1296 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1300 // load course stuff first
1301 load_course_context($USER->id, $coursecontext, $USER->access);
1303 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1305 load_role_access_by_context($roleid, $coursecontext, $USER->access);
1309 * Removes any extra guest roles from current USER->access array.
1310 * This is useful for enrol plugins only.
1313 * @param context_course $coursecontext
1316 function remove_temp_course_roles(context_course $coursecontext) {
1317 global $DB, $USER, $SITE;
1319 if ($coursecontext->instanceid == $SITE->id) {
1320 debugging('Can not use temp roles on the frontpage');
1324 if (empty($USER->access['ra'][$coursecontext->path])) {
1325 //no roles here, weird
1329 $sql = "SELECT DISTINCT ra.roleid AS id
1330 FROM {role_assignments} ra
1331 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1332 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1334 $USER->access['ra'][$coursecontext->path] = array();
1335 foreach($ras as $r) {
1336 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1341 * Returns array of all role archetypes.
1345 function get_role_archetypes() {
1347 'manager' => 'manager',
1348 'coursecreator' => 'coursecreator',
1349 'editingteacher' => 'editingteacher',
1350 'teacher' => 'teacher',
1351 'student' => 'student',
1354 'frontpage' => 'frontpage'
1359 * Assign the defaults found in this capability definition to roles that have
1360 * the corresponding legacy capabilities assigned to them.
1362 * @param string $capability
1363 * @param array $legacyperms an array in the format (example):
1364 * 'guest' => CAP_PREVENT,
1365 * 'student' => CAP_ALLOW,
1366 * 'teacher' => CAP_ALLOW,
1367 * 'editingteacher' => CAP_ALLOW,
1368 * 'coursecreator' => CAP_ALLOW,
1369 * 'manager' => CAP_ALLOW
1370 * @return boolean success or failure.
1372 function assign_legacy_capabilities($capability, $legacyperms) {
1374 $archetypes = get_role_archetypes();
1376 foreach ($legacyperms as $type => $perm) {
1378 $systemcontext = context_system::instance();
1379 if ($type === 'admin') {
1380 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1384 if (!array_key_exists($type, $archetypes)) {
1385 print_error('invalidlegacy', '', '', $type);
1388 if ($roles = get_archetype_roles($type)) {
1389 foreach ($roles as $role) {
1390 // Assign a site level capability.
1391 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1401 * Verify capability risks.
1403 * @param stdClass $capability a capability - a row from the capabilities table.
1404 * @return boolean whether this capability is safe - that is, whether people with the
1405 * safeoverrides capability should be allowed to change it.
1407 function is_safe_capability($capability) {
1408 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1412 * Get the local override (if any) for a given capability in a role in a context
1414 * @param int $roleid
1415 * @param int $contextid
1416 * @param string $capability
1417 * @return stdClass local capability override
1419 function get_local_override($roleid, $contextid, $capability) {
1421 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1425 * Returns context instance plus related course and cm instances
1427 * @param int $contextid
1428 * @return array of ($context, $course, $cm)
1430 function get_context_info_array($contextid) {
1433 $context = context::instance_by_id($contextid, MUST_EXIST);
1437 if ($context->contextlevel == CONTEXT_COURSE) {
1438 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1440 } else if ($context->contextlevel == CONTEXT_MODULE) {
1441 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1442 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1444 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1445 $parent = $context->get_parent_context();
1447 if ($parent->contextlevel == CONTEXT_COURSE) {
1448 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1449 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1450 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1451 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1455 return array($context, $course, $cm);
1459 * Function that creates a role
1461 * @param string $name role name
1462 * @param string $shortname role short name
1463 * @param string $description role description
1464 * @param string $archetype
1465 * @return int id or dml_exception
1467 function create_role($name, $shortname, $description, $archetype = '') {
1470 if (strpos($archetype, 'moodle/legacy:') !== false) {
1471 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1474 // verify role archetype actually exists
1475 $archetypes = get_role_archetypes();
1476 if (empty($archetypes[$archetype])) {
1480 // Insert the role record.
1481 $role = new stdClass();
1482 $role->name = $name;
1483 $role->shortname = $shortname;
1484 $role->description = $description;
1485 $role->archetype = $archetype;
1487 //find free sortorder number
1488 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1489 if (empty($role->sortorder)) {
1490 $role->sortorder = 1;
1492 $id = $DB->insert_record('role', $role);
1498 * Function that deletes a role and cleanups up after it
1500 * @param int $roleid id of role to delete
1501 * @return bool always true
1503 function delete_role($roleid) {
1506 // first unssign all users
1507 role_unassign_all(array('roleid'=>$roleid));
1509 // cleanup all references to this role, ignore errors
1510 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1511 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1512 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1513 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1514 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1515 $DB->delete_records('role_names', array('roleid'=>$roleid));
1516 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1518 // Get role record before it's deleted.
1519 $role = $DB->get_record('role', array('id'=>$roleid));
1521 // Finally delete the role itself.
1522 $DB->delete_records('role', array('id'=>$roleid));
1525 $event = \core\event\role_deleted::create(
1527 'context' => context_system::instance(),
1528 'objectid' => $roleid,
1531 'shortname' => $role->shortname,
1532 'description' => $role->description,
1533 'archetype' => $role->archetype
1537 $event->add_record_snapshot('role', $role);
1544 * Function to write context specific overrides, or default capabilities.
1546 * NOTE: use $context->mark_dirty() after this
1548 * @param string $capability string name
1549 * @param int $permission CAP_ constants
1550 * @param int $roleid role id
1551 * @param int|context $contextid context id
1552 * @param bool $overwrite
1553 * @return bool always true or exception
1555 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1558 if ($contextid instanceof context) {
1559 $context = $contextid;
1561 $context = context::instance_by_id($contextid);
1564 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1565 unassign_capability($capability, $roleid, $context->id);
1569 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1571 if ($existing and !$overwrite) { // We want to keep whatever is there already
1575 $cap = new stdClass();
1576 $cap->contextid = $context->id;
1577 $cap->roleid = $roleid;
1578 $cap->capability = $capability;
1579 $cap->permission = $permission;
1580 $cap->timemodified = time();
1581 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1584 $cap->id = $existing->id;
1585 $DB->update_record('role_capabilities', $cap);
1587 if ($DB->record_exists('context', array('id'=>$context->id))) {
1588 $DB->insert_record('role_capabilities', $cap);
1595 * Unassign a capability from a role.
1597 * NOTE: use $context->mark_dirty() after this
1599 * @param string $capability the name of the capability
1600 * @param int $roleid the role id
1601 * @param int|context $contextid null means all contexts
1602 * @return boolean true or exception
1604 function unassign_capability($capability, $roleid, $contextid = null) {
1607 if (!empty($contextid)) {
1608 if ($contextid instanceof context) {
1609 $context = $contextid;
1611 $context = context::instance_by_id($contextid);
1613 // delete from context rel, if this is the last override in this context
1614 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1616 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1622 * Get the roles that have a given capability assigned to it
1624 * This function does not resolve the actual permission of the capability.
1625 * It just checks for permissions and overrides.
1626 * Use get_roles_with_cap_in_context() if resolution is required.
1628 * @param string $capability capability name (string)
1629 * @param string $permission optional, the permission defined for this capability
1630 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1631 * @param stdClass $context null means any
1632 * @return array of role records
1634 function get_roles_with_capability($capability, $permission = null, $context = null) {
1638 $contexts = $context->get_parent_context_ids(true);
1639 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1640 $contextsql = "AND rc.contextid $insql";
1647 $permissionsql = " AND rc.permission = :permission";
1648 $params['permission'] = $permission;
1650 $permissionsql = '';
1655 WHERE r.id IN (SELECT rc.roleid
1656 FROM {role_capabilities} rc
1657 WHERE rc.capability = :capname
1660 $params['capname'] = $capability;
1663 return $DB->get_records_sql($sql, $params);
1667 * This function makes a role-assignment (a role for a user in a particular context)
1669 * @param int $roleid the role of the id
1670 * @param int $userid userid
1671 * @param int|context $contextid id of the context
1672 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1673 * @param int $itemid id of enrolment/auth plugin
1674 * @param string $timemodified defaults to current time
1675 * @return int new/existing id of the assignment
1677 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1680 // first of all detect if somebody is using old style parameters
1681 if ($contextid === 0 or is_numeric($component)) {
1682 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1685 // now validate all parameters
1686 if (empty($roleid)) {
1687 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1690 if (empty($userid)) {
1691 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1695 if (strpos($component, '_') === false) {
1696 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1700 if ($component !== '' and strpos($component, '_') === false) {
1701 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1705 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1706 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1709 if ($contextid instanceof context) {
1710 $context = $contextid;
1712 $context = context::instance_by_id($contextid, MUST_EXIST);
1715 if (!$timemodified) {
1716 $timemodified = time();
1719 // Check for existing entry
1720 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1723 // role already assigned - this should not happen
1724 if (count($ras) > 1) {
1725 // very weird - remove all duplicates!
1726 $ra = array_shift($ras);
1727 foreach ($ras as $r) {
1728 $DB->delete_records('role_assignments', array('id'=>$r->id));
1734 // actually there is no need to update, reset anything or trigger any event, so just return
1738 // Create a new entry
1739 $ra = new stdClass();
1740 $ra->roleid = $roleid;
1741 $ra->contextid = $context->id;
1742 $ra->userid = $userid;
1743 $ra->component = $component;
1744 $ra->itemid = $itemid;
1745 $ra->timemodified = $timemodified;
1746 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1749 $ra->id = $DB->insert_record('role_assignments', $ra);
1751 // mark context as dirty - again expensive, but needed
1752 $context->mark_dirty();
1754 if (!empty($USER->id) && $USER->id == $userid) {
1755 // If the user is the current user, then do full reload of capabilities too.
1756 reload_all_capabilities();
1759 $event = \core\event\role_assigned::create(array(
1760 'context' => $context,
1761 'objectid' => $ra->roleid,
1762 'relateduserid' => $ra->userid,
1765 'component' => $ra->component,
1766 'itemid' => $ra->itemid
1769 $event->add_record_snapshot('role_assignments', $ra);
1776 * Removes one role assignment
1778 * @param int $roleid
1779 * @param int $userid
1780 * @param int $contextid
1781 * @param string $component
1782 * @param int $itemid
1785 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1786 // first make sure the params make sense
1787 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1788 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1792 if (strpos($component, '_') === false) {
1793 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1797 if ($component !== '' and strpos($component, '_') === false) {
1798 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1802 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1806 * Removes multiple role assignments, parameters may contain:
1807 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1809 * @param array $params role assignment parameters
1810 * @param bool $subcontexts unassign in subcontexts too
1811 * @param bool $includemanual include manual role assignments too
1814 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1815 global $USER, $CFG, $DB;
1818 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1821 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1822 foreach ($params as $key=>$value) {
1823 if (!in_array($key, $allowed)) {
1824 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1828 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1829 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1832 if ($includemanual) {
1833 if (!isset($params['component']) or $params['component'] === '') {
1834 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1839 if (empty($params['contextid'])) {
1840 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1844 $ras = $DB->get_records('role_assignments', $params);
1845 foreach($ras as $ra) {
1846 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1847 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1848 // this is a bit expensive but necessary
1849 $context->mark_dirty();
1850 // If the user is the current user, then do full reload of capabilities too.
1851 if (!empty($USER->id) && $USER->id == $ra->userid) {
1852 reload_all_capabilities();
1854 $event = \core\event\role_unassigned::create(array(
1855 'context' => $context,
1856 'objectid' => $ra->roleid,
1857 'relateduserid' => $ra->userid,
1860 'component' => $ra->component,
1861 'itemid' => $ra->itemid
1864 $event->add_record_snapshot('role_assignments', $ra);
1870 // process subcontexts
1871 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1872 if ($params['contextid'] instanceof context) {
1873 $context = $params['contextid'];
1875 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1879 $contexts = $context->get_child_contexts();
1881 foreach($contexts as $context) {
1882 $mparams['contextid'] = $context->id;
1883 $ras = $DB->get_records('role_assignments', $mparams);
1884 foreach($ras as $ra) {
1885 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1886 // this is a bit expensive but necessary
1887 $context->mark_dirty();
1888 // If the user is the current user, then do full reload of capabilities too.
1889 if (!empty($USER->id) && $USER->id == $ra->userid) {
1890 reload_all_capabilities();
1892 $event = \core\event\role_unassigned::create(
1893 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1894 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1895 $event->add_record_snapshot('role_assignments', $ra);
1902 // do this once more for all manual role assignments
1903 if ($includemanual) {
1904 $params['component'] = '';
1905 role_unassign_all($params, $subcontexts, false);
1910 * Determines if a user is currently logged in
1916 function isloggedin() {
1919 return (!empty($USER->id));
1923 * Determines if a user is logged in as real guest user with username 'guest'.
1927 * @param int|object $user mixed user object or id, $USER if not specified
1928 * @return bool true if user is the real guest user, false if not logged in or other user
1930 function isguestuser($user = null) {
1931 global $USER, $DB, $CFG;
1933 // make sure we have the user id cached in config table, because we are going to use it a lot
1934 if (empty($CFG->siteguest)) {
1935 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1936 // guest does not exist yet, weird
1939 set_config('siteguest', $guestid);
1941 if ($user === null) {
1945 if ($user === null) {
1946 // happens when setting the $USER
1949 } else if (is_numeric($user)) {
1950 return ($CFG->siteguest == $user);
1952 } else if (is_object($user)) {
1953 if (empty($user->id)) {
1954 return false; // not logged in means is not be guest
1956 return ($CFG->siteguest == $user->id);
1960 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1965 * Does user have a (temporary or real) guest access to course?
1969 * @param context $context
1970 * @param stdClass|int $user
1973 function is_guest(context $context, $user = null) {
1976 // first find the course context
1977 $coursecontext = $context->get_course_context();
1979 // make sure there is a real user specified
1980 if ($user === null) {
1981 $userid = isset($USER->id) ? $USER->id : 0;
1983 $userid = is_object($user) ? $user->id : $user;
1986 if (isguestuser($userid)) {
1987 // can not inspect or be enrolled
1991 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1992 // viewing users appear out of nowhere, they are neither guests nor participants
1996 // consider only real active enrolments here
1997 if (is_enrolled($coursecontext, $user, '', true)) {
2005 * Returns true if the user has moodle/course:view capability in the course,
2006 * this is intended for admins, managers (aka small admins), inspectors, etc.
2010 * @param context $context
2011 * @param int|stdClass $user if null $USER is used
2012 * @param string $withcapability extra capability name
2015 function is_viewing(context $context, $user = null, $withcapability = '') {
2016 // first find the course context
2017 $coursecontext = $context->get_course_context();
2019 if (isguestuser($user)) {
2024 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
2025 // admins are allowed to inspect courses
2029 if ($withcapability and !has_capability($withcapability, $context, $user)) {
2030 // site admins always have the capability, but the enrolment above blocks
2038 * Returns true if user is enrolled (is participating) in course
2039 * this is intended for students and teachers.
2041 * Since 2.2 the result for active enrolments and current user are cached.
2043 * @package core_enrol
2046 * @param context $context
2047 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
2048 * @param string $withcapability extra capability name
2049 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2052 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
2055 // first find the course context
2056 $coursecontext = $context->get_course_context();
2058 // make sure there is a real user specified
2059 if ($user === null) {
2060 $userid = isset($USER->id) ? $USER->id : 0;
2062 $userid = is_object($user) ? $user->id : $user;
2065 if (empty($userid)) {
2068 } else if (isguestuser($userid)) {
2069 // guest account can not be enrolled anywhere
2073 if ($coursecontext->instanceid == SITEID) {
2074 // everybody participates on frontpage
2076 // try cached info first - the enrolled flag is set only when active enrolment present
2077 if ($USER->id == $userid) {
2078 $coursecontext->reload_if_dirty();
2079 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
2080 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
2081 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2090 // look for active enrolments only
2091 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
2093 if ($until === false) {
2097 if ($USER->id == $userid) {
2099 $until = ENROL_MAX_TIMESTAMP;
2101 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
2102 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
2103 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
2104 remove_temp_course_roles($coursecontext);
2109 // any enrolment is good for us here, even outdated, disabled or inactive
2111 FROM {user_enrolments} ue
2112 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2113 JOIN {user} u ON u.id = ue.userid
2114 WHERE ue.userid = :userid AND u.deleted = 0";
2115 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2116 if (!$DB->record_exists_sql($sql, $params)) {
2122 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2130 * Returns true if the user is able to access the course.
2132 * This function is in no way, shape, or form a substitute for require_login.
2133 * It should only be used in circumstances where it is not possible to call require_login
2134 * such as the navigation.
2136 * This function checks many of the methods of access to a course such as the view
2137 * capability, enrollments, and guest access. It also makes use of the cache
2138 * generated by require_login for guest access.
2140 * The flags within the $USER object that are used here should NEVER be used outside
2141 * of this function can_access_course and require_login. Doing so WILL break future
2144 * @param stdClass $course record
2145 * @param stdClass|int|null $user user record or id, current user if null
2146 * @param string $withcapability Check for this capability as well.
2147 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2148 * @return boolean Returns true if the user is able to access the course
2150 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
2153 // this function originally accepted $coursecontext parameter
2154 if ($course instanceof context) {
2155 if ($course instanceof context_course) {
2156 debugging('deprecated context parameter, please use $course record');
2157 $coursecontext = $course;
2158 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2160 debugging('Invalid context parameter, please use $course record');
2164 $coursecontext = context_course::instance($course->id);
2167 if (!isset($USER->id)) {
2168 // should never happen
2170 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
2173 // make sure there is a user specified
2174 if ($user === null) {
2175 $userid = $USER->id;
2177 $userid = is_object($user) ? $user->id : $user;
2181 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2185 if ($userid == $USER->id) {
2186 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2187 // the fact that somebody switched role means they can access the course no matter to what role they switched
2192 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2196 if (is_viewing($coursecontext, $userid)) {
2200 if ($userid != $USER->id) {
2201 // for performance reasons we do not verify temporary guest access for other users, sorry...
2202 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2205 // === from here we deal only with $USER ===
2207 $coursecontext->reload_if_dirty();
2209 if (isset($USER->enrol['enrolled'][$course->id])) {
2210 if ($USER->enrol['enrolled'][$course->id] > time()) {
2214 if (isset($USER->enrol['tempguest'][$course->id])) {
2215 if ($USER->enrol['tempguest'][$course->id] > time()) {
2220 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2224 // if not enrolled try to gain temporary guest access
2225 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2226 $enrols = enrol_get_plugins(true);
2227 foreach($instances as $instance) {
2228 if (!isset($enrols[$instance->enrol])) {
2231 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2232 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2233 if ($until !== false and $until > time()) {
2234 $USER->enrol['tempguest'][$course->id] = $until;
2238 if (isset($USER->enrol['tempguest'][$course->id])) {
2239 unset($USER->enrol['tempguest'][$course->id]);
2240 remove_temp_course_roles($coursecontext);
2247 * Returns array with sql code and parameters returning all ids
2248 * of users enrolled into course.
2250 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2252 * @package core_enrol
2255 * @param context $context
2256 * @param string $withcapability
2257 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2258 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2259 * @return array list($sql, $params)
2261 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2264 // use unique prefix just in case somebody makes some SQL magic with the result
2267 $prefix = 'eu'.$i.'_';
2269 // first find the course context
2270 $coursecontext = $context->get_course_context();
2272 $isfrontpage = ($coursecontext->instanceid == SITEID);
2278 list($contextids, $contextpaths) = get_context_info_list($context);
2280 // get all relevant capability info for all roles
2281 if ($withcapability) {
2282 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2283 $cparams['cap'] = $withcapability;
2286 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2287 FROM {role_capabilities} rc
2288 JOIN {context} ctx on rc.contextid = ctx.id
2289 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2290 $rcs = $DB->get_records_sql($sql, $cparams);
2291 foreach ($rcs as $rc) {
2292 $defs[$rc->path][$rc->roleid] = $rc->permission;
2296 if (!empty($defs)) {
2297 foreach ($contextpaths as $path) {
2298 if (empty($defs[$path])) {
2301 foreach($defs[$path] as $roleid => $perm) {
2302 if ($perm == CAP_PROHIBIT) {
2303 $access[$roleid] = CAP_PROHIBIT;
2306 if (!isset($access[$roleid])) {
2307 $access[$roleid] = (int)$perm;
2315 // make lists of roles that are needed and prohibited
2316 $needed = array(); // one of these is enough
2317 $prohibited = array(); // must not have any of these
2318 foreach ($access as $roleid => $perm) {
2319 if ($perm == CAP_PROHIBIT) {
2320 unset($needed[$roleid]);
2321 $prohibited[$roleid] = true;
2322 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2323 $needed[$roleid] = true;
2327 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2328 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2333 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2335 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2336 // everybody not having prohibit has the capability
2338 } else if (empty($needed)) {
2342 if (!empty($prohibited[$defaultuserroleid])) {
2344 } else if (!empty($needed[$defaultuserroleid])) {
2345 // everybody not having prohibit has the capability
2347 } else if (empty($needed)) {
2353 // nobody can match so return some SQL that does not return any results
2354 $wheres[] = "1 = 2";
2359 $ctxids = implode(',', $contextids);
2360 $roleids = implode(',', array_keys($needed));
2361 $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))";
2365 $ctxids = implode(',', $contextids);
2366 $roleids = implode(',', array_keys($prohibited));
2367 $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))";
2368 $wheres[] = "{$prefix}ra4.id IS NULL";
2372 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2373 $params["{$prefix}gmid"] = $groupid;
2379 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2380 $params["{$prefix}gmid"] = $groupid;
2384 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2385 $params["{$prefix}guestid"] = $CFG->siteguest;
2388 // all users are "enrolled" on the frontpage
2390 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2391 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2392 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2395 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2396 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2397 $now = round(time(), -2); // rounding helps caching in DB
2398 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2399 $prefix.'active'=>ENROL_USER_ACTIVE,
2400 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2404 $joins = implode("\n", $joins);
2405 $wheres = "WHERE ".implode(" AND ", $wheres);
2407 $sql = "SELECT DISTINCT {$prefix}u.id
2408 FROM {user} {$prefix}u
2412 return array($sql, $params);
2416 * Returns list of users enrolled into course.
2418 * @package core_enrol
2421 * @param context $context
2422 * @param string $withcapability
2423 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2424 * @param string $userfields requested user record fields
2425 * @param string $orderby
2426 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2427 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2428 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2429 * @return array of user records
2431 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
2432 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
2435 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2436 $sql = "SELECT $userfields
2438 JOIN ($esql) je ON je.id = u.id
2439 WHERE u.deleted = 0";
2442 $sql = "$sql ORDER BY $orderby";
2444 list($sort, $sortparams) = users_order_by_sql('u');
2445 $sql = "$sql ORDER BY $sort";
2446 $params = array_merge($params, $sortparams);
2449 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2453 * Counts list of users enrolled into course (as per above function)
2455 * @package core_enrol
2458 * @param context $context
2459 * @param string $withcapability
2460 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2461 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2462 * @return array of user records
2464 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2467 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2468 $sql = "SELECT count(u.id)
2470 JOIN ($esql) je ON je.id = u.id
2471 WHERE u.deleted = 0";
2473 return $DB->count_records_sql($sql, $params);
2477 * Loads the capability definitions for the component (from file).
2479 * Loads the capability definitions for the component (from file). If no
2480 * capabilities are defined for the component, we simply return an empty array.
2483 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2484 * @return array array of capabilities
2486 function load_capability_def($component) {
2487 $defpath = core_component::get_component_directory($component).'/db/access.php';
2489 $capabilities = array();
2490 if (file_exists($defpath)) {
2492 if (!empty(${$component.'_capabilities'})) {
2493 // BC capability array name
2494 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2495 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2496 $capabilities = ${$component.'_capabilities'};
2500 return $capabilities;
2504 * Gets the capabilities that have been cached in the database for this component.
2507 * @param string $component - examples: 'moodle', 'mod_forum'
2508 * @return array array of capabilities
2510 function get_cached_capabilities($component = 'moodle') {
2512 return $DB->get_records('capabilities', array('component'=>$component));
2516 * Returns default capabilities for given role archetype.
2518 * @param string $archetype role archetype
2521 function get_default_capabilities($archetype) {
2529 $defaults = array();
2530 $components = array();
2531 $allcaps = $DB->get_records('capabilities');
2533 foreach ($allcaps as $cap) {
2534 if (!in_array($cap->component, $components)) {
2535 $components[] = $cap->component;
2536 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2539 foreach($alldefs as $name=>$def) {
2540 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2541 if (isset($def['archetypes'])) {
2542 if (isset($def['archetypes'][$archetype])) {
2543 $defaults[$name] = $def['archetypes'][$archetype];
2545 // 'legacy' is for backward compatibility with 1.9 access.php
2547 if (isset($def['legacy'][$archetype])) {
2548 $defaults[$name] = $def['legacy'][$archetype];
2557 * Return default roles that can be assigned, overridden or switched
2558 * by give role archetype.
2560 * @param string $type assign|override|switch
2561 * @param string $archetype
2562 * @return array of role ids
2564 function get_default_role_archetype_allows($type, $archetype) {
2567 if (empty($archetype)) {
2571 $roles = $DB->get_records('role');
2572 $archetypemap = array();
2573 foreach ($roles as $role) {
2574 if ($role->archetype) {
2575 $archetypemap[$role->archetype][$role->id] = $role->id;
2581 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2582 'coursecreator' => array(),
2583 'editingteacher' => array('teacher', 'student'),
2584 'teacher' => array(),
2585 'student' => array(),
2588 'frontpage' => array(),
2590 'override' => array(
2591 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2592 'coursecreator' => array(),
2593 'editingteacher' => array('teacher', 'student', 'guest'),
2594 'teacher' => array(),
2595 'student' => array(),
2598 'frontpage' => array(),
2601 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2602 'coursecreator' => array(),
2603 'editingteacher' => array('teacher', 'student', 'guest'),
2604 'teacher' => array('student', 'guest'),
2605 'student' => array(),
2608 'frontpage' => array(),
2612 if (!isset($defaults[$type][$archetype])) {
2613 debugging("Unknown type '$type'' or archetype '$archetype''");
2618 foreach ($defaults[$type][$archetype] as $at) {
2619 if (isset($archetypemap[$at])) {
2620 foreach ($archetypemap[$at] as $roleid) {
2621 $return[$roleid] = $roleid;
2630 * Reset role capabilities to default according to selected role archetype.
2631 * If no archetype selected, removes all capabilities.
2633 * This applies to capabilities that are assigned to the role (that you could
2634 * edit in the 'define roles' interface), and not to any capability overrides
2635 * in different locations.
2637 * @param int $roleid ID of role to reset capabilities for
2639 function reset_role_capabilities($roleid) {
2642 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2643 $defaultcaps = get_default_capabilities($role->archetype);
2645 $systemcontext = context_system::instance();
2647 $DB->delete_records('role_capabilities',
2648 array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2650 foreach($defaultcaps as $cap=>$permission) {
2651 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2654 // Mark the system context dirty.
2655 context_system::instance()->mark_dirty();
2659 * Updates the capabilities table with the component capability definitions.
2660 * If no parameters are given, the function updates the core moodle
2663 * Note that the absence of the db/access.php capabilities definition file
2664 * will cause any stored capabilities for the component to be removed from
2668 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2669 * @return boolean true if success, exception in case of any problems
2671 function update_capabilities($component = 'moodle') {
2672 global $DB, $OUTPUT;
2674 $storedcaps = array();
2676 $filecaps = load_capability_def($component);
2677 foreach($filecaps as $capname=>$unused) {
2678 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2679 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2683 $cachedcaps = get_cached_capabilities($component);
2685 foreach ($cachedcaps as $cachedcap) {
2686 array_push($storedcaps, $cachedcap->name);
2687 // update risk bitmasks and context levels in existing capabilities if needed
2688 if (array_key_exists($cachedcap->name, $filecaps)) {
2689 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2690 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2692 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2693 $updatecap = new stdClass();
2694 $updatecap->id = $cachedcap->id;
2695 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2696 $DB->update_record('capabilities', $updatecap);
2698 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2699 $updatecap = new stdClass();
2700 $updatecap->id = $cachedcap->id;
2701 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2702 $DB->update_record('capabilities', $updatecap);
2705 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2706 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2708 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2709 $updatecap = new stdClass();
2710 $updatecap->id = $cachedcap->id;
2711 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2712 $DB->update_record('capabilities', $updatecap);
2718 // Are there new capabilities in the file definition?
2721 foreach ($filecaps as $filecap => $def) {
2723 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2724 if (!array_key_exists('riskbitmask', $def)) {
2725 $def['riskbitmask'] = 0; // no risk if not specified
2727 $newcaps[$filecap] = $def;
2730 // Add new capabilities to the stored definition.
2731 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2732 foreach ($newcaps as $capname => $capdef) {
2733 $capability = new stdClass();
2734 $capability->name = $capname;
2735 $capability->captype = $capdef['captype'];
2736 $capability->contextlevel = $capdef['contextlevel'];
2737 $capability->component = $component;
2738 $capability->riskbitmask = $capdef['riskbitmask'];
2740 $DB->insert_record('capabilities', $capability, false);
2742 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2743 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2744 foreach ($rolecapabilities as $rolecapability){
2745 //assign_capability will update rather than insert if capability exists
2746 if (!assign_capability($capname, $rolecapability->permission,
2747 $rolecapability->roleid, $rolecapability->contextid, true)){
2748 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2752 // we ignore archetype key if we have cloned permissions
2753 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2754 assign_legacy_capabilities($capname, $capdef['archetypes']);
2755 // 'legacy' is for backward compatibility with 1.9 access.php
2756 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2757 assign_legacy_capabilities($capname, $capdef['legacy']);
2760 // Are there any capabilities that have been removed from the file
2761 // definition that we need to delete from the stored capabilities and
2762 // role assignments?
2763 capabilities_cleanup($component, $filecaps);
2765 // reset static caches
2766 accesslib_clear_all_caches(false);
2772 * Deletes cached capabilities that are no longer needed by the component.
2773 * Also unassigns these capabilities from any roles that have them.
2774 * NOTE: this function is called from lib/db/upgrade.php
2777 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2778 * @param array $newcapdef array of the new capability definitions that will be
2779 * compared with the cached capabilities
2780 * @return int number of deprecated capabilities that have been removed
2782 function capabilities_cleanup($component, $newcapdef = null) {
2787 if ($cachedcaps = get_cached_capabilities($component)) {
2788 foreach ($cachedcaps as $cachedcap) {
2789 if (empty($newcapdef) ||
2790 array_key_exists($cachedcap->name, $newcapdef) === false) {
2792 // Remove from capabilities cache.
2793 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2795 // Delete from roles.
2796 if ($roles = get_roles_with_capability($cachedcap->name)) {
2797 foreach($roles as $role) {
2798 if (!unassign_capability($cachedcap->name, $role->id)) {
2799 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2806 return $removedcount;
2810 * Returns an array of all the known types of risk
2811 * The array keys can be used, for example as CSS class names, or in calls to
2812 * print_risk_icon. The values are the corresponding RISK_ constants.
2814 * @return array all the known types of risk.
2816 function get_all_risks() {
2818 'riskmanagetrust' => RISK_MANAGETRUST,
2819 'riskconfig' => RISK_CONFIG,
2820 'riskxss' => RISK_XSS,
2821 'riskpersonal' => RISK_PERSONAL,
2822 'riskspam' => RISK_SPAM,
2823 'riskdataloss' => RISK_DATALOSS,
2828 * Return a link to moodle docs for a given capability name
2830 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2831 * @return string the human-readable capability name as a link to Moodle Docs.
2833 function get_capability_docs_link($capability) {
2834 $url = get_docs_url('Capabilities/' . $capability->name);
2835 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2839 * This function pulls out all the resolved capabilities (overrides and
2840 * defaults) of a role used in capability overrides in contexts at a given
2843 * @param int $roleid
2844 * @param context $context
2845 * @param string $cap capability, optional, defaults to ''
2846 * @return array Array of capabilities
2848 function role_context_capabilities($roleid, context $context, $cap = '') {
2851 $contexts = $context->get_parent_context_ids(true);
2852 $contexts = '('.implode(',', $contexts).')';
2854 $params = array($roleid);
2857 $search = " AND rc.capability = ? ";
2864 FROM {role_capabilities} rc, {context} c
2865 WHERE rc.contextid in $contexts
2867 AND rc.contextid = c.id $search
2868 ORDER BY c.contextlevel DESC, rc.capability DESC";
2870 $capabilities = array();
2872 if ($records = $DB->get_records_sql($sql, $params)) {
2873 // We are traversing via reverse order.
2874 foreach ($records as $record) {
2875 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2876 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2877 $capabilities[$record->capability] = $record->permission;
2881 return $capabilities;
2885 * Constructs array with contextids as first parameter and context paths,
2886 * in both cases bottom top including self.
2889 * @param context $context
2892 function get_context_info_list(context $context) {
2893 $contextids = explode('/', ltrim($context->path, '/'));
2894 $contextpaths = array();
2895 $contextids2 = $contextids;
2896 while ($contextids2) {
2897 $contextpaths[] = '/' . implode('/', $contextids2);
2898 array_pop($contextids2);
2900 return array($contextids, $contextpaths);
2904 * Check if context is the front page context or a context inside it
2906 * Returns true if this context is the front page context, or a context inside it,
2909 * @param context $context a context object.
2912 function is_inside_frontpage(context $context) {
2913 $frontpagecontext = context_course::instance(SITEID);
2914 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2918 * Returns capability information (cached)
2920 * @param string $capabilityname
2921 * @return stdClass or null if capability not found
2923 function get_capability_info($capabilityname) {
2924 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2926 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2928 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2929 $ACCESSLIB_PRIVATE->capabilities = array();
2930 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2931 foreach ($caps as $cap) {
2932 $capname = $cap->name;
2935 $cap->riskbitmask = (int)$cap->riskbitmask;
2936 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2940 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2944 * Returns the human-readable, translated version of the capability.
2945 * Basically a big switch statement.
2947 * @param string $capabilityname e.g. mod/choice:readresponses
2950 function get_capability_string($capabilityname) {
2952 // Typical capability name is 'plugintype/pluginname:capabilityname'
2953 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2955 if ($type === 'moodle') {
2956 $component = 'core_role';
2957 } else if ($type === 'quizreport') {
2959 $component = 'quiz_'.$name;
2961 $component = $type.'_'.$name;
2964 $stringname = $name.':'.$capname;
2966 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2967 return get_string($stringname, $component);
2970 $dir = core_component::get_component_directory($component);
2971 if (!file_exists($dir)) {
2972 // plugin broken or does not exist, do not bother with printing of debug message
2973 return $capabilityname.' ???';
2976 // something is wrong in plugin, better print debug
2977 return get_string($stringname, $component);
2981 * This gets the mod/block/course/core etc strings.
2983 * @param string $component
2984 * @param int $contextlevel
2985 * @return string|bool String is success, false if failed
2987 function get_component_string($component, $contextlevel) {
2989 if ($component === 'moodle' or $component === 'core') {
2990 switch ($contextlevel) {
2991 // TODO MDL-46123: this should probably use context level names instead
2992 case CONTEXT_SYSTEM: return get_string('coresystem');
2993 case CONTEXT_USER: return get_string('users');
2994 case CONTEXT_COURSECAT: return get_string('categories');
2995 case CONTEXT_COURSE: return get_string('course');
2996 case CONTEXT_MODULE: return get_string('activities');
2997 case CONTEXT_BLOCK: return get_string('block');
2998 default: print_error('unknowncontext');
3002 list($type, $name) = core_component::normalize_component($component);
3003 $dir = core_component::get_plugin_directory($type, $name);
3004 if (!file_exists($dir)) {
3005 // plugin not installed, bad luck, there is no way to find the name
3006 return $component.' ???';
3010 // TODO MDL-46123: this is really hacky and should be improved.
3011 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
3012 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
3013 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
3014 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
3015 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
3016 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
3017 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
3019 if (get_string_manager()->string_exists('pluginname', $component)) {
3020 return get_string('activity').': '.get_string('pluginname', $component);
3022 return get_string('activity').': '.get_string('modulename', $component);
3024 default: return get_string('pluginname', $component);
3029 * Gets the list of roles assigned to this context and up (parents)
3030 * from the list of roles that are visible on user profile page
3031 * and participants page.
3033 * @param context $context
3036 function get_profile_roles(context $context) {
3039 if (empty($CFG->profileroles)) {
3043 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
3044 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
3045 $params = array_merge($params, $cparams);
3047 if ($coursecontext = $context->get_course_context(false)) {
3048 $params['coursecontext'] = $coursecontext->id;
3050 $params['coursecontext'] = 0;
3053 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3054 FROM {role_assignments} ra, {role} r
3055 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3056 WHERE r.id = ra.roleid
3057 AND ra.contextid $contextlist
3059 ORDER BY r.sortorder ASC";
3061 return $DB->get_records_sql($sql, $params);
3065 * Gets the list of roles assigned to this context and up (parents)
3067 * @param context $context
3070 function get_roles_used_in_context(context $context) {
3073 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
3075 if ($coursecontext = $context->get_course_context(false)) {
3076 $params['coursecontext'] = $coursecontext->id;
3078 $params['coursecontext'] = 0;
3081 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3082 FROM {role_assignments} ra, {role} r
3083 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3084 WHERE r.id = ra.roleid
3085 AND ra.contextid $contextlist
3086 ORDER BY r.sortorder ASC";
3088 return $DB->get_records_sql($sql, $params);
3092 * This function is used to print roles column in user profile page.
3093 * It is using the CFG->profileroles to limit the list to only interesting roles.
3094 * (The permission tab has full details of user role assignments.)
3096 * @param int $userid
3097 * @param int $courseid
3100 function get_user_roles_in_course($userid, $courseid) {
3103 if (empty($CFG->profileroles)) {
3107 if ($courseid == SITEID) {
3108 $context = context_system::instance();
3110 $context = context_course::instance($courseid);
3113 if (empty($CFG->profileroles)) {
3117 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
3118 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
3119 $params = array_merge($params, $cparams);
3121 if ($coursecontext = $context->get_course_context(false)) {
3122 $params['coursecontext'] = $coursecontext->id;
3124 $params['coursecontext'] = 0;
3127 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3128 FROM {role_assignments} ra, {role} r
3129 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3130 WHERE r.id = ra.roleid
3131 AND ra.contextid $contextlist
3133 AND ra.userid = :userid
3134 ORDER BY r.sortorder ASC";
3135 $params['userid'] = $userid;
3139 if ($roles = $DB->get_records_sql($sql, $params)) {
3140 $rolenames = role_fix_names($roles, $context, ROLENAME_ALIAS, true); // Substitute aliases
3142 foreach ($rolenames as $roleid => $rolename) {
3143 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&roleid='.$roleid.'">'.$rolename.'</a>';
3145 $rolestring = implode(',', $rolenames);
3152 * Checks if a user can assign users to a particular role in this context
3154 * @param context $context
3155 * @param int $targetroleid - the id of the role you want to assign users to
3158 function user_can_assign(context $context, $targetroleid) {
3161 // First check to see if the user is a site administrator.
3162 if (is_siteadmin()) {
3166 // Check if user has override capability.
3167 // If not return false.
3168 if (!has_capability('moodle/role:assign', $context)) {
3171 // pull out all active roles of this user from this context(or above)
3172 if ($userroles = get_user_roles($context)) {
3173 foreach ($userroles as $userrole) {
3174 // if any in the role_allow_override table, then it's ok
3175 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
3185 * Returns all site roles in correct sort order.
3187 * Note: this method does not localise role names or descriptions,
3188 * use role_get_names() if you need role names.
3190 * @param context $context optional context for course role name aliases
3191 * @return array of role records with optional coursealias property
3193 function get_all_roles(context $context = null) {
3196 if (!$context or !$coursecontext = $context->get_course_context(false)) {
3197 $coursecontext = null;
3200 if ($coursecontext) {
3201 $sql = "SELECT r.*, rn.name AS coursealias
3203 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3204 ORDER BY r.sortorder ASC";
3205 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
3208 return $DB->get_records('role', array(), 'sortorder ASC');
3213 * Returns roles of a specified archetype
3215 * @param string $archetype
3216 * @return array of full role records
3218 function get_archetype_roles($archetype) {
3220 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
3224 * Gets all the user roles assigned in this context, or higher contexts
3225 * this is mainly used when checking if a user can assign a role, or overriding a role
3226 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3227 * allow_override tables
3229 * @param context $context
3230 * @param int $userid
3231 * @param bool $checkparentcontexts defaults to true
3232 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
3235 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
3238 if (empty($userid)) {
3239 if (empty($USER->id)) {
3242 $userid = $USER->id;
3245 if ($checkparentcontexts) {
3246 $contextids = $context->get_parent_context_ids();
3248 $contextids = array();
3250 $contextids[] = $context->id;
3252 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3254 array_unshift($params, $userid);
3256 $sql = "SELECT ra.*, r.name, r.shortname
3257 FROM {role_assignments} ra, {role} r, {context} c
3259 AND ra.roleid = r.id
3260 AND ra.contextid = c.id
3261 AND ra.contextid $contextids
3264 return $DB->get_records_sql($sql ,$params);
3268 * Like get_user_roles, but adds in the authenticated user role, and the front
3269 * page roles, if applicable.
3271 * @param context $context the context.
3272 * @param int $userid optional. Defaults to $USER->id
3273 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3275 function get_user_roles_with_special(context $context, $userid = 0) {
3278 if (empty($userid)) {
3279 if (empty($USER->id)) {
3282 $userid = $USER->id;
3285 $ras = get_user_roles($context, $userid);
3287 // Add front-page role if relevant.
3288 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3289 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3290 is_inside_frontpage($context);
3291 if ($defaultfrontpageroleid && $isfrontpage) {
3292 $frontpagecontext = context_course::instance(SITEID);
3293 $ra = new stdClass();
3294 $ra->userid = $userid;
3295 $ra->contextid = $frontpagecontext->id;
3296 $ra->roleid = $defaultfrontpageroleid;
3300 // Add authenticated user role if relevant.
3301 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3302 if ($defaultuserroleid && !isguestuser($userid)) {
3303 $systemcontext = context_system::instance();
3304 $ra = new stdClass();
3305 $ra->userid = $userid;
3306 $ra->contextid = $systemcontext->id;
3307 $ra->roleid = $defaultuserroleid;
3315 * Creates a record in the role_allow_override table
3317 * @param int $sroleid source roleid
3318 * @param int $troleid target roleid
3321 function allow_override($sroleid, $troleid) {
3324 $record = new stdClass();
3325 $record->roleid = $sroleid;
3326 $record->allowoverride = $troleid;
3327 $DB->insert_record('role_allow_override', $record);
3331 * Creates a record in the role_allow_assign table
3333 * @param int $fromroleid source roleid
3334 * @param int $targetroleid target roleid
3337 function allow_assign($fromroleid, $targetroleid) {
3340 $record = new stdClass();
3341 $record->roleid = $fromroleid;
3342 $record->allowassign = $targetroleid;
3343 $DB->insert_record('role_allow_assign', $record);
3347 * Creates a record in the role_allow_switch table
3349 * @param int $fromroleid source roleid
3350 * @param int $targetroleid target roleid
3353 function allow_switch($fromroleid, $targetroleid) {
3356 $record = new stdClass();
3357 $record->roleid = $fromroleid;
3358 $record->allowswitch = $targetroleid;
3359 $DB->insert_record('role_allow_switch', $record);
3363 * Gets a list of roles that this user can assign in this context
3365 * @param context $context the context.
3366 * @param int $rolenamedisplay the type of role name to display. One of the
3367 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3368 * @param bool $withusercounts if true, count the number of users with each role.
3369 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3370 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3371 * if $withusercounts is true, returns a list of three arrays,
3372 * $rolenames, $rolecounts, and $nameswithcounts.
3374 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3377 // make sure there is a real user specified
3378 if ($user === null) {
3379 $userid = isset($USER->id) ? $USER->id : 0;
3381 $userid = is_object($user) ? $user->id : $user;
3384 if (!has_capability('moodle/role:assign', $context, $userid)) {
3385 if ($withusercounts) {
3386 return array(array(), array(), array());
3395 if ($withusercounts) {
3396 $extrafields = ', (SELECT count(u.id)
3397 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3398 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3400 $params['conid'] = $context->id;
3403 if (is_siteadmin($userid)) {
3404 // show all roles allowed in this context to admins
3405 $assignrestriction = "";
3407 $parents = $context->get_parent_context_ids(true);
3408 $contexts = implode(',' , $parents);
3409 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3410 FROM {role_allow_assign} raa
3411 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3412 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3413 ) ar ON ar.id = r.id";
3414 $params['userid'] = $userid;
3416 $params['contextlevel'] = $context->contextlevel;
3418 if ($coursecontext = $context->get_course_context(false)) {
3419 $params['coursecontext'] = $coursecontext->id;
3421 $params['coursecontext'] = 0; // no course aliases
3422 $coursecontext = null;
3424 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3427 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3428 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3429 ORDER BY r.sortorder ASC";
3430 $roles = $DB->get_records_sql($sql, $params);
3432 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3434 if (!$withusercounts) {
3438 $rolecounts = array();
3439 $nameswithcounts = array();
3440 foreach ($roles as $role) {
3441 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3442 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3444 return array($rolenames, $rolecounts, $nameswithcounts);
3448 * Gets a list of roles that this user can switch to in a context
3450 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3451 * This function just process the contents of the role_allow_switch table. You also need to
3452 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3454 * @param context $context a context.
3455 * @return array an array $roleid => $rolename.
3457 function get_switchable_roles(context $context) {
3463 if (!is_siteadmin()) {
3464 // Admins are allowed to switch to any role with.
3465 // Others are subject to the additional constraint that the switch-to role must be allowed by
3466 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3467 $parents = $context->get_parent_context_ids(true);
3468 $contexts = implode(',' , $parents);
3470 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3471 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3472 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3473 $params['userid'] = $USER->id;
3476 if ($coursecontext = $context->get_course_context(false)) {
3477 $params['coursecontext'] = $coursecontext->id;
3479 $params['coursecontext'] = 0; // no course aliases
3480 $coursecontext = null;
3484 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3485 FROM (SELECT DISTINCT rc.roleid
3486 FROM {role_capabilities} rc
3489 JOIN {role} r ON r.id = idlist.roleid
3490 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3491 ORDER BY r.sortorder";
3492 $roles = $DB->get_records_sql($query, $params);
3494 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3498 * Gets a list of roles that this user can override in this context.
3500 * @param context $context the context.
3501 * @param int $rolenamedisplay the type of role name to display. One of the
3502 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3503 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3504 * @return array if $withcounts is false, then an array $roleid => $rolename.
3505 * if $withusercounts is true, returns a list of three arrays,
3506 * $rolenames, $rolecounts, and $nameswithcounts.
3508 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3511 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3513 return array(array(), array(), array());
3519 $parents = $context->get_parent_context_ids(true);
3520 $contexts = implode(',' , $parents);
3525 $params['userid'] = $USER->id;
3527 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3528 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3529 $params['conid'] = $context->id;
3532 if ($coursecontext = $context->get_course_context(false)) {
3533 $params['coursecontext'] = $coursecontext->id;
3535 $params['coursecontext'] = 0; // no course aliases
3536 $coursecontext = null;
3539 if (is_siteadmin()) {
3540 // show all roles to admins
3541 $roles = $DB->get_records_sql("
3542 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3544 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3545 ORDER BY ro.sortorder ASC", $params);
3548 $roles = $DB->get_records_sql("
3549 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3551 JOIN (SELECT DISTINCT r.id
3553 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3554 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3555 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3556 ) inline_view ON ro.id = inline_view.id
3557 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3558 ORDER BY ro.sortorder ASC", $params);
3561 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3567 $rolecounts = array();
3568 $nameswithcounts = array();
3569 foreach ($roles as $role) {
3570 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3571 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3573 return array($rolenames, $rolecounts, $nameswithcounts);
3577 * Create a role menu suitable for default role selection in enrol plugins.
3579 * @package core_enrol
3581 * @param context $context
3582 * @param int $addroleid current or default role - always added to list
3583 * @return array roleid=>localised role name
3585 function get_default_enrol_roles(context $context, $addroleid = null) {
3588 $params = array('contextlevel'=>CONTEXT_COURSE);
3590 if ($coursecontext = $context->get_course_context(false)) {
3591 $params['coursecontext'] = $coursecontext->id;
3593 $params['coursecontext'] = 0; // no course names
3594 $coursecontext = null;
3598 $addrole = "OR r.id = :addroleid";
3599 $params['addroleid'] = $addroleid;
3604 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3606 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3607 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3608 WHERE rcl.id IS NOT NULL $addrole
3609 ORDER BY sortorder DESC";
3611 $roles = $DB->get_records_sql($sql, $params);
3613 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3617 * Return context levels where this role is assignable.
3619 * @param integer $roleid the id of a role.
3620 * @return array list of the context levels at which this role may be assigned.
3622 function get_role_contextlevels($roleid) {
3624 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3625 'contextlevel', 'id,contextlevel');
3629 * Return roles suitable for assignment at the specified context level.
3631 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3633 * @param integer $contextlevel a contextlevel.
3634 * @return array list of role ids that are assignable at this context level.
3636 function get_roles_for_contextlevels($contextlevel) {
3638 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3643 * Returns default context levels where roles can be assigned.
3645 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3646 * from the array returned by get_role_archetypes();
3647 * @return array list of the context levels at which this type of role may be assigned by default.
3649 function get_default_contextlevels($rolearchetype) {
3650 static $defaults = array(
3651 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3652 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3653 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3654 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3655 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3658 'frontpage' => array());
3660 if (isset($defaults[$rolearchetype])) {
3661 return $defaults[$rolearchetype];