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)
38 * What courses has this user access to?
39 * - get_enrolled_users()
41 * What users can do X in this context?
42 * - get_users_by_capability()
47 * - role_unassign_all()
50 * Advanced - for internal use only
51 * - load_all_capabilities()
52 * - reload_all_capabilities()
53 * - has_capability_in_accessdata()
54 * - get_user_access_sitewide()
55 * - load_course_context()
56 * - load_role_access_by_context()
59 * <b>Name conventions</b>
65 * Access control data is held in the "accessdata" array
66 * which - for the logged-in user, will be in $USER->access
68 * For other users can be generated and passed around (but may also be cached
69 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser).
71 * $accessdata is a multidimensional array, holding
72 * role assignments (RAs), role-capabilities-perm sets
73 * (role defs) and a list of courses we have loaded
76 * Things are keyed on "contextpaths" (the path field of
77 * the context table) for fast walking up/down the tree.
79 * $accessdata['ra'][$contextpath] = array($roleid=>$roleid)
80 * [$contextpath] = array($roleid=>$roleid)
81 * [$contextpath] = array($roleid=>$roleid)
84 * Role definitions are stored like this
85 * (no cap merge is done - so it's compact)
88 * $accessdata['rdef']["$contextpath:$roleid"]['mod/forum:viewpost'] = 1
89 * ['mod/forum:editallpost'] = -1
90 * ['mod/forum:startdiscussion'] = -1000
93 * See how has_capability_in_accessdata() walks up the tree.
95 * First we only load rdef and ra down to the course level, but not below.
96 * This keeps accessdata small and compact. Below-the-course ra/rdef
97 * are loaded as needed. We keep track of which courses we have loaded ra/rdef in
99 * $accessdata['loaded'] = array($courseid1=>1, $courseid2=>1)
102 * <b>Stale accessdata</b>
104 * For the logged-in user, accessdata is long-lived.
106 * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
107 * context paths affected by changes. Any check at-or-below
108 * a dirty context will trigger a transparent reload of accessdata.
110 * Changes at the system level will force the reload for everyone.
112 * <b>Default role caps</b>
113 * The default role assignment is not in the DB, so we
114 * add it manually to accessdata.
116 * This means that functions that work directly off the
117 * DB need to ensure that the default role caps
118 * are dealt with appropriately.
122 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
123 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
126 defined('MOODLE_INTERNAL') || die();
128 /** No capability change */
129 define('CAP_INHERIT', 0);
130 /** Allow permission, overrides CAP_PREVENT defined in parent contexts */
131 define('CAP_ALLOW', 1);
132 /** Prevent permission, overrides CAP_ALLOW defined in parent contexts */
133 define('CAP_PREVENT', -1);
134 /** Prohibit permission, overrides everything in current and child contexts */
135 define('CAP_PROHIBIT', -1000);
137 /** System context level - only one instance in every system */
138 define('CONTEXT_SYSTEM', 10);
139 /** User context level - one instance for each user describing what others can do to user */
140 define('CONTEXT_USER', 30);
141 /** Course category context level - one instance for each category */
142 define('CONTEXT_COURSECAT', 40);
143 /** Course context level - one instances for each course */
144 define('CONTEXT_COURSE', 50);
145 /** Course module context level - one instance for each course module */
146 define('CONTEXT_MODULE', 70);
148 * Block context level - one instance for each block, sticky blocks are tricky
149 * because ppl think they should be able to override them at lower contexts.
150 * Any other context level instance can be parent of block context.
152 define('CONTEXT_BLOCK', 80);
154 /** Capability allow management of trusts - NOT IMPLEMENTED YET - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
155 define('RISK_MANAGETRUST', 0x0001);
156 /** Capability allows changes in system configuration - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
157 define('RISK_CONFIG', 0x0002);
158 /** Capability allows user to add scritped content - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
159 define('RISK_XSS', 0x0004);
160 /** Capability allows access to personal user information - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
161 define('RISK_PERSONAL', 0x0008);
162 /** Capability allows users to add content otehrs may see - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
163 define('RISK_SPAM', 0x0010);
164 /** capability allows mass delete of data belonging to other users - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
165 define('RISK_DATALOSS', 0x0020);
167 /** rolename displays - the name as defined in the role definition */
168 define('ROLENAME_ORIGINAL', 0);
169 /** rolename displays - the name as defined by a role alias */
170 define('ROLENAME_ALIAS', 1);
171 /** rolename displays - Both, like this: Role alias (Original) */
172 define('ROLENAME_BOTH', 2);
173 /** rolename displays - the name as defined in the role definition and the shortname in brackets */
174 define('ROLENAME_ORIGINALANDSHORT', 3);
175 /** rolename displays - the name as defined by a role alias, in raw form suitable for editing */
176 define('ROLENAME_ALIAS_RAW', 4);
177 /** rolename displays - the name is simply short role name */
178 define('ROLENAME_SHORT', 5);
180 /** maximum size of context cache - it is possible to tweak this config.php or in any script before inclusion of context.php */
181 if (!defined('CONTEXT_CACHE_MAX_SIZE')) {
182 define('CONTEXT_CACHE_MAX_SIZE', 2500);
186 * Although this looks like a global variable, it isn't really.
188 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
189 * It is used to cache various bits of data between function calls for performance reasons.
190 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
191 * as methods of a class, instead of functions.
194 * @global stdClass $ACCESSLIB_PRIVATE
195 * @name $ACCESSLIB_PRIVATE
197 global $ACCESSLIB_PRIVATE;
198 $ACCESSLIB_PRIVATE = new stdClass();
199 $ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache, loaded from DB once per page
200 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
201 $ACCESSLIB_PRIVATE->rolepermissions = array(); // role permissions cache - helps a lot with mem usage
202 $ACCESSLIB_PRIVATE->capabilities = null; // detailed information about the capabilities
205 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
207 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
208 * accesslib's private caches. You need to do this before setting up test data,
209 * and also at the end of the tests.
213 function accesslib_clear_all_caches_for_unit_testing() {
214 global $UNITTEST, $USER;
215 if (empty($UNITTEST->running)) {
216 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
219 accesslib_clear_all_caches(true);
221 unset($USER->access);
225 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
227 * This reset does not touch global $USER.
230 * @param bool $resetcontexts
233 function accesslib_clear_all_caches($resetcontexts) {
234 global $ACCESSLIB_PRIVATE;
236 $ACCESSLIB_PRIVATE->dirtycontexts = null;
237 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
238 $ACCESSLIB_PRIVATE->rolepermissions = array();
239 $ACCESSLIB_PRIVATE->capabilities = null;
241 if ($resetcontexts) {
242 context_helper::reset_caches();
247 * Gets the accessdata for role "sitewide" (system down to course)
253 function get_role_access($roleid) {
254 global $DB, $ACCESSLIB_PRIVATE;
256 /* Get it in 1 DB query...
257 * - relevant role caps at the root and down
258 * to the course level - but not below
261 //TODO: MUC - this could be cached in shared memory to speed up first page loading, web crawlers, etc.
263 $accessdata = get_empty_accessdata();
265 $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
268 // Overrides for the role IN ANY CONTEXTS
269 // down to COURSE - not below -
271 $sql = "SELECT ctx.path,
272 rc.capability, rc.permission
274 JOIN {role_capabilities} rc ON rc.contextid = ctx.id
275 LEFT JOIN {context} cctx
276 ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
277 WHERE rc.roleid = ? AND cctx.id IS NULL";
278 $params = array($roleid);
280 // we need extra caching in CLI scripts and cron
281 $rs = $DB->get_recordset_sql($sql, $params);
282 foreach ($rs as $rd) {
283 $k = "{$rd->path}:{$roleid}";
284 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
288 // share the role definitions
289 foreach ($accessdata['rdef'] as $k=>$unused) {
290 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
291 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
293 $accessdata['rdef_count']++;
294 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
301 * Get the default guest role, this is used for guest account,
302 * search engine spiders, etc.
304 * @return stdClass role record
306 function get_guest_role() {
309 if (empty($CFG->guestroleid)) {
310 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
311 $guestrole = array_shift($roles); // Pick the first one
312 set_config('guestroleid', $guestrole->id);
315 debugging('Can not find any guest role!');
319 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
322 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
323 set_config('guestroleid', '');
324 return get_guest_role();
330 * Check whether a user has a particular capability in a given context.
333 * $context = get_context_instance(CONTEXT_MODULE, $cm->id);
334 * has_capability('mod/forum:replypost',$context)
336 * By default checks the capabilities of the current user, but you can pass a
337 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
339 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
340 * or capabilities with XSS, config or data loss risks.
342 * @param string $capability the name of the capability to check. For example mod/forum:view
343 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
344 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
345 * @param boolean $doanything If false, ignores effect of admin role assignment
346 * @return boolean true if the user has this capability. Otherwise false.
348 function has_capability($capability, context $context, $user = null, $doanything = true) {
349 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
351 if (during_initial_install()) {
352 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cli/install.php" or $SCRIPT === "/$CFG->admin/cli/install_database.php") {
353 // we are in an installer - roles can not work yet
360 if (strpos($capability, 'moodle/legacy:') === 0) {
361 throw new coding_exception('Legacy capabilities can not be used any more!');
364 if (!is_bool($doanything)) {
365 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
368 // capability must exist
369 if (!$capinfo = get_capability_info($capability)) {
370 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
374 if (!isset($USER->id)) {
375 // should never happen
379 // make sure there is a real user specified
380 if ($user === null) {
383 $userid = is_object($user) ? $user->id : $user;
386 // make sure forcelogin cuts off not-logged-in users if enabled
387 if (!empty($CFG->forcelogin) and $userid == 0) {
391 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
392 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
393 if (isguestuser($userid) or $userid == 0) {
398 // somehow make sure the user is not deleted and actually exists
400 if ($userid == $USER->id and isset($USER->deleted)) {
401 // this prevents one query per page, it is a bit of cheating,
402 // but hopefully session is terminated properly once user is deleted
403 if ($USER->deleted) {
407 if (!context_user::instance($userid, IGNORE_MISSING)) {
408 // no user context == invalid userid
414 // context path/depth must be valid
415 if (empty($context->path) or $context->depth == 0) {
416 // this should not happen often, each upgrade tries to rebuild the context paths
417 debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()');
418 if (is_siteadmin($userid)) {
425 // Find out if user is admin - it is not possible to override the doanything in any way
426 // and it is not possible to switch to admin role either.
428 if (is_siteadmin($userid)) {
429 if ($userid != $USER->id) {
432 // make sure switchrole is not used in this context
433 if (empty($USER->access['rsw'])) {
436 $parts = explode('/', trim($context->path, '/'));
439 foreach ($parts as $part) {
440 $path .= '/' . $part;
441 if (!empty($USER->access['rsw'][$path])) {
449 //ok, admin switched role in this context, let's use normal access control rules
453 // Careful check for staleness...
454 $context->reload_if_dirty();
456 if ($USER->id == $userid) {
457 if (!isset($USER->access)) {
458 load_all_capabilities();
460 $access =& $USER->access;
463 // make sure user accessdata is really loaded
464 get_user_accessdata($userid, true);
465 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
469 // Load accessdata for below-the-course context if necessary,
470 // all contexts at and above all courses are already loaded
471 if ($context->contextlevel != CONTEXT_COURSE and $coursecontext = $context->get_course_context(false)) {
472 load_course_context($userid, $coursecontext, $access);
475 return has_capability_in_accessdata($capability, $context, $access);
479 * Check if the user has any one of several capabilities from a list.
481 * This is just a utility method that calls has_capability in a loop. Try to put
482 * the capabilities that most users are likely to have first in the list for best
485 * @see has_capability()
486 * @param array $capabilities an array of capability names.
487 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
488 * @param integer $userid A user id. By default (null) checks the permissions of the current user.
489 * @param boolean $doanything If false, ignore effect of admin role assignment
490 * @return boolean true if the user has any of these capabilities. Otherwise false.
492 function has_any_capability(array $capabilities, context $context, $userid = null, $doanything = true) {
493 foreach ($capabilities as $capability) {
494 if (has_capability($capability, $context, $userid, $doanything)) {
502 * Check if the user has all the capabilities in a list.
504 * This is just a utility method that calls has_capability in a loop. Try to put
505 * the capabilities that fewest users are likely to have first in the list for best
508 * @see has_capability()
509 * @param array $capabilities an array of capability names.
510 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
511 * @param integer $userid A user id. By default (null) checks the permissions of the current user.
512 * @param boolean $doanything If false, ignore effect of admin role assignment
513 * @return boolean true if the user has all of these capabilities. Otherwise false.
515 function has_all_capabilities(array $capabilities, context $context, $userid = null, $doanything = true) {
516 foreach ($capabilities as $capability) {
517 if (!has_capability($capability, $context, $userid, $doanything)) {
525 * Check if the user is an admin at the site level.
527 * Please note that use of proper capabilities is always encouraged,
528 * this function is supposed to be used from core or for temporary hacks.
530 * @param int|stdClass $user_or_id user id or user object
531 * @return bool true if user is one of the administrators, false otherwise
533 function is_siteadmin($user_or_id = null) {
536 if ($user_or_id === null) {
540 if (empty($user_or_id)) {
543 if (!empty($user_or_id->id)) {
544 $userid = $user_or_id->id;
546 $userid = $user_or_id;
549 $siteadmins = explode(',', $CFG->siteadmins);
550 return in_array($userid, $siteadmins);
554 * Returns true if user has at least one role assign
555 * of 'coursecontact' role (is potentially listed in some course descriptions).
560 function has_coursecontact_role($userid) {
563 if (empty($CFG->coursecontact)) {
567 FROM {role_assignments}
568 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
569 return $DB->record_exists_sql($sql, array('userid'=>$userid));
573 * Does the user have a capability to do something?
575 * Walk the accessdata array and return true/false.
576 * Deals with prohibits, role switching, aggregating
579 * The main feature of here is being FAST and with no
584 * Switch Role merges with default role
585 * ------------------------------------
586 * If you are a teacher in course X, you have at least
587 * teacher-in-X + defaultloggedinuser-sitewide. So in the
588 * course you'll have techer+defaultloggedinuser.
589 * We try to mimic that in switchrole.
591 * Permission evaluation
592 * ---------------------
593 * Originally there was an extremely complicated way
594 * to determine the user access that dealt with
595 * "locality" or role assignments and role overrides.
596 * Now we simply evaluate access for each role separately
597 * and then verify if user has at least one role with allow
598 * and at the same time no role with prohibit.
601 * @param string $capability
602 * @param context $context
603 * @param array $accessdata
606 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
609 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
610 $path = $context->path;
611 $paths = array($path);
612 while($path = rtrim($path, '0123456789')) {
613 $path = rtrim($path, '/');
621 $switchedrole = false;
623 // Find out if role switched
624 if (!empty($accessdata['rsw'])) {
625 // From the bottom up...
626 foreach ($paths as $path) {
627 if (isset($accessdata['rsw'][$path])) {
628 // Found a switchrole assignment - check for that role _plus_ the default user role
629 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
630 $switchedrole = true;
636 if (!$switchedrole) {
637 // get all users roles in this context and above
638 foreach ($paths as $path) {
639 if (isset($accessdata['ra'][$path])) {
640 foreach ($accessdata['ra'][$path] as $roleid) {
641 $roles[$roleid] = null;
647 // Now find out what access is given to each role, going bottom-->up direction
649 foreach ($roles as $roleid => $ignored) {
650 foreach ($paths as $path) {
651 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
652 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
653 if ($perm === CAP_PROHIBIT) {
654 // any CAP_PROHIBIT found means no permission for the user
657 if (is_null($roles[$roleid])) {
658 $roles[$roleid] = $perm;
662 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
663 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
670 * A convenience function that tests has_capability, and displays an error if
671 * the user does not have that capability.
673 * NOTE before Moodle 2.0, this function attempted to make an appropriate
674 * require_login call before checking the capability. This is no longer the case.
675 * You must call require_login (or one of its variants) if you want to check the
676 * user is logged in, before you call this function.
678 * @see has_capability()
680 * @param string $capability the name of the capability to check. For example mod/forum:view
681 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
682 * @param int $userid A user id. By default (null) checks the permissions of the current user.
683 * @param bool $doanything If false, ignore effect of admin role assignment
684 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
685 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
686 * @return void terminates with an error if the user does not have the given capability.
688 function require_capability($capability, context $context, $userid = null, $doanything = true,
689 $errormessage = 'nopermissions', $stringfile = '') {
690 if (!has_capability($capability, $context, $userid, $doanything)) {
691 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
696 * Return a nested array showing role assignments
697 * all relevant role capabilities for the user at
698 * site/course_category/course levels
700 * We do _not_ delve deeper than courses because the number of
701 * overrides at the module/block levels can be HUGE.
703 * [ra] => [/path][roleid]=roleid
704 * [rdef] => [/path:roleid][capability]=permission
707 * @param int $userid - the id of the user
708 * @return array access info array
710 function get_user_access_sitewide($userid) {
711 global $CFG, $DB, $ACCESSLIB_PRIVATE;
713 /* Get in a few cheap DB queries...
715 * - relevant role caps
716 * - above and within this user's RAs
717 * - below this user's RAs - limited to course level
720 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
721 $raparents = array();
722 $accessdata = get_empty_accessdata();
724 // start with the default role
725 if (!empty($CFG->defaultuserroleid)) {
726 $syscontext = context_system::instance();
727 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
728 $raparents[$CFG->defaultuserroleid][$syscontext->path] = $syscontext->path;
731 // load the "default frontpage role"
732 if (!empty($CFG->defaultfrontpageroleid)) {
733 $frontpagecontext = context_course::instance(get_site()->id);
734 if ($frontpagecontext->path) {
735 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
736 $raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->path] = $frontpagecontext->path;
740 // preload every assigned role at and above course context
741 $sql = "SELECT ctx.path, ra.roleid
742 FROM {role_assignments} ra
743 JOIN {context} ctx ON ctx.id = ra.contextid
744 LEFT JOIN {context} cctx
745 ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
746 WHERE ra.userid = :userid AND cctx.id IS NULL";
749 $params = array('userid'=>$userid);
750 $rs = $DB->get_recordset_sql($sql, $params);
751 foreach ($rs as $ra) {
752 // RAs leafs are arrays to support multi-role assignments...
753 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
754 $raparents[$ra->roleid][$ra->path] = $ra->path;
758 if (empty($raparents)) {
762 // now get overrides of interesting roles in all interesting child contexts
763 // hopefully we will not run out of SQL limits here,
764 // users would have to have very many roles above course context...
769 foreach ($raparents as $roleid=>$paths) {
771 list($paths, $rparams) = $DB->get_in_or_equal($paths, SQL_PARAMS_NAMED, 'p'.$cp.'_');
772 $params = array_merge($params, $rparams);
773 $params['r'.$cp] = $roleid;
774 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
775 FROM {role_capabilities} rc
777 ON (ctx.id = rc.contextid)
778 LEFT JOIN {context} cctx
779 ON (cctx.contextlevel = ".CONTEXT_COURSE."
780 AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
783 AND (ctx.id = pctx.id
784 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
785 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
786 WHERE rc.roleid = :r{$cp}
787 AND cctx.id IS NULL)";
790 // fixed capability order is necessary for rdef dedupe
791 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
793 foreach ($rs as $rd) {
794 $k = $rd->path.':'.$rd->roleid;
795 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
799 // share the role definitions
800 foreach ($accessdata['rdef'] as $k=>$unused) {
801 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
802 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
804 $accessdata['rdef_count']++;
805 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
812 * Add to the access ctrl array the data needed by a user for a given course.
814 * This function injects all course related access info into the accessdata array.
817 * @param int $userid the id of the user
818 * @param context_course $coursecontext course context
819 * @param array $accessdata accessdata array (modified)
820 * @return void modifies $accessdata parameter
822 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
823 global $DB, $CFG, $ACCESSLIB_PRIVATE;
825 if (empty($coursecontext->path)) {
826 // weird, this should not happen
830 if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
831 // already loaded, great!
837 if (empty($userid)) {
838 if (!empty($CFG->notloggedinroleid)) {
839 $roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
842 } else if (isguestuser($userid)) {
843 if ($guestrole = get_guest_role()) {
844 $roles[$guestrole->id] = $guestrole->id;
848 // Interesting role assignments at, above and below the course context
849 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
850 $params['userid'] = $userid;
851 $params['children'] = $coursecontext->path."/%";
852 $sql = "SELECT ra.*, ctx.path
853 FROM {role_assignments} ra
854 JOIN {context} ctx ON ra.contextid = ctx.id
855 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
856 $rs = $DB->get_recordset_sql($sql, $params);
858 // add missing role definitions
859 foreach ($rs as $ra) {
860 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
861 $roles[$ra->roleid] = $ra->roleid;
865 // add the "default frontpage role" when on the frontpage
866 if (!empty($CFG->defaultfrontpageroleid)) {
867 $frontpagecontext = context_course::instance(get_site()->id);
868 if ($frontpagecontext->id == $coursecontext->id) {
869 $roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
873 // do not forget the default role
874 if (!empty($CFG->defaultuserroleid)) {
875 $roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
880 // weird, default roles must be missing...
881 $accessdata['loaded'][$coursecontext->instanceid] = 1;
885 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
886 $params = array('c'=>$coursecontext->id);
887 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
888 $params = array_merge($params, $rparams);
889 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
890 $params = array_merge($params, $rparams);
892 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
893 FROM {role_capabilities} rc
895 ON (ctx.id = rc.contextid)
898 AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
899 WHERE rc.roleid $roleids
900 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
901 $rs = $DB->get_recordset_sql($sql, $params);
904 foreach ($rs as $rd) {
905 $k = $rd->path.':'.$rd->roleid;
906 if (isset($accessdata['rdef'][$k])) {
909 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
913 // share new role definitions
914 foreach ($newrdefs as $k=>$unused) {
915 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
916 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
918 $accessdata['rdef_count']++;
919 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
922 $accessdata['loaded'][$coursecontext->instanceid] = 1;
924 // we want to deduplicate the USER->access from time to time, this looks like a good place,
925 // because we have to do it before the end of session
926 dedupe_user_access();
930 * Add to the access ctrl array the data needed by a role for a given context.
932 * The data is added in the rdef key.
933 * This role-centric function is useful for role_switching
934 * and temporary course roles.
937 * @param int $roleid the id of the user
938 * @param context $context needs path!
939 * @param array $accessdata accessdata array (is modified)
942 function load_role_access_by_context($roleid, context $context, &$accessdata) {
943 global $DB, $ACCESSLIB_PRIVATE;
945 /* Get the relevant rolecaps into rdef
946 * - relevant role caps
951 if (empty($context->path)) {
952 // weird, this should not happen
956 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
957 $params['roleid'] = $roleid;
958 $params['childpath'] = $context->path.'/%';
960 $sql = "SELECT ctx.path, rc.capability, rc.permission
961 FROM {role_capabilities} rc
962 JOIN {context} ctx ON (rc.contextid = ctx.id)
963 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
964 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
965 $rs = $DB->get_recordset_sql($sql, $params);
968 foreach ($rs as $rd) {
969 $k = $rd->path.':'.$roleid;
970 if (isset($accessdata['rdef'][$k])) {
973 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
977 // share new role definitions
978 foreach ($newrdefs as $k=>$unused) {
979 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
980 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
982 $accessdata['rdef_count']++;
983 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
988 * Returns empty accessdata structure.
989 * @return array empt accessdata
991 function get_empty_accessdata() {
992 $accessdata = array(); // named list
993 $accessdata['ra'] = array();
994 $accessdata['rdef'] = array();
995 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
996 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
997 $accessdata['loaded'] = array(); // loaded course contexts
998 $accessdata['time'] = time();
1004 * Get accessdata for a given user.
1007 * @param int $userid
1008 * @param bool $preloadonly true means do not return access array
1009 * @return array accessdata
1011 function get_user_accessdata($userid, $preloadonly=false) {
1012 global $CFG, $ACCESSLIB_PRIVATE, $USER;
1014 if (!empty($USER->acces['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1015 // share rdef from USER session with rolepermissions cache in order to conserve memory
1016 foreach($USER->acces['rdef'] as $k=>$v) {
1017 $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->acces['rdef'][$k];
1019 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->acces;
1022 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
1023 if (empty($userid)) {
1024 if (!empty($CFG->notloggedinroleid)) {
1025 $accessdata = get_role_access($CFG->notloggedinroleid);
1028 return get_empty_accessdata();
1031 } else if (isguestuser($userid)) {
1032 if ($guestrole = get_guest_role()) {
1033 $accessdata = get_role_access($guestrole->id);
1036 return get_empty_accessdata();
1040 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1043 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1049 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1054 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1055 * this function looks for contexts with the same overrides and shares them.
1060 function dedupe_user_access() {
1064 // no session in CLI --> no compression necessary
1068 if (empty($USER->access['rdef_count'])) {
1069 // weird, this should not happen
1073 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1074 if ($USER->access['rdef_count'] - $USER->access['rdef_lcc'] > 10) {
1075 // do not compress after each change, wait till there is more stuff to be done
1080 foreach ($USER->access['rdef'] as $k=>$def) {
1081 $hash = sha1(serialize($def));
1082 if (isset($hashmap[$hash])) {
1083 $USER->access['rdef'][$k] =& $hashmap[$hash];
1085 $hashmap[$hash] =& $USER->access['rdef'][$k];
1089 $USER->access['rdef_lcc'] = $USER->access['rdef_count'];
1093 * A convenience function to completely load all the capabilities
1094 * for the current user. It is called from has_capability() and functions change permissions.
1096 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1097 * @see check_enrolment_plugins()
1102 function load_all_capabilities() {
1105 // roles not installed yet - we are in the middle of installation
1106 if (during_initial_install()) {
1110 if (!isset($USER->id)) {
1111 // this should not happen
1115 unset($USER->access);
1116 $USER->access = get_user_accessdata($USER->id);
1118 // deduplicate the overrides to minimize session size
1119 dedupe_user_access();
1121 // Clear to force a refresh
1122 unset($USER->mycourses);
1123 unset($USER->enrol);
1127 * A convenience function to completely reload all the capabilities
1128 * for the current user when roles have been updated in a relevant
1129 * context -- but PRESERVING switchroles and loginas.
1130 * This function resets all accesslib and context caches.
1132 * That is - completely transparent to the user.
1134 * Note: reloads $USER->access completely.
1139 function reload_all_capabilities() {
1140 global $USER, $DB, $ACCESSLIB_PRIVATE;
1144 if (isset($USER->access['rsw'])) {
1145 $sw = $USER->access['rsw'];
1148 accesslib_clear_all_caches(true);
1149 unset($USER->access);
1150 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
1152 load_all_capabilities();
1154 foreach ($sw as $path => $roleid) {
1155 if ($record = $DB->get_record('context', array('path'=>$path))) {
1156 $context = context::instance_by_id($record->id);
1157 role_switch($roleid, $context);
1163 * Adds a temp role to current USER->access array.
1165 * Useful for the "temporary guest" access we grant to logged-in users.
1167 * @param context_course $coursecontext
1168 * @param int $roleid
1171 function load_temp_course_role(context_course $coursecontext, $roleid) {
1174 //TODO: this gets removed if there are any dirty contexts, we should probably store list of these temp roles somewhere (skodak)
1176 if (empty($roleid)) {
1177 debugging('invalid role specified in load_temp_course_role()');
1181 if (!isset($USER->access)) {
1182 load_all_capabilities();
1185 $coursecontext->reload_if_dirty();
1187 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1191 // load course stuff first
1192 load_course_context($USER->id, $coursecontext, $USER->access);
1194 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1196 load_role_access_by_context($roleid, $coursecontext, $USER->access);
1200 * Removes any extra guest roles from current USER->access array.
1202 * @param context_course $coursecontext
1205 function remove_temp_course_roles(context_course $coursecontext) {
1208 if (empty($USER->access['ra'][$coursecontext->path])) {
1209 //no roles here, weird
1213 $sql = "SELECT DISTINCT ra.roleid AS id
1214 FROM {role_assignments} ra
1215 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1216 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1218 $USER->access['ra'][$coursecontext->path] = array();
1219 foreach($ras as $r) {
1220 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1225 * Returns array of all role archetypes.
1229 function get_role_archetypes() {
1231 'manager' => 'manager',
1232 'coursecreator' => 'coursecreator',
1233 'editingteacher' => 'editingteacher',
1234 'teacher' => 'teacher',
1235 'student' => 'student',
1238 'frontpage' => 'frontpage'
1243 * Assign the defaults found in this capability definition to roles that have
1244 * the corresponding legacy capabilities assigned to them.
1246 * @param string $capability
1247 * @param array $legacyperms an array in the format (example):
1248 * 'guest' => CAP_PREVENT,
1249 * 'student' => CAP_ALLOW,
1250 * 'teacher' => CAP_ALLOW,
1251 * 'editingteacher' => CAP_ALLOW,
1252 * 'coursecreator' => CAP_ALLOW,
1253 * 'manager' => CAP_ALLOW
1254 * @return boolean success or failure.
1256 function assign_legacy_capabilities($capability, $legacyperms) {
1258 $archetypes = get_role_archetypes();
1260 foreach ($legacyperms as $type => $perm) {
1262 $systemcontext = context_system::instance();
1263 if ($type === 'admin') {
1264 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1268 if (!array_key_exists($type, $archetypes)) {
1269 print_error('invalidlegacy', '', '', $type);
1272 if ($roles = get_archetype_roles($type)) {
1273 foreach ($roles as $role) {
1274 // Assign a site level capability.
1275 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1285 * Verify capability risks.
1287 * @param object $capability a capability - a row from the capabilities table.
1288 * @return boolean whether this capability is safe - that is, whether people with the
1289 * safeoverrides capability should be allowed to change it.
1291 function is_safe_capability($capability) {
1292 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1296 * Get the local override (if any) for a given capability in a role in a context
1298 * @param int $roleid
1299 * @param int $contextid
1300 * @param string $capability
1301 * @return stdClass local capability override
1303 function get_local_override($roleid, $contextid, $capability) {
1305 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1309 * Returns context instance plus related course and cm instances
1311 * @param int $contextid
1312 * @return array of ($context, $course, $cm)
1314 function get_context_info_array($contextid) {
1317 $context = context::instance_by_id($contextid, MUST_EXIST);
1321 if ($context->contextlevel == CONTEXT_COURSE) {
1322 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1324 } else if ($context->contextlevel == CONTEXT_MODULE) {
1325 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1326 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1328 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1329 $parent = $context->get_parent_context();
1331 if ($parent->contextlevel == CONTEXT_COURSE) {
1332 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1333 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1334 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1335 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1339 return array($context, $course, $cm);
1343 * Function that creates a role
1345 * @param string $name role name
1346 * @param string $shortname role short name
1347 * @param string $description role description
1348 * @param string $archetype
1349 * @return int id or dml_exception
1351 function create_role($name, $shortname, $description, $archetype = '') {
1354 if (strpos($archetype, 'moodle/legacy:') !== false) {
1355 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1358 // verify role archetype actually exists
1359 $archetypes = get_role_archetypes();
1360 if (empty($archetypes[$archetype])) {
1364 // Insert the role record.
1365 $role = new stdClass();
1366 $role->name = $name;
1367 $role->shortname = $shortname;
1368 $role->description = $description;
1369 $role->archetype = $archetype;
1371 //find free sortorder number
1372 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1373 if (empty($role->sortorder)) {
1374 $role->sortorder = 1;
1376 $id = $DB->insert_record('role', $role);
1382 * Function that deletes a role and cleanups up after it
1384 * @param int $roleid id of role to delete
1385 * @return bool always true
1387 function delete_role($roleid) {
1390 // first unssign all users
1391 role_unassign_all(array('roleid'=>$roleid));
1393 // cleanup all references to this role, ignore errors
1394 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1395 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1396 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1397 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1398 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1399 $DB->delete_records('role_names', array('roleid'=>$roleid));
1400 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1402 // finally delete the role itself
1403 // get this before the name is gone for logging
1404 $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
1406 $DB->delete_records('role', array('id'=>$roleid));
1408 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
1414 * Function to write context specific overrides, or default capabilities.
1416 * NOTE: use $context->mark_dirty() after this
1418 * @param string $capability string name
1419 * @param int $permission CAP_ constants
1420 * @param int $roleid role id
1421 * @param int|context $contextid context id
1422 * @param bool $overwrite
1423 * @return bool always true or exception
1425 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1428 if ($contextid instanceof context) {
1429 $context = $contextid;
1431 $context = context::instance_by_id($contextid);
1434 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1435 unassign_capability($capability, $roleid, $context->id);
1439 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1441 if ($existing and !$overwrite) { // We want to keep whatever is there already
1445 $cap = new stdClass();
1446 $cap->contextid = $context->id;
1447 $cap->roleid = $roleid;
1448 $cap->capability = $capability;
1449 $cap->permission = $permission;
1450 $cap->timemodified = time();
1451 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1454 $cap->id = $existing->id;
1455 $DB->update_record('role_capabilities', $cap);
1457 if ($DB->record_exists('context', array('id'=>$context->id))) {
1458 $DB->insert_record('role_capabilities', $cap);
1465 * Unassign a capability from a role.
1467 * NOTE: use $context->mark_dirty() after this
1469 * @param string $capability the name of the capability
1470 * @param int $roleid the role id
1471 * @param int|context $contextid null means all contexts
1472 * @return boolean true or exception
1474 function unassign_capability($capability, $roleid, $contextid = null) {
1477 if (!empty($contextid)) {
1478 if ($contextid instanceof context) {
1479 $context = $contextid;
1481 $context = context::instance_by_id($contextid);
1483 // delete from context rel, if this is the last override in this context
1484 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1486 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1492 * Get the roles that have a given capability assigned to it
1494 * This function does not resolve the actual permission of the capability.
1495 * It just checks for permissions and overrides.
1496 * Use get_roles_with_cap_in_context() if resolution is required.
1498 * @param string $capability - capability name (string)
1499 * @param string $permission - optional, the permission defined for this capability
1500 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1501 * @param stdClass $context, null means any
1502 * @return array of role records
1504 function get_roles_with_capability($capability, $permission = null, $context = null) {
1508 $contexts = $context->get_parent_context_ids(true);
1509 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1510 $contextsql = "AND rc.contextid $insql";
1517 $permissionsql = " AND rc.permission = :permission";
1518 $params['permission'] = $permission;
1520 $permissionsql = '';
1525 WHERE r.id IN (SELECT rc.roleid
1526 FROM {role_capabilities} rc
1527 WHERE rc.capability = :capname
1530 $params['capname'] = $capability;
1533 return $DB->get_records_sql($sql, $params);
1538 * This function makes a role-assignment (a role for a user in a particular context)
1540 * @param int $roleid the role of the id
1541 * @param int $userid userid
1542 * @param int|context $contextid id of the context
1543 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1544 * @param int $itemid id of enrolment/auth plugin
1545 * @param string $timemodified defaults to current time
1546 * @return int new/existing id of the assignment
1548 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1551 // first of all detect if somebody is using old style parameters
1552 if ($contextid === 0 or is_numeric($component)) {
1553 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1556 // now validate all parameters
1557 if (empty($roleid)) {
1558 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1561 if (empty($userid)) {
1562 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1566 if (strpos($component, '_') === false) {
1567 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1571 if ($component !== '' and strpos($component, '_') === false) {
1572 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1576 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1577 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1580 if ($contextid instanceof context) {
1581 $context = $contextid;
1583 $context = context::instance_by_id($contextid, MUST_EXIST);
1586 if (!$timemodified) {
1587 $timemodified = time();
1590 /// Check for existing entry
1591 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1594 // role already assigned - this should not happen
1595 if (count($ras) > 1) {
1596 // very weird - remove all duplicates!
1597 $ra = array_shift($ras);
1598 foreach ($ras as $r) {
1599 $DB->delete_records('role_assignments', array('id'=>$r->id));
1605 // actually there is no need to update, reset anything or trigger any event, so just return
1609 // Create a new entry
1610 $ra = new stdClass();
1611 $ra->roleid = $roleid;
1612 $ra->contextid = $context->id;
1613 $ra->userid = $userid;
1614 $ra->component = $component;
1615 $ra->itemid = $itemid;
1616 $ra->timemodified = $timemodified;
1617 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1619 $ra->id = $DB->insert_record('role_assignments', $ra);
1621 // mark context as dirty - again expensive, but needed
1622 $context->mark_dirty();
1624 if (!empty($USER->id) && $USER->id == $userid) {
1625 // If the user is the current user, then do full reload of capabilities too.
1626 reload_all_capabilities();
1629 events_trigger('role_assigned', $ra);
1635 * Removes one role assignment
1637 * @param int $roleid
1638 * @param int $userid
1639 * @param int|context $contextid
1640 * @param string $component
1641 * @param int $itemid
1644 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1645 // first make sure the params make sense
1646 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1647 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1651 if (strpos($component, '_') === false) {
1652 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1656 if ($component !== '' and strpos($component, '_') === false) {
1657 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1661 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1665 * Removes multiple role assignments, parameters may contain:
1666 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1668 * @param array $params role assignment parameters
1669 * @param bool $subcontexts unassign in subcontexts too
1670 * @param bool $includemanual include manual role assignments too
1673 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1674 global $USER, $CFG, $DB;
1677 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1680 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1681 foreach ($params as $key=>$value) {
1682 if (!in_array($key, $allowed)) {
1683 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1687 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1688 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1691 if ($includemanual) {
1692 if (!isset($params['component']) or $params['component'] === '') {
1693 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1698 if (empty($params['contextid'])) {
1699 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1703 $ras = $DB->get_records('role_assignments', $params);
1704 foreach($ras as $ra) {
1705 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1706 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1707 // this is a bit expensive but necessary
1708 $context->mark_dirty();
1709 /// If the user is the current user, then do full reload of capabilities too.
1710 if (!empty($USER->id) && $USER->id == $ra->userid) {
1711 reload_all_capabilities();
1714 events_trigger('role_unassigned', $ra);
1718 // process subcontexts
1719 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1720 if ($params['contextid'] instanceof context) {
1721 $context = $params['contextid'];
1723 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1727 $contexts = $context->get_child_contexts();
1729 foreach($contexts as $context) {
1730 $mparams['contextid'] = $context->id;
1731 $ras = $DB->get_records('role_assignments', $mparams);
1732 foreach($ras as $ra) {
1733 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1734 // this is a bit expensive but necessary
1735 $context->mark_dirty();
1736 /// If the user is the current user, then do full reload of capabilities too.
1737 if (!empty($USER->id) && $USER->id == $ra->userid) {
1738 reload_all_capabilities();
1740 events_trigger('role_unassigned', $ra);
1746 // do this once more for all manual role assignments
1747 if ($includemanual) {
1748 $params['component'] = '';
1749 role_unassign_all($params, $subcontexts, false);
1754 * Determines if a user is currently logged in
1758 function isloggedin() {
1761 return (!empty($USER->id));
1765 * Determines if a user is logged in as real guest user with username 'guest'.
1767 * @param int|object $user mixed user object or id, $USER if not specified
1768 * @return bool true if user is the real guest user, false if not logged in or other user
1770 function isguestuser($user = null) {
1771 global $USER, $DB, $CFG;
1773 // make sure we have the user id cached in config table, because we are going to use it a lot
1774 if (empty($CFG->siteguest)) {
1775 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1776 // guest does not exist yet, weird
1779 set_config('siteguest', $guestid);
1781 if ($user === null) {
1785 if ($user === null) {
1786 // happens when setting the $USER
1789 } else if (is_numeric($user)) {
1790 return ($CFG->siteguest == $user);
1792 } else if (is_object($user)) {
1793 if (empty($user->id)) {
1794 return false; // not logged in means is not be guest
1796 return ($CFG->siteguest == $user->id);
1800 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1805 * Does user have a (temporary or real) guest access to course?
1807 * @param context $context
1808 * @param stdClass|int $user
1811 function is_guest(context $context, $user = null) {
1814 // first find the course context
1815 $coursecontext = $context->get_course_context();
1817 // make sure there is a real user specified
1818 if ($user === null) {
1819 $userid = isset($USER->id) ? $USER->id : 0;
1821 $userid = is_object($user) ? $user->id : $user;
1824 if (isguestuser($userid)) {
1825 // can not inspect or be enrolled
1829 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1830 // viewing users appear out of nowhere, they are neither guests nor participants
1834 // consider only real active enrolments here
1835 if (is_enrolled($coursecontext, $user, '', true)) {
1843 * Returns true if the user has moodle/course:view capability in the course,
1844 * this is intended for admins, managers (aka small admins), inspectors, etc.
1846 * @param context $context
1847 * @param int|stdClass $user, if null $USER is used
1848 * @param string $withcapability extra capability name
1851 function is_viewing(context $context, $user = null, $withcapability = '') {
1852 // first find the course context
1853 $coursecontext = $context->get_course_context();
1855 if (isguestuser($user)) {
1860 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1861 // admins are allowed to inspect courses
1865 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1866 // site admins always have the capability, but the enrolment above blocks
1874 * Returns true if user is enrolled (is participating) in course
1875 * this is intended for students and teachers.
1877 * @param context $context
1878 * @param int|stdClass $user, if null $USER is used, otherwise user object or id expected
1879 * @param string $withcapability extra capability name
1880 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1883 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1886 // first find the course context
1887 $coursecontext = $context->get_course_context();
1889 // make sure there is a real user specified
1890 if ($user === null) {
1891 $userid = isset($USER->id) ? $USER->id : 0;
1893 $userid = is_object($user) ? $user->id : $user;
1896 if (empty($userid)) {
1899 } else if (isguestuser($userid)) {
1900 // guest account can not be enrolled anywhere
1904 if ($coursecontext->instanceid == SITEID) {
1905 // everybody participates on frontpage
1909 FROM {user_enrolments} ue
1910 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1911 JOIN {user} u ON u.id = ue.userid
1912 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
1913 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
1914 // this result should be very small, better not do the complex time checks in sql for now ;-)
1915 $enrolments = $DB->get_records_sql($sql, $params);
1917 // make sure the enrol period is ok
1919 foreach ($enrolments as $e) {
1920 if ($e->timestart > $now) {
1923 if ($e->timeend and $e->timeend < $now) {
1934 // any enrolment is good for us here, even outdated, disabled or inactive
1936 FROM {user_enrolments} ue
1937 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1938 JOIN {user} u ON u.id = ue.userid
1939 WHERE ue.userid = :userid AND u.deleted = 0";
1940 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
1941 if (!$DB->record_exists_sql($sql, $params)) {
1947 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1955 * Returns true if the user is able to access the course.
1957 * This function is in no way, shape, or form a substitute for require_login.
1958 * It should only be used in circumstances where it is not possible to call require_login
1959 * such as the navigation.
1961 * This function checks many of the methods of access to a course such as the view
1962 * capability, enrollments, and guest access. It also makes use of the cache
1963 * generated by require_login for guest access.
1965 * The flags within the $USER object that are used here should NEVER be used outside
1966 * of this function can_access_course and require_login. Doing so WILL break future
1969 * @param context $context
1970 * @param stdClass|null $user
1971 * @param string $withcapability Check for this capability as well.
1972 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1973 * @param boolean $trustcache If set to false guest access will always be checked
1974 * against the enrolment plugins from the course, rather
1975 * than the cache generated by require_login.
1976 * @return boolean Returns true if the user is able to access the course
1978 function can_access_course(context $context, $user = null, $withcapability = '', $onlyactive = false, $trustcache = true) {
1981 $coursecontext = $context->get_course_context();
1982 $courseid = $coursecontext->instanceid;
1984 // First check the obvious, is the user viewing or is the user enrolled.
1985 if (is_viewing($coursecontext, $user, $withcapability) || is_enrolled($coursecontext, $user, $withcapability, $onlyactive)) {
1986 // How easy was that!
1991 if (!isset($USER->enrol)) {
1992 // Cache hasn't been generated yet so we can't trust it
1993 $trustcache = false;
1995 * These flags within the $USER object should NEVER be used outside of this
1996 * function can_access_course and the function require_login.
1997 * Doing so WILL break future versions!!!!
1999 $USER->enrol = array();
2000 $USER->enrol['enrolled'] = array();
2001 $USER->enrol['tempguest'] = array();
2004 // If we don't trust the cache we need to check with the courses enrolment
2005 // plugin instances to see if the user can access the course as a guest.
2007 // Ok, off to the database we go!
2008 $instances = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2009 $enrols = enrol_get_plugins(true);
2010 foreach($instances as $instance) {
2011 if (!isset($enrols[$instance->enrol])) {
2014 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2015 if ($until !== false) {
2016 // Never use me anywhere but here and require_login
2017 $USER->enrol['tempguest'][$courseid] = $until;
2024 // If we don't already have access (from above) check the cache and see whether
2025 // there is record of it in there.
2026 if (!$access && isset($USER->enrol['tempguest'][$courseid])) {
2027 // Never use me anywhere but here and require_login
2028 if ($USER->enrol['tempguest'][$courseid] == 0) {
2030 } else if ($USER->enrol['tempguest'][$courseid] > time()) {
2034 unset($USER->enrol['tempguest'][$courseid]);
2041 * Returns array with sql code and parameters returning all ids
2042 * of users enrolled into course.
2044 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2046 * @param context $context
2047 * @param string $withcapability
2048 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2049 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2050 * @return array list($sql, $params)
2052 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2055 // use unique prefix just in case somebody makes some SQL magic with the result
2058 $prefix = 'eu'.$i.'_';
2060 // first find the course context
2061 $coursecontext = $context->get_course_context();
2063 $isfrontpage = ($coursecontext->instanceid == SITEID);
2069 list($contextids, $contextpaths) = get_context_info_list($context);
2071 // get all relevant capability info for all roles
2072 if ($withcapability) {
2073 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2074 $cparams['cap'] = $withcapability;
2077 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2078 FROM {role_capabilities} rc
2079 JOIN {context} ctx on rc.contextid = ctx.id
2080 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2081 $rcs = $DB->get_records_sql($sql, $cparams);
2082 foreach ($rcs as $rc) {
2083 $defs[$rc->path][$rc->roleid] = $rc->permission;
2087 if (!empty($defs)) {
2088 foreach ($contextpaths as $path) {
2089 if (empty($defs[$path])) {
2092 foreach($defs[$path] as $roleid => $perm) {
2093 if ($perm == CAP_PROHIBIT) {
2094 $access[$roleid] = CAP_PROHIBIT;
2097 if (!isset($access[$roleid])) {
2098 $access[$roleid] = (int)$perm;
2106 // make lists of roles that are needed and prohibited
2107 $needed = array(); // one of these is enough
2108 $prohibited = array(); // must not have any of these
2109 foreach ($access as $roleid => $perm) {
2110 if ($perm == CAP_PROHIBIT) {
2111 unset($needed[$roleid]);
2112 $prohibited[$roleid] = true;
2113 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2114 $needed[$roleid] = true;
2118 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2119 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2124 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2126 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2127 // everybody not having prohibit has the capability
2129 } else if (empty($needed)) {
2133 if (!empty($prohibited[$defaultuserroleid])) {
2135 } else if (!empty($needed[$defaultuserroleid])) {
2136 // everybody not having prohibit has the capability
2138 } else if (empty($needed)) {
2144 // nobody can match so return some SQL that does not return any results
2145 $wheres[] = "1 = 2";
2150 $ctxids = implode(',', $contextids);
2151 $roleids = implode(',', array_keys($needed));
2152 $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))";
2156 $ctxids = implode(',', $contextids);
2157 $roleids = implode(',', array_keys($prohibited));
2158 $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))";
2159 $wheres[] = "{$prefix}ra4.id IS NULL";
2163 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2164 $params["{$prefix}gmid"] = $groupid;
2170 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2171 $params["{$prefix}gmid"] = $groupid;
2175 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2176 $params["{$prefix}guestid"] = $CFG->siteguest;
2179 // all users are "enrolled" on the frontpage
2181 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2182 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2183 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2186 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2187 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2188 $now = round(time(), -2); // rounding helps caching in DB
2189 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2190 $prefix.'active'=>ENROL_USER_ACTIVE,
2191 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2195 $joins = implode("\n", $joins);
2196 $wheres = "WHERE ".implode(" AND ", $wheres);
2198 $sql = "SELECT DISTINCT {$prefix}u.id
2199 FROM {user} {$prefix}u
2203 return array($sql, $params);
2207 * Returns list of users enrolled into course.
2209 * @param context $context
2210 * @param string $withcapability
2211 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2212 * @param string $userfields requested user record fields
2213 * @param string $orderby
2214 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2215 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2216 * @return array of user records
2218 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = '', $limitfrom = 0, $limitnum = 0) {
2221 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2222 $sql = "SELECT $userfields
2224 JOIN ($esql) je ON je.id = u.id
2225 WHERE u.deleted = 0";
2228 $sql = "$sql ORDER BY $orderby";
2230 $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
2233 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2237 * Counts list of users enrolled into course (as per above function)
2239 * @param context $context
2240 * @param string $withcapability
2241 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2242 * @return array of user records
2244 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0) {
2247 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2248 $sql = "SELECT count(u.id)
2250 JOIN ($esql) je ON je.id = u.id
2251 WHERE u.deleted = 0";
2253 return $DB->count_records_sql($sql, $params);
2257 * Loads the capability definitions for the component (from file).
2259 * Loads the capability definitions for the component (from file). If no
2260 * capabilities are defined for the component, we simply return an empty array.
2262 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2263 * @return array array of capabilities
2265 function load_capability_def($component) {
2266 $defpath = get_component_directory($component).'/db/access.php';
2268 $capabilities = array();
2269 if (file_exists($defpath)) {
2271 if (!empty(${$component.'_capabilities'})) {
2272 // BC capability array name
2273 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2274 debugging('componentname_capabilities array is deprecated, please use capabilities array only in access.php files');
2275 $capabilities = ${$component.'_capabilities'};
2279 return $capabilities;
2283 * Gets the capabilities that have been cached in the database for this component.
2285 * @param string $component - examples: 'moodle', 'mod_forum'
2286 * @return array array of capabilities
2288 function get_cached_capabilities($component = 'moodle') {
2290 return $DB->get_records('capabilities', array('component'=>$component));
2294 * Returns default capabilities for given role archetype.
2296 * @param string $archetype role archetype
2299 function get_default_capabilities($archetype) {
2307 $defaults = array();
2308 $components = array();
2309 $allcaps = $DB->get_records('capabilities');
2311 foreach ($allcaps as $cap) {
2312 if (!in_array($cap->component, $components)) {
2313 $components[] = $cap->component;
2314 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2317 foreach($alldefs as $name=>$def) {
2318 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2319 if (isset($def['archetypes'])) {
2320 if (isset($def['archetypes'][$archetype])) {
2321 $defaults[$name] = $def['archetypes'][$archetype];
2323 // 'legacy' is for backward compatibility with 1.9 access.php
2325 if (isset($def['legacy'][$archetype])) {
2326 $defaults[$name] = $def['legacy'][$archetype];
2335 * Reset role capabilities to default according to selected role archetype.
2336 * If no archetype selected, removes all capabilities.
2338 * @param int $roleid
2341 function reset_role_capabilities($roleid) {
2344 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2345 $defaultcaps = get_default_capabilities($role->archetype);
2347 $systemcontext = context_system::instance();
2349 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2351 foreach($defaultcaps as $cap=>$permission) {
2352 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2357 * Updates the capabilities table with the component capability definitions.
2358 * If no parameters are given, the function updates the core moodle
2361 * Note that the absence of the db/access.php capabilities definition file
2362 * will cause any stored capabilities for the component to be removed from
2365 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2366 * @return boolean true if success, exception in case of any problems
2368 function update_capabilities($component = 'moodle') {
2369 global $DB, $OUTPUT;
2371 $storedcaps = array();
2373 $filecaps = load_capability_def($component);
2374 foreach($filecaps as $capname=>$unused) {
2375 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2376 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2380 $cachedcaps = get_cached_capabilities($component);
2382 foreach ($cachedcaps as $cachedcap) {
2383 array_push($storedcaps, $cachedcap->name);
2384 // update risk bitmasks and context levels in existing capabilities if needed
2385 if (array_key_exists($cachedcap->name, $filecaps)) {
2386 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2387 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2389 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2390 $updatecap = new stdClass();
2391 $updatecap->id = $cachedcap->id;
2392 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2393 $DB->update_record('capabilities', $updatecap);
2395 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2396 $updatecap = new stdClass();
2397 $updatecap->id = $cachedcap->id;
2398 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2399 $DB->update_record('capabilities', $updatecap);
2402 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2403 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2405 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2406 $updatecap = new stdClass();
2407 $updatecap->id = $cachedcap->id;
2408 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2409 $DB->update_record('capabilities', $updatecap);
2415 // Are there new capabilities in the file definition?
2418 foreach ($filecaps as $filecap => $def) {
2420 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2421 if (!array_key_exists('riskbitmask', $def)) {
2422 $def['riskbitmask'] = 0; // no risk if not specified
2424 $newcaps[$filecap] = $def;
2427 // Add new capabilities to the stored definition.
2428 foreach ($newcaps as $capname => $capdef) {
2429 $capability = new stdClass();
2430 $capability->name = $capname;
2431 $capability->captype = $capdef['captype'];
2432 $capability->contextlevel = $capdef['contextlevel'];
2433 $capability->component = $component;
2434 $capability->riskbitmask = $capdef['riskbitmask'];
2436 $DB->insert_record('capabilities', $capability, false);
2438 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
2439 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2440 foreach ($rolecapabilities as $rolecapability){
2441 //assign_capability will update rather than insert if capability exists
2442 if (!assign_capability($capname, $rolecapability->permission,
2443 $rolecapability->roleid, $rolecapability->contextid, true)){
2444 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2448 // we ignore archetype key if we have cloned permissions
2449 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2450 assign_legacy_capabilities($capname, $capdef['archetypes']);
2451 // 'legacy' is for backward compatibility with 1.9 access.php
2452 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2453 assign_legacy_capabilities($capname, $capdef['legacy']);
2456 // Are there any capabilities that have been removed from the file
2457 // definition that we need to delete from the stored capabilities and
2458 // role assignments?
2459 capabilities_cleanup($component, $filecaps);
2461 // reset static caches
2462 accesslib_clear_all_caches(false);
2468 * Deletes cached capabilities that are no longer needed by the component.
2469 * Also unassigns these capabilities from any roles that have them.
2471 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2472 * @param array $newcapdef array of the new capability definitions that will be
2473 * compared with the cached capabilities
2474 * @return int number of deprecated capabilities that have been removed
2476 function capabilities_cleanup($component, $newcapdef = null) {
2481 if ($cachedcaps = get_cached_capabilities($component)) {
2482 foreach ($cachedcaps as $cachedcap) {
2483 if (empty($newcapdef) ||
2484 array_key_exists($cachedcap->name, $newcapdef) === false) {
2486 // Remove from capabilities cache.
2487 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2489 // Delete from roles.
2490 if ($roles = get_roles_with_capability($cachedcap->name)) {
2491 foreach($roles as $role) {
2492 if (!unassign_capability($cachedcap->name, $role->id)) {
2493 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2500 return $removedcount;
2510 * Returns an array of all the known types of risk
2511 * The array keys can be used, for example as CSS class names, or in calls to
2512 * print_risk_icon. The values are the corresponding RISK_ constants.
2514 * @return array all the known types of risk.
2516 function get_all_risks() {
2518 'riskmanagetrust' => RISK_MANAGETRUST,
2519 'riskconfig' => RISK_CONFIG,
2520 'riskxss' => RISK_XSS,
2521 'riskpersonal' => RISK_PERSONAL,
2522 'riskspam' => RISK_SPAM,
2523 'riskdataloss' => RISK_DATALOSS,
2528 * Return a link to moodle docs for a given capability name
2530 * @param object $capability a capability - a row from the mdl_capabilities table.
2531 * @return string the human-readable capability name as a link to Moodle Docs.
2533 function get_capability_docs_link($capability) {
2534 $url = get_docs_url('Capabilities/' . $capability->name);
2535 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2539 * This function pulls out all the resolved capabilities (overrides and
2540 * defaults) of a role used in capability overrides in contexts at a given
2543 * @param context $context
2544 * @param int $roleid
2545 * @param string $cap capability, optional, defaults to ''
2546 * @return array of capabilities
2548 function role_context_capabilities($roleid, context $context, $cap = '') {
2551 $contexts = $context->get_parent_context_ids(true);
2552 $contexts = '('.implode(',', $contexts).')';
2554 $params = array($roleid);
2557 $search = " AND rc.capability = ? ";
2564 FROM {role_capabilities} rc, {context} c
2565 WHERE rc.contextid in $contexts
2567 AND rc.contextid = c.id $search
2568 ORDER BY c.contextlevel DESC, rc.capability DESC";
2570 $capabilities = array();
2572 if ($records = $DB->get_records_sql($sql, $params)) {
2573 // We are traversing via reverse order.
2574 foreach ($records as $record) {
2575 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2576 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2577 $capabilities[$record->capability] = $record->permission;
2581 return $capabilities;
2585 * Constructs array with contextids as first parameter and context paths,
2586 * in both cases bottom top including self.
2589 * @param context $context
2592 function get_context_info_list(context $context) {
2593 $contextids = explode('/', ltrim($context->path, '/'));
2594 $contextpaths = array();
2595 $contextids2 = $contextids;
2596 while ($contextids2) {
2597 $contextpaths[] = '/' . implode('/', $contextids2);
2598 array_pop($contextids2);
2600 return array($contextids, $contextpaths);
2604 * Check if context is the front page context or a context inside it
2606 * Returns true if this context is the front page context, or a context inside it,
2609 * @param context $context a context object.
2612 function is_inside_frontpage(context $context) {
2613 $frontpagecontext = context_course::instance(SITEID);
2614 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2618 * Returns capability information (cached)
2620 * @param string $capabilityname
2621 * @return object or null if capability not found
2623 function get_capability_info($capabilityname) {
2624 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2626 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2628 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2629 $ACCESSLIB_PRIVATE->capabilities = array();
2630 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2631 foreach ($caps as $cap) {
2632 $capname = $cap->name;
2635 $cap->riskbitmask = (int)$cap->riskbitmask;
2636 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2640 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2644 * Returns the human-readable, translated version of the capability.
2645 * Basically a big switch statement.
2647 * @param string $capabilityname e.g. mod/choice:readresponses
2650 function get_capability_string($capabilityname) {
2652 // Typical capability name is 'plugintype/pluginname:capabilityname'
2653 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2655 if ($type === 'moodle') {
2656 $component = 'core_role';
2657 } else if ($type === 'quizreport') {
2659 $component = 'quiz_'.$name;
2661 $component = $type.'_'.$name;
2664 $stringname = $name.':'.$capname;
2666 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2667 return get_string($stringname, $component);
2670 $dir = get_component_directory($component);
2671 if (!file_exists($dir)) {
2672 // plugin broken or does not exist, do not bother with printing of debug message
2673 return $capabilityname.' ???';
2676 // something is wrong in plugin, better print debug
2677 return get_string($stringname, $component);
2681 * This gets the mod/block/course/core etc strings.
2683 * @param string $component
2684 * @param int $contextlevel
2685 * @return string|bool String is success, false if failed
2687 function get_component_string($component, $contextlevel) {
2689 if ($component === 'moodle' or $component === 'core') {
2690 switch ($contextlevel) {
2691 // TODO: this should probably use context level names instead
2692 case CONTEXT_SYSTEM: return get_string('coresystem');
2693 case CONTEXT_USER: return get_string('users');
2694 case CONTEXT_COURSECAT: return get_string('categories');
2695 case CONTEXT_COURSE: return get_string('course');
2696 case CONTEXT_MODULE: return get_string('activities');
2697 case CONTEXT_BLOCK: return get_string('block');
2698 default: print_error('unknowncontext');
2702 list($type, $name) = normalize_component($component);
2703 $dir = get_plugin_directory($type, $name);
2704 if (!file_exists($dir)) {
2705 // plugin not installed, bad luck, there is no way to find the name
2706 return $component.' ???';
2710 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2711 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2712 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2713 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2714 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2715 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2716 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2717 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2719 if (get_string_manager()->string_exists('pluginname', $component)) {
2720 return get_string('activity').': '.get_string('pluginname', $component);
2722 return get_string('activity').': '.get_string('modulename', $component);
2724 default: return get_string('pluginname', $component);
2729 * Gets the list of roles assigned to this context and up (parents)
2730 * from the list of roles that are visible on user profile page
2731 * and participants page.
2733 * @param context $context
2736 function get_profile_roles(context $context) {
2739 if (empty($CFG->profileroles)) {
2743 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2744 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2745 $params = array_merge($params, $cparams);
2747 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2748 FROM {role_assignments} ra, {role} r
2749 WHERE r.id = ra.roleid
2750 AND ra.contextid $contextlist
2752 ORDER BY r.sortorder ASC";
2754 return $DB->get_records_sql($sql, $params);
2758 * Gets the list of roles assigned to this context and up (parents)
2760 * @param context $context
2763 function get_roles_used_in_context(context $context) {
2766 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true));
2768 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2769 FROM {role_assignments} ra, {role} r
2770 WHERE r.id = ra.roleid
2771 AND ra.contextid $contextlist
2772 ORDER BY r.sortorder ASC";
2774 return $DB->get_records_sql($sql, $params);
2778 * This function is used to print roles column in user profile page.
2779 * It is using the CFG->profileroles to limit the list to only interesting roles.
2780 * (The permission tab has full details of user role assignments.)
2782 * @param int $userid
2783 * @param int $courseid
2786 function get_user_roles_in_course($userid, $courseid) {
2789 if (empty($CFG->profileroles)) {
2793 if ($courseid == SITEID) {
2794 $context = context_system::instance();
2796 $context = context_course::instance($courseid);
2799 if (empty($CFG->profileroles)) {
2803 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2804 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2805 $params = array_merge($params, $cparams);
2807 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2808 FROM {role_assignments} ra, {role} r
2809 WHERE r.id = ra.roleid
2810 AND ra.contextid $contextlist
2812 AND ra.userid = :userid
2813 ORDER BY r.sortorder ASC";
2814 $params['userid'] = $userid;
2818 if ($roles = $DB->get_records_sql($sql, $params)) {
2819 foreach ($roles as $userrole) {
2820 $rolenames[$userrole->id] = $userrole->name;
2823 $rolenames = role_fix_names($rolenames, $context); // Substitute aliases
2825 foreach ($rolenames as $roleid => $rolename) {
2826 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&roleid='.$roleid.'">'.$rolename.'</a>';
2828 $rolestring = implode(',', $rolenames);
2835 * Checks if a user can assign users to a particular role in this context
2837 * @param context $context
2838 * @param int $targetroleid - the id of the role you want to assign users to
2841 function user_can_assign(context $context, $targetroleid) {
2844 // first check if user has override capability
2845 // if not return false;
2846 if (!has_capability('moodle/role:assign', $context)) {
2849 // pull out all active roles of this user from this context(or above)
2850 if ($userroles = get_user_roles($context)) {
2851 foreach ($userroles as $userrole) {
2852 // if any in the role_allow_override table, then it's ok
2853 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2863 * Returns all site roles in correct sort order.
2867 function get_all_roles() {
2869 return $DB->get_records('role', null, 'sortorder ASC');
2873 * Returns roles of a specified archetype
2875 * @param string $archetype
2876 * @return array of full role records
2878 function get_archetype_roles($archetype) {
2880 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2884 * Gets all the user roles assigned in this context, or higher contexts
2885 * this is mainly used when checking if a user can assign a role, or overriding a role
2886 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2887 * allow_override tables
2889 * @param context $context
2890 * @param int $userid
2891 * @param bool $checkparentcontexts defaults to true
2892 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2895 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2898 if (empty($userid)) {
2899 if (empty($USER->id)) {
2902 $userid = $USER->id;
2905 if ($checkparentcontexts) {
2906 $contextids = $context->get_parent_context_ids();
2908 $contextids = array();
2910 $contextids[] = $context->id;
2912 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2914 array_unshift($params, $userid);
2916 $sql = "SELECT ra.*, r.name, r.shortname
2917 FROM {role_assignments} ra, {role} r, {context} c
2919 AND ra.roleid = r.id
2920 AND ra.contextid = c.id
2921 AND ra.contextid $contextids
2924 return $DB->get_records_sql($sql ,$params);
2928 * Creates a record in the role_allow_override table
2930 * @param int $sroleid source roleid
2931 * @param int $troleid target roleid
2934 function allow_override($sroleid, $troleid) {
2937 $record = new stdClass();
2938 $record->roleid = $sroleid;
2939 $record->allowoverride = $troleid;
2940 $DB->insert_record('role_allow_override', $record);
2944 * Creates a record in the role_allow_assign table
2946 * @param int $fromroleid source roleid
2947 * @param int $targetroleid target roleid
2950 function allow_assign($fromroleid, $targetroleid) {
2953 $record = new stdClass();
2954 $record->roleid = $fromroleid;
2955 $record->allowassign = $targetroleid;
2956 $DB->insert_record('role_allow_assign', $record);
2960 * Creates a record in the role_allow_switch table
2962 * @param int $fromroleid source roleid
2963 * @param int $targetroleid target roleid
2966 function allow_switch($fromroleid, $targetroleid) {
2969 $record = new stdClass();
2970 $record->roleid = $fromroleid;
2971 $record->allowswitch = $targetroleid;
2972 $DB->insert_record('role_allow_switch', $record);
2976 * Gets a list of roles that this user can assign in this context
2978 * @param context $context the context.
2979 * @param int $rolenamedisplay the type of role name to display. One of the
2980 * ROLENAME_X constants. Default ROLENAME_ALIAS.
2981 * @param bool $withusercounts if true, count the number of users with each role.
2982 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
2983 * @return array if $withusercounts is false, then an array $roleid => $rolename.
2984 * if $withusercounts is true, returns a list of three arrays,
2985 * $rolenames, $rolecounts, and $nameswithcounts.
2987 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
2990 // make sure there is a real user specified
2991 if ($user === null) {
2992 $userid = isset($USER->id) ? $USER->id : 0;
2994 $userid = is_object($user) ? $user->id : $user;
2997 if (!has_capability('moodle/role:assign', $context, $userid)) {
2998 if ($withusercounts) {
2999 return array(array(), array(), array());
3005 $parents = $context->get_parent_context_ids(true);
3006 $contexts = implode(',' , $parents);
3010 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT or $rolenamedisplay == ROLENAME_SHORT) {
3011 $extrafields .= ', r.shortname';
3014 if ($withusercounts) {
3015 $extrafields = ', (SELECT count(u.id)
3016 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3017 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3019 $params['conid'] = $context->id;
3022 if (is_siteadmin($userid)) {
3023 // show all roles allowed in this context to admins
3024 $assignrestriction = "";
3026 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3027 FROM {role_allow_assign} raa
3028 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3029 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3030 ) ar ON ar.id = r.id";
3031 $params['userid'] = $userid;
3033 $params['contextlevel'] = $context->contextlevel;
3034 $sql = "SELECT r.id, r.name $extrafields
3037 JOIN {role_context_levels} rcl ON r.id = rcl.roleid
3038 WHERE rcl.contextlevel = :contextlevel
3039 ORDER BY r.sortorder ASC";
3040 $roles = $DB->get_records_sql($sql, $params);
3042 $rolenames = array();
3043 foreach ($roles as $role) {
3044 if ($rolenamedisplay == ROLENAME_SHORT) {
3045 $rolenames[$role->id] = $role->shortname;
3048 $rolenames[$role->id] = $role->name;
3049 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3050 $rolenames[$role->id] .= ' (' . $role->shortname . ')';
3053 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT and $rolenamedisplay != ROLENAME_SHORT) {
3054 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3057 if (!$withusercounts) {
3061 $rolecounts = array();
3062 $nameswithcounts = array();
3063 foreach ($roles as $role) {
3064 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3065 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3067 return array($rolenames, $rolecounts, $nameswithcounts);
3071 * Gets a list of roles that this user can switch to in a context
3073 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3074 * This function just process the contents of the role_allow_switch table. You also need to
3075 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3077 * @param context $context a context.
3078 * @return array an array $roleid => $rolename.
3080 function get_switchable_roles(context $context) {
3086 if (!is_siteadmin()) {
3087 // Admins are allowed to switch to any role with.
3088 // Others are subject to the additional constraint that the switch-to role must be allowed by
3089 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3090 $parents = $context->get_parent_context_ids(true);
3091 $contexts = implode(',' , $parents);
3093 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3094 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3095 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3096 $params['userid'] = $USER->id;
3101 FROM (SELECT DISTINCT rc.roleid
3102 FROM {role_capabilities} rc
3105 JOIN {role} r ON r.id = idlist.roleid
3106 ORDER BY r.sortorder";
3108 $rolenames = $DB->get_records_sql_menu($query, $params);
3109 return role_fix_names($rolenames, $context, ROLENAME_ALIAS);
3113 * Gets a list of roles that this user can override in this context.
3115 * @param context $context the context.
3116 * @param int $rolenamedisplay the type of role name to display. One of the
3117 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3118 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3119 * @return array if $withcounts is false, then an array $roleid => $rolename.
3120 * if $withusercounts is true, returns a list of three arrays,
3121 * $rolenames, $rolecounts, and $nameswithcounts.
3123 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3126 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3128 return array(array(), array(), array());
3134 $parents = $context->get_parent_context_ids(true);
3135 $contexts = implode(',' , $parents);
3139 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3140 $extrafields .= ', ro.shortname';
3143 $params['userid'] = $USER->id;
3145 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3146 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3147 $params['conid'] = $context->id;
3150 if (is_siteadmin()) {
3151 // show all roles to admins
3152 $roles = $DB->get_records_sql("
3153 SELECT ro.id, ro.name$extrafields
3155 ORDER BY ro.sortorder ASC", $params);
3158 $roles = $DB->get_records_sql("
3159 SELECT ro.id, ro.name$extrafields
3161 JOIN (SELECT DISTINCT r.id
3163 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3164 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3165 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3166 ) inline_view ON ro.id = inline_view.id
3167 ORDER BY ro.sortorder ASC", $params);
3170 $rolenames = array();
3171 foreach ($roles as $role) {
3172 $rolenames[$role->id] = $role->name;
3173 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3174 $rolenames[$role->id] .= ' (' . $role->shortname . ')';
3177 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT) {
3178 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3185 $rolecounts = array();
3186 $nameswithcounts = array();
3187 foreach ($roles as $role) {
3188 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3189 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3191 return array($rolenames, $rolecounts, $nameswithcounts);
3195 * Create a role menu suitable for default role selection in enrol plugins.
3196 * @param context $context
3197 * @param int $addroleid current or default role - always added to list
3198 * @return array roleid=>localised role name
3200 function get_default_enrol_roles(context $context, $addroleid = null) {
3203 $params = array('contextlevel'=>CONTEXT_COURSE);
3205 $addrole = "OR r.id = :addroleid";
3206 $params['addroleid'] = $addroleid;
3210 $sql = "SELECT r.id, r.name
3212 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3213 WHERE rcl.id IS NOT NULL $addrole
3214 ORDER BY sortorder DESC";
3216 $roles = $DB->get_records_sql_menu($sql, $params);
3217 $roles = role_fix_names($roles, $context, ROLENAME_BOTH);
3223 * Return context levels where this role is assignable.
3224 * @param integer $roleid the id of a role.
3225 * @return array list of the context levels at which this role may be assigned.
3227 function get_role_contextlevels($roleid) {
3229 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3230 'contextlevel', 'id,contextlevel');
3234 * Return roles suitable for assignment at the specified context level.
3236 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3238 * @param integer $contextlevel a contextlevel.
3239 * @return array list of role ids that are assignable at this context level.
3241 function get_roles_for_contextlevels($contextlevel) {
3243 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3248 * Returns default context levels where roles can be assigned.
3250 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3251 * from the array returned by get_role_archetypes();
3252 * @return array list of the context levels at which this type of role may be assigned by default.
3254 function get_default_contextlevels($rolearchetype) {
3255 static $defaults = array(
3256 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3257 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3258 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3259 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3260 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3263 'frontpage' => array());
3265 if (isset($defaults[$rolearchetype])) {
3266 return $defaults[$rolearchetype];
3273 * Set the context levels at which a particular role can be assigned.
3274 * Throws exceptions in case of error.
3276 * @param integer $roleid the id of a role.
3277 * @param array $contextlevels the context levels at which this role should be assignable,
3278 * duplicate levels are removed.
3281 function set_role_contextlevels($roleid, array $contextlevels) {
3283 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3284 $rcl = new stdClass();
3285 $rcl->roleid = $roleid;
3286 $contextlevels = array_unique($contextlevels);
3287 foreach ($contextlevels as $level) {
3288 $rcl->contextlevel = $level;
3289 $DB->insert_record('role_context_levels', $rcl, false, true);
3294 * Who has this capability in this context?
3296 * This can be a very expensive call - use sparingly and keep
3297 * the results if you are going to need them again soon.
3299 * Note if $fields is empty this function attempts to get u.*
3300 * which can get rather large - and has a serious perf impact
3303 * @param context $context
3304 * @param string|array $capability - capability name(s)
3305 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3306 * @param string $sort - the sort order. Default is lastaccess time.
3307 * @param mixed $limitfrom - number of records to skip (offset)
3308 * @param mixed $limitnum - number of records to fetch
3309 * @param string|array $groups - single group or array of groups - only return
3310 * users who are in one of these group(s).
3311 * @param string|array $exceptions - list of users to exclude, comma separated or array
3312 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3313 * @param bool $view_ignored - use get_enrolled_sql() instead
3314 * @param bool $useviewallgroups if $groups is set the return users who
3315 * have capability both $capability and moodle/site:accessallgroups
3316 * in this context, as well as users who have $capability and who are
3320 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3321 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3324 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3325 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3327 $ctxids = trim($context->path, '/');
3328 $ctxids = str_replace('/', ',', $ctxids);
3330 // Context is the frontpage
3331 $iscoursepage = false; // coursepage other than fp
3332 $isfrontpage = false;
3333 if ($context->contextlevel == CONTEXT_COURSE) {
3334 if ($context->instanceid == SITEID) {
3335 $isfrontpage = true;
3337 $iscoursepage = true;
3340 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3342 $caps = (array)$capability;
3344 // construct list of context paths bottom-->top
3345 list($contextids, $paths) = get_context_info_list($context);
3347 // we need to find out all roles that have these capabilities either in definition or in overrides
3349 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3350 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3351 $params = array_merge($params, $params2);
3352 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3353 FROM {role_capabilities} rc
3354 JOIN {context} ctx on rc.contextid = ctx.id
3355 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3357 $rcs = $DB->get_records_sql($sql, $params);
3358 foreach ($rcs as $rc) {
3359 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3362 // go through the permissions bottom-->top direction to evaluate the current permission,
3363 // first one wins (prohibit is an exception that always wins)
3365 foreach ($caps as $cap) {
3366 foreach ($paths as $path) {
3367 if (empty($defs[$cap][$path])) {
3370 foreach($defs[$cap][$path] as $roleid => $perm) {
3371 if ($perm == CAP_PROHIBIT) {
3372 $access[$cap][$roleid] = CAP_PROHIBIT;
3375 if (!isset($access[$cap][$roleid])) {
3376 $access[$cap][$roleid] = (int)$perm;
3382 // make lists of roles that are needed and prohibited in this context
3383 $needed = array(); // one of these is enough
3384 $prohibited = array(); // must not have any of these
3385 foreach ($caps as $cap) {
3386 if (empty($access[$cap])) {
3389 foreach ($access[$cap] as $roleid => $perm) {
3390 if ($perm == CAP_PROHIBIT) {
3391 unset($needed[$cap][$roleid]);
3392 $prohibited[$cap][$roleid] = true;
3393 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3394 $needed[$cap][$roleid] = true;
3397 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3398 // easy, nobody has the permission
3399 unset($needed[$cap]);
3400 unset($prohibited[$cap]);
3401 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3402 // everybody is disqualified on the frontapge
3403 unset($needed[$cap]);
3404 unset($prohibited[$cap]);
3406 if (empty($prohibited[$cap])) {
3407 unset($prohibited[$cap]);
3411 if (empty($needed)) {
3412 // there can not be anybody if no roles match this request
3416 if (empty($prohibited)) {
3417 // we can compact the needed roles
3419 foreach ($needed as $cap) {
3420 foreach ($cap as $roleid=>$unused) {
3424 $needed = array('any'=>$n);
3428 /// ***** Set up default fields ******
3429 if (empty($fields)) {
3430 if ($iscoursepage) {
3431 $fields = 'u.*, ul.timeaccess AS lastaccess';
3436 if (debugging('', DEBUG_DEVELOPER) && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3437 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3441 /// Set up default sort
3442 if (empty($sort)) { // default to course lastaccess or just lastaccess
3443 if ($iscoursepage) {
3444 $sort = 'ul.timeaccess';
3446 $sort = 'u.lastaccess';
3450 // Prepare query clauses
3451 $wherecond = array();
3455 // User lastaccess JOIN
3456 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3457 // user_lastaccess is not required MDL-13810
3459 if ($iscoursepage) {
3460 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3462 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3466 /// We never return deleted users or guest account.
3467 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3468 $params['guestid'] = $CFG->siteguest;
3472 $groups = (array)$groups;
3473 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3474 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3475 $params = array_merge($params, $grpparams);
3477 if ($useviewallgroups) {
3478 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3479 if (!empty($viewallgroupsusers)) {
3480 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3482 $wherecond[] = "($grouptest)";
3485 $wherecond[] = "($grouptest)";
3490 if (!empty($exceptions)) {
3491 $exceptions = (array)$exceptions;
3492 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3493 $params = array_merge($params, $exparams);
3494 $wherecond[] = "u.id $exsql";
3497 // now add the needed and prohibited roles conditions as joins
3498 if (!empty($needed['any'])) {
3499 // simple case - there are no prohibits involved
3500 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3503 $joins[] = "JOIN (SELECT DISTINCT userid
3504 FROM {role_assignments}
3505 WHERE contextid IN ($ctxids)
3506 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3507 ) ra ON ra.userid = u.id";
3512 foreach ($needed as $cap=>$unused) {
3513 if (empty($prohibited[$cap])) {
3514 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3518 $unions[] = "SELECT userid
3519 FROM {role_assignments}
3520 WHERE contextid IN ($ctxids)
3521 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3524 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3525 // nobody can have this cap because it is prevented in default roles
3528 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3529 // everybody except the prohibitted - hiding does not matter
3530 $unions[] = "SELECT id AS userid
3532 WHERE id NOT IN (SELECT userid
3533 FROM {role_assignments}
3534 WHERE contextid IN ($ctxids)
3535 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3538 $unions[] = "SELECT userid
3539 FROM {role_assignments}
3540 WHERE contextid IN ($ctxids)
3541 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3542 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3548 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3550 // only prohibits found - nobody can be matched
3551 $wherecond[] = "1 = 2";
3556 // Collect WHERE conditions and needed joins
3557 $where = implode(' AND ', $wherecond);
3558 if ($where !== '') {
3559 $where = 'WHERE ' . $where;
3561 $joins = implode("\n", $joins);
3563 /// Ok, let's get the users!
3564 $sql = "SELECT $fields
3570 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3574 * Re-sort a users array based on a sorting policy
3576 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3577 * based on a sorting policy. This is to support the odd practice of
3578 * sorting teachers by 'authority', where authority was "lowest id of the role
3581 * Will execute 1 database query. Only suitable for small numbers of users, as it
3582 * uses an u.id IN() clause.
3584 * Notes about the sorting criteria.
3586 * As a default, we cannot rely on role.sortorder because then
3587 * admins/coursecreators will always win. That is why the sane
3588 * rule "is locality matters most", with sortorder as 2nd
3591 * If you want role.sortorder, use the 'sortorder' policy, and
3592 * name explicitly what roles you want to cover. It's probably
3593 * a good idea to see what roles have the capabilities you want
3594 * (array_diff() them against roiles that have 'can-do-anything'
3595 * to weed out admin-ish roles. Or fetch a list of roles from
3596 * variables like $CFG->coursecontact .
3598 * @param array $users Users array, keyed on userid
3599 * @param context $context
3600 * @param array $roles ids of the roles to include, optional
3601 * @param string $sortpolicy defaults to locality, more about
3602 * @return array sorted copy of the array
3604 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3607 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3608 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3609 if (empty($roles)) {
3612 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3615 $sql = "SELECT ra.userid
3616 FROM {role_assignments} ra
3620 ON ra.contextid=ctx.id
3625 // Default 'locality' policy -- read PHPDoc notes
3626 // about sort policies...
3627 $orderby = 'ORDER BY '
3628 .'ctx.depth DESC, ' /* locality wins */
3629 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3630 .'ra.id'; /* role assignment order tie-breaker */
3631 if ($sortpolicy === 'sortorder') {
3632 $orderby = 'ORDER BY '
3633 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3634 .'ra.id'; /* role assignment order tie-breaker */
3637 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3638 $sortedusers = array();
3641 foreach ($sortedids as $id) {
3643 if (isset($seen[$id])) {