2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * This file contains functions for managing user access
20 * <b>Public API vs internals</b>
22 * General users probably only care about
25 * - context_course::instance($courseid), context_module::instance($cm->id), context_coursecat::instance($catid)
26 * - context::instance_by_id($contextid)
27 * - $context->get_parent_contexts();
28 * - $context->get_child_contexts();
30 * Whether the user can do something...
32 * - has_any_capability()
33 * - has_all_capabilities()
34 * - require_capability()
35 * - require_login() (from moodlelib)
43 * What courses has this user access to?
44 * - get_enrolled_users()
46 * What users can do X in this context?
47 * - get_enrolled_users() - at and bellow course context
48 * - get_users_by_capability() - above course context
53 * - role_unassign_all()
55 * Advanced - for internal use only
56 * - load_all_capabilities()
57 * - reload_all_capabilities()
58 * - has_capability_in_accessdata()
59 * - get_user_access_sitewide()
60 * - load_course_context()
61 * - load_role_access_by_context()
64 * <b>Name conventions</b>
70 * Access control data is held in the "accessdata" array
71 * which - for the logged-in user, will be in $USER->access
73 * For other users can be generated and passed around (but may also be cached
74 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser).
76 * $accessdata is a multidimensional array, holding
77 * role assignments (RAs), role-capabilities-perm sets
78 * (role defs) and a list of courses we have loaded
81 * Things are keyed on "contextpaths" (the path field of
82 * the context table) for fast walking up/down the tree.
84 * $accessdata['ra'][$contextpath] = array($roleid=>$roleid)
85 * [$contextpath] = array($roleid=>$roleid)
86 * [$contextpath] = array($roleid=>$roleid)
89 * Role definitions are stored like this
90 * (no cap merge is done - so it's compact)
93 * $accessdata['rdef']["$contextpath:$roleid"]['mod/forum:viewpost'] = 1
94 * ['mod/forum:editallpost'] = -1
95 * ['mod/forum:startdiscussion'] = -1000
98 * See how has_capability_in_accessdata() walks up the tree.
100 * First we only load rdef and ra down to the course level, but not below.
101 * This keeps accessdata small and compact. Below-the-course ra/rdef
102 * are loaded as needed. We keep track of which courses we have loaded ra/rdef in
104 * $accessdata['loaded'] = array($courseid1=>1, $courseid2=>1)
107 * <b>Stale accessdata</b>
109 * For the logged-in user, accessdata is long-lived.
111 * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
112 * context paths affected by changes. Any check at-or-below
113 * a dirty context will trigger a transparent reload of accessdata.
115 * Changes at the system level will force the reload for everyone.
117 * <b>Default role caps</b>
118 * The default role assignment is not in the DB, so we
119 * add it manually to accessdata.
121 * This means that functions that work directly off the
122 * DB need to ensure that the default role caps
123 * are dealt with appropriately.
125 * @package core_access
126 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
127 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
130 defined('MOODLE_INTERNAL') || die();
132 /** No capability change */
133 define('CAP_INHERIT', 0);
134 /** Allow permission, overrides CAP_PREVENT defined in parent contexts */
135 define('CAP_ALLOW', 1);
136 /** Prevent permission, overrides CAP_ALLOW defined in parent contexts */
137 define('CAP_PREVENT', -1);
138 /** Prohibit permission, overrides everything in current and child contexts */
139 define('CAP_PROHIBIT', -1000);
141 /** System context level - only one instance in every system */
142 define('CONTEXT_SYSTEM', 10);
143 /** User context level - one instance for each user describing what others can do to user */
144 define('CONTEXT_USER', 30);
145 /** Course category context level - one instance for each category */
146 define('CONTEXT_COURSECAT', 40);
147 /** Course context level - one instances for each course */
148 define('CONTEXT_COURSE', 50);
149 /** Course module context level - one instance for each course module */
150 define('CONTEXT_MODULE', 70);
152 * Block context level - one instance for each block, sticky blocks are tricky
153 * because ppl think they should be able to override them at lower contexts.
154 * Any other context level instance can be parent of block context.
156 define('CONTEXT_BLOCK', 80);
158 /** Capability allow management of trusts - NOT IMPLEMENTED YET - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
159 define('RISK_MANAGETRUST', 0x0001);
160 /** Capability allows changes in system configuration - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
161 define('RISK_CONFIG', 0x0002);
162 /** Capability allows user to add scripted content - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
163 define('RISK_XSS', 0x0004);
164 /** Capability allows access to personal user information - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
165 define('RISK_PERSONAL', 0x0008);
166 /** Capability allows users to add content others may see - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
167 define('RISK_SPAM', 0x0010);
168 /** capability allows mass delete of data belonging to other users - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
169 define('RISK_DATALOSS', 0x0020);
171 /** rolename displays - the name as defined in the role definition, localised if name empty */
172 define('ROLENAME_ORIGINAL', 0);
173 /** rolename displays - the name as defined by a role alias at the course level, falls back to ROLENAME_ORIGINAL if alias not present */
174 define('ROLENAME_ALIAS', 1);
175 /** rolename displays - Both, like this: Role alias (Original) */
176 define('ROLENAME_BOTH', 2);
177 /** rolename displays - the name as defined in the role definition and the shortname in brackets */
178 define('ROLENAME_ORIGINALANDSHORT', 3);
179 /** rolename displays - the name as defined by a role alias, in raw form suitable for editing */
180 define('ROLENAME_ALIAS_RAW', 4);
181 /** rolename displays - the name is simply short role name */
182 define('ROLENAME_SHORT', 5);
184 if (!defined('CONTEXT_CACHE_MAX_SIZE')) {
185 /** maximum size of context cache - it is possible to tweak this config.php or in any script before inclusion of context.php */
186 define('CONTEXT_CACHE_MAX_SIZE', 2500);
190 * Although this looks like a global variable, it isn't really.
192 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
193 * It is used to cache various bits of data between function calls for performance reasons.
194 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
195 * as methods of a class, instead of functions.
198 * @global stdClass $ACCESSLIB_PRIVATE
199 * @name $ACCESSLIB_PRIVATE
201 global $ACCESSLIB_PRIVATE;
202 $ACCESSLIB_PRIVATE = new stdClass();
203 $ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache, loaded from DB once per page
204 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
205 $ACCESSLIB_PRIVATE->rolepermissions = array(); // role permissions cache - helps a lot with mem usage
208 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
210 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
211 * accesslib's private caches. You need to do this before setting up test data,
212 * and also at the end of the tests.
217 function accesslib_clear_all_caches_for_unit_testing() {
220 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
223 accesslib_clear_all_caches(true);
225 unset($USER->access);
229 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
231 * This reset does not touch global $USER.
234 * @param bool $resetcontexts
237 function accesslib_clear_all_caches($resetcontexts) {
238 global $ACCESSLIB_PRIVATE;
240 $ACCESSLIB_PRIVATE->dirtycontexts = null;
241 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
242 $ACCESSLIB_PRIVATE->rolepermissions = array();
244 if ($resetcontexts) {
245 context_helper::reset_caches();
250 * Gets the accessdata for role "sitewide" (system down to course)
256 function get_role_access($roleid) {
257 global $DB, $ACCESSLIB_PRIVATE;
259 /* Get it in 1 DB query...
260 * - relevant role caps at the root and down
261 * to the course level - but not below
264 //TODO: MUC - this could be cached in shared memory to speed up first page loading, web crawlers, etc.
266 $accessdata = get_empty_accessdata();
268 $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
270 // Overrides for the role IN ANY CONTEXTS down to COURSE - not below -.
273 $sql = "SELECT ctx.path,
274 rc.capability, rc.permission
276 JOIN {role_capabilities} rc ON rc.contextid = ctx.id
277 LEFT JOIN {context} cctx
278 ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
279 WHERE rc.roleid = ? AND cctx.id IS NULL";
280 $params = array($roleid);
283 // Note: the commented out query is 100% accurate but slow, so let's cheat instead by hardcoding the blocks mess directly.
285 $sql = "SELECT COALESCE(ctx.path, bctx.path) AS path, rc.capability, rc.permission
286 FROM {role_capabilities} rc
287 LEFT JOIN {context} ctx ON (ctx.id = rc.contextid AND ctx.contextlevel <= ".CONTEXT_COURSE.")
288 LEFT JOIN ({context} bctx
289 JOIN {block_instances} bi ON (bi.id = bctx.instanceid)
290 JOIN {context} pctx ON (pctx.id = bi.parentcontextid AND pctx.contextlevel < ".CONTEXT_COURSE.")
291 ) ON (bctx.id = rc.contextid AND bctx.contextlevel = ".CONTEXT_BLOCK.")
292 WHERE rc.roleid = :roleid AND (ctx.id IS NOT NULL OR bctx.id IS NOT NULL)";
293 $params = array('roleid'=>$roleid);
295 // we need extra caching in CLI scripts and cron
296 $rs = $DB->get_recordset_sql($sql, $params);
297 foreach ($rs as $rd) {
298 $k = "{$rd->path}:{$roleid}";
299 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
303 // share the role definitions
304 foreach ($accessdata['rdef'] as $k=>$unused) {
305 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
306 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
308 $accessdata['rdef_count']++;
309 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
316 * Get the default guest role, this is used for guest account,
317 * search engine spiders, etc.
319 * @return stdClass role record
321 function get_guest_role() {
324 if (empty($CFG->guestroleid)) {
325 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
326 $guestrole = array_shift($roles); // Pick the first one
327 set_config('guestroleid', $guestrole->id);
330 debugging('Can not find any guest role!');
334 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
337 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
338 set_config('guestroleid', '');
339 return get_guest_role();
345 * Check whether a user has a particular capability in a given context.
348 * $context = context_module::instance($cm->id);
349 * has_capability('mod/forum:replypost', $context)
351 * By default checks the capabilities of the current user, but you can pass a
352 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
354 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
355 * or capabilities with XSS, config or data loss risks.
359 * @param string $capability the name of the capability to check. For example mod/forum:view
360 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
361 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
362 * @param boolean $doanything If false, ignores effect of admin role assignment
363 * @return boolean true if the user has this capability. Otherwise false.
365 function has_capability($capability, context $context, $user = null, $doanything = true) {
366 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
368 if (during_initial_install()) {
369 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cli/install.php" or $SCRIPT === "/$CFG->admin/cli/install_database.php") {
370 // we are in an installer - roles can not work yet
377 if (strpos($capability, 'moodle/legacy:') === 0) {
378 throw new coding_exception('Legacy capabilities can not be used any more!');
381 if (!is_bool($doanything)) {
382 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
385 // capability must exist
386 if (!$capinfo = get_capability_info($capability)) {
387 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
391 if (!isset($USER->id)) {
392 // should never happen
394 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER);
397 // make sure there is a real user specified
398 if ($user === null) {
401 $userid = is_object($user) ? $user->id : $user;
404 // make sure forcelogin cuts off not-logged-in users if enabled
405 if (!empty($CFG->forcelogin) and $userid == 0) {
409 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
410 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
411 if (isguestuser($userid) or $userid == 0) {
416 // somehow make sure the user is not deleted and actually exists
418 if ($userid == $USER->id and isset($USER->deleted)) {
419 // this prevents one query per page, it is a bit of cheating,
420 // but hopefully session is terminated properly once user is deleted
421 if ($USER->deleted) {
425 if (!context_user::instance($userid, IGNORE_MISSING)) {
426 // no user context == invalid userid
432 // context path/depth must be valid
433 if (empty($context->path) or $context->depth == 0) {
434 // this should not happen often, each upgrade tries to rebuild the context paths
435 debugging('Context id '.$context->id.' does not have valid path, please use context_helper::build_all_paths()');
436 if (is_siteadmin($userid)) {
443 // Find out if user is admin - it is not possible to override the doanything in any way
444 // and it is not possible to switch to admin role either.
446 if (is_siteadmin($userid)) {
447 if ($userid != $USER->id) {
450 // make sure switchrole is not used in this context
451 if (empty($USER->access['rsw'])) {
454 $parts = explode('/', trim($context->path, '/'));
457 foreach ($parts as $part) {
458 $path .= '/' . $part;
459 if (!empty($USER->access['rsw'][$path])) {
467 //ok, admin switched role in this context, let's use normal access control rules
471 // Careful check for staleness...
472 $context->reload_if_dirty();
474 if ($USER->id == $userid) {
475 if (!isset($USER->access)) {
476 load_all_capabilities();
478 $access =& $USER->access;
481 // make sure user accessdata is really loaded
482 get_user_accessdata($userid, true);
483 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
487 // Load accessdata for below-the-course context if necessary,
488 // all contexts at and above all courses are already loaded
489 if ($context->contextlevel != CONTEXT_COURSE and $coursecontext = $context->get_course_context(false)) {
490 load_course_context($userid, $coursecontext, $access);
493 return has_capability_in_accessdata($capability, $context, $access);
497 * Check if the user has any one of several capabilities from a list.
499 * This is just a utility method that calls has_capability in a loop. Try to put
500 * the capabilities that most users are likely to have first in the list for best
504 * @see has_capability()
506 * @param array $capabilities an array of capability names.
507 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
508 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
509 * @param boolean $doanything If false, ignore effect of admin role assignment
510 * @return boolean true if the user has any of these capabilities. Otherwise false.
512 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
513 foreach ($capabilities as $capability) {
514 if (has_capability($capability, $context, $user, $doanything)) {
522 * Check if the user has all the capabilities in a list.
524 * This is just a utility method that calls has_capability in a loop. Try to put
525 * the capabilities that fewest users are likely to have first in the list for best
529 * @see has_capability()
531 * @param array $capabilities an array of capability names.
532 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
533 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
534 * @param boolean $doanything If false, ignore effect of admin role assignment
535 * @return boolean true if the user has all of these capabilities. Otherwise false.
537 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
538 foreach ($capabilities as $capability) {
539 if (!has_capability($capability, $context, $user, $doanything)) {
547 * Is course creator going to have capability in a new course?
549 * This is intended to be used in enrolment plugins before or during course creation,
550 * do not use after the course is fully created.
554 * @param string $capability the name of the capability to check.
555 * @param context $context course or category context where is course going to be created
556 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
557 * @return boolean true if the user will have this capability.
559 * @throws coding_exception if different type of context submitted
561 function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) {
564 if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) {
565 throw new coding_exception('Only course or course category context expected');
568 if (has_capability($capability, $context, $user)) {
569 // User already has the capability, it could be only removed if CAP_PROHIBIT
570 // was involved here, but we ignore that.
574 if (!has_capability('moodle/course:create', $context, $user)) {
578 if (!enrol_is_enabled('manual')) {
582 if (empty($CFG->creatornewroleid)) {
586 if ($context->contextlevel == CONTEXT_COURSE) {
587 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
591 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
596 // Most likely they will be enrolled after the course creation is finished,
597 // does the new role have the required capability?
598 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
599 return isset($neededroles[$CFG->creatornewroleid]);
603 * Check if the user is an admin at the site level.
605 * Please note that use of proper capabilities is always encouraged,
606 * this function is supposed to be used from core or for temporary hacks.
610 * @param int|stdClass $user_or_id user id or user object
611 * @return bool true if user is one of the administrators, false otherwise
613 function is_siteadmin($user_or_id = null) {
616 if ($user_or_id === null) {
620 if (empty($user_or_id)) {
623 if (!empty($user_or_id->id)) {
624 $userid = $user_or_id->id;
626 $userid = $user_or_id;
629 // Because this script is called many times (150+ for course page) with
630 // the same parameters, it is worth doing minor optimisations. This static
631 // cache stores the value for a single userid, saving about 2ms from course
632 // page load time without using significant memory. As the static cache
633 // also includes the value it depends on, this cannot break unit tests.
634 static $knownid, $knownresult, $knownsiteadmins;
635 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
639 $knownsiteadmins = $CFG->siteadmins;
641 $siteadmins = explode(',', $CFG->siteadmins);
642 $knownresult = in_array($userid, $siteadmins);
647 * Returns true if user has at least one role assign
648 * of 'coursecontact' role (is potentially listed in some course descriptions).
653 function has_coursecontact_role($userid) {
656 if (empty($CFG->coursecontact)) {
660 FROM {role_assignments}
661 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
662 return $DB->record_exists_sql($sql, array('userid'=>$userid));
666 * Does the user have a capability to do something?
668 * Walk the accessdata array and return true/false.
669 * Deals with prohibits, role switching, aggregating
672 * The main feature of here is being FAST and with no
677 * Switch Role merges with default role
678 * ------------------------------------
679 * If you are a teacher in course X, you have at least
680 * teacher-in-X + defaultloggedinuser-sitewide. So in the
681 * course you'll have techer+defaultloggedinuser.
682 * We try to mimic that in switchrole.
684 * Permission evaluation
685 * ---------------------
686 * Originally there was an extremely complicated way
687 * to determine the user access that dealt with
688 * "locality" or role assignments and role overrides.
689 * Now we simply evaluate access for each role separately
690 * and then verify if user has at least one role with allow
691 * and at the same time no role with prohibit.
694 * @param string $capability
695 * @param context $context
696 * @param array $accessdata
699 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
702 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
703 $path = $context->path;
704 $paths = array($path);
705 while($path = rtrim($path, '0123456789')) {
706 $path = rtrim($path, '/');
714 $switchedrole = false;
716 // Find out if role switched
717 if (!empty($accessdata['rsw'])) {
718 // From the bottom up...
719 foreach ($paths as $path) {
720 if (isset($accessdata['rsw'][$path])) {
721 // Found a switchrole assignment - check for that role _plus_ the default user role
722 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
723 $switchedrole = true;
729 if (!$switchedrole) {
730 // get all users roles in this context and above
731 foreach ($paths as $path) {
732 if (isset($accessdata['ra'][$path])) {
733 foreach ($accessdata['ra'][$path] as $roleid) {
734 $roles[$roleid] = null;
740 // Now find out what access is given to each role, going bottom-->up direction
742 foreach ($roles as $roleid => $ignored) {
743 foreach ($paths as $path) {
744 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
745 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
746 if ($perm === CAP_PROHIBIT) {
747 // any CAP_PROHIBIT found means no permission for the user
750 if (is_null($roles[$roleid])) {
751 $roles[$roleid] = $perm;
755 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
756 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
763 * A convenience function that tests has_capability, and displays an error if
764 * the user does not have that capability.
766 * NOTE before Moodle 2.0, this function attempted to make an appropriate
767 * require_login call before checking the capability. This is no longer the case.
768 * You must call require_login (or one of its variants) if you want to check the
769 * user is logged in, before you call this function.
771 * @see has_capability()
773 * @param string $capability the name of the capability to check. For example mod/forum:view
774 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
775 * @param int $userid A user id. By default (null) checks the permissions of the current user.
776 * @param bool $doanything If false, ignore effect of admin role assignment
777 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
778 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
779 * @return void terminates with an error if the user does not have the given capability.
781 function require_capability($capability, context $context, $userid = null, $doanything = true,
782 $errormessage = 'nopermissions', $stringfile = '') {
783 if (!has_capability($capability, $context, $userid, $doanything)) {
784 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
789 * Return a nested array showing role assignments
790 * all relevant role capabilities for the user at
791 * site/course_category/course levels
793 * We do _not_ delve deeper than courses because the number of
794 * overrides at the module/block levels can be HUGE.
796 * [ra] => [/path][roleid]=roleid
797 * [rdef] => [/path:roleid][capability]=permission
800 * @param int $userid - the id of the user
801 * @return array access info array
803 function get_user_access_sitewide($userid) {
804 global $CFG, $DB, $ACCESSLIB_PRIVATE;
806 /* Get in a few cheap DB queries...
808 * - relevant role caps
809 * - above and within this user's RAs
810 * - below this user's RAs - limited to course level
813 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
814 $raparents = array();
815 $accessdata = get_empty_accessdata();
817 // start with the default role
818 if (!empty($CFG->defaultuserroleid)) {
819 $syscontext = context_system::instance();
820 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
821 $raparents[$CFG->defaultuserroleid][$syscontext->id] = $syscontext->id;
824 // load the "default frontpage role"
825 if (!empty($CFG->defaultfrontpageroleid)) {
826 $frontpagecontext = context_course::instance(get_site()->id);
827 if ($frontpagecontext->path) {
828 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
829 $raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->id] = $frontpagecontext->id;
833 // preload every assigned role at and above course context
834 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
835 FROM {role_assignments} ra
837 ON ctx.id = ra.contextid
838 LEFT JOIN {block_instances} bi
839 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
840 LEFT JOIN {context} bpctx
841 ON (bpctx.id = bi.parentcontextid)
842 WHERE ra.userid = :userid
843 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")";
844 $params = array('userid'=>$userid);
845 $rs = $DB->get_recordset_sql($sql, $params);
846 foreach ($rs as $ra) {
847 // RAs leafs are arrays to support multi-role assignments...
848 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
849 $raparents[$ra->roleid][$ra->contextid] = $ra->contextid;
853 if (empty($raparents)) {
857 // now get overrides of interesting roles in all interesting child contexts
858 // hopefully we will not run out of SQL limits here,
859 // users would have to have very many roles at/above course context...
864 foreach ($raparents as $roleid=>$ras) {
866 list($sqlcids, $cids) = $DB->get_in_or_equal($ras, SQL_PARAMS_NAMED, 'c'.$cp.'_');
867 $params = array_merge($params, $cids);
868 $params['r'.$cp] = $roleid;
869 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
870 FROM {role_capabilities} rc
872 ON (ctx.id = rc.contextid)
875 AND (ctx.id = pctx.id
876 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
877 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
878 LEFT JOIN {block_instances} bi
879 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
880 LEFT JOIN {context} bpctx
881 ON (bpctx.id = bi.parentcontextid)
882 WHERE rc.roleid = :r{$cp}
883 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")
887 // fixed capability order is necessary for rdef dedupe
888 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
890 foreach ($rs as $rd) {
891 $k = $rd->path.':'.$rd->roleid;
892 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
896 // share the role definitions
897 foreach ($accessdata['rdef'] as $k=>$unused) {
898 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
899 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
901 $accessdata['rdef_count']++;
902 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
909 * Add to the access ctrl array the data needed by a user for a given course.
911 * This function injects all course related access info into the accessdata array.
914 * @param int $userid the id of the user
915 * @param context_course $coursecontext course context
916 * @param array $accessdata accessdata array (modified)
917 * @return void modifies $accessdata parameter
919 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
920 global $DB, $CFG, $ACCESSLIB_PRIVATE;
922 if (empty($coursecontext->path)) {
923 // weird, this should not happen
927 if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
928 // already loaded, great!
934 if (empty($userid)) {
935 if (!empty($CFG->notloggedinroleid)) {
936 $roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
939 } else if (isguestuser($userid)) {
940 if ($guestrole = get_guest_role()) {
941 $roles[$guestrole->id] = $guestrole->id;
945 // Interesting role assignments at, above and below the course context
946 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
947 $params['userid'] = $userid;
948 $params['children'] = $coursecontext->path."/%";
949 $sql = "SELECT ra.*, ctx.path
950 FROM {role_assignments} ra
951 JOIN {context} ctx ON ra.contextid = ctx.id
952 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
953 $rs = $DB->get_recordset_sql($sql, $params);
955 // add missing role definitions
956 foreach ($rs as $ra) {
957 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
958 $roles[$ra->roleid] = $ra->roleid;
962 // add the "default frontpage role" when on the frontpage
963 if (!empty($CFG->defaultfrontpageroleid)) {
964 $frontpagecontext = context_course::instance(get_site()->id);
965 if ($frontpagecontext->id == $coursecontext->id) {
966 $roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
970 // do not forget the default role
971 if (!empty($CFG->defaultuserroleid)) {
972 $roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
977 // weird, default roles must be missing...
978 $accessdata['loaded'][$coursecontext->instanceid] = 1;
982 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
983 $params = array('c'=>$coursecontext->id);
984 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
985 $params = array_merge($params, $rparams);
986 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
987 $params = array_merge($params, $rparams);
989 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
990 FROM {role_capabilities} rc
992 ON (ctx.id = rc.contextid)
995 AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
996 WHERE rc.roleid $roleids
997 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
998 $rs = $DB->get_recordset_sql($sql, $params);
1000 $newrdefs = array();
1001 foreach ($rs as $rd) {
1002 $k = $rd->path.':'.$rd->roleid;
1003 if (isset($accessdata['rdef'][$k])) {
1006 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
1010 // share new role definitions
1011 foreach ($newrdefs as $k=>$unused) {
1012 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
1013 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
1015 $accessdata['rdef_count']++;
1016 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1019 $accessdata['loaded'][$coursecontext->instanceid] = 1;
1021 // we want to deduplicate the USER->access from time to time, this looks like a good place,
1022 // because we have to do it before the end of session
1023 dedupe_user_access();
1027 * Add to the access ctrl array the data needed by a role for a given context.
1029 * The data is added in the rdef key.
1030 * This role-centric function is useful for role_switching
1031 * and temporary course roles.
1034 * @param int $roleid the id of the user
1035 * @param context $context needs path!
1036 * @param array $accessdata accessdata array (is modified)
1039 function load_role_access_by_context($roleid, context $context, &$accessdata) {
1040 global $DB, $ACCESSLIB_PRIVATE;
1042 /* Get the relevant rolecaps into rdef
1043 * - relevant role caps
1044 * - at ctx and above
1048 if (empty($context->path)) {
1049 // weird, this should not happen
1053 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
1054 $params['roleid'] = $roleid;
1055 $params['childpath'] = $context->path.'/%';
1057 $sql = "SELECT ctx.path, rc.capability, rc.permission
1058 FROM {role_capabilities} rc
1059 JOIN {context} ctx ON (rc.contextid = ctx.id)
1060 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
1061 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
1062 $rs = $DB->get_recordset_sql($sql, $params);
1064 $newrdefs = array();
1065 foreach ($rs as $rd) {
1066 $k = $rd->path.':'.$roleid;
1067 if (isset($accessdata['rdef'][$k])) {
1070 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
1074 // share new role definitions
1075 foreach ($newrdefs as $k=>$unused) {
1076 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
1077 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
1079 $accessdata['rdef_count']++;
1080 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1085 * Returns empty accessdata structure.
1088 * @return array empt accessdata
1090 function get_empty_accessdata() {
1091 $accessdata = array(); // named list
1092 $accessdata['ra'] = array();
1093 $accessdata['rdef'] = array();
1094 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
1095 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
1096 $accessdata['loaded'] = array(); // loaded course contexts
1097 $accessdata['time'] = time();
1098 $accessdata['rsw'] = array();
1104 * Get accessdata for a given user.
1107 * @param int $userid
1108 * @param bool $preloadonly true means do not return access array
1109 * @return array accessdata
1111 function get_user_accessdata($userid, $preloadonly=false) {
1112 global $CFG, $ACCESSLIB_PRIVATE, $USER;
1114 if (!empty($USER->access['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1115 // share rdef from USER session with rolepermissions cache in order to conserve memory
1116 foreach ($USER->access['rdef'] as $k=>$v) {
1117 $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->access['rdef'][$k];
1119 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->access;
1122 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
1123 if (empty($userid)) {
1124 if (!empty($CFG->notloggedinroleid)) {
1125 $accessdata = get_role_access($CFG->notloggedinroleid);
1128 return get_empty_accessdata();
1131 } else if (isguestuser($userid)) {
1132 if ($guestrole = get_guest_role()) {
1133 $accessdata = get_role_access($guestrole->id);
1136 return get_empty_accessdata();
1140 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1143 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1149 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1154 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1155 * this function looks for contexts with the same overrides and shares them.
1160 function dedupe_user_access() {
1164 // no session in CLI --> no compression necessary
1168 if (empty($USER->access['rdef_count'])) {
1169 // weird, this should not happen
1173 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1174 if ($USER->access['rdef_count'] - $USER->access['rdef_lcc'] > 10) {
1175 // do not compress after each change, wait till there is more stuff to be done
1180 foreach ($USER->access['rdef'] as $k=>$def) {
1181 $hash = sha1(serialize($def));
1182 if (isset($hashmap[$hash])) {
1183 $USER->access['rdef'][$k] =& $hashmap[$hash];
1185 $hashmap[$hash] =& $USER->access['rdef'][$k];
1189 $USER->access['rdef_lcc'] = $USER->access['rdef_count'];
1193 * A convenience function to completely load all the capabilities
1194 * for the current user. It is called from has_capability() and functions change permissions.
1196 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1197 * @see check_enrolment_plugins()
1202 function load_all_capabilities() {
1205 // roles not installed yet - we are in the middle of installation
1206 if (during_initial_install()) {
1210 if (!isset($USER->id)) {
1211 // this should not happen
1215 unset($USER->access);
1216 $USER->access = get_user_accessdata($USER->id);
1218 // deduplicate the overrides to minimize session size
1219 dedupe_user_access();
1221 // Clear to force a refresh
1222 unset($USER->mycourses);
1224 // init/reset internal enrol caches - active course enrolments and temp access
1225 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1229 * A convenience function to completely reload all the capabilities
1230 * for the current user when roles have been updated in a relevant
1231 * context -- but PRESERVING switchroles and loginas.
1232 * This function resets all accesslib and context caches.
1234 * That is - completely transparent to the user.
1236 * Note: reloads $USER->access completely.
1241 function reload_all_capabilities() {
1242 global $USER, $DB, $ACCESSLIB_PRIVATE;
1246 if (!empty($USER->access['rsw'])) {
1247 $sw = $USER->access['rsw'];
1250 accesslib_clear_all_caches(true);
1251 unset($USER->access);
1252 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
1254 load_all_capabilities();
1256 foreach ($sw as $path => $roleid) {
1257 if ($record = $DB->get_record('context', array('path'=>$path))) {
1258 $context = context::instance_by_id($record->id);
1259 role_switch($roleid, $context);
1265 * Adds a temp role to current USER->access array.
1267 * Useful for the "temporary guest" access we grant to logged-in users.
1268 * This is useful for enrol plugins only.
1271 * @param context_course $coursecontext
1272 * @param int $roleid
1275 function load_temp_course_role(context_course $coursecontext, $roleid) {
1276 global $USER, $SITE;
1278 if (empty($roleid)) {
1279 debugging('invalid role specified in load_temp_course_role()');
1283 if ($coursecontext->instanceid == $SITE->id) {
1284 debugging('Can not use temp roles on the frontpage');
1288 if (!isset($USER->access)) {
1289 load_all_capabilities();
1292 $coursecontext->reload_if_dirty();
1294 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1298 // load course stuff first
1299 load_course_context($USER->id, $coursecontext, $USER->access);
1301 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1303 load_role_access_by_context($roleid, $coursecontext, $USER->access);
1307 * Removes any extra guest roles from current USER->access array.
1308 * This is useful for enrol plugins only.
1311 * @param context_course $coursecontext
1314 function remove_temp_course_roles(context_course $coursecontext) {
1315 global $DB, $USER, $SITE;
1317 if ($coursecontext->instanceid == $SITE->id) {
1318 debugging('Can not use temp roles on the frontpage');
1322 if (empty($USER->access['ra'][$coursecontext->path])) {
1323 //no roles here, weird
1327 $sql = "SELECT DISTINCT ra.roleid AS id
1328 FROM {role_assignments} ra
1329 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1330 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1332 $USER->access['ra'][$coursecontext->path] = array();
1333 foreach($ras as $r) {
1334 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1339 * Returns array of all role archetypes.
1343 function get_role_archetypes() {
1345 'manager' => 'manager',
1346 'coursecreator' => 'coursecreator',
1347 'editingteacher' => 'editingteacher',
1348 'teacher' => 'teacher',
1349 'student' => 'student',
1352 'frontpage' => 'frontpage'
1357 * Assign the defaults found in this capability definition to roles that have
1358 * the corresponding legacy capabilities assigned to them.
1360 * @param string $capability
1361 * @param array $legacyperms an array in the format (example):
1362 * 'guest' => CAP_PREVENT,
1363 * 'student' => CAP_ALLOW,
1364 * 'teacher' => CAP_ALLOW,
1365 * 'editingteacher' => CAP_ALLOW,
1366 * 'coursecreator' => CAP_ALLOW,
1367 * 'manager' => CAP_ALLOW
1368 * @return boolean success or failure.
1370 function assign_legacy_capabilities($capability, $legacyperms) {
1372 $archetypes = get_role_archetypes();
1374 foreach ($legacyperms as $type => $perm) {
1376 $systemcontext = context_system::instance();
1377 if ($type === 'admin') {
1378 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1382 if (!array_key_exists($type, $archetypes)) {
1383 print_error('invalidlegacy', '', '', $type);
1386 if ($roles = get_archetype_roles($type)) {
1387 foreach ($roles as $role) {
1388 // Assign a site level capability.
1389 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1399 * Verify capability risks.
1401 * @param stdClass $capability a capability - a row from the capabilities table.
1402 * @return boolean whether this capability is safe - that is, whether people with the
1403 * safeoverrides capability should be allowed to change it.
1405 function is_safe_capability($capability) {
1406 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1410 * Get the local override (if any) for a given capability in a role in a context
1412 * @param int $roleid
1413 * @param int $contextid
1414 * @param string $capability
1415 * @return stdClass local capability override
1417 function get_local_override($roleid, $contextid, $capability) {
1419 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1423 * Returns context instance plus related course and cm instances
1425 * @param int $contextid
1426 * @return array of ($context, $course, $cm)
1428 function get_context_info_array($contextid) {
1431 $context = context::instance_by_id($contextid, MUST_EXIST);
1435 if ($context->contextlevel == CONTEXT_COURSE) {
1436 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1438 } else if ($context->contextlevel == CONTEXT_MODULE) {
1439 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1440 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1442 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1443 $parent = $context->get_parent_context();
1445 if ($parent->contextlevel == CONTEXT_COURSE) {
1446 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1447 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1448 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1449 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1453 return array($context, $course, $cm);
1457 * Function that creates a role
1459 * @param string $name role name
1460 * @param string $shortname role short name
1461 * @param string $description role description
1462 * @param string $archetype
1463 * @return int id or dml_exception
1465 function create_role($name, $shortname, $description, $archetype = '') {
1468 if (strpos($archetype, 'moodle/legacy:') !== false) {
1469 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1472 // verify role archetype actually exists
1473 $archetypes = get_role_archetypes();
1474 if (empty($archetypes[$archetype])) {
1478 // Insert the role record.
1479 $role = new stdClass();
1480 $role->name = $name;
1481 $role->shortname = $shortname;
1482 $role->description = $description;
1483 $role->archetype = $archetype;
1485 //find free sortorder number
1486 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1487 if (empty($role->sortorder)) {
1488 $role->sortorder = 1;
1490 $id = $DB->insert_record('role', $role);
1496 * Function that deletes a role and cleanups up after it
1498 * @param int $roleid id of role to delete
1499 * @return bool always true
1501 function delete_role($roleid) {
1504 // first unssign all users
1505 role_unassign_all(array('roleid'=>$roleid));
1507 // cleanup all references to this role, ignore errors
1508 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1509 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1510 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1511 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1512 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1513 $DB->delete_records('role_names', array('roleid'=>$roleid));
1514 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1516 // Get role record before it's deleted.
1517 $role = $DB->get_record('role', array('id'=>$roleid));
1519 // Finally delete the role itself.
1520 $DB->delete_records('role', array('id'=>$roleid));
1523 $event = \core\event\role_deleted::create(
1525 'context' => context_system::instance(),
1526 'objectid' => $roleid,
1529 'shortname' => $role->shortname,
1530 'description' => $role->description,
1531 'archetype' => $role->archetype
1535 $event->add_record_snapshot('role', $role);
1542 * Function to write context specific overrides, or default capabilities.
1544 * NOTE: use $context->mark_dirty() after this
1546 * @param string $capability string name
1547 * @param int $permission CAP_ constants
1548 * @param int $roleid role id
1549 * @param int|context $contextid context id
1550 * @param bool $overwrite
1551 * @return bool always true or exception
1553 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1556 if ($contextid instanceof context) {
1557 $context = $contextid;
1559 $context = context::instance_by_id($contextid);
1562 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1563 unassign_capability($capability, $roleid, $context->id);
1567 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1569 if ($existing and !$overwrite) { // We want to keep whatever is there already
1573 $cap = new stdClass();
1574 $cap->contextid = $context->id;
1575 $cap->roleid = $roleid;
1576 $cap->capability = $capability;
1577 $cap->permission = $permission;
1578 $cap->timemodified = time();
1579 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1582 $cap->id = $existing->id;
1583 $DB->update_record('role_capabilities', $cap);
1585 if ($DB->record_exists('context', array('id'=>$context->id))) {
1586 $DB->insert_record('role_capabilities', $cap);
1593 * Unassign a capability from a role.
1595 * NOTE: use $context->mark_dirty() after this
1597 * @param string $capability the name of the capability
1598 * @param int $roleid the role id
1599 * @param int|context $contextid null means all contexts
1600 * @return boolean true or exception
1602 function unassign_capability($capability, $roleid, $contextid = null) {
1605 if (!empty($contextid)) {
1606 if ($contextid instanceof context) {
1607 $context = $contextid;
1609 $context = context::instance_by_id($contextid);
1611 // delete from context rel, if this is the last override in this context
1612 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1614 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1620 * Get the roles that have a given capability assigned to it
1622 * This function does not resolve the actual permission of the capability.
1623 * It just checks for permissions and overrides.
1624 * Use get_roles_with_cap_in_context() if resolution is required.
1626 * @param string $capability capability name (string)
1627 * @param string $permission optional, the permission defined for this capability
1628 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1629 * @param stdClass $context null means any
1630 * @return array of role records
1632 function get_roles_with_capability($capability, $permission = null, $context = null) {
1636 $contexts = $context->get_parent_context_ids(true);
1637 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1638 $contextsql = "AND rc.contextid $insql";
1645 $permissionsql = " AND rc.permission = :permission";
1646 $params['permission'] = $permission;
1648 $permissionsql = '';
1653 WHERE r.id IN (SELECT rc.roleid
1654 FROM {role_capabilities} rc
1655 WHERE rc.capability = :capname
1658 $params['capname'] = $capability;
1661 return $DB->get_records_sql($sql, $params);
1665 * This function makes a role-assignment (a role for a user in a particular context)
1667 * @param int $roleid the role of the id
1668 * @param int $userid userid
1669 * @param int|context $contextid id of the context
1670 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1671 * @param int $itemid id of enrolment/auth plugin
1672 * @param string $timemodified defaults to current time
1673 * @return int new/existing id of the assignment
1675 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1676 global $USER, $DB, $CFG;
1678 // first of all detect if somebody is using old style parameters
1679 if ($contextid === 0 or is_numeric($component)) {
1680 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1683 // now validate all parameters
1684 if (empty($roleid)) {
1685 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1688 if (empty($userid)) {
1689 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1693 if (strpos($component, '_') === false) {
1694 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1698 if ($component !== '' and strpos($component, '_') === false) {
1699 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1703 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1704 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1707 if ($contextid instanceof context) {
1708 $context = $contextid;
1710 $context = context::instance_by_id($contextid, MUST_EXIST);
1713 if (!$timemodified) {
1714 $timemodified = time();
1717 // Check for existing entry
1718 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1721 // role already assigned - this should not happen
1722 if (count($ras) > 1) {
1723 // very weird - remove all duplicates!
1724 $ra = array_shift($ras);
1725 foreach ($ras as $r) {
1726 $DB->delete_records('role_assignments', array('id'=>$r->id));
1732 // actually there is no need to update, reset anything or trigger any event, so just return
1736 // Create a new entry
1737 $ra = new stdClass();
1738 $ra->roleid = $roleid;
1739 $ra->contextid = $context->id;
1740 $ra->userid = $userid;
1741 $ra->component = $component;
1742 $ra->itemid = $itemid;
1743 $ra->timemodified = $timemodified;
1744 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1747 $ra->id = $DB->insert_record('role_assignments', $ra);
1749 // mark context as dirty - again expensive, but needed
1750 $context->mark_dirty();
1752 if (!empty($USER->id) && $USER->id == $userid) {
1753 // If the user is the current user, then do full reload of capabilities too.
1754 reload_all_capabilities();
1757 require_once($CFG->libdir . '/coursecatlib.php');
1758 coursecat::role_assignment_changed($roleid, $context);
1760 $event = \core\event\role_assigned::create(array(
1761 'context' => $context,
1762 'objectid' => $ra->roleid,
1763 'relateduserid' => $ra->userid,
1766 'component' => $ra->component,
1767 'itemid' => $ra->itemid
1770 $event->add_record_snapshot('role_assignments', $ra);
1777 * Removes one role assignment
1779 * @param int $roleid
1780 * @param int $userid
1781 * @param int $contextid
1782 * @param string $component
1783 * @param int $itemid
1786 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1787 // first make sure the params make sense
1788 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1789 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1793 if (strpos($component, '_') === false) {
1794 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1798 if ($component !== '' and strpos($component, '_') === false) {
1799 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1803 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1807 * Removes multiple role assignments, parameters may contain:
1808 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1810 * @param array $params role assignment parameters
1811 * @param bool $subcontexts unassign in subcontexts too
1812 * @param bool $includemanual include manual role assignments too
1815 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1816 global $USER, $CFG, $DB;
1817 require_once($CFG->libdir . '/coursecatlib.php');
1820 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1823 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1824 foreach ($params as $key=>$value) {
1825 if (!in_array($key, $allowed)) {
1826 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1830 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1831 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1834 if ($includemanual) {
1835 if (!isset($params['component']) or $params['component'] === '') {
1836 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1841 if (empty($params['contextid'])) {
1842 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1846 $ras = $DB->get_records('role_assignments', $params);
1847 foreach($ras as $ra) {
1848 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1849 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1850 // this is a bit expensive but necessary
1851 $context->mark_dirty();
1852 // If the user is the current user, then do full reload of capabilities too.
1853 if (!empty($USER->id) && $USER->id == $ra->userid) {
1854 reload_all_capabilities();
1856 $event = \core\event\role_unassigned::create(array(
1857 'context' => $context,
1858 'objectid' => $ra->roleid,
1859 'relateduserid' => $ra->userid,
1862 'component' => $ra->component,
1863 'itemid' => $ra->itemid
1866 $event->add_record_snapshot('role_assignments', $ra);
1868 coursecat::role_assignment_changed($ra->roleid, $context);
1873 // process subcontexts
1874 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1875 if ($params['contextid'] instanceof context) {
1876 $context = $params['contextid'];
1878 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1882 $contexts = $context->get_child_contexts();
1884 foreach($contexts as $context) {
1885 $mparams['contextid'] = $context->id;
1886 $ras = $DB->get_records('role_assignments', $mparams);
1887 foreach($ras as $ra) {
1888 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1889 // this is a bit expensive but necessary
1890 $context->mark_dirty();
1891 // If the user is the current user, then do full reload of capabilities too.
1892 if (!empty($USER->id) && $USER->id == $ra->userid) {
1893 reload_all_capabilities();
1895 $event = \core\event\role_unassigned::create(
1896 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1897 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1898 $event->add_record_snapshot('role_assignments', $ra);
1900 coursecat::role_assignment_changed($ra->roleid, $context);
1906 // do this once more for all manual role assignments
1907 if ($includemanual) {
1908 $params['component'] = '';
1909 role_unassign_all($params, $subcontexts, false);
1914 * Determines if a user is currently logged in
1920 function isloggedin() {
1923 return (!empty($USER->id));
1927 * Determines if a user is logged in as real guest user with username 'guest'.
1931 * @param int|object $user mixed user object or id, $USER if not specified
1932 * @return bool true if user is the real guest user, false if not logged in or other user
1934 function isguestuser($user = null) {
1935 global $USER, $DB, $CFG;
1937 // make sure we have the user id cached in config table, because we are going to use it a lot
1938 if (empty($CFG->siteguest)) {
1939 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1940 // guest does not exist yet, weird
1943 set_config('siteguest', $guestid);
1945 if ($user === null) {
1949 if ($user === null) {
1950 // happens when setting the $USER
1953 } else if (is_numeric($user)) {
1954 return ($CFG->siteguest == $user);
1956 } else if (is_object($user)) {
1957 if (empty($user->id)) {
1958 return false; // not logged in means is not be guest
1960 return ($CFG->siteguest == $user->id);
1964 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1969 * Does user have a (temporary or real) guest access to course?
1973 * @param context $context
1974 * @param stdClass|int $user
1977 function is_guest(context $context, $user = null) {
1980 // first find the course context
1981 $coursecontext = $context->get_course_context();
1983 // make sure there is a real user specified
1984 if ($user === null) {
1985 $userid = isset($USER->id) ? $USER->id : 0;
1987 $userid = is_object($user) ? $user->id : $user;
1990 if (isguestuser($userid)) {
1991 // can not inspect or be enrolled
1995 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1996 // viewing users appear out of nowhere, they are neither guests nor participants
2000 // consider only real active enrolments here
2001 if (is_enrolled($coursecontext, $user, '', true)) {
2009 * Returns true if the user has moodle/course:view capability in the course,
2010 * this is intended for admins, managers (aka small admins), inspectors, etc.
2014 * @param context $context
2015 * @param int|stdClass $user if null $USER is used
2016 * @param string $withcapability extra capability name
2019 function is_viewing(context $context, $user = null, $withcapability = '') {
2020 // first find the course context
2021 $coursecontext = $context->get_course_context();
2023 if (isguestuser($user)) {
2028 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
2029 // admins are allowed to inspect courses
2033 if ($withcapability and !has_capability($withcapability, $context, $user)) {
2034 // site admins always have the capability, but the enrolment above blocks
2042 * Returns true if user is enrolled (is participating) in course
2043 * this is intended for students and teachers.
2045 * Since 2.2 the result for active enrolments and current user are cached.
2047 * @package core_enrol
2050 * @param context $context
2051 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
2052 * @param string $withcapability extra capability name
2053 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2056 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
2059 // first find the course context
2060 $coursecontext = $context->get_course_context();
2062 // make sure there is a real user specified
2063 if ($user === null) {
2064 $userid = isset($USER->id) ? $USER->id : 0;
2066 $userid = is_object($user) ? $user->id : $user;
2069 if (empty($userid)) {
2072 } else if (isguestuser($userid)) {
2073 // guest account can not be enrolled anywhere
2077 if ($coursecontext->instanceid == SITEID) {
2078 // everybody participates on frontpage
2080 // try cached info first - the enrolled flag is set only when active enrolment present
2081 if ($USER->id == $userid) {
2082 $coursecontext->reload_if_dirty();
2083 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
2084 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
2085 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2094 // look for active enrolments only
2095 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
2097 if ($until === false) {
2101 if ($USER->id == $userid) {
2103 $until = ENROL_MAX_TIMESTAMP;
2105 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
2106 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
2107 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
2108 remove_temp_course_roles($coursecontext);
2113 // any enrolment is good for us here, even outdated, disabled or inactive
2115 FROM {user_enrolments} ue
2116 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2117 JOIN {user} u ON u.id = ue.userid
2118 WHERE ue.userid = :userid AND u.deleted = 0";
2119 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2120 if (!$DB->record_exists_sql($sql, $params)) {
2126 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2134 * Returns true if the user is able to access the course.
2136 * This function is in no way, shape, or form a substitute for require_login.
2137 * It should only be used in circumstances where it is not possible to call require_login
2138 * such as the navigation.
2140 * This function checks many of the methods of access to a course such as the view
2141 * capability, enrollments, and guest access. It also makes use of the cache
2142 * generated by require_login for guest access.
2144 * The flags within the $USER object that are used here should NEVER be used outside
2145 * of this function can_access_course and require_login. Doing so WILL break future
2148 * @param stdClass $course record
2149 * @param stdClass|int|null $user user record or id, current user if null
2150 * @param string $withcapability Check for this capability as well.
2151 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2152 * @return boolean Returns true if the user is able to access the course
2154 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
2157 // this function originally accepted $coursecontext parameter
2158 if ($course instanceof context) {
2159 if ($course instanceof context_course) {
2160 debugging('deprecated context parameter, please use $course record');
2161 $coursecontext = $course;
2162 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2164 debugging('Invalid context parameter, please use $course record');
2168 $coursecontext = context_course::instance($course->id);
2171 if (!isset($USER->id)) {
2172 // should never happen
2174 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
2177 // make sure there is a user specified
2178 if ($user === null) {
2179 $userid = $USER->id;
2181 $userid = is_object($user) ? $user->id : $user;
2185 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2189 if ($userid == $USER->id) {
2190 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2191 // the fact that somebody switched role means they can access the course no matter to what role they switched
2196 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2200 if (is_viewing($coursecontext, $userid)) {
2204 if ($userid != $USER->id) {
2205 // for performance reasons we do not verify temporary guest access for other users, sorry...
2206 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2209 // === from here we deal only with $USER ===
2211 $coursecontext->reload_if_dirty();
2213 if (isset($USER->enrol['enrolled'][$course->id])) {
2214 if ($USER->enrol['enrolled'][$course->id] > time()) {
2218 if (isset($USER->enrol['tempguest'][$course->id])) {
2219 if ($USER->enrol['tempguest'][$course->id] > time()) {
2224 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2228 // if not enrolled try to gain temporary guest access
2229 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2230 $enrols = enrol_get_plugins(true);
2231 foreach($instances as $instance) {
2232 if (!isset($enrols[$instance->enrol])) {
2235 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2236 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2237 if ($until !== false and $until > time()) {
2238 $USER->enrol['tempguest'][$course->id] = $until;
2242 if (isset($USER->enrol['tempguest'][$course->id])) {
2243 unset($USER->enrol['tempguest'][$course->id]);
2244 remove_temp_course_roles($coursecontext);
2251 * Returns array with sql code and parameters returning all ids
2252 * of users enrolled into course.
2254 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2256 * @package core_enrol
2259 * @param context $context
2260 * @param string $withcapability
2261 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2262 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2263 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
2264 * @return array list($sql, $params)
2266 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false, $onlysuspended = false) {
2269 // use unique prefix just in case somebody makes some SQL magic with the result
2272 $prefix = 'eu'.$i.'_';
2274 // first find the course context
2275 $coursecontext = $context->get_course_context();
2277 $isfrontpage = ($coursecontext->instanceid == SITEID);
2279 if ($onlyactive && $onlysuspended) {
2280 throw new coding_exception("Both onlyactive and onlysuspended are set, this is probably not what you want!");
2282 if ($isfrontpage && $onlysuspended) {
2283 throw new coding_exception("onlysuspended is not supported on frontpage; please add your own early-exit!");
2290 list($contextids, $contextpaths) = get_context_info_list($context);
2292 // get all relevant capability info for all roles
2293 if ($withcapability) {
2294 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2295 $cparams['cap'] = $withcapability;
2298 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2299 FROM {role_capabilities} rc
2300 JOIN {context} ctx on rc.contextid = ctx.id
2301 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2302 $rcs = $DB->get_records_sql($sql, $cparams);
2303 foreach ($rcs as $rc) {
2304 $defs[$rc->path][$rc->roleid] = $rc->permission;
2308 if (!empty($defs)) {
2309 foreach ($contextpaths as $path) {
2310 if (empty($defs[$path])) {
2313 foreach($defs[$path] as $roleid => $perm) {
2314 if ($perm == CAP_PROHIBIT) {
2315 $access[$roleid] = CAP_PROHIBIT;
2318 if (!isset($access[$roleid])) {
2319 $access[$roleid] = (int)$perm;
2327 // make lists of roles that are needed and prohibited
2328 $needed = array(); // one of these is enough
2329 $prohibited = array(); // must not have any of these
2330 foreach ($access as $roleid => $perm) {
2331 if ($perm == CAP_PROHIBIT) {
2332 unset($needed[$roleid]);
2333 $prohibited[$roleid] = true;
2334 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2335 $needed[$roleid] = true;
2339 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2340 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2345 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2347 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2348 // everybody not having prohibit has the capability
2350 } else if (empty($needed)) {
2354 if (!empty($prohibited[$defaultuserroleid])) {
2356 } else if (!empty($needed[$defaultuserroleid])) {
2357 // everybody not having prohibit has the capability
2359 } else if (empty($needed)) {
2365 // nobody can match so return some SQL that does not return any results
2366 $wheres[] = "1 = 2";
2371 $ctxids = implode(',', $contextids);
2372 $roleids = implode(',', array_keys($needed));
2373 $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))";
2377 $ctxids = implode(',', $contextids);
2378 $roleids = implode(',', array_keys($prohibited));
2379 $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))";
2380 $wheres[] = "{$prefix}ra4.id IS NULL";
2384 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2385 $params["{$prefix}gmid"] = $groupid;
2391 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2392 $params["{$prefix}gmid"] = $groupid;
2396 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2397 $params["{$prefix}guestid"] = $CFG->siteguest;
2400 // all users are "enrolled" on the frontpage
2402 $where1 = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2403 $where2 = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2404 $ejoin = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2405 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2407 if (!$onlysuspended) {
2408 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2411 $wheres[] = "$where1 AND $where2";
2414 // Suspended only where there is enrolment but ALL are suspended.
2415 // Consider multiple enrols where one is not suspended or plain role_assign.
2416 $enrolselect = "SELECT DISTINCT {$prefix}ue.userid FROM {user_enrolments} {$prefix}ue $ejoin WHERE $where1 AND $where2";
2417 $joins[] = "JOIN {user_enrolments} {$prefix}ue1 ON {$prefix}ue1.userid = {$prefix}u.id";
2418 $joins[] = "JOIN {enrol} {$prefix}e1 ON ({$prefix}e1.id = {$prefix}ue1.enrolid AND {$prefix}e1.courseid = :{$prefix}_e1_courseid)";
2419 $params["{$prefix}_e1_courseid"] = $coursecontext->instanceid;
2420 $wheres[] = "{$prefix}u.id NOT IN ($enrolselect)";
2423 if ($onlyactive || $onlysuspended) {
2424 $now = round(time(), -2); // rounding helps caching in DB
2425 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2426 $prefix.'active'=>ENROL_USER_ACTIVE,
2427 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2431 $joins = implode("\n", $joins);
2432 $wheres = "WHERE ".implode(" AND ", $wheres);
2434 $sql = "SELECT DISTINCT {$prefix}u.id
2435 FROM {user} {$prefix}u
2439 return array($sql, $params);
2443 * Returns list of users enrolled into course.
2445 * @package core_enrol
2448 * @param context $context
2449 * @param string $withcapability
2450 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2451 * @param string $userfields requested user record fields
2452 * @param string $orderby
2453 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2454 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2455 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2456 * @return array of user records
2458 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
2459 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
2462 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2463 $sql = "SELECT $userfields
2465 JOIN ($esql) je ON je.id = u.id
2466 WHERE u.deleted = 0";
2469 $sql = "$sql ORDER BY $orderby";
2471 list($sort, $sortparams) = users_order_by_sql('u');
2472 $sql = "$sql ORDER BY $sort";
2473 $params = array_merge($params, $sortparams);
2476 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2480 * Counts list of users enrolled into course (as per above function)
2482 * @package core_enrol
2485 * @param context $context
2486 * @param string $withcapability
2487 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2488 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2489 * @return array of user records
2491 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2494 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2495 $sql = "SELECT count(u.id)
2497 JOIN ($esql) je ON je.id = u.id
2498 WHERE u.deleted = 0";
2500 return $DB->count_records_sql($sql, $params);
2504 * Loads the capability definitions for the component (from file).
2506 * Loads the capability definitions for the component (from file). If no
2507 * capabilities are defined for the component, we simply return an empty array.
2510 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2511 * @return array array of capabilities
2513 function load_capability_def($component) {
2514 $defpath = core_component::get_component_directory($component).'/db/access.php';
2516 $capabilities = array();
2517 if (file_exists($defpath)) {
2519 if (!empty(${$component.'_capabilities'})) {
2520 // BC capability array name
2521 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2522 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2523 $capabilities = ${$component.'_capabilities'};
2527 return $capabilities;
2531 * Gets the capabilities that have been cached in the database for this component.
2534 * @param string $component - examples: 'moodle', 'mod_forum'
2535 * @return array array of capabilities
2537 function get_cached_capabilities($component = 'moodle') {
2539 $caps = get_all_capabilities();
2540 $componentcaps = array();
2541 foreach ($caps as $cap) {
2542 if ($cap['component'] == $component) {
2543 $componentcaps[] = (object) $cap;
2546 return $componentcaps;
2550 * Returns default capabilities for given role archetype.
2552 * @param string $archetype role archetype
2555 function get_default_capabilities($archetype) {
2563 $defaults = array();
2564 $components = array();
2565 $allcaps = get_all_capabilities();
2567 foreach ($allcaps as $cap) {
2568 if (!in_array($cap['component'], $components)) {
2569 $components[] = $cap['component'];
2570 $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
2573 foreach($alldefs as $name=>$def) {
2574 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2575 if (isset($def['archetypes'])) {
2576 if (isset($def['archetypes'][$archetype])) {
2577 $defaults[$name] = $def['archetypes'][$archetype];
2579 // 'legacy' is for backward compatibility with 1.9 access.php
2581 if (isset($def['legacy'][$archetype])) {
2582 $defaults[$name] = $def['legacy'][$archetype];
2591 * Return default roles that can be assigned, overridden or switched
2592 * by give role archetype.
2594 * @param string $type assign|override|switch
2595 * @param string $archetype
2596 * @return array of role ids
2598 function get_default_role_archetype_allows($type, $archetype) {
2601 if (empty($archetype)) {
2605 $roles = $DB->get_records('role');
2606 $archetypemap = array();
2607 foreach ($roles as $role) {
2608 if ($role->archetype) {
2609 $archetypemap[$role->archetype][$role->id] = $role->id;
2615 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2616 'coursecreator' => array(),
2617 'editingteacher' => array('teacher', 'student'),
2618 'teacher' => array(),
2619 'student' => array(),
2622 'frontpage' => array(),
2624 'override' => array(
2625 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2626 'coursecreator' => array(),
2627 'editingteacher' => array('teacher', 'student', 'guest'),
2628 'teacher' => array(),
2629 'student' => array(),
2632 'frontpage' => array(),
2635 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2636 'coursecreator' => array(),
2637 'editingteacher' => array('teacher', 'student', 'guest'),
2638 'teacher' => array('student', 'guest'),
2639 'student' => array(),
2642 'frontpage' => array(),
2646 if (!isset($defaults[$type][$archetype])) {
2647 debugging("Unknown type '$type'' or archetype '$archetype''");
2652 foreach ($defaults[$type][$archetype] as $at) {
2653 if (isset($archetypemap[$at])) {
2654 foreach ($archetypemap[$at] as $roleid) {
2655 $return[$roleid] = $roleid;
2664 * Reset role capabilities to default according to selected role archetype.
2665 * If no archetype selected, removes all capabilities.
2667 * This applies to capabilities that are assigned to the role (that you could
2668 * edit in the 'define roles' interface), and not to any capability overrides
2669 * in different locations.
2671 * @param int $roleid ID of role to reset capabilities for
2673 function reset_role_capabilities($roleid) {
2676 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2677 $defaultcaps = get_default_capabilities($role->archetype);
2679 $systemcontext = context_system::instance();
2681 $DB->delete_records('role_capabilities',
2682 array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2684 foreach($defaultcaps as $cap=>$permission) {
2685 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2688 // Mark the system context dirty.
2689 context_system::instance()->mark_dirty();
2693 * Updates the capabilities table with the component capability definitions.
2694 * If no parameters are given, the function updates the core moodle
2697 * Note that the absence of the db/access.php capabilities definition file
2698 * will cause any stored capabilities for the component to be removed from
2702 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2703 * @return boolean true if success, exception in case of any problems
2705 function update_capabilities($component = 'moodle') {
2706 global $DB, $OUTPUT;
2708 $storedcaps = array();
2710 $filecaps = load_capability_def($component);
2711 foreach($filecaps as $capname=>$unused) {
2712 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2713 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2717 // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2718 // So ensure our updating is based on fresh data.
2719 cache::make('core', 'capabilities')->delete('core_capabilities');
2721 $cachedcaps = get_cached_capabilities($component);
2723 foreach ($cachedcaps as $cachedcap) {
2724 array_push($storedcaps, $cachedcap->name);
2725 // update risk bitmasks and context levels in existing capabilities if needed
2726 if (array_key_exists($cachedcap->name, $filecaps)) {
2727 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2728 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2730 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2731 $updatecap = new stdClass();
2732 $updatecap->id = $cachedcap->id;
2733 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2734 $DB->update_record('capabilities', $updatecap);
2736 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2737 $updatecap = new stdClass();
2738 $updatecap->id = $cachedcap->id;
2739 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2740 $DB->update_record('capabilities', $updatecap);
2743 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2744 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2746 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2747 $updatecap = new stdClass();
2748 $updatecap->id = $cachedcap->id;
2749 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2750 $DB->update_record('capabilities', $updatecap);
2756 // Flush the cached again, as we have changed DB.
2757 cache::make('core', 'capabilities')->delete('core_capabilities');
2759 // Are there new capabilities in the file definition?
2762 foreach ($filecaps as $filecap => $def) {
2764 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2765 if (!array_key_exists('riskbitmask', $def)) {
2766 $def['riskbitmask'] = 0; // no risk if not specified
2768 $newcaps[$filecap] = $def;
2771 // Add new capabilities to the stored definition.
2772 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2773 foreach ($newcaps as $capname => $capdef) {
2774 $capability = new stdClass();
2775 $capability->name = $capname;
2776 $capability->captype = $capdef['captype'];
2777 $capability->contextlevel = $capdef['contextlevel'];
2778 $capability->component = $component;
2779 $capability->riskbitmask = $capdef['riskbitmask'];
2781 $DB->insert_record('capabilities', $capability, false);
2783 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2784 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2785 foreach ($rolecapabilities as $rolecapability){
2786 //assign_capability will update rather than insert if capability exists
2787 if (!assign_capability($capname, $rolecapability->permission,
2788 $rolecapability->roleid, $rolecapability->contextid, true)){
2789 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2793 // we ignore archetype key if we have cloned permissions
2794 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2795 assign_legacy_capabilities($capname, $capdef['archetypes']);
2796 // 'legacy' is for backward compatibility with 1.9 access.php
2797 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2798 assign_legacy_capabilities($capname, $capdef['legacy']);
2801 // Are there any capabilities that have been removed from the file
2802 // definition that we need to delete from the stored capabilities and
2803 // role assignments?
2804 capabilities_cleanup($component, $filecaps);
2806 // reset static caches
2807 accesslib_clear_all_caches(false);
2809 // Flush the cached again, as we have changed DB.
2810 cache::make('core', 'capabilities')->delete('core_capabilities');
2816 * Deletes cached capabilities that are no longer needed by the component.
2817 * Also unassigns these capabilities from any roles that have them.
2818 * NOTE: this function is called from lib/db/upgrade.php
2821 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2822 * @param array $newcapdef array of the new capability definitions that will be
2823 * compared with the cached capabilities
2824 * @return int number of deprecated capabilities that have been removed
2826 function capabilities_cleanup($component, $newcapdef = null) {
2831 if ($cachedcaps = get_cached_capabilities($component)) {
2832 foreach ($cachedcaps as $cachedcap) {
2833 if (empty($newcapdef) ||
2834 array_key_exists($cachedcap->name, $newcapdef) === false) {
2836 // Remove from capabilities cache.
2837 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2839 // Delete from roles.
2840 if ($roles = get_roles_with_capability($cachedcap->name)) {
2841 foreach($roles as $role) {
2842 if (!unassign_capability($cachedcap->name, $role->id)) {
2843 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2850 if ($removedcount) {
2851 cache::make('core', 'capabilities')->delete('core_capabilities');
2853 return $removedcount;
2857 * Returns an array of all the known types of risk
2858 * The array keys can be used, for example as CSS class names, or in calls to
2859 * print_risk_icon. The values are the corresponding RISK_ constants.
2861 * @return array all the known types of risk.
2863 function get_all_risks() {
2865 'riskmanagetrust' => RISK_MANAGETRUST,
2866 'riskconfig' => RISK_CONFIG,
2867 'riskxss' => RISK_XSS,
2868 'riskpersonal' => RISK_PERSONAL,
2869 'riskspam' => RISK_SPAM,
2870 'riskdataloss' => RISK_DATALOSS,
2875 * Return a link to moodle docs for a given capability name
2877 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2878 * @return string the human-readable capability name as a link to Moodle Docs.
2880 function get_capability_docs_link($capability) {
2881 $url = get_docs_url('Capabilities/' . $capability->name);
2882 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2886 * This function pulls out all the resolved capabilities (overrides and
2887 * defaults) of a role used in capability overrides in contexts at a given
2890 * @param int $roleid
2891 * @param context $context
2892 * @param string $cap capability, optional, defaults to ''
2893 * @return array Array of capabilities
2895 function role_context_capabilities($roleid, context $context, $cap = '') {
2898 $contexts = $context->get_parent_context_ids(true);
2899 $contexts = '('.implode(',', $contexts).')';
2901 $params = array($roleid);
2904 $search = " AND rc.capability = ? ";
2911 FROM {role_capabilities} rc, {context} c
2912 WHERE rc.contextid in $contexts
2914 AND rc.contextid = c.id $search
2915 ORDER BY c.contextlevel DESC, rc.capability DESC";
2917 $capabilities = array();
2919 if ($records = $DB->get_records_sql($sql, $params)) {
2920 // We are traversing via reverse order.
2921 foreach ($records as $record) {
2922 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2923 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2924 $capabilities[$record->capability] = $record->permission;
2928 return $capabilities;
2932 * Constructs array with contextids as first parameter and context paths,
2933 * in both cases bottom top including self.
2936 * @param context $context
2939 function get_context_info_list(context $context) {
2940 $contextids = explode('/', ltrim($context->path, '/'));
2941 $contextpaths = array();
2942 $contextids2 = $contextids;
2943 while ($contextids2) {
2944 $contextpaths[] = '/' . implode('/', $contextids2);
2945 array_pop($contextids2);
2947 return array($contextids, $contextpaths);
2951 * Check if context is the front page context or a context inside it
2953 * Returns true if this context is the front page context, or a context inside it,
2956 * @param context $context a context object.
2959 function is_inside_frontpage(context $context) {
2960 $frontpagecontext = context_course::instance(SITEID);
2961 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2965 * Returns capability information (cached)
2967 * @param string $capabilityname
2968 * @return stdClass or null if capability not found
2970 function get_capability_info($capabilityname) {
2971 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2973 $caps = get_all_capabilities();
2975 if (!isset($caps[$capabilityname])) {
2979 return (object) $caps[$capabilityname];
2983 * Returns all capabilitiy records, preferably from MUC and not database.
2985 * @return array All capability records indexed by capability name
2987 function get_all_capabilities() {
2989 $cache = cache::make('core', 'capabilities');
2990 if (!$allcaps = $cache->get('core_capabilities')) {
2991 $rs = $DB->get_recordset('capabilities');
2993 foreach ($rs as $capability) {
2994 $capability->riskbitmask = (int) $capability->riskbitmask;
2995 $allcaps[$capability->name] = (array) $capability;
2998 $cache->set('core_capabilities', $allcaps);
3004 * Returns the human-readable, translated version of the capability.
3005 * Basically a big switch statement.
3007 * @param string $capabilityname e.g. mod/choice:readresponses
3010 function get_capability_string($capabilityname) {
3012 // Typical capability name is 'plugintype/pluginname:capabilityname'
3013 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
3015 if ($type === 'moodle') {
3016 $component = 'core_role';
3017 } else if ($type === 'quizreport') {
3019 $component = 'quiz_'.$name;
3021 $component = $type.'_'.$name;
3024 $stringname = $name.':'.$capname;
3026 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
3027 return get_string($stringname, $component);
3030 $dir = core_component::get_component_directory($component);
3031 if (!file_exists($dir)) {
3032 // plugin broken or does not exist, do not bother with printing of debug message
3033 return $capabilityname.' ???';
3036 // something is wrong in plugin, better print debug
3037 return get_string($stringname, $component);
3041 * This gets the mod/block/course/core etc strings.
3043 * @param string $component
3044 * @param int $contextlevel
3045 * @return string|bool String is success, false if failed
3047 function get_component_string($component, $contextlevel) {
3049 if ($component === 'moodle' or $component === 'core') {
3050 switch ($contextlevel) {
3051 // TODO MDL-46123: this should probably use context level names instead
3052 case CONTEXT_SYSTEM: return get_string('coresystem');
3053 case CONTEXT_USER: return get_string('users');
3054 case CONTEXT_COURSECAT: return get_string('categories');
3055 case CONTEXT_COURSE: return get_string('course');
3056 case CONTEXT_MODULE: return get_string('activities');
3057 case CONTEXT_BLOCK: return get_string('block');
3058 default: print_error('unknowncontext');
3062 list($type, $name) = core_component::normalize_component($component);
3063 $dir = core_component::get_plugin_directory($type, $name);
3064 if (!file_exists($dir)) {
3065 // plugin not installed, bad luck, there is no way to find the name
3066 return $component.' ???';
3070 // TODO MDL-46123: this is really hacky and should be improved.
3071 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
3072 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
3073 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
3074 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
3075 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
3076 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
3077 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
3079 if (get_string_manager()->string_exists('pluginname', $component)) {
3080 return get_string('activity').': '.get_string('pluginname', $component);
3082 return get_string('activity').': '.get_string('modulename', $component);
3084 default: return get_string('pluginname', $component);
3089 * Gets the list of roles assigned to this context and up (parents)
3090 * from the list of roles that are visible on user profile page
3091 * and participants page.
3093 * @param context $context
3096 function get_profile_roles(context $context) {
3099 if (empty($CFG->profileroles)) {
3103 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
3104 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
3105 $params = array_merge($params, $cparams);
3107 if ($coursecontext = $context->get_course_context(false)) {
3108 $params['coursecontext'] = $coursecontext->id;
3110 $params['coursecontext'] = 0;
3113 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3114 FROM {role_assignments} ra, {role} r
3115 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3116 WHERE r.id = ra.roleid
3117 AND ra.contextid $contextlist
3119 ORDER BY r.sortorder ASC";
3121 return $DB->get_records_sql($sql, $params);
3125 * Gets the list of roles assigned to this context and up (parents)
3127 * @param context $context
3130 function get_roles_used_in_context(context $context) {
3133 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
3135 if ($coursecontext = $context->get_course_context(false)) {
3136 $params['coursecontext'] = $coursecontext->id;
3138 $params['coursecontext'] = 0;
3141 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3142 FROM {role_assignments} ra, {role} r
3143 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3144 WHERE r.id = ra.roleid
3145 AND ra.contextid $contextlist
3146 ORDER BY r.sortorder ASC";
3148 return $DB->get_records_sql($sql, $params);
3152 * This function is used to print roles column in user profile page.
3153 * It is using the CFG->profileroles to limit the list to only interesting roles.
3154 * (The permission tab has full details of user role assignments.)
3156 * @param int $userid
3157 * @param int $courseid
3160 function get_user_roles_in_course($userid, $courseid) {
3163 if (empty($CFG->profileroles)) {
3167 if ($courseid == SITEID) {
3168 $context = context_system::instance();
3170 $context = context_course::instance($courseid);
3173 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
3174 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
3175 $params = array_merge($params, $cparams);
3177 if ($coursecontext = $context->get_course_context(false)) {
3178 $params['coursecontext'] = $coursecontext->id;
3180 $params['coursecontext'] = 0;
3183 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3184 FROM {role_assignments} ra, {role} r
3185 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3186 WHERE r.id = ra.roleid
3187 AND ra.contextid $contextlist
3189 AND ra.userid = :userid
3190 ORDER BY r.sortorder ASC";
3191 $params['userid'] = $userid;
3195 if ($roles = $DB->get_records_sql($sql, $params)) {
3196 $rolenames = role_fix_names($roles, $context, ROLENAME_ALIAS, true); // Substitute aliases
3198 foreach ($rolenames as $roleid => $rolename) {
3199 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&roleid='.$roleid.'">'.$rolename.'</a>';
3201 $rolestring = implode(',', $rolenames);
3208 * Checks if a user can assign users to a particular role in this context
3210 * @param context $context
3211 * @param int $targetroleid - the id of the role you want to assign users to
3214 function user_can_assign(context $context, $targetroleid) {
3217 // First check to see if the user is a site administrator.
3218 if (is_siteadmin()) {
3222 // Check if user has override capability.
3223 // If not return false.
3224 if (!has_capability('moodle/role:assign', $context)) {
3227 // pull out all active roles of this user from this context(or above)
3228 if ($userroles = get_user_roles($context)) {
3229 foreach ($userroles as $userrole) {
3230 // if any in the role_allow_override table, then it's ok
3231 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
3241 * Returns all site roles in correct sort order.
3243 * Note: this method does not localise role names or descriptions,
3244 * use role_get_names() if you need role names.
3246 * @param context $context optional context for course role name aliases
3247 * @return array of role records with optional coursealias property
3249 function get_all_roles(context $context = null) {
3252 if (!$context or !$coursecontext = $context->get_course_context(false)) {
3253 $coursecontext = null;
3256 if ($coursecontext) {
3257 $sql = "SELECT r.*, rn.name AS coursealias
3259 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3260 ORDER BY r.sortorder ASC";
3261 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
3264 return $DB->get_records('role', array(), 'sortorder ASC');
3269 * Returns roles of a specified archetype
3271 * @param string $archetype
3272 * @return array of full role records
3274 function get_archetype_roles($archetype) {
3276 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
3280 * Gets all the user roles assigned in this context, or higher contexts
3281 * this is mainly used when checking if a user can assign a role, or overriding a role
3282 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3283 * allow_override tables
3285 * @param context $context
3286 * @param int $userid
3287 * @param bool $checkparentcontexts defaults to true
3288 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
3291 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
3294 if (empty($userid)) {
3295 if (empty($USER->id)) {
3298 $userid = $USER->id;
3301 if ($checkparentcontexts) {
3302 $contextids = $context->get_parent_context_ids();
3304 $contextids = array();
3306 $contextids[] = $context->id;
3308 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3310 array_unshift($params, $userid);
3312 $sql = "SELECT ra.*, r.name, r.shortname
3313 FROM {role_assignments} ra, {role} r, {context} c
3315 AND ra.roleid = r.id
3316 AND ra.contextid = c.id
3317 AND ra.contextid $contextids
3320 return $DB->get_records_sql($sql ,$params);
3324 * Like get_user_roles, but adds in the authenticated user role, and the front
3325 * page roles, if applicable.
3327 * @param context $context the context.
3328 * @param int $userid optional. Defaults to $USER->id
3329 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3331 function get_user_roles_with_special(context $context, $userid = 0) {
3334 if (empty($userid)) {
3335 if (empty($USER->id)) {
3338 $userid = $USER->id;
3341 $ras = get_user_roles($context, $userid);
3343 // Add front-page role if relevant.
3344 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3345 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3346 is_inside_frontpage($context);
3347 if ($defaultfrontpageroleid && $isfrontpage) {
3348 $frontpagecontext = context_course::instance(SITEID);
3349 $ra = new stdClass();
3350 $ra->userid = $userid;
3351 $ra->contextid = $frontpagecontext->id;
3352 $ra->roleid = $defaultfrontpageroleid;
3356 // Add authenticated user role if relevant.
3357 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3358 if ($defaultuserroleid && !isguestuser($userid)) {
3359 $systemcontext = context_system::instance();
3360 $ra = new stdClass();
3361 $ra->userid = $userid;
3362 $ra->contextid = $systemcontext->id;
3363 $ra->roleid = $defaultuserroleid;
3371 * Creates a record in the role_allow_override table
3373 * @param int $sroleid source roleid
3374 * @param int $troleid target roleid
3377 function allow_override($sroleid, $troleid) {
3380 $record = new stdClass();
3381 $record->roleid = $sroleid;
3382 $record->allowoverride = $troleid;
3383 $DB->insert_record('role_allow_override', $record);
3387 * Creates a record in the role_allow_assign table
3389 * @param int $fromroleid source roleid
3390 * @param int $targetroleid target roleid
3393 function allow_assign($fromroleid, $targetroleid) {
3396 $record = new stdClass();
3397 $record->roleid = $fromroleid;
3398 $record->allowassign = $targetroleid;
3399 $DB->insert_record('role_allow_assign', $record);
3403 * Creates a record in the role_allow_switch table
3405 * @param int $fromroleid source roleid
3406 * @param int $targetroleid target roleid
3409 function allow_switch($fromroleid, $targetroleid) {
3412 $record = new stdClass();
3413 $record->roleid = $fromroleid;
3414 $record->allowswitch = $targetroleid;
3415 $DB->insert_record('role_allow_switch', $record);
3419 * Gets a list of roles that this user can assign in this context
3421 * @param context $context the context.
3422 * @param int $rolenamedisplay the type of role name to display. One of the
3423 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3424 * @param bool $withusercounts if true, count the number of users with each role.
3425 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3426 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3427 * if $withusercounts is true, returns a list of three arrays,
3428 * $rolenames, $rolecounts, and $nameswithcounts.
3430 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3433 // make sure there is a real user specified
3434 if ($user === null) {
3435 $userid = isset($USER->id) ? $USER->id : 0;
3437 $userid = is_object($user) ? $user->id : $user;
3440 if (!has_capability('moodle/role:assign', $context, $userid)) {
3441 if ($withusercounts) {
3442 return array(array(), array(), array());
3451 if ($withusercounts) {
3452 $extrafields = ', (SELECT count(u.id)
3453 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3454 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3456 $params['conid'] = $context->id;
3459 if (is_siteadmin($userid)) {
3460 // show all roles allowed in this context to admins
3461 $assignrestriction = "";
3463 $parents = $context->get_parent_context_ids(true);
3464 $contexts = implode(',' , $parents);
3465 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3466 FROM {role_allow_assign} raa
3467 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3468 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3469 ) ar ON ar.id = r.id";
3470 $params['userid'] = $userid;
3472 $params['contextlevel'] = $context->contextlevel;
3474 if ($coursecontext = $context->get_course_context(false)) {
3475 $params['coursecontext'] = $coursecontext->id;
3477 $params['coursecontext'] = 0; // no course aliases
3478 $coursecontext = null;
3480 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3483 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3484 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3485 ORDER BY r.sortorder ASC";
3486 $roles = $DB->get_records_sql($sql, $params);
3488 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3490 if (!$withusercounts) {
3494 $rolecounts = array();
3495 $nameswithcounts = array();
3496 foreach ($roles as $role) {
3497 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3498 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3500 return array($rolenames, $rolecounts, $nameswithcounts);
3504 * Gets a list of roles that this user can switch to in a context
3506 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3507 * This function just process the contents of the role_allow_switch table. You also need to
3508 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3510 * @param context $context a context.
3511 * @return array an array $roleid => $rolename.
3513 function get_switchable_roles(context $context) {
3519 if (!is_siteadmin()) {
3520 // Admins are allowed to switch to any role with.
3521 // Others are subject to the additional constraint that the switch-to role must be allowed by
3522 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3523 $parents = $context->get_parent_context_ids(true);
3524 $contexts = implode(',' , $parents);
3526 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3527 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3528 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3529 $params['userid'] = $USER->id;
3532 if ($coursecontext = $context->get_course_context(false)) {
3533 $params['coursecontext'] = $coursecontext->id;
3535 $params['coursecontext'] = 0; // no course aliases
3536 $coursecontext = null;
3540 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3541 FROM (SELECT DISTINCT rc.roleid
3542 FROM {role_capabilities} rc
3545 JOIN {role} r ON r.id = idlist.roleid
3546 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3547 ORDER BY r.sortorder";
3548 $roles = $DB->get_records_sql($query, $params);
3550 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3554 * Gets a list of roles that this user can override in this context.
3556 * @param context $context the context.
3557 * @param int $rolenamedisplay the type of role name to display. One of the
3558 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3559 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3560 * @return array if $withcounts is false, then an array $roleid => $rolename.
3561 * if $withusercounts is true, returns a list of three arrays,
3562 * $rolenames, $rolecounts, and $nameswithcounts.
3564 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3567 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3569 return array(array(), array(), array());
3575 $parents = $context->get_parent_context_ids(true);
3576 $contexts = implode(',' , $parents);
3581 $params['userid'] = $USER->id;
3583 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3584 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3585 $params['conid'] = $context->id;
3588 if ($coursecontext = $context->get_course_context(false)) {
3589 $params['coursecontext'] = $coursecontext->id;
3591 $params['coursecontext'] = 0; // no course aliases
3592 $coursecontext = null;
3595 if (is_siteadmin()) {
3596 // show all roles to admins
3597 $roles = $DB->get_records_sql("
3598 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3600 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3601 ORDER BY ro.sortorder ASC", $params);
3604 $roles = $DB->get_records_sql("
3605 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3607 JOIN (SELECT DISTINCT r.id
3609 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3610 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3611 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3612 ) inline_view ON ro.id = inline_view.id
3613 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3614 ORDER BY ro.sortorder ASC", $params);
3617 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3623 $rolecounts = array();
3624 $nameswithcounts = array();
3625 foreach ($roles as $role) {
3626 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3627 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3629 return array($rolenames, $rolecounts, $nameswithcounts);
3633 * Create a role menu suitable for default role selection in enrol plugins.
3635 * @package core_enrol
3637 * @param context $context
3638 * @param int $addroleid current or default role - always added to list
3639 * @return array roleid=>localised role name
3641 function get_default_enrol_roles(context $context, $addroleid = null) {
3644 $params = array('contextlevel'=>CONTEXT_COURSE);
3646 if ($coursecontext = $context->get_course_context(false)) {
3647 $params['coursecontext'] = $coursecontext->id;
3649 $params['coursecontext'] = 0; // no course names
3650 $coursecontext = null;
3654 $addrole = "OR r.id = :addroleid";
3655 $params['addroleid'] = $addroleid;
3660 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3662 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3663 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)