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 * Check if the user is an admin at the site level.
551 * Please note that use of proper capabilities is always encouraged,
552 * this function is supposed to be used from core or for temporary hacks.
556 * @param int|stdClass $user_or_id user id or user object
557 * @return bool true if user is one of the administrators, false otherwise
559 function is_siteadmin($user_or_id = null) {
562 if ($user_or_id === null) {
566 if (empty($user_or_id)) {
569 if (!empty($user_or_id->id)) {
570 $userid = $user_or_id->id;
572 $userid = $user_or_id;
575 // Because this script is called many times (150+ for course page) with
576 // the same parameters, it is worth doing minor optimisations. This static
577 // cache stores the value for a single userid, saving about 2ms from course
578 // page load time without using significant memory. As the static cache
579 // also includes the value it depends on, this cannot break unit tests.
580 static $knownid, $knownresult, $knownsiteadmins;
581 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
585 $knownsiteadmins = $CFG->siteadmins;
587 $siteadmins = explode(',', $CFG->siteadmins);
588 $knownresult = in_array($userid, $siteadmins);
593 * Returns true if user has at least one role assign
594 * of 'coursecontact' role (is potentially listed in some course descriptions).
599 function has_coursecontact_role($userid) {
602 if (empty($CFG->coursecontact)) {
606 FROM {role_assignments}
607 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
608 return $DB->record_exists_sql($sql, array('userid'=>$userid));
612 * Does the user have a capability to do something?
614 * Walk the accessdata array and return true/false.
615 * Deals with prohibits, role switching, aggregating
618 * The main feature of here is being FAST and with no
623 * Switch Role merges with default role
624 * ------------------------------------
625 * If you are a teacher in course X, you have at least
626 * teacher-in-X + defaultloggedinuser-sitewide. So in the
627 * course you'll have techer+defaultloggedinuser.
628 * We try to mimic that in switchrole.
630 * Permission evaluation
631 * ---------------------
632 * Originally there was an extremely complicated way
633 * to determine the user access that dealt with
634 * "locality" or role assignments and role overrides.
635 * Now we simply evaluate access for each role separately
636 * and then verify if user has at least one role with allow
637 * and at the same time no role with prohibit.
640 * @param string $capability
641 * @param context $context
642 * @param array $accessdata
645 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
648 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
649 $path = $context->path;
650 $paths = array($path);
651 while($path = rtrim($path, '0123456789')) {
652 $path = rtrim($path, '/');
660 $switchedrole = false;
662 // Find out if role switched
663 if (!empty($accessdata['rsw'])) {
664 // From the bottom up...
665 foreach ($paths as $path) {
666 if (isset($accessdata['rsw'][$path])) {
667 // Found a switchrole assignment - check for that role _plus_ the default user role
668 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
669 $switchedrole = true;
675 if (!$switchedrole) {
676 // get all users roles in this context and above
677 foreach ($paths as $path) {
678 if (isset($accessdata['ra'][$path])) {
679 foreach ($accessdata['ra'][$path] as $roleid) {
680 $roles[$roleid] = null;
686 // Now find out what access is given to each role, going bottom-->up direction
688 foreach ($roles as $roleid => $ignored) {
689 foreach ($paths as $path) {
690 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
691 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
692 if ($perm === CAP_PROHIBIT) {
693 // any CAP_PROHIBIT found means no permission for the user
696 if (is_null($roles[$roleid])) {
697 $roles[$roleid] = $perm;
701 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
702 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
709 * A convenience function that tests has_capability, and displays an error if
710 * the user does not have that capability.
712 * NOTE before Moodle 2.0, this function attempted to make an appropriate
713 * require_login call before checking the capability. This is no longer the case.
714 * You must call require_login (or one of its variants) if you want to check the
715 * user is logged in, before you call this function.
717 * @see has_capability()
719 * @param string $capability the name of the capability to check. For example mod/forum:view
720 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
721 * @param int $userid A user id. By default (null) checks the permissions of the current user.
722 * @param bool $doanything If false, ignore effect of admin role assignment
723 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
724 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
725 * @return void terminates with an error if the user does not have the given capability.
727 function require_capability($capability, context $context, $userid = null, $doanything = true,
728 $errormessage = 'nopermissions', $stringfile = '') {
729 if (!has_capability($capability, $context, $userid, $doanything)) {
730 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
735 * Return a nested array showing role assignments
736 * all relevant role capabilities for the user at
737 * site/course_category/course levels
739 * We do _not_ delve deeper than courses because the number of
740 * overrides at the module/block levels can be HUGE.
742 * [ra] => [/path][roleid]=roleid
743 * [rdef] => [/path:roleid][capability]=permission
746 * @param int $userid - the id of the user
747 * @return array access info array
749 function get_user_access_sitewide($userid) {
750 global $CFG, $DB, $ACCESSLIB_PRIVATE;
752 /* Get in a few cheap DB queries...
754 * - relevant role caps
755 * - above and within this user's RAs
756 * - below this user's RAs - limited to course level
759 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
760 $raparents = array();
761 $accessdata = get_empty_accessdata();
763 // start with the default role
764 if (!empty($CFG->defaultuserroleid)) {
765 $syscontext = context_system::instance();
766 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
767 $raparents[$CFG->defaultuserroleid][$syscontext->id] = $syscontext->id;
770 // load the "default frontpage role"
771 if (!empty($CFG->defaultfrontpageroleid)) {
772 $frontpagecontext = context_course::instance(get_site()->id);
773 if ($frontpagecontext->path) {
774 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
775 $raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->id] = $frontpagecontext->id;
779 // preload every assigned role at and above course context
780 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
781 FROM {role_assignments} ra
783 ON ctx.id = ra.contextid
784 LEFT JOIN {block_instances} bi
785 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
786 LEFT JOIN {context} bpctx
787 ON (bpctx.id = bi.parentcontextid)
788 WHERE ra.userid = :userid
789 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")";
790 $params = array('userid'=>$userid);
791 $rs = $DB->get_recordset_sql($sql, $params);
792 foreach ($rs as $ra) {
793 // RAs leafs are arrays to support multi-role assignments...
794 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
795 $raparents[$ra->roleid][$ra->contextid] = $ra->contextid;
799 if (empty($raparents)) {
803 // now get overrides of interesting roles in all interesting child contexts
804 // hopefully we will not run out of SQL limits here,
805 // users would have to have very many roles at/above course context...
810 foreach ($raparents as $roleid=>$ras) {
812 list($sqlcids, $cids) = $DB->get_in_or_equal($ras, SQL_PARAMS_NAMED, 'c'.$cp.'_');
813 $params = array_merge($params, $cids);
814 $params['r'.$cp] = $roleid;
815 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
816 FROM {role_capabilities} rc
818 ON (ctx.id = rc.contextid)
821 AND (ctx.id = pctx.id
822 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
823 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
824 LEFT JOIN {block_instances} bi
825 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
826 LEFT JOIN {context} bpctx
827 ON (bpctx.id = bi.parentcontextid)
828 WHERE rc.roleid = :r{$cp}
829 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")
833 // fixed capability order is necessary for rdef dedupe
834 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
836 foreach ($rs as $rd) {
837 $k = $rd->path.':'.$rd->roleid;
838 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
842 // share the role definitions
843 foreach ($accessdata['rdef'] as $k=>$unused) {
844 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
845 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
847 $accessdata['rdef_count']++;
848 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
855 * Add to the access ctrl array the data needed by a user for a given course.
857 * This function injects all course related access info into the accessdata array.
860 * @param int $userid the id of the user
861 * @param context_course $coursecontext course context
862 * @param array $accessdata accessdata array (modified)
863 * @return void modifies $accessdata parameter
865 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
866 global $DB, $CFG, $ACCESSLIB_PRIVATE;
868 if (empty($coursecontext->path)) {
869 // weird, this should not happen
873 if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
874 // already loaded, great!
880 if (empty($userid)) {
881 if (!empty($CFG->notloggedinroleid)) {
882 $roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
885 } else if (isguestuser($userid)) {
886 if ($guestrole = get_guest_role()) {
887 $roles[$guestrole->id] = $guestrole->id;
891 // Interesting role assignments at, above and below the course context
892 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
893 $params['userid'] = $userid;
894 $params['children'] = $coursecontext->path."/%";
895 $sql = "SELECT ra.*, ctx.path
896 FROM {role_assignments} ra
897 JOIN {context} ctx ON ra.contextid = ctx.id
898 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
899 $rs = $DB->get_recordset_sql($sql, $params);
901 // add missing role definitions
902 foreach ($rs as $ra) {
903 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
904 $roles[$ra->roleid] = $ra->roleid;
908 // add the "default frontpage role" when on the frontpage
909 if (!empty($CFG->defaultfrontpageroleid)) {
910 $frontpagecontext = context_course::instance(get_site()->id);
911 if ($frontpagecontext->id == $coursecontext->id) {
912 $roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
916 // do not forget the default role
917 if (!empty($CFG->defaultuserroleid)) {
918 $roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
923 // weird, default roles must be missing...
924 $accessdata['loaded'][$coursecontext->instanceid] = 1;
928 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
929 $params = array('c'=>$coursecontext->id);
930 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
931 $params = array_merge($params, $rparams);
932 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
933 $params = array_merge($params, $rparams);
935 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
936 FROM {role_capabilities} rc
938 ON (ctx.id = rc.contextid)
941 AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
942 WHERE rc.roleid $roleids
943 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
944 $rs = $DB->get_recordset_sql($sql, $params);
947 foreach ($rs as $rd) {
948 $k = $rd->path.':'.$rd->roleid;
949 if (isset($accessdata['rdef'][$k])) {
952 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
956 // share new role definitions
957 foreach ($newrdefs as $k=>$unused) {
958 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
959 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
961 $accessdata['rdef_count']++;
962 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
965 $accessdata['loaded'][$coursecontext->instanceid] = 1;
967 // we want to deduplicate the USER->access from time to time, this looks like a good place,
968 // because we have to do it before the end of session
969 dedupe_user_access();
973 * Add to the access ctrl array the data needed by a role for a given context.
975 * The data is added in the rdef key.
976 * This role-centric function is useful for role_switching
977 * and temporary course roles.
980 * @param int $roleid the id of the user
981 * @param context $context needs path!
982 * @param array $accessdata accessdata array (is modified)
985 function load_role_access_by_context($roleid, context $context, &$accessdata) {
986 global $DB, $ACCESSLIB_PRIVATE;
988 /* Get the relevant rolecaps into rdef
989 * - relevant role caps
994 if (empty($context->path)) {
995 // weird, this should not happen
999 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
1000 $params['roleid'] = $roleid;
1001 $params['childpath'] = $context->path.'/%';
1003 $sql = "SELECT ctx.path, rc.capability, rc.permission
1004 FROM {role_capabilities} rc
1005 JOIN {context} ctx ON (rc.contextid = ctx.id)
1006 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
1007 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
1008 $rs = $DB->get_recordset_sql($sql, $params);
1010 $newrdefs = array();
1011 foreach ($rs as $rd) {
1012 $k = $rd->path.':'.$roleid;
1013 if (isset($accessdata['rdef'][$k])) {
1016 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
1020 // share new role definitions
1021 foreach ($newrdefs as $k=>$unused) {
1022 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
1023 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
1025 $accessdata['rdef_count']++;
1026 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1031 * Returns empty accessdata structure.
1034 * @return array empt accessdata
1036 function get_empty_accessdata() {
1037 $accessdata = array(); // named list
1038 $accessdata['ra'] = array();
1039 $accessdata['rdef'] = array();
1040 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
1041 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
1042 $accessdata['loaded'] = array(); // loaded course contexts
1043 $accessdata['time'] = time();
1044 $accessdata['rsw'] = array();
1050 * Get accessdata for a given user.
1053 * @param int $userid
1054 * @param bool $preloadonly true means do not return access array
1055 * @return array accessdata
1057 function get_user_accessdata($userid, $preloadonly=false) {
1058 global $CFG, $ACCESSLIB_PRIVATE, $USER;
1060 if (!empty($USER->acces['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1061 // share rdef from USER session with rolepermissions cache in order to conserve memory
1062 foreach($USER->acces['rdef'] as $k=>$v) {
1063 $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->acces['rdef'][$k];
1065 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->acces;
1068 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
1069 if (empty($userid)) {
1070 if (!empty($CFG->notloggedinroleid)) {
1071 $accessdata = get_role_access($CFG->notloggedinroleid);
1074 return get_empty_accessdata();
1077 } else if (isguestuser($userid)) {
1078 if ($guestrole = get_guest_role()) {
1079 $accessdata = get_role_access($guestrole->id);
1082 return get_empty_accessdata();
1086 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1089 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1095 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1100 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1101 * this function looks for contexts with the same overrides and shares them.
1106 function dedupe_user_access() {
1110 // no session in CLI --> no compression necessary
1114 if (empty($USER->access['rdef_count'])) {
1115 // weird, this should not happen
1119 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1120 if ($USER->access['rdef_count'] - $USER->access['rdef_lcc'] > 10) {
1121 // do not compress after each change, wait till there is more stuff to be done
1126 foreach ($USER->access['rdef'] as $k=>$def) {
1127 $hash = sha1(serialize($def));
1128 if (isset($hashmap[$hash])) {
1129 $USER->access['rdef'][$k] =& $hashmap[$hash];
1131 $hashmap[$hash] =& $USER->access['rdef'][$k];
1135 $USER->access['rdef_lcc'] = $USER->access['rdef_count'];
1139 * A convenience function to completely load all the capabilities
1140 * for the current user. It is called from has_capability() and functions change permissions.
1142 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1143 * @see check_enrolment_plugins()
1148 function load_all_capabilities() {
1151 // roles not installed yet - we are in the middle of installation
1152 if (during_initial_install()) {
1156 if (!isset($USER->id)) {
1157 // this should not happen
1161 unset($USER->access);
1162 $USER->access = get_user_accessdata($USER->id);
1164 // deduplicate the overrides to minimize session size
1165 dedupe_user_access();
1167 // Clear to force a refresh
1168 unset($USER->mycourses);
1170 // init/reset internal enrol caches - active course enrolments and temp access
1171 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1175 * A convenience function to completely reload all the capabilities
1176 * for the current user when roles have been updated in a relevant
1177 * context -- but PRESERVING switchroles and loginas.
1178 * This function resets all accesslib and context caches.
1180 * That is - completely transparent to the user.
1182 * Note: reloads $USER->access completely.
1187 function reload_all_capabilities() {
1188 global $USER, $DB, $ACCESSLIB_PRIVATE;
1192 if (!empty($USER->access['rsw'])) {
1193 $sw = $USER->access['rsw'];
1196 accesslib_clear_all_caches(true);
1197 unset($USER->access);
1198 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
1200 load_all_capabilities();
1202 foreach ($sw as $path => $roleid) {
1203 if ($record = $DB->get_record('context', array('path'=>$path))) {
1204 $context = context::instance_by_id($record->id);
1205 role_switch($roleid, $context);
1211 * Adds a temp role to current USER->access array.
1213 * Useful for the "temporary guest" access we grant to logged-in users.
1214 * This is useful for enrol plugins only.
1217 * @param context_course $coursecontext
1218 * @param int $roleid
1221 function load_temp_course_role(context_course $coursecontext, $roleid) {
1222 global $USER, $SITE;
1224 if (empty($roleid)) {
1225 debugging('invalid role specified in load_temp_course_role()');
1229 if ($coursecontext->instanceid == $SITE->id) {
1230 debugging('Can not use temp roles on the frontpage');
1234 if (!isset($USER->access)) {
1235 load_all_capabilities();
1238 $coursecontext->reload_if_dirty();
1240 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1244 // load course stuff first
1245 load_course_context($USER->id, $coursecontext, $USER->access);
1247 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1249 load_role_access_by_context($roleid, $coursecontext, $USER->access);
1253 * Removes any extra guest roles from current USER->access array.
1254 * This is useful for enrol plugins only.
1257 * @param context_course $coursecontext
1260 function remove_temp_course_roles(context_course $coursecontext) {
1261 global $DB, $USER, $SITE;
1263 if ($coursecontext->instanceid == $SITE->id) {
1264 debugging('Can not use temp roles on the frontpage');
1268 if (empty($USER->access['ra'][$coursecontext->path])) {
1269 //no roles here, weird
1273 $sql = "SELECT DISTINCT ra.roleid AS id
1274 FROM {role_assignments} ra
1275 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1276 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1278 $USER->access['ra'][$coursecontext->path] = array();
1279 foreach($ras as $r) {
1280 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1285 * Returns array of all role archetypes.
1289 function get_role_archetypes() {
1291 'manager' => 'manager',
1292 'coursecreator' => 'coursecreator',
1293 'editingteacher' => 'editingteacher',
1294 'teacher' => 'teacher',
1295 'student' => 'student',
1298 'frontpage' => 'frontpage'
1303 * Assign the defaults found in this capability definition to roles that have
1304 * the corresponding legacy capabilities assigned to them.
1306 * @param string $capability
1307 * @param array $legacyperms an array in the format (example):
1308 * 'guest' => CAP_PREVENT,
1309 * 'student' => CAP_ALLOW,
1310 * 'teacher' => CAP_ALLOW,
1311 * 'editingteacher' => CAP_ALLOW,
1312 * 'coursecreator' => CAP_ALLOW,
1313 * 'manager' => CAP_ALLOW
1314 * @return boolean success or failure.
1316 function assign_legacy_capabilities($capability, $legacyperms) {
1318 $archetypes = get_role_archetypes();
1320 foreach ($legacyperms as $type => $perm) {
1322 $systemcontext = context_system::instance();
1323 if ($type === 'admin') {
1324 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1328 if (!array_key_exists($type, $archetypes)) {
1329 print_error('invalidlegacy', '', '', $type);
1332 if ($roles = get_archetype_roles($type)) {
1333 foreach ($roles as $role) {
1334 // Assign a site level capability.
1335 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1345 * Verify capability risks.
1347 * @param stdClass $capability a capability - a row from the capabilities table.
1348 * @return boolean whether this capability is safe - that is, whether people with the
1349 * safeoverrides capability should be allowed to change it.
1351 function is_safe_capability($capability) {
1352 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1356 * Get the local override (if any) for a given capability in a role in a context
1358 * @param int $roleid
1359 * @param int $contextid
1360 * @param string $capability
1361 * @return stdClass local capability override
1363 function get_local_override($roleid, $contextid, $capability) {
1365 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1369 * Returns context instance plus related course and cm instances
1371 * @param int $contextid
1372 * @return array of ($context, $course, $cm)
1374 function get_context_info_array($contextid) {
1377 $context = context::instance_by_id($contextid, MUST_EXIST);
1381 if ($context->contextlevel == CONTEXT_COURSE) {
1382 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1384 } else if ($context->contextlevel == CONTEXT_MODULE) {
1385 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1386 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1388 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1389 $parent = $context->get_parent_context();
1391 if ($parent->contextlevel == CONTEXT_COURSE) {
1392 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1393 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1394 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1395 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1399 return array($context, $course, $cm);
1403 * Function that creates a role
1405 * @param string $name role name
1406 * @param string $shortname role short name
1407 * @param string $description role description
1408 * @param string $archetype
1409 * @return int id or dml_exception
1411 function create_role($name, $shortname, $description, $archetype = '') {
1414 if (strpos($archetype, 'moodle/legacy:') !== false) {
1415 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1418 // verify role archetype actually exists
1419 $archetypes = get_role_archetypes();
1420 if (empty($archetypes[$archetype])) {
1424 // Insert the role record.
1425 $role = new stdClass();
1426 $role->name = $name;
1427 $role->shortname = $shortname;
1428 $role->description = $description;
1429 $role->archetype = $archetype;
1431 //find free sortorder number
1432 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1433 if (empty($role->sortorder)) {
1434 $role->sortorder = 1;
1436 $id = $DB->insert_record('role', $role);
1442 * Function that deletes a role and cleanups up after it
1444 * @param int $roleid id of role to delete
1445 * @return bool always true
1447 function delete_role($roleid) {
1450 // first unssign all users
1451 role_unassign_all(array('roleid'=>$roleid));
1453 // cleanup all references to this role, ignore errors
1454 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1455 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1456 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1457 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1458 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1459 $DB->delete_records('role_names', array('roleid'=>$roleid));
1460 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1462 // finally delete the role itself
1463 // get this before the name is gone for logging
1464 $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
1466 $DB->delete_records('role', array('id'=>$roleid));
1468 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
1474 * Function to write context specific overrides, or default capabilities.
1476 * NOTE: use $context->mark_dirty() after this
1478 * @param string $capability string name
1479 * @param int $permission CAP_ constants
1480 * @param int $roleid role id
1481 * @param int|context $contextid context id
1482 * @param bool $overwrite
1483 * @return bool always true or exception
1485 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1488 if ($contextid instanceof context) {
1489 $context = $contextid;
1491 $context = context::instance_by_id($contextid);
1494 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1495 unassign_capability($capability, $roleid, $context->id);
1499 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1501 if ($existing and !$overwrite) { // We want to keep whatever is there already
1505 $cap = new stdClass();
1506 $cap->contextid = $context->id;
1507 $cap->roleid = $roleid;
1508 $cap->capability = $capability;
1509 $cap->permission = $permission;
1510 $cap->timemodified = time();
1511 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1514 $cap->id = $existing->id;
1515 $DB->update_record('role_capabilities', $cap);
1517 if ($DB->record_exists('context', array('id'=>$context->id))) {
1518 $DB->insert_record('role_capabilities', $cap);
1525 * Unassign a capability from a role.
1527 * NOTE: use $context->mark_dirty() after this
1529 * @param string $capability the name of the capability
1530 * @param int $roleid the role id
1531 * @param int|context $contextid null means all contexts
1532 * @return boolean true or exception
1534 function unassign_capability($capability, $roleid, $contextid = null) {
1537 if (!empty($contextid)) {
1538 if ($contextid instanceof context) {
1539 $context = $contextid;
1541 $context = context::instance_by_id($contextid);
1543 // delete from context rel, if this is the last override in this context
1544 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1546 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1552 * Get the roles that have a given capability assigned to it
1554 * This function does not resolve the actual permission of the capability.
1555 * It just checks for permissions and overrides.
1556 * Use get_roles_with_cap_in_context() if resolution is required.
1558 * @param string $capability capability name (string)
1559 * @param string $permission optional, the permission defined for this capability
1560 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1561 * @param stdClass $context null means any
1562 * @return array of role records
1564 function get_roles_with_capability($capability, $permission = null, $context = null) {
1568 $contexts = $context->get_parent_context_ids(true);
1569 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1570 $contextsql = "AND rc.contextid $insql";
1577 $permissionsql = " AND rc.permission = :permission";
1578 $params['permission'] = $permission;
1580 $permissionsql = '';
1585 WHERE r.id IN (SELECT rc.roleid
1586 FROM {role_capabilities} rc
1587 WHERE rc.capability = :capname
1590 $params['capname'] = $capability;
1593 return $DB->get_records_sql($sql, $params);
1597 * This function makes a role-assignment (a role for a user in a particular context)
1599 * @param int $roleid the role of the id
1600 * @param int $userid userid
1601 * @param int|context $contextid id of the context
1602 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1603 * @param int $itemid id of enrolment/auth plugin
1604 * @param string $timemodified defaults to current time
1605 * @return int new/existing id of the assignment
1607 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1610 // first of all detect if somebody is using old style parameters
1611 if ($contextid === 0 or is_numeric($component)) {
1612 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1615 // now validate all parameters
1616 if (empty($roleid)) {
1617 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1620 if (empty($userid)) {
1621 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1625 if (strpos($component, '_') === false) {
1626 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1630 if ($component !== '' and strpos($component, '_') === false) {
1631 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1635 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1636 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1639 if ($contextid instanceof context) {
1640 $context = $contextid;
1642 $context = context::instance_by_id($contextid, MUST_EXIST);
1645 if (!$timemodified) {
1646 $timemodified = time();
1649 // Check for existing entry
1650 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1653 // role already assigned - this should not happen
1654 if (count($ras) > 1) {
1655 // very weird - remove all duplicates!
1656 $ra = array_shift($ras);
1657 foreach ($ras as $r) {
1658 $DB->delete_records('role_assignments', array('id'=>$r->id));
1664 // actually there is no need to update, reset anything or trigger any event, so just return
1668 // Create a new entry
1669 $ra = new stdClass();
1670 $ra->roleid = $roleid;
1671 $ra->contextid = $context->id;
1672 $ra->userid = $userid;
1673 $ra->component = $component;
1674 $ra->itemid = $itemid;
1675 $ra->timemodified = $timemodified;
1676 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1678 $ra->id = $DB->insert_record('role_assignments', $ra);
1680 // mark context as dirty - again expensive, but needed
1681 $context->mark_dirty();
1683 if (!empty($USER->id) && $USER->id == $userid) {
1684 // If the user is the current user, then do full reload of capabilities too.
1685 reload_all_capabilities();
1688 events_trigger('role_assigned', $ra);
1694 * Removes one role assignment
1696 * @param int $roleid
1697 * @param int $userid
1698 * @param int $contextid
1699 * @param string $component
1700 * @param int $itemid
1703 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1704 // first make sure the params make sense
1705 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1706 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1710 if (strpos($component, '_') === false) {
1711 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1715 if ($component !== '' and strpos($component, '_') === false) {
1716 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1720 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1724 * Removes multiple role assignments, parameters may contain:
1725 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1727 * @param array $params role assignment parameters
1728 * @param bool $subcontexts unassign in subcontexts too
1729 * @param bool $includemanual include manual role assignments too
1732 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1733 global $USER, $CFG, $DB;
1736 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1739 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1740 foreach ($params as $key=>$value) {
1741 if (!in_array($key, $allowed)) {
1742 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1746 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1747 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1750 if ($includemanual) {
1751 if (!isset($params['component']) or $params['component'] === '') {
1752 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1757 if (empty($params['contextid'])) {
1758 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1762 $ras = $DB->get_records('role_assignments', $params);
1763 foreach($ras as $ra) {
1764 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1765 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1766 // this is a bit expensive but necessary
1767 $context->mark_dirty();
1768 // If the user is the current user, then do full reload of capabilities too.
1769 if (!empty($USER->id) && $USER->id == $ra->userid) {
1770 reload_all_capabilities();
1773 events_trigger('role_unassigned', $ra);
1777 // process subcontexts
1778 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1779 if ($params['contextid'] instanceof context) {
1780 $context = $params['contextid'];
1782 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1786 $contexts = $context->get_child_contexts();
1788 foreach($contexts as $context) {
1789 $mparams['contextid'] = $context->id;
1790 $ras = $DB->get_records('role_assignments', $mparams);
1791 foreach($ras as $ra) {
1792 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1793 // this is a bit expensive but necessary
1794 $context->mark_dirty();
1795 // If the user is the current user, then do full reload of capabilities too.
1796 if (!empty($USER->id) && $USER->id == $ra->userid) {
1797 reload_all_capabilities();
1799 events_trigger('role_unassigned', $ra);
1805 // do this once more for all manual role assignments
1806 if ($includemanual) {
1807 $params['component'] = '';
1808 role_unassign_all($params, $subcontexts, false);
1813 * Determines if a user is currently logged in
1819 function isloggedin() {
1822 return (!empty($USER->id));
1826 * Determines if a user is logged in as real guest user with username 'guest'.
1830 * @param int|object $user mixed user object or id, $USER if not specified
1831 * @return bool true if user is the real guest user, false if not logged in or other user
1833 function isguestuser($user = null) {
1834 global $USER, $DB, $CFG;
1836 // make sure we have the user id cached in config table, because we are going to use it a lot
1837 if (empty($CFG->siteguest)) {
1838 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1839 // guest does not exist yet, weird
1842 set_config('siteguest', $guestid);
1844 if ($user === null) {
1848 if ($user === null) {
1849 // happens when setting the $USER
1852 } else if (is_numeric($user)) {
1853 return ($CFG->siteguest == $user);
1855 } else if (is_object($user)) {
1856 if (empty($user->id)) {
1857 return false; // not logged in means is not be guest
1859 return ($CFG->siteguest == $user->id);
1863 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1868 * Does user have a (temporary or real) guest access to course?
1872 * @param context $context
1873 * @param stdClass|int $user
1876 function is_guest(context $context, $user = null) {
1879 // first find the course context
1880 $coursecontext = $context->get_course_context();
1882 // make sure there is a real user specified
1883 if ($user === null) {
1884 $userid = isset($USER->id) ? $USER->id : 0;
1886 $userid = is_object($user) ? $user->id : $user;
1889 if (isguestuser($userid)) {
1890 // can not inspect or be enrolled
1894 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1895 // viewing users appear out of nowhere, they are neither guests nor participants
1899 // consider only real active enrolments here
1900 if (is_enrolled($coursecontext, $user, '', true)) {
1908 * Returns true if the user has moodle/course:view capability in the course,
1909 * this is intended for admins, managers (aka small admins), inspectors, etc.
1913 * @param context $context
1914 * @param int|stdClass $user if null $USER is used
1915 * @param string $withcapability extra capability name
1918 function is_viewing(context $context, $user = null, $withcapability = '') {
1919 // first find the course context
1920 $coursecontext = $context->get_course_context();
1922 if (isguestuser($user)) {
1927 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1928 // admins are allowed to inspect courses
1932 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1933 // site admins always have the capability, but the enrolment above blocks
1941 * Returns true if user is enrolled (is participating) in course
1942 * this is intended for students and teachers.
1944 * Since 2.2 the result for active enrolments and current user are cached.
1946 * @package core_enrol
1949 * @param context $context
1950 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1951 * @param string $withcapability extra capability name
1952 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1955 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1958 // first find the course context
1959 $coursecontext = $context->get_course_context();
1961 // make sure there is a real user specified
1962 if ($user === null) {
1963 $userid = isset($USER->id) ? $USER->id : 0;
1965 $userid = is_object($user) ? $user->id : $user;
1968 if (empty($userid)) {
1971 } else if (isguestuser($userid)) {
1972 // guest account can not be enrolled anywhere
1976 if ($coursecontext->instanceid == SITEID) {
1977 // everybody participates on frontpage
1979 // try cached info first - the enrolled flag is set only when active enrolment present
1980 if ($USER->id == $userid) {
1981 $coursecontext->reload_if_dirty();
1982 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1983 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
1984 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1993 // look for active enrolments only
1994 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1996 if ($until === false) {
2000 if ($USER->id == $userid) {
2002 $until = ENROL_MAX_TIMESTAMP;
2004 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
2005 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
2006 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
2007 remove_temp_course_roles($coursecontext);
2012 // any enrolment is good for us here, even outdated, disabled or inactive
2014 FROM {user_enrolments} ue
2015 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2016 JOIN {user} u ON u.id = ue.userid
2017 WHERE ue.userid = :userid AND u.deleted = 0";
2018 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2019 if (!$DB->record_exists_sql($sql, $params)) {
2025 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2033 * Returns true if the user is able to access the course.
2035 * This function is in no way, shape, or form a substitute for require_login.
2036 * It should only be used in circumstances where it is not possible to call require_login
2037 * such as the navigation.
2039 * This function checks many of the methods of access to a course such as the view
2040 * capability, enrollments, and guest access. It also makes use of the cache
2041 * generated by require_login for guest access.
2043 * The flags within the $USER object that are used here should NEVER be used outside
2044 * of this function can_access_course and require_login. Doing so WILL break future
2047 * @param stdClass $course record
2048 * @param stdClass|int|null $user user record or id, current user if null
2049 * @param string $withcapability Check for this capability as well.
2050 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2051 * @return boolean Returns true if the user is able to access the course
2053 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
2056 // this function originally accepted $coursecontext parameter
2057 if ($course instanceof context) {
2058 if ($course instanceof context_course) {
2059 debugging('deprecated context parameter, please use $course record');
2060 $coursecontext = $course;
2061 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2063 debugging('Invalid context parameter, please use $course record');
2067 $coursecontext = context_course::instance($course->id);
2070 if (!isset($USER->id)) {
2071 // should never happen
2073 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
2076 // make sure there is a user specified
2077 if ($user === null) {
2078 $userid = $USER->id;
2080 $userid = is_object($user) ? $user->id : $user;
2084 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2088 if ($userid == $USER->id) {
2089 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2090 // the fact that somebody switched role means they can access the course no matter to what role they switched
2095 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2099 if (is_viewing($coursecontext, $userid)) {
2103 if ($userid != $USER->id) {
2104 // for performance reasons we do not verify temporary guest access for other users, sorry...
2105 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2108 // === from here we deal only with $USER ===
2110 $coursecontext->reload_if_dirty();
2112 if (isset($USER->enrol['enrolled'][$course->id])) {
2113 if ($USER->enrol['enrolled'][$course->id] > time()) {
2117 if (isset($USER->enrol['tempguest'][$course->id])) {
2118 if ($USER->enrol['tempguest'][$course->id] > time()) {
2123 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2127 // if not enrolled try to gain temporary guest access
2128 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2129 $enrols = enrol_get_plugins(true);
2130 foreach($instances as $instance) {
2131 if (!isset($enrols[$instance->enrol])) {
2134 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2135 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2136 if ($until !== false and $until > time()) {
2137 $USER->enrol['tempguest'][$course->id] = $until;
2141 if (isset($USER->enrol['tempguest'][$course->id])) {
2142 unset($USER->enrol['tempguest'][$course->id]);
2143 remove_temp_course_roles($coursecontext);
2150 * Returns array with sql code and parameters returning all ids
2151 * of users enrolled into course.
2153 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2155 * @package core_enrol
2158 * @param context $context
2159 * @param string $withcapability
2160 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2161 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2162 * @return array list($sql, $params)
2164 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2167 // use unique prefix just in case somebody makes some SQL magic with the result
2170 $prefix = 'eu'.$i.'_';
2172 // first find the course context
2173 $coursecontext = $context->get_course_context();
2175 $isfrontpage = ($coursecontext->instanceid == SITEID);
2181 list($contextids, $contextpaths) = get_context_info_list($context);
2183 // get all relevant capability info for all roles
2184 if ($withcapability) {
2185 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2186 $cparams['cap'] = $withcapability;
2189 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2190 FROM {role_capabilities} rc
2191 JOIN {context} ctx on rc.contextid = ctx.id
2192 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2193 $rcs = $DB->get_records_sql($sql, $cparams);
2194 foreach ($rcs as $rc) {
2195 $defs[$rc->path][$rc->roleid] = $rc->permission;
2199 if (!empty($defs)) {
2200 foreach ($contextpaths as $path) {
2201 if (empty($defs[$path])) {
2204 foreach($defs[$path] as $roleid => $perm) {
2205 if ($perm == CAP_PROHIBIT) {
2206 $access[$roleid] = CAP_PROHIBIT;
2209 if (!isset($access[$roleid])) {
2210 $access[$roleid] = (int)$perm;
2218 // make lists of roles that are needed and prohibited
2219 $needed = array(); // one of these is enough
2220 $prohibited = array(); // must not have any of these
2221 foreach ($access as $roleid => $perm) {
2222 if ($perm == CAP_PROHIBIT) {
2223 unset($needed[$roleid]);
2224 $prohibited[$roleid] = true;
2225 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2226 $needed[$roleid] = true;
2230 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2231 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2236 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2238 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2239 // everybody not having prohibit has the capability
2241 } else if (empty($needed)) {
2245 if (!empty($prohibited[$defaultuserroleid])) {
2247 } else if (!empty($needed[$defaultuserroleid])) {
2248 // everybody not having prohibit has the capability
2250 } else if (empty($needed)) {
2256 // nobody can match so return some SQL that does not return any results
2257 $wheres[] = "1 = 2";
2262 $ctxids = implode(',', $contextids);
2263 $roleids = implode(',', array_keys($needed));
2264 $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))";
2268 $ctxids = implode(',', $contextids);
2269 $roleids = implode(',', array_keys($prohibited));
2270 $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))";
2271 $wheres[] = "{$prefix}ra4.id IS NULL";
2275 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2276 $params["{$prefix}gmid"] = $groupid;
2282 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2283 $params["{$prefix}gmid"] = $groupid;
2287 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2288 $params["{$prefix}guestid"] = $CFG->siteguest;
2291 // all users are "enrolled" on the frontpage
2293 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2294 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2295 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2298 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2299 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2300 $now = round(time(), -2); // rounding helps caching in DB
2301 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2302 $prefix.'active'=>ENROL_USER_ACTIVE,
2303 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2307 $joins = implode("\n", $joins);
2308 $wheres = "WHERE ".implode(" AND ", $wheres);
2310 $sql = "SELECT DISTINCT {$prefix}u.id
2311 FROM {user} {$prefix}u
2315 return array($sql, $params);
2319 * Returns list of users enrolled into course.
2321 * @package core_enrol
2324 * @param context $context
2325 * @param string $withcapability
2326 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2327 * @param string $userfields requested user record fields
2328 * @param string $orderby
2329 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2330 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2331 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2332 * @return array of user records
2334 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
2335 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
2338 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2339 $sql = "SELECT $userfields
2341 JOIN ($esql) je ON je.id = u.id
2342 WHERE u.deleted = 0";
2345 $sql = "$sql ORDER BY $orderby";
2347 list($sort, $sortparams) = users_order_by_sql('u');
2348 $sql = "$sql ORDER BY $sort";
2349 $params = array_merge($params, $sortparams);
2352 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2356 * Counts list of users enrolled into course (as per above function)
2358 * @package core_enrol
2361 * @param context $context
2362 * @param string $withcapability
2363 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2364 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2365 * @return array of user records
2367 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2370 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2371 $sql = "SELECT count(u.id)
2373 JOIN ($esql) je ON je.id = u.id
2374 WHERE u.deleted = 0";
2376 return $DB->count_records_sql($sql, $params);
2380 * Loads the capability definitions for the component (from file).
2382 * Loads the capability definitions for the component (from file). If no
2383 * capabilities are defined for the component, we simply return an empty array.
2386 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2387 * @return array array of capabilities
2389 function load_capability_def($component) {
2390 $defpath = get_component_directory($component).'/db/access.php';
2392 $capabilities = array();
2393 if (file_exists($defpath)) {
2395 if (!empty(${$component.'_capabilities'})) {
2396 // BC capability array name
2397 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2398 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2399 $capabilities = ${$component.'_capabilities'};
2403 return $capabilities;
2407 * Gets the capabilities that have been cached in the database for this component.
2410 * @param string $component - examples: 'moodle', 'mod_forum'
2411 * @return array array of capabilities
2413 function get_cached_capabilities($component = 'moodle') {
2415 return $DB->get_records('capabilities', array('component'=>$component));
2419 * Returns default capabilities for given role archetype.
2421 * @param string $archetype role archetype
2424 function get_default_capabilities($archetype) {
2432 $defaults = array();
2433 $components = array();
2434 $allcaps = $DB->get_records('capabilities');
2436 foreach ($allcaps as $cap) {
2437 if (!in_array($cap->component, $components)) {
2438 $components[] = $cap->component;
2439 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2442 foreach($alldefs as $name=>$def) {
2443 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2444 if (isset($def['archetypes'])) {
2445 if (isset($def['archetypes'][$archetype])) {
2446 $defaults[$name] = $def['archetypes'][$archetype];
2448 // 'legacy' is for backward compatibility with 1.9 access.php
2450 if (isset($def['legacy'][$archetype])) {
2451 $defaults[$name] = $def['legacy'][$archetype];
2460 * Return default roles that can be assigned, overridden or switched
2461 * by give role archetype.
2463 * @param string $type assign|override|switch
2464 * @param string $archetype
2465 * @return array of role ids
2467 function get_default_role_archetype_allows($type, $archetype) {
2470 if (empty($archetype)) {
2474 $roles = $DB->get_records('role');
2475 $archetypemap = array();
2476 foreach ($roles as $role) {
2477 if ($role->archetype) {
2478 $archetypemap[$role->archetype][$role->id] = $role->id;
2484 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2485 'coursecreator' => array(),
2486 'editingteacher' => array('teacher', 'student'),
2487 'teacher' => array(),
2488 'student' => array(),
2491 'frontpage' => array(),
2493 'override' => array(
2494 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2495 'coursecreator' => array(),
2496 'editingteacher' => array('teacher', 'student', 'guest'),
2497 'teacher' => array(),
2498 'student' => array(),
2501 'frontpage' => array(),
2504 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2505 'coursecreator' => array(),
2506 'editingteacher' => array('teacher', 'student', 'guest'),
2507 'teacher' => array('student', 'guest'),
2508 'student' => array(),
2511 'frontpage' => array(),
2515 if (!isset($defaults[$type][$archetype])) {
2516 debugging("Unknown type '$type'' or archetype '$archetype''");
2521 foreach ($defaults[$type][$archetype] as $at) {
2522 if (isset($archetypemap[$at])) {
2523 foreach ($archetypemap[$at] as $roleid) {
2524 $return[$roleid] = $roleid;
2533 * Reset role capabilities to default according to selected role archetype.
2534 * If no archetype selected, removes all capabilities.
2536 * @param int $roleid
2539 function reset_role_capabilities($roleid) {
2542 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2543 $defaultcaps = get_default_capabilities($role->archetype);
2545 $systemcontext = context_system::instance();
2547 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2549 foreach($defaultcaps as $cap=>$permission) {
2550 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2555 * Updates the capabilities table with the component capability definitions.
2556 * If no parameters are given, the function updates the core moodle
2559 * Note that the absence of the db/access.php capabilities definition file
2560 * will cause any stored capabilities for the component to be removed from
2564 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2565 * @return boolean true if success, exception in case of any problems
2567 function update_capabilities($component = 'moodle') {
2568 global $DB, $OUTPUT;
2570 $storedcaps = array();
2572 $filecaps = load_capability_def($component);
2573 foreach($filecaps as $capname=>$unused) {
2574 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2575 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2579 $cachedcaps = get_cached_capabilities($component);
2581 foreach ($cachedcaps as $cachedcap) {
2582 array_push($storedcaps, $cachedcap->name);
2583 // update risk bitmasks and context levels in existing capabilities if needed
2584 if (array_key_exists($cachedcap->name, $filecaps)) {
2585 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2586 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2588 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2589 $updatecap = new stdClass();
2590 $updatecap->id = $cachedcap->id;
2591 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2592 $DB->update_record('capabilities', $updatecap);
2594 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2595 $updatecap = new stdClass();
2596 $updatecap->id = $cachedcap->id;
2597 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2598 $DB->update_record('capabilities', $updatecap);
2601 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2602 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2604 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2605 $updatecap = new stdClass();
2606 $updatecap->id = $cachedcap->id;
2607 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2608 $DB->update_record('capabilities', $updatecap);
2614 // Are there new capabilities in the file definition?
2617 foreach ($filecaps as $filecap => $def) {
2619 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2620 if (!array_key_exists('riskbitmask', $def)) {
2621 $def['riskbitmask'] = 0; // no risk if not specified
2623 $newcaps[$filecap] = $def;
2626 // Add new capabilities to the stored definition.
2627 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2628 foreach ($newcaps as $capname => $capdef) {
2629 $capability = new stdClass();
2630 $capability->name = $capname;
2631 $capability->captype = $capdef['captype'];
2632 $capability->contextlevel = $capdef['contextlevel'];
2633 $capability->component = $component;
2634 $capability->riskbitmask = $capdef['riskbitmask'];
2636 $DB->insert_record('capabilities', $capability, false);
2638 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2639 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2640 foreach ($rolecapabilities as $rolecapability){
2641 //assign_capability will update rather than insert if capability exists
2642 if (!assign_capability($capname, $rolecapability->permission,
2643 $rolecapability->roleid, $rolecapability->contextid, true)){
2644 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2648 // we ignore archetype key if we have cloned permissions
2649 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2650 assign_legacy_capabilities($capname, $capdef['archetypes']);
2651 // 'legacy' is for backward compatibility with 1.9 access.php
2652 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2653 assign_legacy_capabilities($capname, $capdef['legacy']);
2656 // Are there any capabilities that have been removed from the file
2657 // definition that we need to delete from the stored capabilities and
2658 // role assignments?
2659 capabilities_cleanup($component, $filecaps);
2661 // reset static caches
2662 accesslib_clear_all_caches(false);
2668 * Deletes cached capabilities that are no longer needed by the component.
2669 * Also unassigns these capabilities from any roles that have them.
2672 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2673 * @param array $newcapdef array of the new capability definitions that will be
2674 * compared with the cached capabilities
2675 * @return int number of deprecated capabilities that have been removed
2677 function capabilities_cleanup($component, $newcapdef = null) {
2682 if ($cachedcaps = get_cached_capabilities($component)) {
2683 foreach ($cachedcaps as $cachedcap) {
2684 if (empty($newcapdef) ||
2685 array_key_exists($cachedcap->name, $newcapdef) === false) {
2687 // Remove from capabilities cache.
2688 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2690 // Delete from roles.
2691 if ($roles = get_roles_with_capability($cachedcap->name)) {
2692 foreach($roles as $role) {
2693 if (!unassign_capability($cachedcap->name, $role->id)) {
2694 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2701 return $removedcount;
2705 * Returns an array of all the known types of risk
2706 * The array keys can be used, for example as CSS class names, or in calls to
2707 * print_risk_icon. The values are the corresponding RISK_ constants.
2709 * @return array all the known types of risk.
2711 function get_all_risks() {
2713 'riskmanagetrust' => RISK_MANAGETRUST,
2714 'riskconfig' => RISK_CONFIG,
2715 'riskxss' => RISK_XSS,
2716 'riskpersonal' => RISK_PERSONAL,
2717 'riskspam' => RISK_SPAM,
2718 'riskdataloss' => RISK_DATALOSS,
2723 * Return a link to moodle docs for a given capability name
2725 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2726 * @return string the human-readable capability name as a link to Moodle Docs.
2728 function get_capability_docs_link($capability) {
2729 $url = get_docs_url('Capabilities/' . $capability->name);
2730 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2734 * This function pulls out all the resolved capabilities (overrides and
2735 * defaults) of a role used in capability overrides in contexts at a given
2738 * @param int $roleid
2739 * @param context $context
2740 * @param string $cap capability, optional, defaults to ''
2741 * @return array Array of capabilities
2743 function role_context_capabilities($roleid, context $context, $cap = '') {
2746 $contexts = $context->get_parent_context_ids(true);
2747 $contexts = '('.implode(',', $contexts).')';
2749 $params = array($roleid);
2752 $search = " AND rc.capability = ? ";
2759 FROM {role_capabilities} rc, {context} c
2760 WHERE rc.contextid in $contexts
2762 AND rc.contextid = c.id $search
2763 ORDER BY c.contextlevel DESC, rc.capability DESC";
2765 $capabilities = array();
2767 if ($records = $DB->get_records_sql($sql, $params)) {
2768 // We are traversing via reverse order.
2769 foreach ($records as $record) {
2770 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2771 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2772 $capabilities[$record->capability] = $record->permission;
2776 return $capabilities;
2780 * Constructs array with contextids as first parameter and context paths,
2781 * in both cases bottom top including self.
2784 * @param context $context
2787 function get_context_info_list(context $context) {
2788 $contextids = explode('/', ltrim($context->path, '/'));
2789 $contextpaths = array();
2790 $contextids2 = $contextids;
2791 while ($contextids2) {
2792 $contextpaths[] = '/' . implode('/', $contextids2);
2793 array_pop($contextids2);
2795 return array($contextids, $contextpaths);
2799 * Check if context is the front page context or a context inside it
2801 * Returns true if this context is the front page context, or a context inside it,
2804 * @param context $context a context object.
2807 function is_inside_frontpage(context $context) {
2808 $frontpagecontext = context_course::instance(SITEID);
2809 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2813 * Returns capability information (cached)
2815 * @param string $capabilityname
2816 * @return stdClass or null if capability not found
2818 function get_capability_info($capabilityname) {
2819 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2821 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2823 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2824 $ACCESSLIB_PRIVATE->capabilities = array();
2825 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2826 foreach ($caps as $cap) {
2827 $capname = $cap->name;
2830 $cap->riskbitmask = (int)$cap->riskbitmask;
2831 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2835 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2839 * Returns the human-readable, translated version of the capability.
2840 * Basically a big switch statement.
2842 * @param string $capabilityname e.g. mod/choice:readresponses
2845 function get_capability_string($capabilityname) {
2847 // Typical capability name is 'plugintype/pluginname:capabilityname'
2848 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2850 if ($type === 'moodle') {
2851 $component = 'core_role';
2852 } else if ($type === 'quizreport') {
2854 $component = 'quiz_'.$name;
2856 $component = $type.'_'.$name;
2859 $stringname = $name.':'.$capname;
2861 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2862 return get_string($stringname, $component);
2865 $dir = get_component_directory($component);
2866 if (!file_exists($dir)) {
2867 // plugin broken or does not exist, do not bother with printing of debug message
2868 return $capabilityname.' ???';
2871 // something is wrong in plugin, better print debug
2872 return get_string($stringname, $component);
2876 * This gets the mod/block/course/core etc strings.
2878 * @param string $component
2879 * @param int $contextlevel
2880 * @return string|bool String is success, false if failed
2882 function get_component_string($component, $contextlevel) {
2884 if ($component === 'moodle' or $component === 'core') {
2885 switch ($contextlevel) {
2886 // TODO: this should probably use context level names instead
2887 case CONTEXT_SYSTEM: return get_string('coresystem');
2888 case CONTEXT_USER: return get_string('users');
2889 case CONTEXT_COURSECAT: return get_string('categories');
2890 case CONTEXT_COURSE: return get_string('course');
2891 case CONTEXT_MODULE: return get_string('activities');
2892 case CONTEXT_BLOCK: return get_string('block');
2893 default: print_error('unknowncontext');
2897 list($type, $name) = normalize_component($component);
2898 $dir = get_plugin_directory($type, $name);
2899 if (!file_exists($dir)) {
2900 // plugin not installed, bad luck, there is no way to find the name
2901 return $component.' ???';
2905 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2906 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2907 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2908 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2909 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2910 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2911 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2912 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2914 if (get_string_manager()->string_exists('pluginname', $component)) {
2915 return get_string('activity').': '.get_string('pluginname', $component);
2917 return get_string('activity').': '.get_string('modulename', $component);
2919 default: return get_string('pluginname', $component);
2924 * Gets the list of roles assigned to this context and up (parents)
2925 * from the list of roles that are visible on user profile page
2926 * and participants page.
2928 * @param context $context
2931 function get_profile_roles(context $context) {
2934 if (empty($CFG->profileroles)) {
2938 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2939 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2940 $params = array_merge($params, $cparams);
2942 if ($coursecontext = $context->get_course_context(false)) {
2943 $params['coursecontext'] = $coursecontext->id;
2945 $params['coursecontext'] = 0;
2948 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2949 FROM {role_assignments} ra, {role} r
2950 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2951 WHERE r.id = ra.roleid
2952 AND ra.contextid $contextlist
2954 ORDER BY r.sortorder ASC";
2956 return $DB->get_records_sql($sql, $params);
2960 * Gets the list of roles assigned to this context and up (parents)
2962 * @param context $context
2965 function get_roles_used_in_context(context $context) {
2968 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2970 if ($coursecontext = $context->get_course_context(false)) {
2971 $params['coursecontext'] = $coursecontext->id;
2973 $params['coursecontext'] = 0;
2976 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2977 FROM {role_assignments} ra, {role} r
2978 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2979 WHERE r.id = ra.roleid
2980 AND ra.contextid $contextlist
2981 ORDER BY r.sortorder ASC";
2983 return $DB->get_records_sql($sql, $params);
2987 * This function is used to print roles column in user profile page.
2988 * It is using the CFG->profileroles to limit the list to only interesting roles.
2989 * (The permission tab has full details of user role assignments.)
2991 * @param int $userid
2992 * @param int $courseid
2995 function get_user_roles_in_course($userid, $courseid) {
2998 if (empty($CFG->profileroles)) {
3002 if ($courseid == SITEID) {
3003 $context = context_system::instance();
3005 $context = context_course::instance($courseid);
3008 if (empty($CFG->profileroles)) {
3012 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
3013 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
3014 $params = array_merge($params, $cparams);
3016 if ($coursecontext = $context->get_course_context(false)) {
3017 $params['coursecontext'] = $coursecontext->id;
3019 $params['coursecontext'] = 0;
3022 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3023 FROM {role_assignments} ra, {role} r
3024 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3025 WHERE r.id = ra.roleid
3026 AND ra.contextid $contextlist
3028 AND ra.userid = :userid
3029 ORDER BY r.sortorder ASC";
3030 $params['userid'] = $userid;
3034 if ($roles = $DB->get_records_sql($sql, $params)) {
3035 $rolenames = role_fix_names($roles, $context, ROLENAME_ALIAS, true); // Substitute aliases
3037 foreach ($rolenames as $roleid => $rolename) {
3038 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&roleid='.$roleid.'">'.$rolename.'</a>';
3040 $rolestring = implode(',', $rolenames);
3047 * Checks if a user can assign users to a particular role in this context
3049 * @param context $context
3050 * @param int $targetroleid - the id of the role you want to assign users to
3053 function user_can_assign(context $context, $targetroleid) {
3056 // First check to see if the user is a site administrator.
3057 if (is_siteadmin()) {
3061 // Check if user has override capability.
3062 // If not return false.
3063 if (!has_capability('moodle/role:assign', $context)) {
3066 // pull out all active roles of this user from this context(or above)
3067 if ($userroles = get_user_roles($context)) {
3068 foreach ($userroles as $userrole) {
3069 // if any in the role_allow_override table, then it's ok
3070 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
3080 * Returns all site roles in correct sort order.
3082 * Note: this method does not localise role names or descriptions,
3083 * use role_get_names() if you need role names.
3085 * @param context $context optional context for course role name aliases
3086 * @return array of role records with optional coursealias property
3088 function get_all_roles(context $context = null) {
3091 if (!$context or !$coursecontext = $context->get_course_context(false)) {
3092 $coursecontext = null;
3095 if ($coursecontext) {
3096 $sql = "SELECT r.*, rn.name AS coursealias
3098 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3099 ORDER BY r.sortorder ASC";
3100 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
3103 return $DB->get_records('role', array(), 'sortorder ASC');
3108 * Returns roles of a specified archetype
3110 * @param string $archetype
3111 * @return array of full role records
3113 function get_archetype_roles($archetype) {
3115 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
3119 * Gets all the user roles assigned in this context, or higher contexts
3120 * this is mainly used when checking if a user can assign a role, or overriding a role
3121 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3122 * allow_override tables
3124 * @param context $context
3125 * @param int $userid
3126 * @param bool $checkparentcontexts defaults to true
3127 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
3130 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
3133 if (empty($userid)) {
3134 if (empty($USER->id)) {
3137 $userid = $USER->id;
3140 if ($checkparentcontexts) {
3141 $contextids = $context->get_parent_context_ids();
3143 $contextids = array();
3145 $contextids[] = $context->id;
3147 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3149 array_unshift($params, $userid);
3151 $sql = "SELECT ra.*, r.name, r.shortname
3152 FROM {role_assignments} ra, {role} r, {context} c
3154 AND ra.roleid = r.id
3155 AND ra.contextid = c.id
3156 AND ra.contextid $contextids
3159 return $DB->get_records_sql($sql ,$params);
3163 * Like get_user_roles, but adds in the authenticated user role, and the front
3164 * page roles, if applicable.
3166 * @param context $context the context.
3167 * @param int $userid optional. Defaults to $USER->id
3168 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3170 function get_user_roles_with_special(context $context, $userid = 0) {
3173 if (empty($userid)) {
3174 if (empty($USER->id)) {
3177 $userid = $USER->id;
3180 $ras = get_user_roles($context, $userid);
3182 // Add front-page role if relevant.
3183 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3184 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3185 is_inside_frontpage($context);
3186 if ($defaultfrontpageroleid && $isfrontpage) {
3187 $frontpagecontext = context_course::instance(SITEID);
3188 $ra = new stdClass();
3189 $ra->userid = $userid;
3190 $ra->contextid = $frontpagecontext->id;
3191 $ra->roleid = $defaultfrontpageroleid;
3195 // Add authenticated user role if relevant.
3196 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3197 if ($defaultuserroleid && !isguestuser($userid)) {
3198 $systemcontext = context_system::instance();
3199 $ra = new stdClass();
3200 $ra->userid = $userid;
3201 $ra->contextid = $systemcontext->id;
3202 $ra->roleid = $defaultuserroleid;
3210 * Creates a record in the role_allow_override table
3212 * @param int $sroleid source roleid
3213 * @param int $troleid target roleid
3216 function allow_override($sroleid, $troleid) {
3219 $record = new stdClass();
3220 $record->roleid = $sroleid;
3221 $record->allowoverride = $troleid;
3222 $DB->insert_record('role_allow_override', $record);
3226 * Creates a record in the role_allow_assign table
3228 * @param int $fromroleid source roleid
3229 * @param int $targetroleid target roleid
3232 function allow_assign($fromroleid, $targetroleid) {
3235 $record = new stdClass();
3236 $record->roleid = $fromroleid;
3237 $record->allowassign = $targetroleid;
3238 $DB->insert_record('role_allow_assign', $record);
3242 * Creates a record in the role_allow_switch table
3244 * @param int $fromroleid source roleid
3245 * @param int $targetroleid target roleid
3248 function allow_switch($fromroleid, $targetroleid) {
3251 $record = new stdClass();
3252 $record->roleid = $fromroleid;
3253 $record->allowswitch = $targetroleid;
3254 $DB->insert_record('role_allow_switch', $record);
3258 * Gets a list of roles that this user can assign in this context
3260 * @param context $context the context.
3261 * @param int $rolenamedisplay the type of role name to display. One of the
3262 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3263 * @param bool $withusercounts if true, count the number of users with each role.
3264 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3265 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3266 * if $withusercounts is true, returns a list of three arrays,
3267 * $rolenames, $rolecounts, and $nameswithcounts.
3269 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3272 // make sure there is a real user specified
3273 if ($user === null) {
3274 $userid = isset($USER->id) ? $USER->id : 0;
3276 $userid = is_object($user) ? $user->id : $user;
3279 if (!has_capability('moodle/role:assign', $context, $userid)) {
3280 if ($withusercounts) {
3281 return array(array(), array(), array());
3290 if ($withusercounts) {
3291 $extrafields = ', (SELECT count(u.id)
3292 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3293 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3295 $params['conid'] = $context->id;
3298 if (is_siteadmin($userid)) {
3299 // show all roles allowed in this context to admins
3300 $assignrestriction = "";
3302 $parents = $context->get_parent_context_ids(true);
3303 $contexts = implode(',' , $parents);
3304 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3305 FROM {role_allow_assign} raa
3306 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3307 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3308 ) ar ON ar.id = r.id";
3309 $params['userid'] = $userid;
3311 $params['contextlevel'] = $context->contextlevel;
3313 if ($coursecontext = $context->get_course_context(false)) {
3314 $params['coursecontext'] = $coursecontext->id;
3316 $params['coursecontext'] = 0; // no course aliases
3317 $coursecontext = null;
3319 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3322 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3323 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3324 ORDER BY r.sortorder ASC";
3325 $roles = $DB->get_records_sql($sql, $params);
3327 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3329 if (!$withusercounts) {
3333 $rolecounts = array();
3334 $nameswithcounts = array();
3335 foreach ($roles as $role) {
3336 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3337 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3339 return array($rolenames, $rolecounts, $nameswithcounts);
3343 * Gets a list of roles that this user can switch to in a context
3345 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3346 * This function just process the contents of the role_allow_switch table. You also need to
3347 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3349 * @param context $context a context.
3350 * @return array an array $roleid => $rolename.
3352 function get_switchable_roles(context $context) {
3358 if (!is_siteadmin()) {
3359 // Admins are allowed to switch to any role with.
3360 // Others are subject to the additional constraint that the switch-to role must be allowed by
3361 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3362 $parents = $context->get_parent_context_ids(true);
3363 $contexts = implode(',' , $parents);
3365 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3366 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3367 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3368 $params['userid'] = $USER->id;
3371 if ($coursecontext = $context->get_course_context(false)) {
3372 $params['coursecontext'] = $coursecontext->id;
3374 $params['coursecontext'] = 0; // no course aliases
3375 $coursecontext = null;
3379 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3380 FROM (SELECT DISTINCT rc.roleid
3381 FROM {role_capabilities} rc
3384 JOIN {role} r ON r.id = idlist.roleid
3385 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3386 ORDER BY r.sortorder";
3387 $roles = $DB->get_records_sql($query, $params);
3389 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3393 * Gets a list of roles that this user can override in this context.
3395 * @param context $context the context.
3396 * @param int $rolenamedisplay the type of role name to display. One of the
3397 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3398 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3399 * @return array if $withcounts is false, then an array $roleid => $rolename.
3400 * if $withusercounts is true, returns a list of three arrays,
3401 * $rolenames, $rolecounts, and $nameswithcounts.
3403 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3406 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3408 return array(array(), array(), array());
3414 $parents = $context->get_parent_context_ids(true);
3415 $contexts = implode(',' , $parents);
3420 $params['userid'] = $USER->id;
3422 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3423 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3424 $params['conid'] = $context->id;
3427 if ($coursecontext = $context->get_course_context(false)) {
3428 $params['coursecontext'] = $coursecontext->id;
3430 $params['coursecontext'] = 0; // no course aliases
3431 $coursecontext = null;
3434 if (is_siteadmin()) {
3435 // show all roles to admins
3436 $roles = $DB->get_records_sql("
3437 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3439 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3440 ORDER BY ro.sortorder ASC", $params);
3443 $roles = $DB->get_records_sql("
3444 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3446 JOIN (SELECT DISTINCT r.id
3448 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3449 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3450 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3451 ) inline_view ON ro.id = inline_view.id
3452 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3453 ORDER BY ro.sortorder ASC", $params);
3456 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3462 $rolecounts = array();
3463 $nameswithcounts = array();
3464 foreach ($roles as $role) {
3465 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3466 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3468 return array($rolenames, $rolecounts, $nameswithcounts);
3472 * Create a role menu suitable for default role selection in enrol plugins.
3474 * @package core_enrol
3476 * @param context $context
3477 * @param int $addroleid current or default role - always added to list
3478 * @return array roleid=>localised role name
3480 function get_default_enrol_roles(context $context, $addroleid = null) {
3483 $params = array('contextlevel'=>CONTEXT_COURSE);
3485 if ($coursecontext = $context->get_course_context(false)) {
3486 $params['coursecontext'] = $coursecontext->id;
3488 $params['coursecontext'] = 0; // no course names
3489 $coursecontext = null;
3493 $addrole = "OR r.id = :addroleid";
3494 $params['addroleid'] = $addroleid;
3499 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3501 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3502 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3503 WHERE rcl.id IS NOT NULL $addrole
3504 ORDER BY sortorder DESC";
3506 $roles = $DB->get_records_sql($sql, $params);
3508 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3512 * Return context levels where this role is assignable.
3514 * @param integer $roleid the id of a role.
3515 * @return array list of the context levels at which this role may be assigned.
3517 function get_role_contextlevels($roleid) {
3519 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3520 'contextlevel', 'id,contextlevel');
3524 * Return roles suitable for assignment at the specified context level.
3526 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3528 * @param integer $contextlevel a contextlevel.
3529 * @return array list of role ids that are assignable at this context level.
3531 function get_roles_for_contextlevels($contextlevel) {
3533 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3538 * Returns default context levels where roles can be assigned.
3540 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3541 * from the array returned by get_role_archetypes();
3542 * @return array list of the context levels at which this type of role may be assigned by default.
3544 function get_default_contextlevels($rolearchetype) {
3545 static $defaults = array(
3546 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3547 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3548 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3549 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3550 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3553 'frontpage' => array());
3555 if (isset($defaults[$rolearchetype])) {
3556 return $defaults[$rolearchetype];
3563 * Set the context levels at which a particular role can be assigned.
3564 * Throws exceptions in case of error.
3566 * @param integer $roleid the id of a role.
3567 * @param array $contextlevels the context levels at which this role should be assignable,
3568 * duplicate levels are removed.
3571 function set_role_contextlevels($roleid, array $contextlevels) {
3573 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3574 $rcl = new stdClass();
3575 $rcl->roleid = $roleid;
3576 $contextlevels = array_unique($contextlevels);
3577 foreach ($contextlevels as $level) {
3578 $rcl->contextlevel = $level;
3579 $DB->insert_record('role_context_levels', $rcl, false, true);
3584 * Who has this capability in this context?
3586 * This can be a very expensive call - use sparingly and keep
3587 * the results if you are going to need them again soon.
3589 * Note if $fields is empty this function attempts to get u.*
3590 * which can get rather large - and has a serious perf impact
3593 * @param context $context
3594 * @param string|array $capability - capability name(s)
3595 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3596 * @param string $sort - the sort order. Default is lastaccess time.
3597 * @param mixed $limitfrom - number of records to skip (offset)
3598 * @param mixed $limitnum - number of records to fetch
3599 * @param string|array $groups - single group or array of groups - only return
3600 * users who are in one of these group(s).
3601 * @param string|array $exceptions - list of users to exclude, comma separated or array
3602 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3603 * @param bool $view_ignored - use get_enrolled_sql() instead
3604 * @param bool $useviewallgroups if $groups is set the return users who
3605 * have capability both $capability and moodle/site:accessallgroups
3606 * in this context, as well as users who have $capability and who are
3608 * @return array of user records
3610 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3611 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3614 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3615 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3617 $ctxids = trim($context->path, '/');
3618 $ctxids = str_replace('/', ',', $ctxids);
3620 // Context is the frontpage
3621 $iscoursepage = false; // coursepage other than fp
3622 $isfrontpage = false;
3623 if ($context->contextlevel == CONTEXT_COURSE) {
3624 if ($context->instanceid == SITEID) {
3625 $isfrontpage = true;
3627 $iscoursepage = true;
3630 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3632 $caps = (array)$capability;
3634 // construct list of context paths bottom-->top
3635 list($contextids, $paths) = get_context_info_list($context);
3637 // we need to find out all roles that have these capabilities either in definition or in overrides
3639 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3640 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3641 $params = array_merge($params, $params2);
3642 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3643 FROM {role_capabilities} rc
3644 JOIN {context} ctx on rc.contextid = ctx.id
3645 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3647 $rcs = $DB->get_records_sql($sql, $params);
3648 foreach ($rcs as $rc) {
3649 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3652 // go through the permissions bottom-->top direction to evaluate the current permission,
3653 // first one wins (prohibit is an exception that always wins)
3655 foreach ($caps as $cap) {
3656 foreach ($paths as $path) {
3657 if (empty($defs[$cap][$path])) {
3660 foreach($defs[$cap][$path] as $roleid => $perm) {
3661 if ($perm == CAP_PROHIBIT) {
3662 $access[$cap][$roleid] = CAP_PROHIBIT;
3665 if (!isset($access[$cap][$roleid])) {
3666 $access[$cap][$roleid] = (int)$perm;
3672 // make lists of roles that are needed and prohibited in this context
3673 $needed = array(); // one of these is enough
3674 $prohibited = array(); // must not have any of these
3675 foreach ($caps as $cap) {
3676 if (empty($access[$cap])) {
3679 foreach ($access[$cap] as $roleid => $perm) {
3680 if ($perm == CAP_PROHIBIT) {
3681 unset($needed[$cap][$roleid]);
3682 $prohibited[$cap][$roleid] = true;
3683 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3684 $needed[$cap][$roleid] = true;
3687 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3688 // easy, nobody has the permission
3689 unset($needed[$cap]);
3690 unset($prohibited[$cap]);
3691 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3692 // everybody is disqualified on the frontpage
3693 unset($needed[$cap]);
3694 unset($prohibited[$cap]);
3696 if (empty($prohibited[$cap])) {
3697 unset($prohibited[$cap]);
3701 if (empty($needed)) {
3702 // there can not be anybody if no roles match this request
3706 if (empty($prohibited)) {
3707 // we can compact the needed roles
3709 foreach ($needed as $cap) {
3710 foreach ($cap as $roleid=>$unused) {
3714 $needed = array('any'=>$n);
3718 // ***** Set up default fields ******
3719 if (empty($fields)) {
3720 if ($iscoursepage) {
3721 $fields = 'u.*, ul.timeaccess AS lastaccess';
3726 if (debugging('', DEBUG_DEVELOPER) && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3727 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3731 // Set up default sort
3732 if (empty($sort)) { // default to course lastaccess or just lastaccess
3733 if ($iscoursepage) {
3734 $sort = 'ul.timeaccess';
3736 $sort = 'u.lastaccess';
3740 // Prepare query clauses
3741 $wherecond = array();
3745 // User lastaccess JOIN
3746 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3747 // user_lastaccess is not required MDL-13810
3749 if ($iscoursepage) {
3750 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3752 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3756 // We never return deleted users or guest account.
3757 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3758 $params['guestid'] = $CFG->siteguest;
3762 $groups = (array)$groups;
3763 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3764 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3765 $params = array_merge($params, $grpparams);
3767 if ($useviewallgroups) {
3768 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3769 if (!empty($viewallgroupsusers)) {
3770 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3772 $wherecond[] = "($grouptest)";
3775 $wherecond[] = "($grouptest)";
3780 if (!empty($exceptions)) {
3781 $exceptions = (array)$exceptions;
3782 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3783 $params = array_merge($params, $exparams);
3784 $wherecond[] = "u.id $exsql";
3787 // now add the needed and prohibited roles conditions as joins
3788 if (!empty($needed['any'])) {
3789 // simple case - there are no prohibits involved
3790 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3793 $joins[] = "JOIN (SELECT DISTINCT userid
3794 FROM {role_assignments}
3795 WHERE contextid IN ($ctxids)
3796 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3797 ) ra ON ra.userid = u.id";
3802 foreach ($needed as $cap=>$unused) {
3803 if (empty($prohibited[$cap])) {
3804 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3808 $unions[] = "SELECT userid
3809 FROM {role_assignments}
3810 WHERE contextid IN ($ctxids)
3811 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3814 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3815 // nobody can have this cap because it is prevented in default roles
3818 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3819 // everybody except the prohibitted - hiding does not matter
3820 $unions[] = "SELECT id AS userid
3822 WHERE id NOT IN (SELECT userid
3823 FROM {role_assignments}
3824 WHERE contextid IN ($ctxids)
3825 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3828 $unions[] = "SELECT userid
3829 FROM {role_assignments}
3830 WHERE contextid IN ($ctxids)
3831 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3832 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3838 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3840 // only prohibits found - nobody can be matched
3841 $wherecond[] = "1 = 2";
3846 // Collect WHERE conditions and needed joins
3847 $where = implode(' AND ', $wherecond);
3848 if ($where !== '') {
3849 $where = 'WHERE ' . $where;
3851 $joins = implode("\n", $joins);
3853 // Ok, let's get the users!
3854 $sql = "SELECT $fields
3860 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3864 * Re-sort a users array based on a sorting policy
3866 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3867 * based on a sorting policy. This is to support the odd practice of
3868 * sorting teachers by 'authority', where authority was "lowest id of the role
3871 * Will execute 1 database query. Only suitable for small numbers of users, as it
3872 * uses an u.id IN() clause.
3874 * Notes about the sorting criteria.
3876 * As a default, we cannot rely on role.sortorder because then
3877 * admins/coursecreators will always win. That is why the sane
3878 * rule "is locality matters most", with sortorder as 2nd
3881 * If you want role.sortorder, use the 'sortorder' policy, and
3882 * name explicitly what roles you want to cover. It's probably
3883 * a good idea to see what roles have the capabilities you want
3884 * (array_diff() them against roiles that have 'can-do-anything'
3885 * to weed out admin-ish roles. Or fetch a list of roles from
3886 * variables like $CFG->coursecontact .
3888 * @param array $users Users array, keyed on userid
3889 * @param context $context
3890 * @param array $roles ids of the roles to include, optional
3891 * @param string $sortpolicy defaults to locality, more about
3892 * @return array sorted copy of the array
3894 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3897 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3898 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3899 if (empty($roles)) {
3902 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3905 $sql = "SELECT ra.userid
3906 FROM {role_assignments} ra
3910 ON ra.contextid=ctx.id
3915 // Default 'locality' policy -- read PHPDoc notes
3916 // about sort policies...
3917 $orderby = 'ORDER BY '
3918 .'ctx.depth DESC, ' /* locality wins */
3919 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3920 .'ra.id'; /* role assignment order tie-breaker */
3921 if ($sortpolicy === 'sortorder') {
3922 $orderby = 'ORDER BY '
3923 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3924 .'ra.id'; /* role assignment order tie-breaker */
3927 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3928 $sortedusers = array();
3931 foreach ($sortedids as $id) {
3933 if (isset($seen[$id])) {
3939 $sortedusers[$id] = $users[$id];
3941 return $sortedusers;
3945 * Gets all the users assigned this role in this context or higher
3947 * @param int $roleid (can also be an array of ints!)
3948 * @param context $context
3949 * @param bool $parent if true, get list of users assigned in higher context too
3950 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3951 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3952 * null => use default sort from users_order_by_sql.
3953 * @param bool $all true means all, false means limit to enrolled users
3954 * @param string $group defaults to ''
3955 * @param mixed $limitfrom defaults to ''
3956 * @param mixed $limitnum defaults to ''
3957 * @param string $extrawheretest defaults to ''
3958 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3961 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3962 $sort = null, $all = true, $group = '',
3963 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3966 if (empty($fields)) {
3967 $allnames = get_all_user_name_fields(true, 'u');
3968 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
3969 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3970 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3971 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3972 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3975 $parentcontexts = '';
3977 $parentcontexts = substr($context->path, 1); // kill leading slash
3978 $parentcontexts = str_replace('/', ',', $parentcontexts);
3979 if ($parentcontexts !== '') {
3980 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3985 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
3986 $roleselect = "AND ra.roleid $rids";
3992 if ($coursecontext = $context->get_course_context(false)) {
3993 $params['coursecontext'] = $coursecontext->id;
3995 $params['coursecontext'] = 0;
3999 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
4000 $groupselect = " AND gm.groupid = :groupid ";
4001 $params['groupid'] = $group;
4007 $params['contextid'] = $context->id;
4009 if ($extrawheretest) {
4010 $extrawheretest = ' AND ' . $extrawheretest;
4013 if ($whereorsortparams) {
4014 $params = array_merge($params, $whereorsortparams);
4018 list($sort, $sortparams) = users_order_by_sql('u');
4019 $params = array_merge($params, $sortparams);
4022 if ($all === null) {
4023 // Previously null was used to indicate that parameter was not used.
4026 if (!$all and $coursecontext) {
4027 // Do not use get_enrolled_sql() here for performance reasons.
4028 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
4029 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
4030 $params['ecourseid'] = $coursecontext->instanceid;
4035 $sql = "SELECT DISTINCT $fields, ra.roleid
4036 FROM {role_assignments} ra
4037 JOIN {user} u ON u.id = ra.userid
4038 JOIN {role} r ON ra.roleid = r.id
4040 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
4042 WHERE (ra.contextid = :contextid $parentcontexts)
4046 ORDER BY $sort"; // join now so that we can just use fullname() later
4048 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
4052 * Counts all the users assigned this role in this context or higher
4054 * @param int|array $roleid either int or an array of ints
4055 * @param context $context
4056 * @param bool $parent if true, get list of users assigned in higher context too
4057 * @return int Returns the result count
4059 function count_role_users($roleid, context $context, $parent = false) {
4063 if ($contexts = $context->get_parent_context_ids()) {
4064 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4066 $parentcontexts = '';
4069 $parentcontexts = '';
4073 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
4074 $roleselect = "AND r.roleid $rids";
4080 array_unshift($params, $context->id);
4082 $sql = "SELECT COUNT(u.id)
4083 FROM {role_assignments} r
4084 JOIN {user} u ON u.id = r.userid
4085 WHERE (r.contextid = ? $parentcontexts)
4089 return $DB->count_records_sql($sql, $params);
4093 * This function gets the list of courses that this user has a particular capability in.
4094 * It is still not very efficient.
4096 * @param string $capability Capability in question
4097 * @param int $userid User ID or null for current user
4098 * @param bool $doanything True if 'doanything' is permitted (default)
4099 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4100 * otherwise use a comma-separated list of the fields you require, not including id
4101 * @param string $orderby If set, use a comma-separated list of fields from course
4102 * table with sql modifiers (DESC) if needed
4103 * @return array Array of courses, may have zero entries. Or false if query failed.
4105 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
4108 // Convert fields list and ordering
4110 if ($fieldsexceptid) {
4111 $fields = explode(',', $fieldsexceptid);
4112 foreach($fields as $field) {
4113 $fieldlist .= ',c.'.$field;
4117 $fields = explode(',', $orderby);
4119 foreach($fields as $field) {
4123 $orderby .= 'c.'.$field;
4125 $orderby = 'ORDER BY '.$orderby;
4128 // Obtain a list of everything relevant about all courses including context.
4129 // Note the result can be used directly as a context (we are going to), the course
4130 // fields are just appended.
4132 $contextpreload = context_helper::get_preload_record_columns_sql('x');
4135 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
4137 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
4139 // Check capability for each course in turn
4140 foreach ($rs as $course) {
4141 context_helper::preload_from_record($course);
4142 $context = context_course::instance($course->id);
4143 if (has_capability($capability, $context, $userid, $doanything)) {
4144 // We've got the capability. Make the record look like a course record
4146 $courses[] = $course;
4150 return empty($courses) ? false : $courses;
4154 * This function finds the roles assigned directly to this context only
4155 * i.e. no roles in parent contexts
4157 * @param context $context
4160 function get_roles_on_exact_context(context $context) {
4163 return $DB->get_records_sql("SELECT r.*
4164 FROM {role_assignments} ra, {role} r
4165 WHERE ra.roleid = r.id AND ra.contextid = ?",
4166 array($context->id));
4170 * Switches the current user to another role for the current session and only
4171 * in the given context.
4173 * The caller *must* check
4174 * - that this op is allowed
4175 * - that the requested role can be switched to in this context (use get_switchable_roles)
4176 * - that the requested role is NOT $CFG->defaultuserroleid
4178 * To "unswitch" pass 0 as the roleid.
4180 * This function *will* modify $USER->access - beware
4182 * @param integer $roleid the role to switch to.
4183 * @param context $context the context in which to perform the switch.
4184 * @return bool success or failure.
4186 function role_switch($roleid, context $context) {
4192 // - Add the ghost RA to $USER->access
4193 // as $USER->access['rsw'][$path] = $roleid
4195 // - Make sure $USER->access['rdef'] has the roledefs
4196 // it needs to honour the switcherole
4198 // Roledefs will get loaded "deep" here - down to the last child
4199 // context. Note that
4201 // - When visiting subcontexts, our selective accessdata loading
4202 // will still work fine - though those ra/rdefs will be ignored
4203 // appropriately while the switch is in place
4205 // - If a switcherole happens at a category with tons of courses
4206 // (that have many overrides for switched-to role), the session
4207 // will get... quite large. Sometimes you just can't win.
4209 // To un-switch just unset($USER->access['rsw'][$path])
4211 // Note: it is not possible to switch to roles that do not have course:view
4213 if (!isset($USER->access)) {
4214 load_all_capabilities();
4218 // Add the switch RA
4220 unset($USER->access['rsw'][$context->path]);
4224 $USER->access['rsw'][$context->path] = $roleid;
4227 load_role_access_by_context($roleid, $context, $USER->access);
4233 * Checks if the user has switched roles within the given course.
4235 * Note: You can only switch roles within the course, hence it takes a course id
4236 * rather than a context. On that note Petr volunteered to implement this across
4237 * all other contexts, all requests for this should be forwarded to him ;)
4239 * @param int $courseid The id of the course to check
4240 * @return bool True if the user has switched roles within the course.
4242 function is_role_switched($courseid) {
4244 $context = context_course::instance($courseid, MUST_EXIST);
4245 return (!empty($USER->access['rsw'][$context->path]));
4249 * Get any role that has an override on exact context
4251 * @param context $context The context to check
4252 * @return array An array of roles
4254 function get_roles_with_override_on_context(context $context) {
4257 return $DB->get_records_sql("SELECT r.*
4258 FROM {role_capabilities} rc, {role} r
4259 WHERE rc.roleid = r.id AND rc.contextid = ?",
4260 array($context->id));
4264 * Get all capabilities for this role on this context (overrides)
4266 * @param stdClass $role
4267 * @param context $context
4270 function get_capabilities_from_role_on_context($role, context $context) {
4273 return $DB->get_records_sql("SELECT *
4274 FROM {role_capabilities}
4275 WHERE contextid = ? AND roleid = ?",
4276 array($context->id, $role->id));
4280 * Find out which roles has assignment on this context
4282 * @param context $context
4286 function get_roles_with_assignment_on_context(context $context) {
4289 return $DB->get_records_sql("SELECT r.*
4290 FROM {role_assignments} ra, {role} r
4291 WHERE ra.roleid = r.id AND ra.contextid = ?",
4292 array($context->id));
4296 * Find all user assignment of users for this role, on this context
4298 * @param stdClass $role
4299 * @param context $context
4302 function get_users_from_role_on_context($role, context $context) {
4305 return $DB->get_records_sql("SELECT *
4306 FROM {role_assignments}
4307 WHERE contextid = ? AND roleid = ?",
4308 array($context->id, $role->id));
4312 * Simple function returning a boolean true if user has roles