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_roles_sitewide_accessdata()
62 * <b>Name conventions</b>
65 * "ra" means role assignment
66 * "rdef" means role definition
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 switches and initialization time.
79 * Things are keyed on "contextpaths" (the path field of
80 * the context table) for fast walking up/down the tree.
82 * $accessdata['ra'][$contextpath] = array($roleid=>$roleid)
83 * [$contextpath] = array($roleid=>$roleid)
84 * [$contextpath] = array($roleid=>$roleid)
87 * <b>Stale accessdata</b>
89 * For the logged-in user, accessdata is long-lived.
91 * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
92 * context paths affected by changes. Any check at-or-below
93 * a dirty context will trigger a transparent reload of accessdata.
95 * Changes at the system level will force the reload for everyone.
97 * <b>Default role caps</b>
98 * The default role assignment is not in the DB, so we
99 * add it manually to accessdata.
101 * This means that functions that work directly off the
102 * DB need to ensure that the default role caps
103 * are dealt with appropriately.
105 * @package core_access
106 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
107 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
110 defined('MOODLE_INTERNAL') ||
die();
112 /** No capability change */
113 define('CAP_INHERIT', 0);
114 /** Allow permission, overrides CAP_PREVENT defined in parent contexts */
115 define('CAP_ALLOW', 1);
116 /** Prevent permission, overrides CAP_ALLOW defined in parent contexts */
117 define('CAP_PREVENT', -1);
118 /** Prohibit permission, overrides everything in current and child contexts */
119 define('CAP_PROHIBIT', -1000);
121 /** System context level - only one instance in every system */
122 define('CONTEXT_SYSTEM', 10);
123 /** User context level - one instance for each user describing what others can do to user */
124 define('CONTEXT_USER', 30);
125 /** Course category context level - one instance for each category */
126 define('CONTEXT_COURSECAT', 40);
127 /** Course context level - one instances for each course */
128 define('CONTEXT_COURSE', 50);
129 /** Course module context level - one instance for each course module */
130 define('CONTEXT_MODULE', 70);
132 * Block context level - one instance for each block, sticky blocks are tricky
133 * because ppl think they should be able to override them at lower contexts.
134 * Any other context level instance can be parent of block context.
136 define('CONTEXT_BLOCK', 80);
138 /** Capability allow management of trusts - NOT IMPLEMENTED YET - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
139 define('RISK_MANAGETRUST', 0x0001);
140 /** Capability allows changes in system configuration - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
141 define('RISK_CONFIG', 0x0002);
142 /** Capability allows user to add scripted content - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
143 define('RISK_XSS', 0x0004);
144 /** Capability allows access to personal user information - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
145 define('RISK_PERSONAL', 0x0008);
146 /** Capability allows users to add content others may see - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
147 define('RISK_SPAM', 0x0010);
148 /** capability allows mass delete of data belonging to other users - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
149 define('RISK_DATALOSS', 0x0020);
151 /** rolename displays - the name as defined in the role definition, localised if name empty */
152 define('ROLENAME_ORIGINAL', 0);
153 /** rolename displays - the name as defined by a role alias at the course level, falls back to ROLENAME_ORIGINAL if alias not present */
154 define('ROLENAME_ALIAS', 1);
155 /** rolename displays - Both, like this: Role alias (Original) */
156 define('ROLENAME_BOTH', 2);
157 /** rolename displays - the name as defined in the role definition and the shortname in brackets */
158 define('ROLENAME_ORIGINALANDSHORT', 3);
159 /** rolename displays - the name as defined by a role alias, in raw form suitable for editing */
160 define('ROLENAME_ALIAS_RAW', 4);
161 /** rolename displays - the name is simply short role name */
162 define('ROLENAME_SHORT', 5);
164 if (!defined('CONTEXT_CACHE_MAX_SIZE')) {
165 /** maximum size of context cache - it is possible to tweak this config.php or in any script before inclusion of context.php */
166 define('CONTEXT_CACHE_MAX_SIZE', 2500);
170 * Although this looks like a global variable, it isn't really.
172 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
173 * It is used to cache various bits of data between function calls for performance reasons.
174 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
175 * as methods of a class, instead of functions.
178 * @global stdClass $ACCESSLIB_PRIVATE
179 * @name $ACCESSLIB_PRIVATE
181 global $ACCESSLIB_PRIVATE;
182 $ACCESSLIB_PRIVATE = new stdClass();
183 $ACCESSLIB_PRIVATE->cacheroledefs
= array(); // Holds site-wide role definitions.
184 $ACCESSLIB_PRIVATE->dirtycontexts
= null; // Dirty contexts cache, loaded from DB once per page
185 $ACCESSLIB_PRIVATE->dirtyusers
= null; // Dirty users cache, loaded from DB once per $USER->id
186 $ACCESSLIB_PRIVATE->accessdatabyuser
= array(); // Holds the cache of $accessdata structure for users (including $USER)
189 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
191 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
192 * accesslib's private caches. You need to do this before setting up test data,
193 * and also at the end of the tests.
198 function accesslib_clear_all_caches_for_unit_testing() {
201 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
204 accesslib_clear_all_caches(true);
205 accesslib_reset_role_cache();
207 unset($USER->access
);
211 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
213 * This reset does not touch global $USER.
216 * @param bool $resetcontexts
219 function accesslib_clear_all_caches($resetcontexts) {
220 global $ACCESSLIB_PRIVATE;
222 $ACCESSLIB_PRIVATE->dirtycontexts
= null;
223 $ACCESSLIB_PRIVATE->dirtyusers
= null;
224 $ACCESSLIB_PRIVATE->accessdatabyuser
= array();
226 if ($resetcontexts) {
227 context_helper
::reset_caches();
232 * Full reset of accesslib's private role cache. ONLY TO BE USED FROM THIS LIBRARY FILE!
234 * This reset does not touch global $USER.
236 * Note: Only use this when the roles that need a refresh are unknown.
238 * @see accesslib_clear_role_cache()
243 function accesslib_reset_role_cache() {
244 global $ACCESSLIB_PRIVATE;
246 $ACCESSLIB_PRIVATE->cacheroledefs
= array();
247 $cache = cache
::make('core', 'roledefs');
252 * Clears accesslib's private cache of a specific role or roles. ONLY BE USED FROM THIS LIBRARY FILE!
254 * This reset does not touch global $USER.
257 * @param int|array $roles
260 function accesslib_clear_role_cache($roles) {
261 global $ACCESSLIB_PRIVATE;
263 if (!is_array($roles)) {
267 foreach ($roles as $role) {
268 if (isset($ACCESSLIB_PRIVATE->cacheroledefs
[$role])) {
269 unset($ACCESSLIB_PRIVATE->cacheroledefs
[$role]);
273 $cache = cache
::make('core', 'roledefs');
274 $cache->delete_many($roles);
278 * Role is assigned at system context.
284 function get_role_access($roleid) {
285 $accessdata = get_empty_accessdata();
286 $accessdata['ra']['/'.SYSCONTEXTID
] = array((int)$roleid => (int)$roleid);
291 * Fetch raw "site wide" role definitions.
292 * Even MUC static acceleration cache appears a bit slow for this.
293 * Important as can be hit hundreds of times per page.
295 * @param array $roleids List of role ids to fetch definitions for.
296 * @return array Complete definition for each requested role.
298 function get_role_definitions(array $roleids) {
299 global $ACCESSLIB_PRIVATE;
301 if (empty($roleids)) {
305 // Grab all keys we have not yet got in our static cache.
306 if ($uncached = array_diff($roleids, array_keys($ACCESSLIB_PRIVATE->cacheroledefs
))) {
307 $cache = cache
::make('core', 'roledefs');
308 foreach ($cache->get_many($uncached) as $roleid => $cachedroledef) {
309 if (is_array($cachedroledef)) {
310 $ACCESSLIB_PRIVATE->cacheroledefs
[$roleid] = $cachedroledef;
314 // Check we have the remaining keys from the MUC.
315 if ($uncached = array_diff($roleids, array_keys($ACCESSLIB_PRIVATE->cacheroledefs
))) {
316 $uncached = get_role_definitions_uncached($uncached);
317 $ACCESSLIB_PRIVATE->cacheroledefs +
= $uncached;
318 $cache->set_many($uncached);
322 // Return just the roles we need.
323 return array_intersect_key($ACCESSLIB_PRIVATE->cacheroledefs
, array_flip($roleids));
327 * Query raw "site wide" role definitions.
329 * @param array $roleids List of role ids to fetch definitions for.
330 * @return array Complete definition for each requested role.
332 function get_role_definitions_uncached(array $roleids) {
335 if (empty($roleids)) {
339 // Create a blank results array: even if a role has no capabilities,
340 // we need to ensure it is included in the results to show we have
341 // loaded all the capabilities that there are.
343 foreach ($roleids as $roleid) {
344 $rdefs[$roleid] = array();
347 // Load all the capabilities for these roles in all contexts.
348 list($sql, $params) = $DB->get_in_or_equal($roleids);
349 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
350 FROM {role_capabilities} rc
351 JOIN {context} ctx ON rc.contextid = ctx.id
352 JOIN {capabilities} cap ON rc.capability = cap.name
353 WHERE rc.roleid $sql";
354 $rs = $DB->get_recordset_sql($sql, $params);
356 // Store the capabilities into the expected data structure.
357 foreach ($rs as $rd) {
358 if (!isset($rdefs[$rd->roleid
][$rd->path
])) {
359 $rdefs[$rd->roleid
][$rd->path
] = array();
361 $rdefs[$rd->roleid
][$rd->path
][$rd->capability
] = (int) $rd->permission
;
366 // Sometimes (e.g. get_user_capability_course_helper::get_capability_info_at_each_context)
367 // we process role definitinons in a way that requires we see parent contexts
368 // before child contexts. This sort ensures that works (and is faster than
369 // sorting in the SQL query).
370 foreach ($rdefs as $roleid => $rdef) {
371 ksort($rdefs[$roleid]);
378 * Get the default guest role, this is used for guest account,
379 * search engine spiders, etc.
381 * @return stdClass role record
383 function get_guest_role() {
386 if (empty($CFG->guestroleid
)) {
387 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
388 $guestrole = array_shift($roles); // Pick the first one
389 set_config('guestroleid', $guestrole->id
);
392 debugging('Can not find any guest role!');
396 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid
))) {
399 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
400 set_config('guestroleid', '');
401 return get_guest_role();
407 * Check whether a user has a particular capability in a given context.
410 * $context = context_module::instance($cm->id);
411 * has_capability('mod/forum:replypost', $context)
413 * By default checks the capabilities of the current user, but you can pass a
414 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
416 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
417 * or capabilities with XSS, config or data loss risks.
421 * @param string $capability the name of the capability to check. For example mod/forum:view
422 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
423 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
424 * @param boolean $doanything If false, ignores effect of admin role assignment
425 * @return boolean true if the user has this capability. Otherwise false.
427 function has_capability($capability, context
$context, $user = null, $doanything = true) {
428 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
430 if (during_initial_install()) {
431 if ($SCRIPT === "/$CFG->admin/index.php"
432 or $SCRIPT === "/$CFG->admin/cli/install.php"
433 or $SCRIPT === "/$CFG->admin/cli/install_database.php"
434 or (defined('BEHAT_UTIL') and BEHAT_UTIL
)
435 or (defined('PHPUNIT_UTIL') and PHPUNIT_UTIL
)) {
436 // we are in an installer - roles can not work yet
443 if (strpos($capability, 'moodle/legacy:') === 0) {
444 throw new coding_exception('Legacy capabilities can not be used any more!');
447 if (!is_bool($doanything)) {
448 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
451 // capability must exist
452 if (!$capinfo = get_capability_info($capability)) {
453 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
457 if (!isset($USER->id
)) {
458 // should never happen
460 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER
);
463 // make sure there is a real user specified
464 if ($user === null) {
467 $userid = is_object($user) ?
$user->id
: $user;
470 // make sure forcelogin cuts off not-logged-in users if enabled
471 if (!empty($CFG->forcelogin
) and $userid == 0) {
475 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
476 if (($capinfo->captype
=== 'write') or ($capinfo->riskbitmask
& (RISK_XSS | RISK_CONFIG | RISK_DATALOSS
))) {
477 if (isguestuser($userid) or $userid == 0) {
482 // Check whether context locking is enabled.
483 if (!empty($CFG->contextlocking
)) {
484 if ($capinfo->captype
=== 'write' && $context->locked
) {
485 // Context locking applies to any write capability in a locked context.
486 // It does not apply to moodle/site:managecontextlocks - this is to allow context locking to be unlocked.
487 if ($capinfo->name
!== 'moodle/site:managecontextlocks') {
488 // It applies to all users who are not site admins.
489 // It also applies to site admins when contextlockappliestoadmin is set.
490 if (!is_siteadmin($userid) ||
!empty($CFG->contextlockappliestoadmin
)) {
497 // somehow make sure the user is not deleted and actually exists
499 if ($userid == $USER->id
and isset($USER->deleted
)) {
500 // this prevents one query per page, it is a bit of cheating,
501 // but hopefully session is terminated properly once user is deleted
502 if ($USER->deleted
) {
506 if (!context_user
::instance($userid, IGNORE_MISSING
)) {
507 // no user context == invalid userid
513 // context path/depth must be valid
514 if (empty($context->path
) or $context->depth
== 0) {
515 // this should not happen often, each upgrade tries to rebuild the context paths
516 debugging('Context id '.$context->id
.' does not have valid path, please use context_helper::build_all_paths()');
517 if (is_siteadmin($userid)) {
524 // Find out if user is admin - it is not possible to override the doanything in any way
525 // and it is not possible to switch to admin role either.
527 if (is_siteadmin($userid)) {
528 if ($userid != $USER->id
) {
531 // make sure switchrole is not used in this context
532 if (empty($USER->access
['rsw'])) {
535 $parts = explode('/', trim($context->path
, '/'));
538 foreach ($parts as $part) {
539 $path .= '/' . $part;
540 if (!empty($USER->access
['rsw'][$path])) {
548 //ok, admin switched role in this context, let's use normal access control rules
552 // Careful check for staleness...
553 $context->reload_if_dirty();
555 if ($USER->id
== $userid) {
556 if (!isset($USER->access
)) {
557 load_all_capabilities();
559 $access =& $USER->access
;
562 // make sure user accessdata is really loaded
563 get_user_accessdata($userid, true);
564 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser
[$userid];
567 return has_capability_in_accessdata($capability, $context, $access);
571 * Check if the user has any one of several capabilities from a list.
573 * This is just a utility method that calls has_capability in a loop. Try to put
574 * the capabilities that most users are likely to have first in the list for best
578 * @see has_capability()
580 * @param array $capabilities an array of capability names.
581 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
582 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
583 * @param boolean $doanything If false, ignore effect of admin role assignment
584 * @return boolean true if the user has any of these capabilities. Otherwise false.
586 function has_any_capability(array $capabilities, context
$context, $user = null, $doanything = true) {
587 foreach ($capabilities as $capability) {
588 if (has_capability($capability, $context, $user, $doanything)) {
596 * Check if the user has all the capabilities in a list.
598 * This is just a utility method that calls has_capability in a loop. Try to put
599 * the capabilities that fewest users are likely to have first in the list for best
603 * @see has_capability()
605 * @param array $capabilities an array of capability names.
606 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
607 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
608 * @param boolean $doanything If false, ignore effect of admin role assignment
609 * @return boolean true if the user has all of these capabilities. Otherwise false.
611 function has_all_capabilities(array $capabilities, context
$context, $user = null, $doanything = true) {
612 foreach ($capabilities as $capability) {
613 if (!has_capability($capability, $context, $user, $doanything)) {
621 * Is course creator going to have capability in a new course?
623 * This is intended to be used in enrolment plugins before or during course creation,
624 * do not use after the course is fully created.
628 * @param string $capability the name of the capability to check.
629 * @param context $context course or category context where is course going to be created
630 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
631 * @return boolean true if the user will have this capability.
633 * @throws coding_exception if different type of context submitted
635 function guess_if_creator_will_have_course_capability($capability, context
$context, $user = null) {
638 if ($context->contextlevel
!= CONTEXT_COURSE
and $context->contextlevel
!= CONTEXT_COURSECAT
) {
639 throw new coding_exception('Only course or course category context expected');
642 if (has_capability($capability, $context, $user)) {
643 // User already has the capability, it could be only removed if CAP_PROHIBIT
644 // was involved here, but we ignore that.
648 if (!has_capability('moodle/course:create', $context, $user)) {
652 if (!enrol_is_enabled('manual')) {
656 if (empty($CFG->creatornewroleid
)) {
660 if ($context->contextlevel
== CONTEXT_COURSE
) {
661 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
665 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
670 // Most likely they will be enrolled after the course creation is finished,
671 // does the new role have the required capability?
672 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
673 return isset($neededroles[$CFG->creatornewroleid
]);
677 * Check if the user is an admin at the site level.
679 * Please note that use of proper capabilities is always encouraged,
680 * this function is supposed to be used from core or for temporary hacks.
684 * @param int|stdClass $user_or_id user id or user object
685 * @return bool true if user is one of the administrators, false otherwise
687 function is_siteadmin($user_or_id = null) {
690 if ($user_or_id === null) {
694 if (empty($user_or_id)) {
697 if (!empty($user_or_id->id
)) {
698 $userid = $user_or_id->id
;
700 $userid = $user_or_id;
703 // Because this script is called many times (150+ for course page) with
704 // the same parameters, it is worth doing minor optimisations. This static
705 // cache stores the value for a single userid, saving about 2ms from course
706 // page load time without using significant memory. As the static cache
707 // also includes the value it depends on, this cannot break unit tests.
708 static $knownid, $knownresult, $knownsiteadmins;
709 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins
) {
713 $knownsiteadmins = $CFG->siteadmins
;
715 $siteadmins = explode(',', $CFG->siteadmins
);
716 $knownresult = in_array($userid, $siteadmins);
721 * Returns true if user has at least one role assign
722 * of 'coursecontact' role (is potentially listed in some course descriptions).
727 function has_coursecontact_role($userid) {
730 if (empty($CFG->coursecontact
)) {
734 FROM {role_assignments}
735 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
736 return $DB->record_exists_sql($sql, array('userid'=>$userid));
740 * Does the user have a capability to do something?
742 * Walk the accessdata array and return true/false.
743 * Deals with prohibits, role switching, aggregating
746 * The main feature of here is being FAST and with no
751 * Switch Role merges with default role
752 * ------------------------------------
753 * If you are a teacher in course X, you have at least
754 * teacher-in-X + defaultloggedinuser-sitewide. So in the
755 * course you'll have techer+defaultloggedinuser.
756 * We try to mimic that in switchrole.
758 * Permission evaluation
759 * ---------------------
760 * Originally there was an extremely complicated way
761 * to determine the user access that dealt with
762 * "locality" or role assignments and role overrides.
763 * Now we simply evaluate access for each role separately
764 * and then verify if user has at least one role with allow
765 * and at the same time no role with prohibit.
768 * @param string $capability
769 * @param context $context
770 * @param array $accessdata
773 function has_capability_in_accessdata($capability, context
$context, array &$accessdata) {
776 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
777 $path = $context->path
;
778 $paths = array($path);
779 while($path = rtrim($path, '0123456789')) {
780 $path = rtrim($path, '/');
788 $switchedrole = false;
790 // Find out if role switched
791 if (!empty($accessdata['rsw'])) {
792 // From the bottom up...
793 foreach ($paths as $path) {
794 if (isset($accessdata['rsw'][$path])) {
795 // Found a switchrole assignment - check for that role _plus_ the default user role
796 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid
=>null);
797 $switchedrole = true;
803 if (!$switchedrole) {
804 // get all users roles in this context and above
805 foreach ($paths as $path) {
806 if (isset($accessdata['ra'][$path])) {
807 foreach ($accessdata['ra'][$path] as $roleid) {
808 $roles[$roleid] = null;
814 // Now find out what access is given to each role, going bottom-->up direction
815 $rdefs = get_role_definitions(array_keys($roles));
818 foreach ($roles as $roleid => $ignored) {
819 foreach ($paths as $path) {
820 if (isset($rdefs[$roleid][$path][$capability])) {
821 $perm = (int)$rdefs[$roleid][$path][$capability];
822 if ($perm === CAP_PROHIBIT
) {
823 // any CAP_PROHIBIT found means no permission for the user
826 if (is_null($roles[$roleid])) {
827 $roles[$roleid] = $perm;
831 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
832 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW
);
839 * A convenience function that tests has_capability, and displays an error if
840 * the user does not have that capability.
842 * NOTE before Moodle 2.0, this function attempted to make an appropriate
843 * require_login call before checking the capability. This is no longer the case.
844 * You must call require_login (or one of its variants) if you want to check the
845 * user is logged in, before you call this function.
847 * @see has_capability()
849 * @param string $capability the name of the capability to check. For example mod/forum:view
850 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
851 * @param int $userid A user id. By default (null) checks the permissions of the current user.
852 * @param bool $doanything If false, ignore effect of admin role assignment
853 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
854 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
855 * @return void terminates with an error if the user does not have the given capability.
857 function require_capability($capability, context
$context, $userid = null, $doanything = true,
858 $errormessage = 'nopermissions', $stringfile = '') {
859 if (!has_capability($capability, $context, $userid, $doanything)) {
860 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
865 * Return a nested array showing all role assignments for the user.
866 * [ra] => [contextpath][roleid] = roleid
869 * @param int $userid - the id of the user
870 * @return array access info array
872 function get_user_roles_sitewide_accessdata($userid) {
875 $accessdata = get_empty_accessdata();
877 // start with the default role
878 if (!empty($CFG->defaultuserroleid
)) {
879 $syscontext = context_system
::instance();
880 $accessdata['ra'][$syscontext->path
][(int)$CFG->defaultuserroleid
] = (int)$CFG->defaultuserroleid
;
883 // load the "default frontpage role"
884 if (!empty($CFG->defaultfrontpageroleid
)) {
885 $frontpagecontext = context_course
::instance(get_site()->id
);
886 if ($frontpagecontext->path
) {
887 $accessdata['ra'][$frontpagecontext->path
][(int)$CFG->defaultfrontpageroleid
] = (int)$CFG->defaultfrontpageroleid
;
891 // Preload every assigned role.
892 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
893 FROM {role_assignments} ra
894 JOIN {context} ctx ON ctx.id = ra.contextid
895 WHERE ra.userid = :userid";
897 $rs = $DB->get_recordset_sql($sql, array('userid' => $userid));
899 foreach ($rs as $ra) {
900 // RAs leafs are arrays to support multi-role assignments...
901 $accessdata['ra'][$ra->path
][(int)$ra->roleid
] = (int)$ra->roleid
;
910 * Returns empty accessdata structure.
913 * @return array empt accessdata
915 function get_empty_accessdata() {
916 $accessdata = array(); // named list
917 $accessdata['ra'] = array();
918 $accessdata['time'] = time();
919 $accessdata['rsw'] = array();
925 * Get accessdata for a given user.
929 * @param bool $preloadonly true means do not return access array
930 * @return array accessdata
932 function get_user_accessdata($userid, $preloadonly=false) {
933 global $CFG, $ACCESSLIB_PRIVATE, $USER;
935 if (isset($USER->access
)) {
936 $ACCESSLIB_PRIVATE->accessdatabyuser
[$USER->id
] = $USER->access
;
939 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser
[$userid])) {
940 if (empty($userid)) {
941 if (!empty($CFG->notloggedinroleid
)) {
942 $accessdata = get_role_access($CFG->notloggedinroleid
);
945 return get_empty_accessdata();
948 } else if (isguestuser($userid)) {
949 if ($guestrole = get_guest_role()) {
950 $accessdata = get_role_access($guestrole->id
);
953 return get_empty_accessdata();
957 // Includes default role and frontpage role.
958 $accessdata = get_user_roles_sitewide_accessdata($userid);
961 $ACCESSLIB_PRIVATE->accessdatabyuser
[$userid] = $accessdata;
967 return $ACCESSLIB_PRIVATE->accessdatabyuser
[$userid];
972 * A convenience function to completely load all the capabilities
973 * for the current user. It is called from has_capability() and functions change permissions.
975 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
976 * @see check_enrolment_plugins()
981 function load_all_capabilities() {
984 // roles not installed yet - we are in the middle of installation
985 if (during_initial_install()) {
989 if (!isset($USER->id
)) {
990 // this should not happen
994 unset($USER->access
);
995 $USER->access
= get_user_accessdata($USER->id
);
997 // Clear to force a refresh
998 unset($USER->mycourses
);
1000 // init/reset internal enrol caches - active course enrolments and temp access
1001 $USER->enrol
= array('enrolled'=>array(), 'tempguest'=>array());
1005 * A convenience function to completely reload all the capabilities
1006 * for the current user when roles have been updated in a relevant
1007 * context -- but PRESERVING switchroles and loginas.
1008 * This function resets all accesslib and context caches.
1010 * That is - completely transparent to the user.
1012 * Note: reloads $USER->access completely.
1017 function reload_all_capabilities() {
1018 global $USER, $DB, $ACCESSLIB_PRIVATE;
1022 if (!empty($USER->access
['rsw'])) {
1023 $sw = $USER->access
['rsw'];
1026 accesslib_clear_all_caches(true);
1027 unset($USER->access
);
1029 // Prevent dirty flags refetching on this page.
1030 $ACCESSLIB_PRIVATE->dirtycontexts
= array();
1031 $ACCESSLIB_PRIVATE->dirtyusers
= array($USER->id
=> false);
1033 load_all_capabilities();
1035 foreach ($sw as $path => $roleid) {
1036 if ($record = $DB->get_record('context', array('path'=>$path))) {
1037 $context = context
::instance_by_id($record->id
);
1038 if (has_capability('moodle/role:switchroles', $context)) {
1039 role_switch($roleid, $context);
1046 * Adds a temp role to current USER->access array.
1048 * Useful for the "temporary guest" access we grant to logged-in users.
1049 * This is useful for enrol plugins only.
1052 * @param context_course $coursecontext
1053 * @param int $roleid
1056 function load_temp_course_role(context_course
$coursecontext, $roleid) {
1057 global $USER, $SITE;
1059 if (empty($roleid)) {
1060 debugging('invalid role specified in load_temp_course_role()');
1064 if ($coursecontext->instanceid
== $SITE->id
) {
1065 debugging('Can not use temp roles on the frontpage');
1069 if (!isset($USER->access
)) {
1070 load_all_capabilities();
1073 $coursecontext->reload_if_dirty();
1075 if (isset($USER->access
['ra'][$coursecontext->path
][$roleid])) {
1079 $USER->access
['ra'][$coursecontext->path
][(int)$roleid] = (int)$roleid;
1083 * Removes any extra guest roles from current USER->access array.
1084 * This is useful for enrol plugins only.
1087 * @param context_course $coursecontext
1090 function remove_temp_course_roles(context_course
$coursecontext) {
1091 global $DB, $USER, $SITE;
1093 if ($coursecontext->instanceid
== $SITE->id
) {
1094 debugging('Can not use temp roles on the frontpage');
1098 if (empty($USER->access
['ra'][$coursecontext->path
])) {
1099 //no roles here, weird
1103 $sql = "SELECT DISTINCT ra.roleid AS id
1104 FROM {role_assignments} ra
1105 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1106 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id
, 'userid'=>$USER->id
));
1108 $USER->access
['ra'][$coursecontext->path
] = array();
1109 foreach($ras as $r) {
1110 $USER->access
['ra'][$coursecontext->path
][(int)$r->id
] = (int)$r->id
;
1115 * Returns array of all role archetypes.
1119 function get_role_archetypes() {
1121 'manager' => 'manager',
1122 'coursecreator' => 'coursecreator',
1123 'editingteacher' => 'editingteacher',
1124 'teacher' => 'teacher',
1125 'student' => 'student',
1128 'frontpage' => 'frontpage'
1133 * Assign the defaults found in this capability definition to roles that have
1134 * the corresponding legacy capabilities assigned to them.
1136 * @param string $capability
1137 * @param array $legacyperms an array in the format (example):
1138 * 'guest' => CAP_PREVENT,
1139 * 'student' => CAP_ALLOW,
1140 * 'teacher' => CAP_ALLOW,
1141 * 'editingteacher' => CAP_ALLOW,
1142 * 'coursecreator' => CAP_ALLOW,
1143 * 'manager' => CAP_ALLOW
1144 * @return boolean success or failure.
1146 function assign_legacy_capabilities($capability, $legacyperms) {
1148 $archetypes = get_role_archetypes();
1150 foreach ($legacyperms as $type => $perm) {
1152 $systemcontext = context_system
::instance();
1153 if ($type === 'admin') {
1154 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1158 if (!array_key_exists($type, $archetypes)) {
1159 print_error('invalidlegacy', '', '', $type);
1162 if ($roles = get_archetype_roles($type)) {
1163 foreach ($roles as $role) {
1164 // Assign a site level capability.
1165 if (!assign_capability($capability, $perm, $role->id
, $systemcontext->id
)) {
1175 * Verify capability risks.
1177 * @param stdClass $capability a capability - a row from the capabilities table.
1178 * @return boolean whether this capability is safe - that is, whether people with the
1179 * safeoverrides capability should be allowed to change it.
1181 function is_safe_capability($capability) {
1182 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL
) & $capability->riskbitmask
);
1186 * Get the local override (if any) for a given capability in a role in a context
1188 * @param int $roleid
1189 * @param int $contextid
1190 * @param string $capability
1191 * @return stdClass local capability override
1193 function get_local_override($roleid, $contextid, $capability) {
1196 return $DB->get_record_sql("
1198 FROM {role_capabilities} rc
1199 JOIN {capability} cap ON rc.capability = cap.name
1200 WHERE rc.roleid = :roleid AND rc.capability = :capability AND rc.contextid = :contextid", [
1201 'roleid' => $roleid,
1202 'contextid' => $contextid,
1203 'capability' => $capability,
1209 * Returns context instance plus related course and cm instances
1211 * @param int $contextid
1212 * @return array of ($context, $course, $cm)
1214 function get_context_info_array($contextid) {
1217 $context = context
::instance_by_id($contextid, MUST_EXIST
);
1221 if ($context->contextlevel
== CONTEXT_COURSE
) {
1222 $course = $DB->get_record('course', array('id'=>$context->instanceid
), '*', MUST_EXIST
);
1224 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
1225 $cm = get_coursemodule_from_id('', $context->instanceid
, 0, false, MUST_EXIST
);
1226 $course = $DB->get_record('course', array('id'=>$cm->course
), '*', MUST_EXIST
);
1228 } else if ($context->contextlevel
== CONTEXT_BLOCK
) {
1229 $parent = $context->get_parent_context();
1231 if ($parent->contextlevel
== CONTEXT_COURSE
) {
1232 $course = $DB->get_record('course', array('id'=>$parent->instanceid
), '*', MUST_EXIST
);
1233 } else if ($parent->contextlevel
== CONTEXT_MODULE
) {
1234 $cm = get_coursemodule_from_id('', $parent->instanceid
, 0, false, MUST_EXIST
);
1235 $course = $DB->get_record('course', array('id'=>$cm->course
), '*', MUST_EXIST
);
1239 return array($context, $course, $cm);
1243 * Function that creates a role
1245 * @param string $name role name
1246 * @param string $shortname role short name
1247 * @param string $description role description
1248 * @param string $archetype
1249 * @return int id or dml_exception
1251 function create_role($name, $shortname, $description, $archetype = '') {
1254 if (strpos($archetype, 'moodle/legacy:') !== false) {
1255 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1258 // verify role archetype actually exists
1259 $archetypes = get_role_archetypes();
1260 if (empty($archetypes[$archetype])) {
1264 // Insert the role record.
1265 $role = new stdClass();
1266 $role->name
= $name;
1267 $role->shortname
= $shortname;
1268 $role->description
= $description;
1269 $role->archetype
= $archetype;
1271 //find free sortorder number
1272 $role->sortorder
= $DB->get_field('role', 'MAX(sortorder) + 1', array());
1273 if (empty($role->sortorder
)) {
1274 $role->sortorder
= 1;
1276 $id = $DB->insert_record('role', $role);
1282 * Function that deletes a role and cleanups up after it
1284 * @param int $roleid id of role to delete
1285 * @return bool always true
1287 function delete_role($roleid) {
1290 // first unssign all users
1291 role_unassign_all(array('roleid'=>$roleid));
1293 // cleanup all references to this role, ignore errors
1294 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1295 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1296 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1297 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1298 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1299 $DB->delete_records('role_names', array('roleid'=>$roleid));
1300 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1302 // Get role record before it's deleted.
1303 $role = $DB->get_record('role', array('id'=>$roleid));
1305 // Finally delete the role itself.
1306 $DB->delete_records('role', array('id'=>$roleid));
1309 $event = \core\event\role_deleted
::create(
1311 'context' => context_system
::instance(),
1312 'objectid' => $roleid,
1315 'shortname' => $role->shortname
,
1316 'description' => $role->description
,
1317 'archetype' => $role->archetype
1321 $event->add_record_snapshot('role', $role);
1324 // Reset any cache of this role, including MUC.
1325 accesslib_clear_role_cache($roleid);
1331 * Function to write context specific overrides, or default capabilities.
1333 * @param string $capability string name
1334 * @param int $permission CAP_ constants
1335 * @param int $roleid role id
1336 * @param int|context $contextid context id
1337 * @param bool $overwrite
1338 * @return bool always true or exception
1340 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1343 if ($contextid instanceof context
) {
1344 $context = $contextid;
1346 $context = context
::instance_by_id($contextid);
1349 // Capability must exist.
1350 if (!$capinfo = get_capability_info($capability)) {
1351 throw new coding_exception("Capability '{$capability}' was not found! This has to be fixed in code.");
1354 if (empty($permission) ||
$permission == CAP_INHERIT
) { // if permission is not set
1355 unassign_capability($capability, $roleid, $context->id
);
1359 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id
, 'roleid'=>$roleid, 'capability'=>$capability));
1361 if ($existing and !$overwrite) { // We want to keep whatever is there already
1365 $cap = new stdClass();
1366 $cap->contextid
= $context->id
;
1367 $cap->roleid
= $roleid;
1368 $cap->capability
= $capability;
1369 $cap->permission
= $permission;
1370 $cap->timemodified
= time();
1371 $cap->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
1374 $cap->id
= $existing->id
;
1375 $DB->update_record('role_capabilities', $cap);
1377 if ($DB->record_exists('context', array('id'=>$context->id
))) {
1378 $DB->insert_record('role_capabilities', $cap);
1382 // Reset any cache of this role, including MUC.
1383 accesslib_clear_role_cache($roleid);
1389 * Unassign a capability from a role.
1391 * @param string $capability the name of the capability
1392 * @param int $roleid the role id
1393 * @param int|context $contextid null means all contexts
1394 * @return boolean true or exception
1396 function unassign_capability($capability, $roleid, $contextid = null) {
1399 // Capability must exist.
1400 if (!$capinfo = get_capability_info($capability)) {
1401 throw new coding_exception("Capability '{$capability}' was not found! This has to be fixed in code.");
1404 if (!empty($contextid)) {
1405 if ($contextid instanceof context
) {
1406 $context = $contextid;
1408 $context = context
::instance_by_id($contextid);
1410 // delete from context rel, if this is the last override in this context
1411 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id
));
1413 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1416 // Reset any cache of this role, including MUC.
1417 accesslib_clear_role_cache($roleid);
1423 * Get the roles that have a given capability assigned to it
1425 * This function does not resolve the actual permission of the capability.
1426 * It just checks for permissions and overrides.
1427 * Use get_roles_with_cap_in_context() if resolution is required.
1429 * @param string $capability capability name (string)
1430 * @param string $permission optional, the permission defined for this capability
1431 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1432 * @param stdClass $context null means any
1433 * @return array of role records
1435 function get_roles_with_capability($capability, $permission = null, $context = null) {
1439 $contexts = $context->get_parent_context_ids(true);
1440 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED
, 'ctx');
1441 $contextsql = "AND rc.contextid $insql";
1448 $permissionsql = " AND rc.permission = :permission";
1449 $params['permission'] = $permission;
1451 $permissionsql = '';
1456 WHERE r.id IN (SELECT rc.roleid
1457 FROM {role_capabilities} rc
1458 JOIN {capabilities} cap ON rc.capability = cap.name
1459 WHERE rc.capability = :capname
1462 $params['capname'] = $capability;
1465 return $DB->get_records_sql($sql, $params);
1469 * This function makes a role-assignment (a role for a user in a particular context)
1471 * @param int $roleid the role of the id
1472 * @param int $userid userid
1473 * @param int|context $contextid id of the context
1474 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1475 * @param int $itemid id of enrolment/auth plugin
1476 * @param string $timemodified defaults to current time
1477 * @return int new/existing id of the assignment
1479 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1482 // first of all detect if somebody is using old style parameters
1483 if ($contextid === 0 or is_numeric($component)) {
1484 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1487 // now validate all parameters
1488 if (empty($roleid)) {
1489 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1492 if (empty($userid)) {
1493 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1497 if (strpos($component, '_') === false) {
1498 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1502 if ($component !== '' and strpos($component, '_') === false) {
1503 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1507 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1508 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1511 if ($contextid instanceof context
) {
1512 $context = $contextid;
1514 $context = context
::instance_by_id($contextid, MUST_EXIST
);
1517 if (!$timemodified) {
1518 $timemodified = time();
1521 // Check for existing entry
1522 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id
, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1525 // role already assigned - this should not happen
1526 if (count($ras) > 1) {
1527 // very weird - remove all duplicates!
1528 $ra = array_shift($ras);
1529 foreach ($ras as $r) {
1530 $DB->delete_records('role_assignments', array('id'=>$r->id
));
1536 // actually there is no need to update, reset anything or trigger any event, so just return
1540 // Create a new entry
1541 $ra = new stdClass();
1542 $ra->roleid
= $roleid;
1543 $ra->contextid
= $context->id
;
1544 $ra->userid
= $userid;
1545 $ra->component
= $component;
1546 $ra->itemid
= $itemid;
1547 $ra->timemodified
= $timemodified;
1548 $ra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
1551 $ra->id
= $DB->insert_record('role_assignments', $ra);
1553 // Role assignments have changed, so mark user as dirty.
1554 mark_user_dirty($userid);
1556 core_course_category
::role_assignment_changed($roleid, $context);
1558 $event = \core\event\role_assigned
::create(array(
1559 'context' => $context,
1560 'objectid' => $ra->roleid
,
1561 'relateduserid' => $ra->userid
,
1564 'component' => $ra->component
,
1565 'itemid' => $ra->itemid
1568 $event->add_record_snapshot('role_assignments', $ra);
1575 * Removes one role assignment
1577 * @param int $roleid
1578 * @param int $userid
1579 * @param int $contextid
1580 * @param string $component
1581 * @param int $itemid
1584 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1585 // first make sure the params make sense
1586 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1587 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1591 if (strpos($component, '_') === false) {
1592 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1596 if ($component !== '' and strpos($component, '_') === false) {
1597 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1601 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1605 * Removes multiple role assignments, parameters may contain:
1606 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1608 * @param array $params role assignment parameters
1609 * @param bool $subcontexts unassign in subcontexts too
1610 * @param bool $includemanual include manual role assignments too
1613 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1614 global $USER, $CFG, $DB;
1617 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1620 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1621 foreach ($params as $key=>$value) {
1622 if (!in_array($key, $allowed)) {
1623 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1627 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1628 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1631 if ($includemanual) {
1632 if (!isset($params['component']) or $params['component'] === '') {
1633 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1638 if (empty($params['contextid'])) {
1639 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1643 $ras = $DB->get_records('role_assignments', $params);
1644 foreach($ras as $ra) {
1645 $DB->delete_records('role_assignments', array('id'=>$ra->id
));
1646 if ($context = context
::instance_by_id($ra->contextid
, IGNORE_MISSING
)) {
1647 // Role assignments have changed, so mark user as dirty.
1648 mark_user_dirty($ra->userid
);
1650 $event = \core\event\role_unassigned
::create(array(
1651 'context' => $context,
1652 'objectid' => $ra->roleid
,
1653 'relateduserid' => $ra->userid
,
1656 'component' => $ra->component
,
1657 'itemid' => $ra->itemid
1660 $event->add_record_snapshot('role_assignments', $ra);
1662 core_course_category
::role_assignment_changed($ra->roleid
, $context);
1667 // process subcontexts
1668 if ($subcontexts and $context = context
::instance_by_id($params['contextid'], IGNORE_MISSING
)) {
1669 if ($params['contextid'] instanceof context
) {
1670 $context = $params['contextid'];
1672 $context = context
::instance_by_id($params['contextid'], IGNORE_MISSING
);
1676 $contexts = $context->get_child_contexts();
1678 foreach($contexts as $context) {
1679 $mparams['contextid'] = $context->id
;
1680 $ras = $DB->get_records('role_assignments', $mparams);
1681 foreach($ras as $ra) {
1682 $DB->delete_records('role_assignments', array('id'=>$ra->id
));
1683 // Role assignments have changed, so mark user as dirty.
1684 mark_user_dirty($ra->userid
);
1686 $event = \core\event\role_unassigned
::create(
1687 array('context'=>$context, 'objectid'=>$ra->roleid
, 'relateduserid'=>$ra->userid
,
1688 'other'=>array('id'=>$ra->id
, 'component'=>$ra->component
, 'itemid'=>$ra->itemid
)));
1689 $event->add_record_snapshot('role_assignments', $ra);
1691 core_course_category
::role_assignment_changed($ra->roleid
, $context);
1697 // do this once more for all manual role assignments
1698 if ($includemanual) {
1699 $params['component'] = '';
1700 role_unassign_all($params, $subcontexts, false);
1705 * Mark a user as dirty (with timestamp) so as to force reloading of the user session.
1707 * @param int $userid
1710 function mark_user_dirty($userid) {
1711 global $CFG, $ACCESSLIB_PRIVATE;
1713 if (during_initial_install()) {
1717 // Throw exception if invalid userid is provided.
1718 if (empty($userid)) {
1719 throw new coding_exception('Invalid user parameter supplied for mark_user_dirty() function!');
1722 // Set dirty flag in database, set dirty field locally, and clear local accessdata cache.
1723 set_cache_flag('accesslib/dirtyusers', $userid, 1, time() +
$CFG->sessiontimeout
);
1724 $ACCESSLIB_PRIVATE->dirtyusers
[$userid] = 1;
1725 unset($ACCESSLIB_PRIVATE->accessdatabyuser
[$userid]);
1729 * Determines if a user is currently logged in
1735 function isloggedin() {
1738 return (!empty($USER->id
));
1742 * Determines if a user is logged in as real guest user with username 'guest'.
1746 * @param int|object $user mixed user object or id, $USER if not specified
1747 * @return bool true if user is the real guest user, false if not logged in or other user
1749 function isguestuser($user = null) {
1750 global $USER, $DB, $CFG;
1752 // make sure we have the user id cached in config table, because we are going to use it a lot
1753 if (empty($CFG->siteguest
)) {
1754 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id
))) {
1755 // guest does not exist yet, weird
1758 set_config('siteguest', $guestid);
1760 if ($user === null) {
1764 if ($user === null) {
1765 // happens when setting the $USER
1768 } else if (is_numeric($user)) {
1769 return ($CFG->siteguest
== $user);
1771 } else if (is_object($user)) {
1772 if (empty($user->id
)) {
1773 return false; // not logged in means is not be guest
1775 return ($CFG->siteguest
== $user->id
);
1779 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1784 * Does user have a (temporary or real) guest access to course?
1788 * @param context $context
1789 * @param stdClass|int $user
1792 function is_guest(context
$context, $user = null) {
1795 // first find the course context
1796 $coursecontext = $context->get_course_context();
1798 // make sure there is a real user specified
1799 if ($user === null) {
1800 $userid = isset($USER->id
) ?
$USER->id
: 0;
1802 $userid = is_object($user) ?
$user->id
: $user;
1805 if (isguestuser($userid)) {
1806 // can not inspect or be enrolled
1810 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1811 // viewing users appear out of nowhere, they are neither guests nor participants
1815 // consider only real active enrolments here
1816 if (is_enrolled($coursecontext, $user, '', true)) {
1824 * Returns true if the user has moodle/course:view capability in the course,
1825 * this is intended for admins, managers (aka small admins), inspectors, etc.
1829 * @param context $context
1830 * @param int|stdClass $user if null $USER is used
1831 * @param string $withcapability extra capability name
1834 function is_viewing(context
$context, $user = null, $withcapability = '') {
1835 // first find the course context
1836 $coursecontext = $context->get_course_context();
1838 if (isguestuser($user)) {
1843 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1844 // admins are allowed to inspect courses
1848 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1849 // site admins always have the capability, but the enrolment above blocks
1857 * Returns true if the user is able to access the course.
1859 * This function is in no way, shape, or form a substitute for require_login.
1860 * It should only be used in circumstances where it is not possible to call require_login
1861 * such as the navigation.
1863 * This function checks many of the methods of access to a course such as the view
1864 * capability, enrollments, and guest access. It also makes use of the cache
1865 * generated by require_login for guest access.
1867 * The flags within the $USER object that are used here should NEVER be used outside
1868 * of this function can_access_course and require_login. Doing so WILL break future
1871 * @param stdClass $course record
1872 * @param stdClass|int|null $user user record or id, current user if null
1873 * @param string $withcapability Check for this capability as well.
1874 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1875 * @return boolean Returns true if the user is able to access the course
1877 function can_access_course(stdClass
$course, $user = null, $withcapability = '', $onlyactive = false) {
1880 // this function originally accepted $coursecontext parameter
1881 if ($course instanceof context
) {
1882 if ($course instanceof context_course
) {
1883 debugging('deprecated context parameter, please use $course record');
1884 $coursecontext = $course;
1885 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid
));
1887 debugging('Invalid context parameter, please use $course record');
1891 $coursecontext = context_course
::instance($course->id
);
1894 if (!isset($USER->id
)) {
1895 // should never happen
1897 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER
);
1900 // make sure there is a user specified
1901 if ($user === null) {
1902 $userid = $USER->id
;
1904 $userid = is_object($user) ?
$user->id
: $user;
1908 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
1912 if ($userid == $USER->id
) {
1913 if (!empty($USER->access
['rsw'][$coursecontext->path
])) {
1914 // the fact that somebody switched role means they can access the course no matter to what role they switched
1919 if (!$course->visible
and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
1923 if (is_viewing($coursecontext, $userid)) {
1927 if ($userid != $USER->id
) {
1928 // for performance reasons we do not verify temporary guest access for other users, sorry...
1929 return is_enrolled($coursecontext, $userid, '', $onlyactive);
1932 // === from here we deal only with $USER ===
1934 $coursecontext->reload_if_dirty();
1936 if (isset($USER->enrol
['enrolled'][$course->id
])) {
1937 if ($USER->enrol
['enrolled'][$course->id
] > time()) {
1941 if (isset($USER->enrol
['tempguest'][$course->id
])) {
1942 if ($USER->enrol
['tempguest'][$course->id
] > time()) {
1947 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
1951 if (!core_course_category
::can_view_course_info($course)) {
1952 // No guest access if user does not have capability to browse courses.
1956 // if not enrolled try to gain temporary guest access
1957 $instances = $DB->get_records('enrol', array('courseid'=>$course->id
, 'status'=>ENROL_INSTANCE_ENABLED
), 'sortorder, id ASC');
1958 $enrols = enrol_get_plugins(true);
1959 foreach($instances as $instance) {
1960 if (!isset($enrols[$instance->enrol
])) {
1963 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
1964 $until = $enrols[$instance->enrol
]->try_guestaccess($instance);
1965 if ($until !== false and $until > time()) {
1966 $USER->enrol
['tempguest'][$course->id
] = $until;
1970 if (isset($USER->enrol
['tempguest'][$course->id
])) {
1971 unset($USER->enrol
['tempguest'][$course->id
]);
1972 remove_temp_course_roles($coursecontext);
1979 * Loads the capability definitions for the component (from file).
1981 * Loads the capability definitions for the component (from file). If no
1982 * capabilities are defined for the component, we simply return an empty array.
1985 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
1986 * @return array array of capabilities
1988 function load_capability_def($component) {
1989 $defpath = core_component
::get_component_directory($component).'/db/access.php';
1991 $capabilities = array();
1992 if (file_exists($defpath)) {
1994 if (!empty($
{$component.'_capabilities'})) {
1995 // BC capability array name
1996 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
1997 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
1998 $capabilities = $
{$component.'_capabilities'};
2002 return $capabilities;
2006 * Gets the capabilities that have been cached in the database for this component.
2009 * @param string $component - examples: 'moodle', 'mod_forum'
2010 * @return array array of capabilities
2012 function get_cached_capabilities($component = 'moodle') {
2014 $caps = get_all_capabilities();
2015 $componentcaps = array();
2016 foreach ($caps as $cap) {
2017 if ($cap['component'] == $component) {
2018 $componentcaps[] = (object) $cap;
2021 return $componentcaps;
2025 * Returns default capabilities for given role archetype.
2027 * @param string $archetype role archetype
2030 function get_default_capabilities($archetype) {
2038 $defaults = array();
2039 $components = array();
2040 $allcaps = get_all_capabilities();
2042 foreach ($allcaps as $cap) {
2043 if (!in_array($cap['component'], $components)) {
2044 $components[] = $cap['component'];
2045 $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
2048 foreach($alldefs as $name=>$def) {
2049 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2050 if (isset($def['archetypes'])) {
2051 if (isset($def['archetypes'][$archetype])) {
2052 $defaults[$name] = $def['archetypes'][$archetype];
2054 // 'legacy' is for backward compatibility with 1.9 access.php
2056 if (isset($def['legacy'][$archetype])) {
2057 $defaults[$name] = $def['legacy'][$archetype];
2066 * Return default roles that can be assigned, overridden or switched
2067 * by give role archetype.
2069 * @param string $type assign|override|switch|view
2070 * @param string $archetype
2071 * @return array of role ids
2073 function get_default_role_archetype_allows($type, $archetype) {
2076 if (empty($archetype)) {
2080 $roles = $DB->get_records('role');
2081 $archetypemap = array();
2082 foreach ($roles as $role) {
2083 if ($role->archetype
) {
2084 $archetypemap[$role->archetype
][$role->id
] = $role->id
;
2090 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2091 'coursecreator' => array(),
2092 'editingteacher' => array('teacher', 'student'),
2093 'teacher' => array(),
2094 'student' => array(),
2097 'frontpage' => array(),
2099 'override' => array(
2100 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2101 'coursecreator' => array(),
2102 'editingteacher' => array('teacher', 'student', 'guest'),
2103 'teacher' => array(),
2104 'student' => array(),
2107 'frontpage' => array(),
2110 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2111 'coursecreator' => array(),
2112 'editingteacher' => array('teacher', 'student', 'guest'),
2113 'teacher' => array('student', 'guest'),
2114 'student' => array(),
2117 'frontpage' => array(),
2120 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2121 'coursecreator' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2122 'editingteacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2123 'teacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2124 'student' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2127 'frontpage' => array(),
2131 if (!isset($defaults[$type][$archetype])) {
2132 debugging("Unknown type '$type'' or archetype '$archetype''");
2137 foreach ($defaults[$type][$archetype] as $at) {
2138 if (isset($archetypemap[$at])) {
2139 foreach ($archetypemap[$at] as $roleid) {
2140 $return[$roleid] = $roleid;
2149 * Reset role capabilities to default according to selected role archetype.
2150 * If no archetype selected, removes all capabilities.
2152 * This applies to capabilities that are assigned to the role (that you could
2153 * edit in the 'define roles' interface), and not to any capability overrides
2154 * in different locations.
2156 * @param int $roleid ID of role to reset capabilities for
2158 function reset_role_capabilities($roleid) {
2161 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST
);
2162 $defaultcaps = get_default_capabilities($role->archetype
);
2164 $systemcontext = context_system
::instance();
2166 $DB->delete_records('role_capabilities',
2167 array('roleid' => $roleid, 'contextid' => $systemcontext->id
));
2169 foreach($defaultcaps as $cap=>$permission) {
2170 assign_capability($cap, $permission, $roleid, $systemcontext->id
);
2173 // Reset any cache of this role, including MUC.
2174 accesslib_clear_role_cache($roleid);
2178 * Updates the capabilities table with the component capability definitions.
2179 * If no parameters are given, the function updates the core moodle
2182 * Note that the absence of the db/access.php capabilities definition file
2183 * will cause any stored capabilities for the component to be removed from
2187 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2188 * @return boolean true if success, exception in case of any problems
2190 function update_capabilities($component = 'moodle') {
2191 global $DB, $OUTPUT;
2193 $storedcaps = array();
2195 $filecaps = load_capability_def($component);
2196 foreach($filecaps as $capname=>$unused) {
2197 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2198 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2202 // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2203 // So ensure our updating is based on fresh data.
2204 cache
::make('core', 'capabilities')->delete('core_capabilities');
2206 $cachedcaps = get_cached_capabilities($component);
2208 foreach ($cachedcaps as $cachedcap) {
2209 array_push($storedcaps, $cachedcap->name
);
2210 // update risk bitmasks and context levels in existing capabilities if needed
2211 if (array_key_exists($cachedcap->name
, $filecaps)) {
2212 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name
])) {
2213 $filecaps[$cachedcap->name
]['riskbitmask'] = 0; // no risk if not specified
2215 if ($cachedcap->captype
!= $filecaps[$cachedcap->name
]['captype']) {
2216 $updatecap = new stdClass();
2217 $updatecap->id
= $cachedcap->id
;
2218 $updatecap->captype
= $filecaps[$cachedcap->name
]['captype'];
2219 $DB->update_record('capabilities', $updatecap);
2221 if ($cachedcap->riskbitmask
!= $filecaps[$cachedcap->name
]['riskbitmask']) {
2222 $updatecap = new stdClass();
2223 $updatecap->id
= $cachedcap->id
;
2224 $updatecap->riskbitmask
= $filecaps[$cachedcap->name
]['riskbitmask'];
2225 $DB->update_record('capabilities', $updatecap);
2228 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name
])) {
2229 $filecaps[$cachedcap->name
]['contextlevel'] = 0; // no context level defined
2231 if ($cachedcap->contextlevel
!= $filecaps[$cachedcap->name
]['contextlevel']) {
2232 $updatecap = new stdClass();
2233 $updatecap->id
= $cachedcap->id
;
2234 $updatecap->contextlevel
= $filecaps[$cachedcap->name
]['contextlevel'];
2235 $DB->update_record('capabilities', $updatecap);
2241 // Flush the cached again, as we have changed DB.
2242 cache
::make('core', 'capabilities')->delete('core_capabilities');
2244 // Are there new capabilities in the file definition?
2247 foreach ($filecaps as $filecap => $def) {
2249 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2250 if (!array_key_exists('riskbitmask', $def)) {
2251 $def['riskbitmask'] = 0; // no risk if not specified
2253 $newcaps[$filecap] = $def;
2256 // Add new capabilities to the stored definition.
2257 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2258 foreach ($newcaps as $capname => $capdef) {
2259 $capability = new stdClass();
2260 $capability->name
= $capname;
2261 $capability->captype
= $capdef['captype'];
2262 $capability->contextlevel
= $capdef['contextlevel'];
2263 $capability->component
= $component;
2264 $capability->riskbitmask
= $capdef['riskbitmask'];
2266 $DB->insert_record('capabilities', $capability, false);
2268 // Flush the cached, as we have changed DB.
2269 cache
::make('core', 'capabilities')->delete('core_capabilities');
2271 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2272 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2273 foreach ($rolecapabilities as $rolecapability){
2274 //assign_capability will update rather than insert if capability exists
2275 if (!assign_capability($capname, $rolecapability->permission
,
2276 $rolecapability->roleid
, $rolecapability->contextid
, true)){
2277 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2281 // we ignore archetype key if we have cloned permissions
2282 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2283 assign_legacy_capabilities($capname, $capdef['archetypes']);
2284 // 'legacy' is for backward compatibility with 1.9 access.php
2285 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2286 assign_legacy_capabilities($capname, $capdef['legacy']);
2289 // Are there any capabilities that have been removed from the file
2290 // definition that we need to delete from the stored capabilities and
2291 // role assignments?
2292 capabilities_cleanup($component, $filecaps);
2294 // reset static caches
2295 accesslib_reset_role_cache();
2297 // Flush the cached again, as we have changed DB.
2298 cache
::make('core', 'capabilities')->delete('core_capabilities');
2304 * Deletes cached capabilities that are no longer needed by the component.
2305 * Also unassigns these capabilities from any roles that have them.
2306 * NOTE: this function is called from lib/db/upgrade.php
2309 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2310 * @param array $newcapdef array of the new capability definitions that will be
2311 * compared with the cached capabilities
2312 * @return int number of deprecated capabilities that have been removed
2314 function capabilities_cleanup($component, $newcapdef = null) {
2319 if ($cachedcaps = get_cached_capabilities($component)) {
2320 foreach ($cachedcaps as $cachedcap) {
2321 if (empty($newcapdef) ||
2322 array_key_exists($cachedcap->name
, $newcapdef) === false) {
2324 // Delete from roles.
2325 if ($roles = get_roles_with_capability($cachedcap->name
)) {
2326 foreach($roles as $role) {
2327 if (!unassign_capability($cachedcap->name
, $role->id
)) {
2328 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name
, 'role'=>$role->name
));
2333 // Remove from role_capabilities for any old ones.
2334 $DB->delete_records('role_capabilities', array('capability' => $cachedcap->name
));
2336 // Remove from capabilities cache.
2337 $DB->delete_records('capabilities', array('name' => $cachedcap->name
));
2342 if ($removedcount) {
2343 cache
::make('core', 'capabilities')->delete('core_capabilities');
2345 return $removedcount;
2349 * Returns an array of all the known types of risk
2350 * The array keys can be used, for example as CSS class names, or in calls to
2351 * print_risk_icon. The values are the corresponding RISK_ constants.
2353 * @return array all the known types of risk.
2355 function get_all_risks() {
2357 'riskmanagetrust' => RISK_MANAGETRUST
,
2358 'riskconfig' => RISK_CONFIG
,
2359 'riskxss' => RISK_XSS
,
2360 'riskpersonal' => RISK_PERSONAL
,
2361 'riskspam' => RISK_SPAM
,
2362 'riskdataloss' => RISK_DATALOSS
,
2367 * Return a link to moodle docs for a given capability name
2369 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2370 * @return string the human-readable capability name as a link to Moodle Docs.
2372 function get_capability_docs_link($capability) {
2373 $url = get_docs_url('Capabilities/' . $capability->name
);
2374 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name
) . '</a>';
2378 * This function pulls out all the resolved capabilities (overrides and
2379 * defaults) of a role used in capability overrides in contexts at a given
2382 * @param int $roleid
2383 * @param context $context
2384 * @param string $cap capability, optional, defaults to ''
2385 * @return array Array of capabilities
2387 function role_context_capabilities($roleid, context
$context, $cap = '') {
2390 $contexts = $context->get_parent_context_ids(true);
2391 $contexts = '('.implode(',', $contexts).')';
2393 $params = array($roleid);
2396 $search = " AND rc.capability = ? ";
2403 FROM {role_capabilities} rc
2404 JOIN {context} c ON rc.contextid = c.id
2405 JOIN {capabilities} cap ON rc.capability = cap.name
2406 WHERE rc.contextid in $contexts
2409 ORDER BY c.contextlevel DESC, rc.capability DESC";
2411 $capabilities = array();
2413 if ($records = $DB->get_records_sql($sql, $params)) {
2414 // We are traversing via reverse order.
2415 foreach ($records as $record) {
2416 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2417 if (!isset($capabilities[$record->capability
]) ||
$record->permission
<-500) {
2418 $capabilities[$record->capability
] = $record->permission
;
2422 return $capabilities;
2426 * Constructs array with contextids as first parameter and context paths,
2427 * in both cases bottom top including self.
2430 * @param context $context
2433 function get_context_info_list(context
$context) {
2434 $contextids = explode('/', ltrim($context->path
, '/'));
2435 $contextpaths = array();
2436 $contextids2 = $contextids;
2437 while ($contextids2) {
2438 $contextpaths[] = '/' . implode('/', $contextids2);
2439 array_pop($contextids2);
2441 return array($contextids, $contextpaths);
2445 * Check if context is the front page context or a context inside it
2447 * Returns true if this context is the front page context, or a context inside it,
2450 * @param context $context a context object.
2453 function is_inside_frontpage(context
$context) {
2454 $frontpagecontext = context_course
::instance(SITEID
);
2455 return strpos($context->path
. '/', $frontpagecontext->path
. '/') === 0;
2459 * Returns capability information (cached)
2461 * @param string $capabilityname
2462 * @return stdClass or null if capability not found
2464 function get_capability_info($capabilityname) {
2465 $caps = get_all_capabilities();
2467 if (!isset($caps[$capabilityname])) {
2471 return (object) $caps[$capabilityname];
2475 * Returns all capabilitiy records, preferably from MUC and not database.
2477 * @return array All capability records indexed by capability name
2479 function get_all_capabilities() {
2481 $cache = cache
::make('core', 'capabilities');
2482 if (!$allcaps = $cache->get('core_capabilities')) {
2483 $rs = $DB->get_recordset('capabilities');
2485 foreach ($rs as $capability) {
2486 $capability->riskbitmask
= (int) $capability->riskbitmask
;
2487 $allcaps[$capability->name
] = (array) $capability;
2490 $cache->set('core_capabilities', $allcaps);
2496 * Returns the human-readable, translated version of the capability.
2497 * Basically a big switch statement.
2499 * @param string $capabilityname e.g. mod/choice:readresponses
2502 function get_capability_string($capabilityname) {
2504 // Typical capability name is 'plugintype/pluginname:capabilityname'
2505 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2507 if ($type === 'moodle') {
2508 $component = 'core_role';
2509 } else if ($type === 'quizreport') {
2511 $component = 'quiz_'.$name;
2513 $component = $type.'_'.$name;
2516 $stringname = $name.':'.$capname;
2518 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2519 return get_string($stringname, $component);
2522 $dir = core_component
::get_component_directory($component);
2523 if (!file_exists($dir)) {
2524 // plugin broken or does not exist, do not bother with printing of debug message
2525 return $capabilityname.' ???';
2528 // something is wrong in plugin, better print debug
2529 return get_string($stringname, $component);
2533 * This gets the mod/block/course/core etc strings.
2535 * @param string $component
2536 * @param int $contextlevel
2537 * @return string|bool String is success, false if failed
2539 function get_component_string($component, $contextlevel) {
2541 if ($component === 'moodle' or $component === 'core') {
2542 switch ($contextlevel) {
2543 // TODO MDL-46123: this should probably use context level names instead
2544 case CONTEXT_SYSTEM
: return get_string('coresystem');
2545 case CONTEXT_USER
: return get_string('users');
2546 case CONTEXT_COURSECAT
: return get_string('categories');
2547 case CONTEXT_COURSE
: return get_string('course');
2548 case CONTEXT_MODULE
: return get_string('activities');
2549 case CONTEXT_BLOCK
: return get_string('block');
2550 default: print_error('unknowncontext');
2554 list($type, $name) = core_component
::normalize_component($component);
2555 $dir = core_component
::get_plugin_directory($type, $name);
2556 if (!file_exists($dir)) {
2557 // plugin not installed, bad luck, there is no way to find the name
2558 return $component.' ???';
2562 // TODO MDL-46123: this is really hacky and should be improved.
2563 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2564 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2565 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2566 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2567 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2568 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2569 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2571 if (get_string_manager()->string_exists('pluginname', $component)) {
2572 return get_string('activity').': '.get_string('pluginname', $component);
2574 return get_string('activity').': '.get_string('modulename', $component);
2576 default: return get_string('pluginname', $component);
2581 * Gets the list of roles assigned to this context and up (parents)
2582 * from the aggregation of:
2583 * a) the list of roles that are visible on user profile page and participants page (profileroles setting) and;
2584 * b) if applicable, those roles that are assigned in the context.
2586 * @param context $context
2589 function get_profile_roles(context
$context) {
2591 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2592 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2593 if (has_capability('moodle/role:assign', $context)) {
2594 $rolesinscope = array_keys(get_all_roles($context));
2596 $rolesinscope = empty($CFG->profileroles
) ?
[] : array_map('trim', explode(',', $CFG->profileroles
));
2599 if (empty($rolesinscope)) {
2603 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED
, 'a');
2604 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'p');
2605 $params = array_merge($params, $cparams);
2607 if ($coursecontext = $context->get_course_context(false)) {
2608 $params['coursecontext'] = $coursecontext->id
;
2610 $params['coursecontext'] = 0;
2613 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2614 FROM {role_assignments} ra, {role} r
2615 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2616 WHERE r.id = ra.roleid
2617 AND ra.contextid $contextlist
2619 ORDER BY r.sortorder ASC";
2621 return $DB->get_records_sql($sql, $params);
2625 * Gets the list of roles assigned to this context and up (parents)
2627 * @param context $context
2628 * @param boolean $includeparents, false means without parents.
2631 function get_roles_used_in_context(context
$context, $includeparents = true) {
2634 if ($includeparents === true) {
2635 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'cl');
2637 list($contextlist, $params) = $DB->get_in_or_equal($context->id
, SQL_PARAMS_NAMED
, 'cl');
2640 if ($coursecontext = $context->get_course_context(false)) {
2641 $params['coursecontext'] = $coursecontext->id
;
2643 $params['coursecontext'] = 0;
2646 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2647 FROM {role_assignments} ra, {role} r
2648 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2649 WHERE r.id = ra.roleid
2650 AND ra.contextid $contextlist
2651 ORDER BY r.sortorder ASC";
2653 return $DB->get_records_sql($sql, $params);
2657 * This function is used to print roles column in user profile page.
2658 * It is using the CFG->profileroles to limit the list to only interesting roles.
2659 * (The permission tab has full details of user role assignments.)
2661 * @param int $userid
2662 * @param int $courseid
2665 function get_user_roles_in_course($userid, $courseid) {
2667 if ($courseid == SITEID
) {
2668 $context = context_system
::instance();
2670 $context = context_course
::instance($courseid);
2672 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2673 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2674 if (has_capability('moodle/role:assign', $context)) {
2675 $rolesinscope = array_keys(get_all_roles($context));
2677 $rolesinscope = empty($CFG->profileroles
) ?
[] : array_map('trim', explode(',', $CFG->profileroles
));
2679 if (empty($rolesinscope)) {
2683 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED
, 'a');
2684 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'p');
2685 $params = array_merge($params, $cparams);
2687 if ($coursecontext = $context->get_course_context(false)) {
2688 $params['coursecontext'] = $coursecontext->id
;
2690 $params['coursecontext'] = 0;
2693 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2694 FROM {role_assignments} ra, {role} r
2695 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2696 WHERE r.id = ra.roleid
2697 AND ra.contextid $contextlist
2699 AND ra.userid = :userid
2700 ORDER BY r.sortorder ASC";
2701 $params['userid'] = $userid;
2705 if ($roles = $DB->get_records_sql($sql, $params)) {
2706 $viewableroles = get_viewable_roles($context, $userid);
2708 $rolenames = array();
2709 foreach ($roles as $roleid => $unused) {
2710 if (isset($viewableroles[$roleid])) {
2711 $url = new moodle_url('/user/index.php', ['contextid' => $context->id
, 'roleid' => $roleid]);
2712 $rolenames[] = '<a href="' . $url . '">' . $viewableroles[$roleid] . '</a>';
2715 $rolestring = implode(',', $rolenames);
2722 * Checks if a user can assign users to a particular role in this context
2724 * @param context $context
2725 * @param int $targetroleid - the id of the role you want to assign users to
2728 function user_can_assign(context
$context, $targetroleid) {
2731 // First check to see if the user is a site administrator.
2732 if (is_siteadmin()) {
2736 // Check if user has override capability.
2737 // If not return false.
2738 if (!has_capability('moodle/role:assign', $context)) {
2741 // pull out all active roles of this user from this context(or above)
2742 if ($userroles = get_user_roles($context)) {
2743 foreach ($userroles as $userrole) {
2744 // if any in the role_allow_override table, then it's ok
2745 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid
, 'allowassign'=>$targetroleid))) {
2755 * Returns all site roles in correct sort order.
2757 * Note: this method does not localise role names or descriptions,
2758 * use role_get_names() if you need role names.
2760 * @param context $context optional context for course role name aliases
2761 * @return array of role records with optional coursealias property
2763 function get_all_roles(context
$context = null) {
2766 if (!$context or !$coursecontext = $context->get_course_context(false)) {
2767 $coursecontext = null;
2770 if ($coursecontext) {
2771 $sql = "SELECT r.*, rn.name AS coursealias
2773 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2774 ORDER BY r.sortorder ASC";
2775 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id
));
2778 return $DB->get_records('role', array(), 'sortorder ASC');
2783 * Returns roles of a specified archetype
2785 * @param string $archetype
2786 * @return array of full role records
2788 function get_archetype_roles($archetype) {
2790 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2794 * Gets all the user roles assigned in this context, or higher contexts for a list of users.
2796 * If you try using the combination $userids = [], $checkparentcontexts = true then this is likely
2797 * to cause an out-of-memory error on large Moodle sites, so this combination is deprecated and
2798 * outputs a warning, even though it is the default.
2800 * @param context $context
2801 * @param array $userids. An empty list means fetch all role assignments for the context.
2802 * @param bool $checkparentcontexts defaults to true
2803 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2806 function get_users_roles(context
$context, $userids = [], $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2809 if (!$userids && $checkparentcontexts) {
2810 debugging('Please do not call get_users_roles() with $checkparentcontexts = true ' .
2811 'and $userids array not set. This combination causes large Moodle sites ' .
2812 'with lots of site-wide role assignemnts to run out of memory.', DEBUG_DEVELOPER
);
2815 if ($checkparentcontexts) {
2816 $contextids = $context->get_parent_context_ids();
2818 $contextids = array();
2820 $contextids[] = $context->id
;
2822 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED
, 'con');
2824 // If userids was passed as an empty array, we fetch all role assignments for the course.
2825 if (empty($userids)) {
2826 $useridlist = ' IS NOT NULL ';
2829 list($useridlist, $uparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED
, 'uids');
2832 $sql = "SELECT ra.*, r.name, r.shortname, ra.userid
2833 FROM {role_assignments} ra, {role} r, {context} c
2834 WHERE ra.userid $useridlist
2835 AND ra.roleid = r.id
2836 AND ra.contextid = c.id
2837 AND ra.contextid $contextids
2840 $all = $DB->get_records_sql($sql , array_merge($params, $uparams));
2842 // Return results grouped by userid.
2844 foreach ($all as $id => $record) {
2845 if (!isset($result[$record->userid
])) {
2846 $result[$record->userid
] = [];
2848 $result[$record->userid
][$record->id
] = $record;
2851 // Make sure all requested users are included in the result, even if they had no role assignments.
2852 foreach ($userids as $id) {
2853 if (!isset($result[$id])) {
2863 * Gets all the user roles assigned in this context, or higher contexts
2864 * this is mainly used when checking if a user can assign a role, or overriding a role
2865 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2866 * allow_override tables
2868 * @param context $context
2869 * @param int $userid
2870 * @param bool $checkparentcontexts defaults to true
2871 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2874 function get_user_roles(context
$context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2877 if (empty($userid)) {
2878 if (empty($USER->id
)) {
2881 $userid = $USER->id
;
2884 if ($checkparentcontexts) {
2885 $contextids = $context->get_parent_context_ids();
2887 $contextids = array();
2889 $contextids[] = $context->id
;
2891 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM
);
2893 array_unshift($params, $userid);
2895 $sql = "SELECT ra.*, r.name, r.shortname
2896 FROM {role_assignments} ra, {role} r, {context} c
2898 AND ra.roleid = r.id
2899 AND ra.contextid = c.id
2900 AND ra.contextid $contextids
2903 return $DB->get_records_sql($sql ,$params);
2907 * Like get_user_roles, but adds in the authenticated user role, and the front
2908 * page roles, if applicable.
2910 * @param context $context the context.
2911 * @param int $userid optional. Defaults to $USER->id
2912 * @return array of objects with fields ->userid, ->contextid and ->roleid.
2914 function get_user_roles_with_special(context
$context, $userid = 0) {
2917 if (empty($userid)) {
2918 if (empty($USER->id
)) {
2921 $userid = $USER->id
;
2924 $ras = get_user_roles($context, $userid);
2926 // Add front-page role if relevant.
2927 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid
) ?
$CFG->defaultfrontpageroleid
: 0;
2928 $isfrontpage = ($context->contextlevel
== CONTEXT_COURSE
&& $context->instanceid
== SITEID
) ||
2929 is_inside_frontpage($context);
2930 if ($defaultfrontpageroleid && $isfrontpage) {
2931 $frontpagecontext = context_course
::instance(SITEID
);
2932 $ra = new stdClass();
2933 $ra->userid
= $userid;
2934 $ra->contextid
= $frontpagecontext->id
;
2935 $ra->roleid
= $defaultfrontpageroleid;
2939 // Add authenticated user role if relevant.
2940 $defaultuserroleid = isset($CFG->defaultuserroleid
) ?
$CFG->defaultuserroleid
: 0;
2941 if ($defaultuserroleid && !isguestuser($userid)) {
2942 $systemcontext = context_system
::instance();
2943 $ra = new stdClass();
2944 $ra->userid
= $userid;
2945 $ra->contextid
= $systemcontext->id
;
2946 $ra->roleid
= $defaultuserroleid;
2954 * Creates a record in the role_allow_override table
2956 * @param int $fromroleid source roleid
2957 * @param int $targetroleid target roleid
2960 function core_role_set_override_allowed($fromroleid, $targetroleid) {
2963 $record = new stdClass();
2964 $record->roleid
= $fromroleid;
2965 $record->allowoverride
= $targetroleid;
2966 $DB->insert_record('role_allow_override', $record);
2970 * Creates a record in the role_allow_assign table
2972 * @param int $fromroleid source roleid
2973 * @param int $targetroleid target roleid
2976 function core_role_set_assign_allowed($fromroleid, $targetroleid) {
2979 $record = new stdClass();
2980 $record->roleid
= $fromroleid;
2981 $record->allowassign
= $targetroleid;
2982 $DB->insert_record('role_allow_assign', $record);
2986 * Creates a record in the role_allow_switch table
2988 * @param int $fromroleid source roleid
2989 * @param int $targetroleid target roleid
2992 function core_role_set_switch_allowed($fromroleid, $targetroleid) {
2995 $record = new stdClass();
2996 $record->roleid
= $fromroleid;
2997 $record->allowswitch
= $targetroleid;
2998 $DB->insert_record('role_allow_switch', $record);
3002 * Creates a record in the role_allow_view table
3004 * @param int $fromroleid source roleid
3005 * @param int $targetroleid target roleid
3008 function core_role_set_view_allowed($fromroleid, $targetroleid) {
3011 $record = new stdClass();
3012 $record->roleid
= $fromroleid;
3013 $record->allowview
= $targetroleid;
3014 $DB->insert_record('role_allow_view', $record);
3018 * Gets a list of roles that this user can assign in this context
3020 * @param context $context the context.
3021 * @param int $rolenamedisplay the type of role name to display. One of the
3022 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3023 * @param bool $withusercounts if true, count the number of users with each role.
3024 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3025 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3026 * if $withusercounts is true, returns a list of three arrays,
3027 * $rolenames, $rolecounts, and $nameswithcounts.
3029 function get_assignable_roles(context
$context, $rolenamedisplay = ROLENAME_ALIAS
, $withusercounts = false, $user = null) {
3032 // make sure there is a real user specified
3033 if ($user === null) {
3034 $userid = isset($USER->id
) ?
$USER->id
: 0;
3036 $userid = is_object($user) ?
$user->id
: $user;
3039 if (!has_capability('moodle/role:assign', $context, $userid)) {
3040 if ($withusercounts) {
3041 return array(array(), array(), array());
3050 if ($withusercounts) {
3051 $extrafields = ', (SELECT COUNT(DISTINCT u.id)
3052 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3053 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3055 $params['conid'] = $context->id
;
3058 if (is_siteadmin($userid)) {
3059 // show all roles allowed in this context to admins
3060 $assignrestriction = "";
3062 $parents = $context->get_parent_context_ids(true);
3063 $contexts = implode(',' , $parents);
3064 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3065 FROM {role_allow_assign} raa
3066 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3067 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3068 ) ar ON ar.id = r.id";
3069 $params['userid'] = $userid;
3071 $params['contextlevel'] = $context->contextlevel
;
3073 if ($coursecontext = $context->get_course_context(false)) {
3074 $params['coursecontext'] = $coursecontext->id
;
3076 $params['coursecontext'] = 0; // no course aliases
3077 $coursecontext = null;
3079 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3082 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3083 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3084 ORDER BY r.sortorder ASC";
3085 $roles = $DB->get_records_sql($sql, $params);
3087 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3089 if (!$withusercounts) {
3093 $rolecounts = array();
3094 $nameswithcounts = array();
3095 foreach ($roles as $role) {
3096 $nameswithcounts[$role->id
] = $rolenames[$role->id
] . ' (' . $roles[$role->id
]->usercount
. ')';
3097 $rolecounts[$role->id
] = $roles[$role->id
]->usercount
;
3099 return array($rolenames, $rolecounts, $nameswithcounts);
3103 * Gets a list of roles that this user can switch to in a context
3105 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3106 * This function just process the contents of the role_allow_switch table. You also need to
3107 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3109 * @param context $context a context.
3110 * @return array an array $roleid => $rolename.
3112 function get_switchable_roles(context
$context) {
3115 // You can't switch roles without this capability.
3116 if (!has_capability('moodle/role:switchroles', $context)) {
3123 if (!is_siteadmin()) {
3124 // Admins are allowed to switch to any role with.
3125 // Others are subject to the additional constraint that the switch-to role must be allowed by
3126 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3127 $parents = $context->get_parent_context_ids(true);
3128 $contexts = implode(',' , $parents);
3130 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3131 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3132 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3133 $params['userid'] = $USER->id
;
3136 if ($coursecontext = $context->get_course_context(false)) {
3137 $params['coursecontext'] = $coursecontext->id
;
3139 $params['coursecontext'] = 0; // no course aliases
3140 $coursecontext = null;
3144 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3145 FROM (SELECT DISTINCT rc.roleid
3146 FROM {role_capabilities} rc
3150 JOIN {role} r ON r.id = idlist.roleid
3151 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3152 ORDER BY r.sortorder";
3153 $roles = $DB->get_records_sql($query, $params);
3155 return role_fix_names($roles, $context, ROLENAME_ALIAS
, true);
3159 * Gets a list of roles that this user can view in a context
3161 * @param context $context a context.
3162 * @param int $userid id of user.
3163 * @return array an array $roleid => $rolename.
3165 function get_viewable_roles(context
$context, $userid = null) {
3168 if ($userid == null) {
3169 $userid = $USER->id
;
3175 if (!is_siteadmin()) {
3176 // Admins are allowed to view any role.
3177 // Others are subject to the additional constraint that the view role must be allowed by
3178 // 'role_allow_view' for some role they have assigned in this context or any parent.
3179 $contexts = $context->get_parent_context_ids(true);
3180 list($insql, $inparams) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED
);
3182 $extrajoins = "JOIN {role_allow_view} ras ON ras.allowview = r.id
3183 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3184 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid $insql";
3186 $params +
= $inparams;
3187 $params['userid'] = $userid;
3190 if ($coursecontext = $context->get_course_context(false)) {
3191 $params['coursecontext'] = $coursecontext->id
;
3193 $params['coursecontext'] = 0; // No course aliases.
3194 $coursecontext = null;
3198 SELECT r.id, r.name, r.shortname, rn.name AS coursealias, r.sortorder
3201 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3203 GROUP BY r.id, r.name, r.shortname, rn.name, r.sortorder
3204 ORDER BY r.sortorder";
3205 $roles = $DB->get_records_sql($query, $params);
3207 return role_fix_names($roles, $context, ROLENAME_ALIAS
, true);
3211 * Gets a list of roles that this user can override in this context.
3213 * @param context $context the context.
3214 * @param int $rolenamedisplay the type of role name to display. One of the
3215 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3216 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3217 * @return array if $withcounts is false, then an array $roleid => $rolename.
3218 * if $withusercounts is true, returns a list of three arrays,
3219 * $rolenames, $rolecounts, and $nameswithcounts.
3221 function get_overridable_roles(context
$context, $rolenamedisplay = ROLENAME_ALIAS
, $withcounts = false) {
3224 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3226 return array(array(), array(), array());
3232 $parents = $context->get_parent_context_ids(true);
3233 $contexts = implode(',' , $parents);
3238 $params['userid'] = $USER->id
;
3240 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3241 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3242 $params['conid'] = $context->id
;
3245 if ($coursecontext = $context->get_course_context(false)) {
3246 $params['coursecontext'] = $coursecontext->id
;
3248 $params['coursecontext'] = 0; // no course aliases
3249 $coursecontext = null;
3252 if (is_siteadmin()) {
3253 // show all roles to admins
3254 $roles = $DB->get_records_sql("
3255 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3257 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3258 ORDER BY ro.sortorder ASC", $params);
3261 $roles = $DB->get_records_sql("
3262 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3264 JOIN (SELECT DISTINCT r.id
3266 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3267 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3268 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3269 ) inline_view ON ro.id = inline_view.id
3270 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3271 ORDER BY ro.sortorder ASC", $params);
3274 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3280 $rolecounts = array();
3281 $nameswithcounts = array();
3282 foreach ($roles as $role) {
3283 $nameswithcounts[$role->id
] = $rolenames[$role->id
] . ' (' . $roles[$role->id
]->overridecount
. ')';
3284 $rolecounts[$role->id
] = $roles[$role->id
]->overridecount
;
3286 return array($rolenames, $rolecounts, $nameswithcounts);
3290 * Create a role menu suitable for default role selection in enrol plugins.
3292 * @package core_enrol
3294 * @param context $context
3295 * @param int $addroleid current or default role - always added to list
3296 * @return array roleid=>localised role name
3298 function get_default_enrol_roles(context
$context, $addroleid = null) {
3301 $params = array('contextlevel'=>CONTEXT_COURSE
);
3303 if ($coursecontext = $context->get_course_context(false)) {
3304 $params['coursecontext'] = $coursecontext->id
;
3306 $params['coursecontext'] = 0; // no course names
3307 $coursecontext = null;
3311 $addrole = "OR r.id = :addroleid";
3312 $params['addroleid'] = $addroleid;
3317 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3319 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3320 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3321 WHERE rcl.id IS NOT NULL $addrole
3322 ORDER BY sortorder DESC";
3324 $roles = $DB->get_records_sql($sql, $params);
3326 return role_fix_names($roles, $context, ROLENAME_BOTH
, true);
3330 * Return context levels where this role is assignable.
3332 * @param integer $roleid the id of a role.
3333 * @return array list of the context levels at which this role may be assigned.
3335 function get_role_contextlevels($roleid) {
3337 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3338 'contextlevel', 'id,contextlevel');
3342 * Return roles suitable for assignment at the specified context level.
3344 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3346 * @param integer $contextlevel a contextlevel.
3347 * @return array list of role ids that are assignable at this context level.
3349 function get_roles_for_contextlevels($contextlevel) {
3351 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3356 * Returns default context levels where roles can be assigned.
3358 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3359 * from the array returned by get_role_archetypes();
3360 * @return array list of the context levels at which this type of role may be assigned by default.
3362 function get_default_contextlevels($rolearchetype) {
3363 static $defaults = array(
3364 'manager' => array(CONTEXT_SYSTEM
, CONTEXT_COURSECAT
, CONTEXT_COURSE
),
3365 'coursecreator' => array(CONTEXT_SYSTEM
, CONTEXT_COURSECAT
),
3366 'editingteacher' => array(CONTEXT_COURSE
, CONTEXT_MODULE
),
3367 'teacher' => array(CONTEXT_COURSE
, CONTEXT_MODULE
),
3368 'student' => array(CONTEXT_COURSE
, CONTEXT_MODULE
),
3371 'frontpage' => array());
3373 if (isset($defaults[$rolearchetype])) {
3374 return $defaults[$rolearchetype];
3381 * Set the context levels at which a particular role can be assigned.
3382 * Throws exceptions in case of error.
3384 * @param integer $roleid the id of a role.
3385 * @param array $contextlevels the context levels at which this role should be assignable,
3386 * duplicate levels are removed.
3389 function set_role_contextlevels($roleid, array $contextlevels) {
3391 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3392 $rcl = new stdClass();
3393 $rcl->roleid
= $roleid;
3394 $contextlevels = array_unique($contextlevels);
3395 foreach ($contextlevels as $level) {
3396 $rcl->contextlevel
= $level;
3397 $DB->insert_record('role_context_levels', $rcl, false, true);
3402 * Who has this capability in this context?
3404 * This can be a very expensive call - use sparingly and keep
3405 * the results if you are going to need them again soon.
3407 * Note if $fields is empty this function attempts to get u.*
3408 * which can get rather large - and has a serious perf impact
3411 * @param context $context
3412 * @param string|array $capability - capability name(s)
3413 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3414 * @param string $sort - the sort order. Default is lastaccess time.
3415 * @param mixed $limitfrom - number of records to skip (offset)
3416 * @param mixed $limitnum - number of records to fetch
3417 * @param string|array $groups - single group or array of groups - only return
3418 * users who are in one of these group(s).
3419 * @param string|array $exceptions - list of users to exclude, comma separated or array
3420 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3421 * @param bool $view_ignored - use get_enrolled_sql() instead
3422 * @param bool $useviewallgroups if $groups is set the return users who
3423 * have capability both $capability and moodle/site:accessallgroups
3424 * in this context, as well as users who have $capability and who are
3426 * @return array of user records
3428 function get_users_by_capability(context
$context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3429 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3432 $defaultuserroleid = isset($CFG->defaultuserroleid
) ?
$CFG->defaultuserroleid
: 0;
3433 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid
) ?
$CFG->defaultfrontpageroleid
: 0;
3435 $ctxids = trim($context->path
, '/');
3436 $ctxids = str_replace('/', ',', $ctxids);
3438 // Context is the frontpage
3439 $iscoursepage = false; // coursepage other than fp
3440 $isfrontpage = false;
3441 if ($context->contextlevel
== CONTEXT_COURSE
) {
3442 if ($context->instanceid
== SITEID
) {
3443 $isfrontpage = true;
3445 $iscoursepage = true;
3448 $isfrontpage = ($isfrontpage ||
is_inside_frontpage($context));
3450 $caps = (array)$capability;
3452 // construct list of context paths bottom-->top
3453 list($contextids, $paths) = get_context_info_list($context);
3455 // we need to find out all roles that have these capabilities either in definition or in overrides
3457 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED
, 'con');
3458 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED
, 'cap');
3460 // Check whether context locking is enabled.
3461 // Filter out any write capability if this is the case.
3462 $excludelockedcaps = '';
3463 $excludelockedcapsparams = [];
3464 if (!empty($CFG->contextlocking
) && $context->locked
) {
3465 $excludelockedcaps = 'AND (cap.captype = :capread OR cap.name = :managelockscap)';
3466 $excludelockedcapsparams['capread'] = 'read';
3467 $excludelockedcapsparams['managelockscap'] = 'moodle/site:managecontextlocks';
3470 $params = array_merge($params, $params2, $excludelockedcapsparams);
3471 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3472 FROM {role_capabilities} rc
3473 JOIN {capabilities} cap ON rc.capability = cap.name
3474 JOIN {context} ctx on rc.contextid = ctx.id
3475 WHERE rc.contextid $incontexts AND rc.capability $incaps $excludelockedcaps";
3477 $rcs = $DB->get_records_sql($sql, $params);
3478 foreach ($rcs as $rc) {
3479 $defs[$rc->capability
][$rc->path
][$rc->roleid
] = $rc->permission
;
3482 // go through the permissions bottom-->top direction to evaluate the current permission,
3483 // first one wins (prohibit is an exception that always wins)
3485 foreach ($caps as $cap) {
3486 foreach ($paths as $path) {
3487 if (empty($defs[$cap][$path])) {
3490 foreach($defs[$cap][$path] as $roleid => $perm) {
3491 if ($perm == CAP_PROHIBIT
) {
3492 $access[$cap][$roleid] = CAP_PROHIBIT
;
3495 if (!isset($access[$cap][$roleid])) {
3496 $access[$cap][$roleid] = (int)$perm;
3502 // make lists of roles that are needed and prohibited in this context
3503 $needed = array(); // one of these is enough
3504 $prohibited = array(); // must not have any of these
3505 foreach ($caps as $cap) {
3506 if (empty($access[$cap])) {
3509 foreach ($access[$cap] as $roleid => $perm) {
3510 if ($perm == CAP_PROHIBIT
) {
3511 unset($needed[$cap][$roleid]);
3512 $prohibited[$cap][$roleid] = true;
3513 } else if ($perm == CAP_ALLOW
and empty($prohibited[$cap][$roleid])) {
3514 $needed[$cap][$roleid] = true;
3517 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3518 // easy, nobody has the permission
3519 unset($needed[$cap]);
3520 unset($prohibited[$cap]);
3521 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3522 // everybody is disqualified on the frontpage
3523 unset($needed[$cap]);
3524 unset($prohibited[$cap]);
3526 if (empty($prohibited[$cap])) {
3527 unset($prohibited[$cap]);
3531 if (empty($needed)) {
3532 // there can not be anybody if no roles match this request
3536 if (empty($prohibited)) {
3537 // we can compact the needed roles
3539 foreach ($needed as $cap) {
3540 foreach ($cap as $roleid=>$unused) {
3544 $needed = array('any'=>$n);
3548 // ***** Set up default fields ******
3549 if (empty($fields)) {
3550 if ($iscoursepage) {
3551 $fields = 'u.*, ul.timeaccess AS lastaccess';
3556 if ($CFG->debugdeveloper
&& strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3557 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER
);
3561 // Set up default sort
3562 if (empty($sort)) { // default to course lastaccess or just lastaccess
3563 if ($iscoursepage) {
3564 $sort = 'ul.timeaccess';
3566 $sort = 'u.lastaccess';
3570 // Prepare query clauses
3571 $wherecond = array();
3575 // User lastaccess JOIN
3576 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3577 // user_lastaccess is not required MDL-13810
3579 if ($iscoursepage) {
3580 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3582 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3586 // We never return deleted users or guest account.
3587 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3588 $params['guestid'] = $CFG->siteguest
;
3592 $groups = (array)$groups;
3593 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED
, 'grp');
3594 $joins[] = "LEFT OUTER JOIN (SELECT DISTINCT userid
3595 FROM {groups_members}
3596 WHERE groupid $grouptest
3597 ) gm ON gm.userid = u.id";
3599 $params = array_merge($params, $grpparams);
3601 $grouptest = 'gm.userid IS NOT NULL';
3602 if ($useviewallgroups) {
3603 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3604 if (!empty($viewallgroupsusers)) {
3605 $grouptest .= ' OR u.id IN (' . implode(',', array_keys($viewallgroupsusers)) . ')';
3608 $wherecond[] = "($grouptest)";
3612 if (!empty($exceptions)) {
3613 $exceptions = (array)$exceptions;
3614 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED
, 'exc', false);
3615 $params = array_merge($params, $exparams);
3616 $wherecond[] = "u.id $exsql";
3619 // now add the needed and prohibited roles conditions as joins
3620 if (!empty($needed['any'])) {
3621 // simple case - there are no prohibits involved
3622 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3625 $joins[] = "JOIN (SELECT DISTINCT userid
3626 FROM {role_assignments}
3627 WHERE contextid IN ($ctxids)
3628 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3629 ) ra ON ra.userid = u.id";
3634 foreach ($needed as $cap=>$unused) {
3635 if (empty($prohibited[$cap])) {
3636 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3640 $unions[] = "SELECT userid
3641 FROM {role_assignments}
3642 WHERE contextid IN ($ctxids)
3643 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3646 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3647 // nobody can have this cap because it is prevented in default roles
3650 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3651 // everybody except the prohibitted - hiding does not matter
3652 $unions[] = "SELECT id AS userid
3654 WHERE id NOT IN (SELECT userid
3655 FROM {role_assignments}
3656 WHERE contextid IN ($ctxids)
3657 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3660 $unions[] = "SELECT userid
3661 FROM {role_assignments}
3662 WHERE contextid IN ($ctxids) AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3665 FROM {role_assignments}
3666 WHERE contextid IN ($ctxids)
3667 AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . ")
3674 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3676 // only prohibits found - nobody can be matched
3677 $wherecond[] = "1 = 2";
3682 // Collect WHERE conditions and needed joins
3683 $where = implode(' AND ', $wherecond);
3684 if ($where !== '') {
3685 $where = 'WHERE ' . $where;
3687 $joins = implode("\n", $joins);
3689 // Ok, let's get the users!
3690 $sql = "SELECT $fields
3696 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3700 * Re-sort a users array based on a sorting policy
3702 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3703 * based on a sorting policy. This is to support the odd practice of
3704 * sorting teachers by 'authority', where authority was "lowest id of the role
3707 * Will execute 1 database query. Only suitable for small numbers of users, as it
3708 * uses an u.id IN() clause.
3710 * Notes about the sorting criteria.
3712 * As a default, we cannot rely on role.sortorder because then
3713 * admins/coursecreators will always win. That is why the sane
3714 * rule "is locality matters most", with sortorder as 2nd
3717 * If you want role.sortorder, use the 'sortorder' policy, and
3718 * name explicitly what roles you want to cover. It's probably
3719 * a good idea to see what roles have the capabilities you want
3720 * (array_diff() them against roiles that have 'can-do-anything'
3721 * to weed out admin-ish roles. Or fetch a list of roles from
3722 * variables like $CFG->coursecontact .
3724 * @param array $users Users array, keyed on userid
3725 * @param context $context
3726 * @param array $roles ids of the roles to include, optional
3727 * @param string $sortpolicy defaults to locality, more about
3728 * @return array sorted copy of the array
3730 function sort_by_roleassignment_authority($users, context
$context, $roles = array(), $sortpolicy = 'locality') {
3733 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3734 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path
, 1)).')';
3735 if (empty($roles)) {
3738 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3741 $sql = "SELECT ra.userid
3742 FROM {role_assignments} ra
3746 ON ra.contextid=ctx.id
3751 // Default 'locality' policy -- read PHPDoc notes
3752 // about sort policies...
3753 $orderby = 'ORDER BY '
3754 .'ctx.depth DESC, ' /* locality wins */
3755 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3756 .'ra.id'; /* role assignment order tie-breaker */
3757 if ($sortpolicy === 'sortorder') {
3758 $orderby = 'ORDER BY '
3759 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3760 .'ra.id'; /* role assignment order tie-breaker */
3763 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3764 $sortedusers = array();
3767 foreach ($sortedids as $id) {
3769 if (isset($seen[$id])) {
3775 $sortedusers[$id] = $users[$id];
3777 return $sortedusers;
3781 * Gets all the users assigned this role in this context or higher
3783 * Note that moodle is based on capabilities and it is usually better
3784 * to check permissions than to check role ids as the capabilities
3785 * system is more flexible. If you really need, you can to use this
3786 * function but consider has_capability() as a possible substitute.
3788 * All $sort fields are added into $fields if not present there yet.
3790 * If $roleid is an array or is empty (all roles) you need to set $fields
3791 * (and $sort by extension) params according to it, as the first field
3792 * returned by the database should be unique (ra.id is the best candidate).
3794 * @param int $roleid (can also be an array of ints!)
3795 * @param context $context
3796 * @param bool $parent if true, get list of users assigned in higher context too
3797 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3798 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3799 * null => use default sort from users_order_by_sql.
3800 * @param bool $all true means all, false means limit to enrolled users
3801 * @param string $group defaults to ''
3802 * @param mixed $limitfrom defaults to ''
3803 * @param mixed $limitnum defaults to ''
3804 * @param string $extrawheretest defaults to ''
3805 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3808 function get_role_users($roleid, context
$context, $parent = false, $fields = '',
3809 $sort = null, $all = true, $group = '',
3810 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3813 if (empty($fields)) {
3814 $allnames = get_all_user_name_fields(true, 'u');
3815 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
3816 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3817 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3818 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3819 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3822 // Prevent wrong function uses.
3823 if ((empty($roleid) ||
is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
3824 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
3825 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
3827 if (!empty($roleid)) {
3828 // Solving partially the issue when specifying multiple roles.
3830 foreach ($roleid as $id) {
3831 // Ignoring duplicated keys keeping the first user appearance.
3832 $users = $users +
get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
3833 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
3839 $parentcontexts = '';
3841 $parentcontexts = substr($context->path
, 1); // kill leading slash
3842 $parentcontexts = str_replace('/', ',', $parentcontexts);
3843 if ($parentcontexts !== '') {
3844 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3849 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED
, 'r');
3850 $roleselect = "AND ra.roleid $rids";
3856 if ($coursecontext = $context->get_course_context(false)) {
3857 $params['coursecontext'] = $coursecontext->id
;
3859 $params['coursecontext'] = 0;
3863 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3864 $groupselect = " AND gm.groupid = :groupid ";
3865 $params['groupid'] = $group;
3871 $params['contextid'] = $context->id
;
3873 if ($extrawheretest) {
3874 $extrawheretest = ' AND ' . $extrawheretest;
3877 if ($whereorsortparams) {
3878 $params = array_merge($params, $whereorsortparams);
3882 list($sort, $sortparams) = users_order_by_sql('u');
3883 $params = array_merge($params, $sortparams);
3886 // Adding the fields from $sort that are not present in $fields.
3887 $sortarray = preg_split('/,\s*/', $sort);
3888 $fieldsarray = preg_split('/,\s*/', $fields);
3890 // Discarding aliases from the fields.
3891 $fieldnames = array();
3892 foreach ($fieldsarray as $key => $field) {
3893 list($fieldnames[$key]) = explode(' ', $field);
3896 $addedfields = array();
3897 foreach ($sortarray as $sortfield) {
3898 // Throw away any additional arguments to the sort (e.g. ASC/DESC).
3899 list($sortfield) = explode(' ', $sortfield);
3900 list($tableprefix) = explode('.', $sortfield);
3901 $fieldpresent = false;
3902 foreach ($fieldnames as $fieldname) {
3903 if ($fieldname === $sortfield ||
$fieldname === $tableprefix.'.*') {
3904 $fieldpresent = true;
3909 if (!$fieldpresent) {
3910 $fieldsarray[] = $sortfield;
3911 $addedfields[] = $sortfield;
3915 $fields = implode(', ', $fieldsarray);
3916 if (!empty($addedfields)) {
3917 $addedfields = implode(', ', $addedfields);
3918 debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
3921 if ($all === null) {
3922 // Previously null was used to indicate that parameter was not used.
3925 if (!$all and $coursecontext) {
3926 // Do not use get_enrolled_sql() here for performance reasons.
3927 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
3928 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
3929 $params['ecourseid'] = $coursecontext->instanceid
;
3934 $sql = "SELECT DISTINCT $fields, ra.roleid
3935 FROM {role_assignments} ra
3936 JOIN {user} u ON u.id = ra.userid
3937 JOIN {role} r ON ra.roleid = r.id
3939 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3941 WHERE (ra.contextid = :contextid $parentcontexts)
3945 ORDER BY $sort"; // join now so that we can just use fullname() later
3947 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3951 * Counts all the users assigned this role in this context or higher
3953 * @param int|array $roleid either int or an array of ints
3954 * @param context $context
3955 * @param bool $parent if true, get list of users assigned in higher context too
3956 * @return int Returns the result count
3958 function count_role_users($roleid, context
$context, $parent = false) {
3962 if ($contexts = $context->get_parent_context_ids()) {
3963 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3965 $parentcontexts = '';
3968 $parentcontexts = '';
3972 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM
);
3973 $roleselect = "AND r.roleid $rids";
3979 array_unshift($params, $context->id
);
3981 $sql = "SELECT COUNT(DISTINCT u.id)
3982 FROM {role_assignments} r
3983 JOIN {user} u ON u.id = r.userid
3984 WHERE (r.contextid = ? $parentcontexts)
3988 return $DB->count_records_sql($sql, $params);
3992 * This function gets the list of courses that this user has a particular capability in.
3994 * It is now reasonably efficient, but bear in mind that if there are users who have the capability
3995 * everywhere, it may return an array of all courses.
3997 * @param string $capability Capability in question
3998 * @param int $userid User ID or null for current user
3999 * @param bool $doanything True if 'doanything' is permitted (default)
4000 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4001 * otherwise use a comma-separated list of the fields you require, not including id.
4002 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
4003 * @param string $orderby If set, use a comma-separated list of fields from course
4004 * table with sql modifiers (DESC) if needed
4005 * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
4006 * @return array|bool Array of courses, if none found false is returned.
4008 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '',
4012 // Default to current user.
4014 $userid = $USER->id
;
4017 if ($doanything && is_siteadmin($userid)) {
4018 // If the user is a site admin and $doanything is enabled then there is no need to restrict
4019 // the list of courses.
4020 $contextlimitsql = '';
4021 $contextlimitparams = [];
4023 // Gets SQL to limit contexts ('x' table) to those where the user has this capability.
4024 list ($contextlimitsql, $contextlimitparams) = \core\access\get_user_capability_course_helper
::get_sql(
4025 $userid, $capability);
4026 if (!$contextlimitsql) {
4027 // If the does not have this capability in any context, return false without querying.
4031 $contextlimitsql = 'WHERE' . $contextlimitsql;
4034 // Convert fields list and ordering
4036 if ($fieldsexceptid) {
4037 $fields = array_map('trim', explode(',', $fieldsexceptid));
4038 foreach($fields as $field) {
4039 // Context fields have a different alias.
4040 if (strpos($field, 'ctx') === 0) {
4043 $realfield = 'contextlevel';
4045 case 'ctxinstance' :
4046 $realfield = 'instanceid';
4049 $realfield = substr($field, 3);
4052 $fieldlist .= ',x.' . $realfield . ' AS ' . $field;
4054 $fieldlist .= ',c.'.$field;
4059 $fields = explode(',', $orderby);
4061 foreach($fields as $field) {
4065 $orderby .= 'c.'.$field;
4067 $orderby = 'ORDER BY '.$orderby;
4071 $rs = $DB->get_recordset_sql("
4072 SELECT c.id $fieldlist
4074 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
4076 $orderby", array_merge([CONTEXT_COURSE
], $contextlimitparams));
4077 foreach ($rs as $course) {
4078 $courses[] = $course;
4085 return empty($courses) ?
false : $courses;
4089 * Switches the current user to another role for the current session and only
4090 * in the given context.
4092 * The caller *must* check
4093 * - that this op is allowed
4094 * - that the requested role can be switched to in this context (use get_switchable_roles)
4095 * - that the requested role is NOT $CFG->defaultuserroleid
4097 * To "unswitch" pass 0 as the roleid.
4099 * This function *will* modify $USER->access - beware
4101 * @param integer $roleid the role to switch to.
4102 * @param context $context the context in which to perform the switch.
4103 * @return bool success or failure.
4105 function role_switch($roleid, context
$context) {
4108 // Add the ghost RA to $USER->access as $USER->access['rsw'][$path] = $roleid.
4109 // To un-switch just unset($USER->access['rsw'][$path]).
4111 // Note: it is not possible to switch to roles that do not have course:view
4113 if (!isset($USER->access
)) {
4114 load_all_capabilities();
4117 // Add the switch RA
4119 unset($USER->access
['rsw'][$context->path
]);
4123 $USER->access
['rsw'][$context->path
] = $roleid;
4129 * Checks if the user has switched roles within the given course.
4131 * Note: You can only switch roles within the course, hence it takes a course id
4132 * rather than a context. On that note Petr volunteered to implement this across
4133 * all other contexts, all requests for this should be forwarded to him ;)
4135 * @param int $courseid The id of the course to check
4136 * @return bool True if the user has switched roles within the course.
4138 function is_role_switched($courseid) {
4140 $context = context_course
::instance($courseid, MUST_EXIST
);
4141 return (!empty($USER->access
['rsw'][$context->path
]));
4145 * Get any role that has an override on exact context
4147 * @param context $context The context to check
4148 * @return array An array of roles
4150 function get_roles_with_override_on_context(context
$context) {
4153 return $DB->get_records_sql("SELECT r.*
4154 FROM {role_capabilities} rc, {role} r
4155 WHERE rc.roleid = r.id AND rc.contextid = ?",
4156 array($context->id
));
4160 * Get all capabilities for this role on this context (overrides)
4162 * @param stdClass $role
4163 * @param context $context
4166 function get_capabilities_from_role_on_context($role, context
$context) {
4169 return $DB->get_records_sql("SELECT *
4170 FROM {role_capabilities}
4171 WHERE contextid = ? AND roleid = ?",
4172 array($context->id
, $role->id
));
4176 * Find all user assignment of users for this role, on this context
4178 * @param stdClass $role
4179 * @param context $context
4182 function get_users_from_role_on_context($role, context
$context) {
4185 return $DB->get_records_sql("SELECT *
4186 FROM {role_assignments}
4187 WHERE contextid = ? AND roleid = ?",
4188 array($context->id
, $role->id
));
4192 * Simple function returning a boolean true if user has roles
4193 * in context or parent contexts, otherwise false.
4195 * @param int $userid
4196 * @param int $roleid
4197 * @param int $contextid empty means any context
4200 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4204 if (!$context = context
::instance_by_id($contextid, IGNORE_MISSING
)) {
4207 $parents = $context->get_parent_context_ids(true);
4208 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED
, 'r');
4209 $params['userid'] = $userid;
4210 $params['roleid'] = $roleid;
4212 $sql = "SELECT COUNT(ra.id)
4213 FROM {role_assignments} ra
4214 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4216 $count = $DB->get_field_sql($sql, $params);
4217 return ($count > 0);
4220 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4225 * Get localised role name or alias if exists and format the text.
4227 * @param stdClass $role role object
4228 * - optional 'coursealias' property should be included for performance reasons if course context used
4229 * - description property is not required here
4230 * @param context|bool $context empty means system context
4231 * @param int $rolenamedisplay type of role name
4232 * @return string localised role name or course role name alias
4234 function role_get_name(stdClass
$role, $context = null, $rolenamedisplay = ROLENAME_ALIAS
) {
4237 if ($rolenamedisplay == ROLENAME_SHORT
) {
4238 return $role->shortname
;
4241 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4242 $coursecontext = null;
4245 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS
or $rolenamedisplay == ROLENAME_BOTH
or $rolenamedisplay == ROLENAME_ALIAS_RAW
)) {
4246 $role = clone($role); // Do not modify parameters.
4247 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id
, 'contextid'=>$coursecontext->id
))) {
4248 $role->coursealias
= $r->name
;
4250 $role->coursealias
= null;
4254 if ($rolenamedisplay == ROLENAME_ALIAS_RAW
) {
4255 if ($coursecontext) {
4256 return $role->coursealias
;
4262 if (trim($role->name
) !== '') {
4263 // For filtering always use context where was the thing defined - system for roles here.
4264 $original = format_string($role->name
, true, array('context'=>context_system
::instance()));
4267 // Empty role->name means we want to see localised role name based on shortname,
4268 // only default roles are supposed to be localised.
4269 switch ($role->shortname
) {
4270 case 'manager': $original = get_string('manager', 'role'); break;
4271 case 'coursecreator': $original = get_string('coursecreators'); break;
4272 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4273 case 'teacher': $original = get_string('noneditingteacher'); break;
4274 case 'student': $original = get_string('defaultcoursestudent'); break;
4275 case 'guest': $original = get_string('guest'); break;
4276 case 'user': $original = get_string('authenticateduser'); break;
4277 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4278 // We should not get here, the role UI should require the name for custom roles!
4279 default: $original = $role->shortname
; break;
4283 if ($rolenamedisplay == ROLENAME_ORIGINAL
) {
4287 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT
) {
4288 return "$original ($role->shortname)";
4291 if ($rolenamedisplay == ROLENAME_ALIAS
) {
4292 if ($coursecontext and trim($role->coursealias
) !== '') {
4293 return format_string($role->coursealias
, true, array('context'=>$coursecontext));
4299 if ($rolenamedisplay == ROLENAME_BOTH
) {
4300 if ($coursecontext and trim($role->coursealias
) !== '') {
4301 return format_string($role->coursealias
, true, array('context'=>$coursecontext)) . " ($original)";
4307 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4311 * Returns localised role description if available.
4312 * If the name is empty it tries to find the default role name using
4313 * hardcoded list of default role names or other methods in the future.
4315 * @param stdClass $role
4316 * @return string localised role name
4318 function role_get_description(stdClass
$role) {
4319 if (!html_is_blank($role->description
)) {
4320 return format_text($role->description
, FORMAT_HTML
, array('context'=>context_system
::instance()));
4323 switch ($role->shortname
) {
4324 case 'manager': return get_string('managerdescription', 'role');
4325 case 'coursecreator': return get_string('coursecreatorsdescription');
4326 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4327 case 'teacher': return get_string('noneditingteacherdescription');
4328 case 'student': return get_string('defaultcoursestudentdescription');
4329 case 'guest': return get_string('guestdescription');
4330 case 'user': return get_string('authenticateduserdescription');
4331 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4337 * Get all the localised role names for a context.
4339 * In new installs default roles have empty names, this function
4340 * add localised role names using current language pack.
4342 * @param context $context the context, null means system context
4343 * @param array of role objects with a ->localname field containing the context-specific role name.
4344 * @param int $rolenamedisplay
4345 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4346 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4348 function role_get_names(context
$context = null, $rolenamedisplay = ROLENAME_ALIAS
, $returnmenu = null) {
4349 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4353 * Prepare list of roles for display, apply aliases and localise default role names.
4355 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4356 * @param context $context the context, null means system context
4357 * @param int $rolenamedisplay
4358 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4359 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4361 function role_fix_names($roleoptions, context
$context = null, $rolenamedisplay = ROLENAME_ALIAS
, $returnmenu = null) {
4364 if (empty($roleoptions)) {
4368 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4369 $coursecontext = null;
4372 // We usually need all role columns...
4373 $first = reset($roleoptions);
4374 if ($returnmenu === null) {
4375 $returnmenu = !is_object($first);
4378 if (!is_object($first) or !property_exists($first, 'shortname')) {
4379 $allroles = get_all_roles($context);
4380 foreach ($roleoptions as $rid => $unused) {
4381 $roleoptions[$rid] = $allroles[$rid];
4385 // Inject coursealias if necessary.
4386 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW
or $rolenamedisplay == ROLENAME_ALIAS
or $rolenamedisplay == ROLENAME_BOTH
)) {
4387 $first = reset($roleoptions);
4388 if (!property_exists($first, 'coursealias')) {
4389 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id
));
4390 foreach ($aliasnames as $alias) {
4391 if (isset($roleoptions[$alias->roleid
])) {
4392 $roleoptions[$alias->roleid
]->coursealias
= $alias->name
;
4398 // Add localname property.
4399 foreach ($roleoptions as $rid => $role) {
4400 $roleoptions[$rid]->localname
= role_get_name($role, $coursecontext, $rolenamedisplay);
4404 return $roleoptions;
4408 foreach ($roleoptions as $rid => $role) {
4409 $menu[$rid] = $role->localname
;
4416 * Aids in detecting if a new line is required when reading a new capability
4418 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4419 * when we read in a new capability.
4420 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4421 * but when we are in grade, all reports/import/export capabilities should be together
4423 * @param string $cap component string a
4424 * @param string $comp component string b
4425 * @param int $contextlevel
4426 * @return bool whether 2 component are in different "sections"
4428 function component_level_changed($cap, $comp, $contextlevel) {
4430 if (strstr($cap->component
, '/') && strstr($comp, '/')) {
4431 $compsa = explode('/', $cap->component
);
4432 $compsb = explode('/', $comp);
4434 // list of system reports
4435 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4439 // we are in gradebook, still
4440 if (($compsa[0] == 'gradeexport' ||
$compsa[0] == 'gradeimport' ||
$compsa[0] == 'gradereport') &&
4441 ($compsb[0] == 'gradeexport' ||
$compsb[0] == 'gradeimport' ||
$compsb[0] == 'gradereport')) {
4445 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4450 return ($cap->component
!= $comp ||
$cap->contextlevel
!= $contextlevel);
4454 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4455 * and return an array of roleids in order.
4457 * @param array $allroles array of roles, as returned by get_all_roles();
4458 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4460 function fix_role_sortorder($allroles) {
4463 $rolesort = array();
4465 foreach ($allroles as $role) {
4466 $rolesort[$i] = $role->id
;
4467 if ($role->sortorder
!= $i) {
4468 $r = new stdClass();
4471 $DB->update_record('role', $r);
4472 $allroles[$role->id
]->sortorder
= $i;
4480 * Switch the sort order of two roles (used in admin/roles/manage.php).
4482 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4483 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4484 * @return boolean success or failure
4486 function switch_roles($first, $second) {
4488 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4489 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder
));
4490 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder
, array('sortorder' => $second->sortorder
));
4491 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder
, array('sortorder' => $temp));
4496 * Duplicates all the base definitions of a role
4498 * @param stdClass $sourcerole role to copy from
4499 * @param int $targetrole id of role to copy to
4501 function role_cap_duplicate($sourcerole, $targetrole) {
4504 $systemcontext = context_system
::instance();
4505 $caps = $DB->get_records_sql("SELECT *
4506 FROM {role_capabilities}
4507 WHERE roleid = ? AND contextid = ?",
4508 array($sourcerole->id
, $systemcontext->id
));
4509 // adding capabilities
4510 foreach ($caps as $cap) {
4512 $cap->roleid
= $targetrole;
4513 $DB->insert_record('role_capabilities', $cap);
4516 // Reset any cache of this role, including MUC.
4517 accesslib_clear_role_cache($targetrole);
4521 * Returns two lists, this can be used to find out if user has capability.
4522 * Having any needed role and no forbidden role in this context means
4523 * user has this capability in this context.
4524 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4526 * @param stdClass $context
4527 * @param string $capability
4528 * @return array($neededroles, $forbiddenroles)
4530 function get_roles_with_cap_in_context($context, $capability) {
4533 $ctxids = trim($context->path
, '/'); // kill leading slash
4534 $ctxids = str_replace('/', ',', $ctxids);
4536 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4537 FROM {role_capabilities} rc
4538 JOIN {context} ctx ON ctx.id = rc.contextid
4539 JOIN {capabilities} cap ON rc.capability = cap.name
4540 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4541 ORDER BY rc.roleid ASC, ctx.depth DESC";
4542 $params = array('cap'=>$capability);
4544 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4545 // no cap definitions --> no capability
4546 return array(array(), array());
4549 $forbidden = array();
4551 foreach($capdefs as $def) {
4552 if (isset($forbidden[$def->roleid
])) {
4555 if ($def->permission
== CAP_PROHIBIT
) {
4556 $forbidden[$def->roleid
] = $def->roleid
;
4557 unset($needed[$def->roleid
]);
4560 if (!isset($needed[$def->roleid
])) {
4561 if ($def->permission
== CAP_ALLOW
) {
4562 $needed[$def->roleid
] = true;
4563 } else if ($def->permission
== CAP_PREVENT
) {
4564 $needed[$def->roleid
] = false;
4570 // remove all those roles not allowing
4571 foreach($needed as $key=>$value) {
4573 unset($needed[$key]);
4575 $needed[$key] = $key;
4579 return array($needed, $forbidden);
4583 * Returns an array of role IDs that have ALL of the the supplied capabilities
4584 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4586 * @param stdClass $context
4587 * @param array $capabilities An array of capabilities
4588 * @return array of roles with all of the required capabilities
4590 function get_roles_with_caps_in_context($context, $capabilities) {
4591 $neededarr = array();
4592 $forbiddenarr = array();
4593 foreach($capabilities as $caprequired) {
4594 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4597 $rolesthatcanrate = array();
4598 if (!empty($neededarr)) {
4599 foreach ($neededarr as $needed) {
4600 if (empty($rolesthatcanrate)) {
4601 $rolesthatcanrate = $needed;
4603 //only want roles that have all caps
4604 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4608 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4609 foreach ($forbiddenarr as $forbidden) {
4610 //remove any roles that are forbidden any of the caps
4611 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4614 return $rolesthatcanrate;
4618 * Returns an array of role names that have ALL of the the supplied capabilities
4619 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4621 * @param stdClass $context
4622 * @param array $capabilities An array of capabilities
4623 * @return array of roles with all of the required capabilities
4625 function get_role_names_with_caps_in_context($context, $capabilities) {
4628 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4629 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4632 foreach ($rolesthatcanrate as $r) {
4633 $roles[$r] = $allroles[$r];
4636 return role_fix_names($roles, $context, ROLENAME_ALIAS
, true);
4640 * This function verifies the prohibit comes from this context
4641 * and there are no more prohibits in parent contexts.
4643 * @param int $roleid
4644 * @param context $context
4645 * @param string $capability name
4648 function prohibit_is_removable($roleid, context
$context, $capability) {
4651 $ctxids = trim($context->path
, '/'); // kill leading slash
4652 $ctxids = str_replace('/', ',', $ctxids);
4654 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT
);
4656 $sql = "SELECT ctx.id
4657 FROM {role_capabilities} rc
4658 JOIN {context} ctx ON ctx.id = rc.contextid
4659 JOIN {capabilities} cap ON rc.capability = cap.name
4660 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4661 ORDER BY ctx.depth DESC";
4663 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4664 // no prohibits == nothing to remove
4668 if (count($prohibits) > 1) {
4669 // more prohibits can not be removed
4673 return !empty($prohibits[$context->id
]);
4677 * More user friendly role permission changing,
4678 * it should produce as few overrides as possible.
4680 * @param int $roleid
4681 * @param stdClass $context
4682 * @param string $capname capability name
4683 * @param int $permission
4686 function role_change_permission($roleid, $context, $capname, $permission) {
4689 if ($permission == CAP_INHERIT
) {
4690 unassign_capability($capname, $roleid, $context->id
);
4694 $ctxids = trim($context->path
, '/'); // kill leading slash
4695 $ctxids = str_replace('/', ',', $ctxids);
4697 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4699 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4700 FROM {role_capabilities} rc
4701 JOIN {context} ctx ON ctx.id = rc.contextid
4702 JOIN {capabilities} cap ON rc.capability = cap.name
4703 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4704 ORDER BY ctx.depth DESC";
4706 if ($existing = $DB->get_records_sql($sql, $params)) {
4707 foreach($existing as $e) {
4708 if ($e->permission
== CAP_PROHIBIT
) {
4709 // prohibit can not be overridden, no point in changing anything
4713 $lowest = array_shift($existing);
4714 if ($lowest->permission
== $permission) {
4715 // permission already set in this context or parent - nothing to do
4719 $parent = array_shift($existing);
4720 if ($parent->permission
== $permission) {
4721 // permission already set in parent context or parent - just unset in this context
4722 // we do this because we want as few overrides as possible for performance reasons
4723 unassign_capability($capname, $roleid, $context->id
);
4729 if ($permission == CAP_PREVENT
) {
4730 // nothing means role does not have permission
4735 // assign the needed capability
4736 assign_capability($capname, $permission, $roleid, $context->id
, true);
4741 * Basic moodle context abstraction class.
4743 * Google confirms that no other important framework is using "context" class,
4744 * we could use something else like mcontext or moodle_context, but we need to type
4745 * this very often which would be annoying and it would take too much space...
4747 * This class is derived from stdClass for backwards compatibility with
4748 * odl $context record that was returned from DML $DB->get_record()
4750 * @package core_access
4752 * @copyright Petr Skoda {@link http://skodak.org}
4753 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4756 * @property-read int $id context id
4757 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4758 * @property-read int $instanceid id of related instance in each context
4759 * @property-read string $path path to context, starts with system context
4760 * @property-read int $depth
4762 abstract class context
extends stdClass
implements IteratorAggregate
{
4766 * Can be accessed publicly through $context->id
4773 * Can be accessed publicly through $context->contextlevel
4774 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4776 protected $_contextlevel;
4779 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4780 * Can be accessed publicly through $context->instanceid
4783 protected $_instanceid;
4786 * The path to the context always starting from the system context
4787 * Can be accessed publicly through $context->path
4793 * The depth of the context in relation to parent contexts
4794 * Can be accessed publicly through $context->depth
4800 * Whether this context is locked or not.
4802 * Can be accessed publicly through $context->locked.
4809 * @var array Context caching info
4811 private static $cache_contextsbyid = array();
4814 * @var array Context caching info
4816 private static $cache_contexts = array();
4820 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4823 protected static $cache_count = 0;
4826 * @var array Context caching info
4828 protected static $cache_preloaded = array();
4831 * @var context_system The system context once initialised
4833 protected static $systemcontext = null;
4836 * Resets the cache to remove all data.
4839 protected static function reset_caches() {
4840 self
::$cache_contextsbyid = array();
4841 self
::$cache_contexts = array();
4842 self
::$cache_count = 0;
4843 self
::$cache_preloaded = array();
4845 self
::$systemcontext = null;
4849 * Adds a context to the cache. If the cache is full, discards a batch of
4853 * @param context $context New context to add
4856 protected static function cache_add(context
$context) {
4857 if (isset(self
::$cache_contextsbyid[$context->id
])) {
4858 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4862 if (self
::$cache_count >= CONTEXT_CACHE_MAX_SIZE
) {
4864 foreach(self
::$cache_contextsbyid as $ctx) {
4867 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4870 if ($i > (CONTEXT_CACHE_MAX_SIZE
/ 3)) {
4871 // we remove oldest third of the contexts to make room for more contexts
4874 unset(self
::$cache_contextsbyid[$ctx->id
]);
4875 unset(self
::$cache_contexts[$ctx->contextlevel
][$ctx->instanceid
]);
4876 self
::$cache_count--;
4880 self
::$cache_contexts[$context->contextlevel
][$context->instanceid
] = $context;
4881 self
::$cache_contextsbyid[$context->id
] = $context;
4882 self
::$cache_count++
;
4886 * Removes a context from the cache.
4889 * @param context $context Context object to remove
4892 protected static function cache_remove(context
$context) {
4893 if (!isset(self
::$cache_contextsbyid[$context->id
])) {
4894 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4897 unset(self
::$cache_contexts[$context->contextlevel
][$context->instanceid
]);
4898 unset(self
::$cache_contextsbyid[$context->id
]);
4900 self
::$cache_count--;
4902 if (self
::$cache_count < 0) {
4903 self
::$cache_count = 0;
4908 * Gets a context from the cache.
4911 * @param int $contextlevel Context level
4912 * @param int $instance Instance ID
4913 * @return context|bool Context or false if not in cache
4915 protected static function cache_get($contextlevel, $instance) {
4916 if (isset(self
::$cache_contexts[$contextlevel][$instance])) {
4917 return self
::$cache_contexts[$contextlevel][$instance];
4923 * Gets a context from the cache based on its id.
4926 * @param int $id Context ID
4927 * @return context|bool Context or false if not in cache
4929 protected static function cache_get_by_id($id) {
4930 if (isset(self
::$cache_contextsbyid[$id])) {
4931 return self
::$cache_contextsbyid[$id];
4937 * Preloads context information from db record and strips the cached info.
4940 * @param stdClass $rec
4941 * @return void (modifies $rec)
4943 protected static function preload_from_record(stdClass
$rec) {
4944 $notenoughdata = false;
4945 $notenoughdata = $notenoughdata ||
empty($rec->ctxid
);
4946 $notenoughdata = $notenoughdata ||
empty($rec->ctxlevel
);
4947 $notenoughdata = $notenoughdata ||
!isset($rec->ctxinstance
);
4948 $notenoughdata = $notenoughdata ||
empty($rec->ctxpath
);
4949 $notenoughdata = $notenoughdata ||
empty($rec->ctxdepth
);
4950 $notenoughdata = $notenoughdata ||
!isset($rec->ctxlocked
);
4951 if ($notenoughdata) {
4952 // The record does not have enough data, passed here repeatedly or context does not exist yet.
4953 if (isset($rec->ctxid
) && !isset($rec->ctxlocked
)) {
4954 debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER
);
4959 $record = (object) [
4960 'id' => $rec->ctxid
,
4961 'contextlevel' => $rec->ctxlevel
,
4962 'instanceid' => $rec->ctxinstance
,
4963 'path' => $rec->ctxpath
,
4964 'depth' => $rec->ctxdepth
,
4965 'locked' => $rec->ctxlocked
,
4969 unset($rec->ctxlevel
);
4970 unset($rec->ctxinstance
);
4971 unset($rec->ctxpath
);
4972 unset($rec->ctxdepth
);
4973 unset($rec->ctxlocked
);
4975 return context
::create_instance_from_record($record);
4979 // ====== magic methods =======
4982 * Magic setter method, we do not want anybody to modify properties from the outside
4983 * @param string $name
4984 * @param mixed $value
4986 public function __set($name, $value) {
4987 debugging('Can not change context instance properties!');
4991 * Magic method getter, redirects to read only values.
4992 * @param string $name
4995 public function __get($name) {
4999 case 'contextlevel':
5000 return $this->_contextlevel
;
5002 return $this->_instanceid
;
5004 return $this->_path
;
5006 return $this->_depth
;
5008 return $this->is_locked();
5011 debugging('Invalid context property accessed! '.$name);
5017 * Full support for isset on our magic read only properties.
5018 * @param string $name
5021 public function __isset($name) {
5024 return isset($this->_id
);
5025 case 'contextlevel':
5026 return isset($this->_contextlevel
);
5028 return isset($this->_instanceid
);
5030 return isset($this->_path
);
5032 return isset($this->_depth
);
5034 // Locked is always set.
5042 * All properties are read only, sorry.
5043 * @param string $name
5045 public function __unset($name) {
5046 debugging('Can not unset context instance properties!');
5049 // ====== implementing method from interface IteratorAggregate ======
5052 * Create an iterator because magic vars can't be seen by 'foreach'.
5054 * Now we can convert context object to array using convert_to_array(),
5055 * and feed it properly to json_encode().
5057 public function getIterator() {
5060 'contextlevel' => $this->contextlevel
,
5061 'instanceid' => $this->instanceid
,
5062 'path' => $this->path
,
5063 'depth' => $this->depth
,
5064 'locked' => $this->locked
,
5066 return new ArrayIterator($ret);
5069 // ====== general context methods ======
5072 * Constructor is protected so that devs are forced to
5073 * use context_xxx::instance() or context::instance_by_id().
5075 * @param stdClass $record
5077 protected function __construct(stdClass
$record) {
5078 $this->_id
= (int)$record->id
;
5079 $this->_contextlevel
= (int)$record->contextlevel
;
5080 $this->_instanceid
= $record->instanceid
;
5081 $this->_path
= $record->path
;
5082 $this->_depth
= $record->depth
;
5084 if (isset($record->locked
)) {
5085 $this->_locked
= $record->locked
;
5086 } else if (!during_initial_install() && !moodle_needs_upgrading()) {
5087 debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER
);
5092 * This function is also used to work around 'protected' keyword problems in context_helper.
5094 * @param stdClass $record
5095 * @return context instance
5097 protected static function create_instance_from_record(stdClass
$record) {
5098 $classname = context_helper
::get_class_for_level($record->contextlevel
);
5100 if ($context = context
::cache_get_by_id($record->id
)) {
5104 $context = new $classname($record);
5105 context
::cache_add($context);
5111 * Copy prepared new contexts from temp table to context table,
5112 * we do this in db specific way for perf reasons only.
5115 protected static function merge_context_temp_table() {
5119 * - mysql does not allow to use FROM in UPDATE statements
5120 * - using two tables after UPDATE works in mysql, but might give unexpected
5121 * results in pg 8 (depends on configuration)
5122 * - using table alias in UPDATE does not work in pg < 8.2
5124 * Different code for each database - mostly for performance reasons
5127 $dbfamily = $DB->get_dbfamily();
5128 if ($dbfamily == 'mysql') {
5129 $updatesql = "UPDATE {context} ct, {context_temp} temp
5130 SET ct.path = temp.path,
5131 ct.depth = temp.depth,
5132 ct.locked = temp.locked
5133 WHERE ct.id = temp.id";
5134 } else if ($dbfamily == 'oracle') {
5135 $updatesql = "UPDATE {context} ct
5136 SET (ct.path, ct.depth, ct.locked) =
5137 (SELECT temp.path, temp.depth, temp.locked
5138 FROM {context_temp} temp
5139 WHERE temp.id=ct.id)
5140 WHERE EXISTS (SELECT 'x'
5141 FROM {context_temp} temp
5142 WHERE temp.id = ct.id)";
5143 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5144 $updatesql = "UPDATE {context}
5145 SET path = temp.path,
5147 locked = temp.locked
5148 FROM {context_temp} temp
5149 WHERE temp.id={context}.id";
5151 // sqlite and others
5152 $updatesql = "UPDATE {context}
5153 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5154 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id),
5155 locked = (SELECT locked FROM {context_temp} WHERE id = {context}.id)
5156 WHERE id IN (SELECT id FROM {context_temp})";
5159 $DB->execute($updatesql);
5163 * Get a context instance as an object, from a given context id.
5166 * @param int $id context id
5167 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5168 * MUST_EXIST means throw exception if no record found
5169 * @return context|bool the context object or false if not found
5171 public static function instance_by_id($id, $strictness = MUST_EXIST
) {
5174 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5175 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5176 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5179 if ($id == SYSCONTEXTID
) {
5180 return context_system
::instance(0, $strictness);
5183 if (is_array($id) or is_object($id) or empty($id)) {
5184 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5187 if ($context = context
::cache_get_by_id($id)) {
5191 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5192 return context
::create_instance_from_record($record);
5199 * Update context info after moving context in the tree structure.
5201 * @param context $newparent
5204 public function update_moved(context
$newparent) {
5207 $frompath = $this->_path
;
5208 $newpath = $newparent->path
. '/' . $this->_id
;
5210 $trans = $DB->start_delegated_transaction();
5213 if (($newparent->depth +
1) != $this->_depth
) {
5214 $diff = $newparent->depth
- $this->_depth +
1;
5215 $setdepth = ", depth = depth + $diff";
5217 $sql = "UPDATE {context}
5221 $params = array($newpath, $this->_id
);
5222 $DB->execute($sql, $params);
5224 $this->_path
= $newpath;
5225 $this->_depth
= $newparent->depth +
1;
5227 $sql = "UPDATE {context}
5228 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+
1))."
5231 $params = array($newpath, "{$frompath}/%");
5232 $DB->execute($sql, $params);
5234 $this->mark_dirty();
5236 context
::reset_caches();
5238 $trans->allow_commit();
5242 * Set whether this context has been locked or not.
5244 * @param bool $locked
5247 public function set_locked(bool $locked) {
5250 if ($this->_locked
== $locked) {
5254 $this->_locked
= $locked;
5255 $DB->set_field('context', 'locked', (int) $locked, ['id' => $this->id
]);
5256 $this->mark_dirty();
5259 $eventname = '\\core\\event\\context_locked';
5261 $eventname = '\\core\\event\\context_unlocked';
5263 $event = $eventname::create(['context' => $this, 'objectid' => $this->id
]);
5266 self
::reset_caches();
5272 * Remove all context path info and optionally rebuild it.
5274 * @param bool $rebuild
5277 public function reset_paths($rebuild = true) {
5281 $this->mark_dirty();
5283 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5284 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5285 if ($this->_contextlevel
!= CONTEXT_SYSTEM
) {
5286 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id
));
5287 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id
));
5289 $this->_path
= null;
5293 context_helper
::build_all_paths(false);
5296 context
::reset_caches();
5300 * Delete all data linked to content, do not delete the context record itself
5302 public function delete_content() {
5305 blocks_delete_all_for_context($this->_id
);
5306 filter_delete_all_for_context($this->_id
);
5308 require_once($CFG->dirroot
. '/comment/lib.php');
5309 comment
::delete_comments(array('contextid'=>$this->_id
));
5311 require_once($CFG->dirroot
.'/rating/lib.php');
5312 $delopt = new stdclass();
5313 $delopt->contextid
= $this->_id
;
5314 $rm = new rating_manager();
5315 $rm->delete_ratings($delopt);
5317 // delete all files attached to this context
5318 $fs = get_file_storage();
5319 $fs->delete_area_files($this->_id
);
5321 // Delete all repository instances attached to this context.
5322 require_once($CFG->dirroot
. '/repository/lib.php');
5323 repository
::delete_all_for_context($this->_id
);
5325 // delete all advanced grading data attached to this context
5326 require_once($CFG->dirroot
.'/grade/grading/lib.php');
5327 grading_manager
::delete_all_for_context($this->_id
);
5329 // now delete stuff from role related tables, role_unassign_all
5330 // and unenrol should be called earlier to do proper cleanup
5331 $DB->delete_records('role_assignments', array('contextid'=>$this->_id
));
5332 $DB->delete_records('role_names', array('contextid'=>$this->_id
));
5333 $this->delete_capabilities();
5337 * Unassign all capabilities from a context.
5339 public function delete_capabilities() {
5342 $ids = $DB->get_fieldset_select('role_capabilities', 'DISTINCT roleid', 'contextid = ?', array($this->_id
));
5344 $DB->delete_records('role_capabilities', array('contextid' => $this->_id
));
5346 // Reset any cache of these roles, including MUC.
5347 accesslib_clear_role_cache($ids);
5352 * Delete the context content and the context record itself
5354 public function delete() {
5357 if ($this->_contextlevel
<= CONTEXT_SYSTEM
) {
5358 throw new coding_exception('Cannot delete system context');
5361 // double check the context still exists
5362 if (!$DB->record_exists('context', array('id'=>$this->_id
))) {
5363 context
::cache_remove($this);
5367 $this->delete_content();
5368 $DB->delete_records('context', array('id'=>$this->_id
));
5369 // purge static context cache if entry present
5370 context
::cache_remove($this);
5373 // ====== context level related methods ======
5376 * Utility method for context creation
5379 * @param int $contextlevel
5380 * @param int $instanceid
5381 * @param string $parentpath
5382 * @return stdClass context record
5384 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5387 $record = new stdClass();
5388 $record->contextlevel
= $contextlevel;
5389 $record->instanceid
= $instanceid;
5391 $record->path
= null; //not known before insert
5392 $record->locked
= 0;
5394 $record->id
= $DB->insert_record('context', $record);
5396 // now add path if known - it can be added later
5397 if (!is_null($parentpath)) {
5398 $record->path
= $parentpath.'/'.$record->id
;
5399 $record->depth
= substr_count($record->path
, '/');
5400 $DB->update_record('context', $record);
5407 * Returns human readable context identifier.
5409 * @param boolean $withprefix whether to prefix the name of the context with the
5410 * type of context, e.g. User, Course, Forum, etc.
5411 * @param boolean $short whether to use the short name of the thing. Only applies
5412 * to course contexts
5413 * @return string the human readable context name.
5415 public function get_context_name($withprefix = true, $short = false) {
5416 // must be implemented in all context levels
5417 throw new coding_exception('can not get name of abstract context');
5421 * Whether the current context is locked.
5425 public function is_locked() {
5426 if ($this->_locked
) {
5430 if ($parent = $this->get_parent_context()) {
5431 return $parent->is_locked();
5438 * Returns the most relevant URL for this context.
5440 * @return moodle_url
5442 public abstract function get_url();
5445 * Returns array of relevant context capability records.
5449 public abstract function get_capabilities();
5452 * Recursive function which, given a context, find all its children context ids.
5454 * For course category contexts it will return immediate children and all subcategory contexts.
5455 * It will NOT recurse into courses or subcategories categories.
5456 * If you want to do that, call it on the returned courses/categories.
5458 * When called for a course context, it will return the modules and blocks
5459 * displayed in the course page and blocks displayed on the module pages.
5461 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5464 * @return array Array of child records
5466 public function get_child_contexts() {
5469 if (empty($this->_path
) or empty($this->_depth
)) {
5470 debugging('Can not find child contexts of context '.$this->_id
.' try rebuilding of context paths');
5474 $sql = "SELECT ctx.*
5476 WHERE ctx.path LIKE ?";
5477 $params = array($this->_path
.'/%');
5478 $records = $DB->get_records_sql($sql, $params);
5481 foreach ($records as $record) {
5482 $result[$record->id
] = context
::create_instance_from_record($record);
5489 * Returns parent contexts of this context in reversed order, i.e. parent first,
5490 * then grand parent, etc.
5492 * @param bool $includeself true means include self too
5493 * @return array of context instances
5495 public function get_parent_contexts($includeself = false) {
5496 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5500 // Preload the contexts to reduce DB calls.
5501 context_helper
::preload_contexts_by_id($contextids);
5504 foreach ($contextids as $contextid) {
5505 $parent = context
::instance_by_id($contextid, MUST_EXIST
);
5506 $result[$parent->id
] = $parent;
5513 * Returns parent context ids of this context in reversed order, i.e. parent first,
5514 * then grand parent, etc.
5516 * @param bool $includeself true means include self too
5517 * @return array of context ids
5519 public function get_parent_context_ids($includeself = false) {
5520 if (empty($this->_path
)) {
5524 $parentcontexts = trim($this->_path
, '/'); // kill leading slash
5525 $parentcontexts = explode('/', $parentcontexts);
5526 if (!$includeself) {
5527 array_pop($parentcontexts); // and remove its own id
5530 return array_reverse($parentcontexts);
5534 * Returns parent context paths of this context.
5536 * @param bool $includeself true means include self too
5537 * @return array of context paths
5539 public function get_parent_context_paths($includeself = false) {
5540 if (empty($this->_path
)) {
5544 $contextids = explode('/', $this->_path
);
5548 foreach ($contextids as $contextid) {
5550 $path .= '/' . $contextid;
5551 $paths[$contextid] = $path;
5555 if (!$includeself) {
5556 unset($paths[$this->_id
]);
5563 * Returns parent context
5567 public function get_parent_context() {
5568 if (empty($this->_path
) or $this->_id
== SYSCONTEXTID
) {
5572 $parentcontexts = trim($this->_path
, '/'); // kill leading slash
5573 $parentcontexts = explode('/', $parentcontexts);
5574 array_pop($parentcontexts); // self
5575 $contextid = array_pop($parentcontexts); // immediate parent
5577 return context
::instance_by_id($contextid, MUST_EXIST
);
5581 * Is this context part of any course? If yes return course context.
5583 * @param bool $strict true means throw exception if not found, false means return false if not found
5584 * @return context_course context of the enclosing course, null if not found or exception
5586 public function get_course_context($strict = true) {
5588 throw new coding_exception('Context does not belong to any course.');
5595 * Returns sql necessary for purging of stale context instances.
5598 * @return string cleanup SQL
5600 protected static function get_cleanup_sql() {
5601 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5605 * Rebuild context paths and depths at context level.
5608 * @param bool $force
5611 protected static function build_paths($force) {
5612 throw new coding_exception('build_paths() method must be implemented in all context levels');
5616 * Create missing context instances at given level
5621 protected static function create_level_instances() {
5622 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5626 * Reset all cached permissions and definitions if the necessary.
5629 public function reload_if_dirty() {
5630 global $ACCESSLIB_PRIVATE, $USER;
5632 // Load dirty contexts list if needed
5634 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts
)) {
5635 // we do not load dirty flags in CLI and cron
5636 $ACCESSLIB_PRIVATE->dirtycontexts
= array();
5639 if (!isset($USER->access
['time'])) {
5640 // Nothing has been loaded yet, so we do not need to check dirty flags now.
5644 // From skodak: No idea why -2 is there, server cluster time difference maybe...
5645 $changedsince = $USER->access
['time'] - 2;
5647 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts
)) {
5648 $ACCESSLIB_PRIVATE->dirtycontexts
= get_cache_flags('accesslib/dirtycontexts', $changedsince);
5651 if (!isset($ACCESSLIB_PRIVATE->dirtyusers
[$USER->id
])) {
5652 $ACCESSLIB_PRIVATE->dirtyusers
[$USER->id
] = get_cache_flag('accesslib/dirtyusers', $USER->id
, $changedsince);
5658 if (!empty($ACCESSLIB_PRIVATE->dirtyusers
[$USER->id
])) {
5660 } else if (!empty($ACCESSLIB_PRIVATE->dirtycontexts
)) {
5661 $paths = $this->get_parent_context_paths(true);
5663 foreach ($paths as $path) {
5664 if (isset($ACCESSLIB_PRIVATE->dirtycontexts
[$path])) {
5672 // Reload all capabilities of USER and others - preserving loginas, roleswitches, etc.
5673 // Then cleanup any marks of dirtyness... at least from our short term memory!
5674 reload_all_capabilities();
5679 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5681 public function mark_dirty() {
5682 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5684 if (during_initial_install()) {
5688 // only if it is a non-empty string
5689 if (is_string($this->_path
) && $this->_path
!== '') {
5690 set_cache_flag('accesslib/dirtycontexts', $this->_path
, 1, time()+
$CFG->sessiontimeout
);
5691 if (isset($ACCESSLIB_PRIVATE->dirtycontexts
)) {
5692 $ACCESSLIB_PRIVATE->dirtycontexts
[$this->_path
] = 1;
5695 $ACCESSLIB_PRIVATE->dirtycontexts
= array($this->_path
=> 1);
5697 if (isset($USER->access
['time'])) {
5698 $ACCESSLIB_PRIVATE->dirtycontexts
= get_cache_flags('accesslib/dirtycontexts', $USER->access
['time']-2);
5700 $ACCESSLIB_PRIVATE->dirtycontexts
= array($this->_path
=> 1);
5702 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5711 * Context maintenance and helper methods.
5713 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5714 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5715 * level implementation from the rest of code, the code completion returns what developers need.
5717 * Thank you Tim Hunt for helping me with this nasty trick.
5719 * @package core_access
5721 * @copyright Petr Skoda {@link http://skodak.org}
5722 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5725 class context_helper
extends context
{
5728 * @var array An array mapping context levels to classes
5730 private static $alllevels;
5733 * Instance does not make sense here, only static use
5735 protected function __construct() {
5739 * Reset internal context levels array.
5741 public static function reset_levels() {
5742 self
::$alllevels = null;
5746 * Initialise context levels, call before using self::$alllevels.
5748 private static function init_levels() {
5751 if (isset(self
::$alllevels)) {
5754 self
::$alllevels = array(
5755 CONTEXT_SYSTEM
=> 'context_system',
5756 CONTEXT_USER
=> 'context_user',
5757 CONTEXT_COURSECAT
=> 'context_coursecat',
5758 CONTEXT_COURSE
=> 'context_course',
5759 CONTEXT_MODULE
=> 'context_module',
5760 CONTEXT_BLOCK
=> 'context_block',
5763 if (empty($CFG->custom_context_classes
)) {
5767 $levels = $CFG->custom_context_classes
;
5768 if (!is_array($levels)) {
5769 $levels = @unserialize
($levels);
5771 if (!is_array($levels)) {
5772 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER
);
5776 // Unsupported custom levels, use with care!!!
5777 foreach ($levels as $level => $classname) {
5778 self
::$alllevels[$level] = $classname;
5780 ksort(self
::$alllevels);
5784 * Returns a class name of the context level class
5787 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5788 * @return string class name of the context class
5790 public static function get_class_for_level($contextlevel) {
5791 self
::init_levels();
5792 if (isset(self
::$alllevels[$contextlevel])) {
5793 return self
::$alllevels[$contextlevel];
5795 throw new coding_exception('Invalid context level specified');
5800 * Returns a list of all context levels
5803 * @return array int=>string (level=>level class name)
5805 public static function get_all_levels() {
5806 self
::init_levels();
5807 return self
::$alllevels;
5811 * Remove stale contexts that belonged to deleted instances.
5812 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5817 public static function cleanup_instances() {
5819 self
::init_levels();
5822 foreach (self
::$alllevels as $level=>$classname) {
5823 $sqls[] = $classname::get_cleanup_sql();
5826 $sql = implode(" UNION ", $sqls);
5828 // it is probably better to use transactions, it might be faster too
5829 $transaction = $DB->start_delegated_transaction();
5831 $rs = $DB->get_recordset_sql($sql);
5832 foreach ($rs as $record) {
5833 $context = context
::create_instance_from_record($record);
5838 $transaction->allow_commit();
5842 * Create all context instances at the given level and above.
5845 * @param int $contextlevel null means all levels
5846 * @param bool $buildpaths
5849 public static function create_instances($contextlevel = null, $buildpaths = true) {
5850 self
::init_levels();
5851 foreach (self
::$alllevels as $level=>$classname) {
5852 if ($contextlevel and $level > $contextlevel) {
5853 // skip potential sub-contexts
5856 $classname::create_level_instances();
5858 $classname::build_paths(false);
5864 * Rebuild paths and depths in all context levels.
5867 * @param bool $force false means add missing only
5870 public static function build_all_paths($force = false) {
5871 self
::init_levels();
5872 foreach (self
::$alllevels as $classname) {
5873 $classname::build_paths($force);
5876 // reset static course cache - it might have incorrect cached data
5877 accesslib_clear_all_caches(true);
5881 * Resets the cache to remove all data.
5884 public static function reset_caches() {
5885 context
::reset_caches();
5889 * Returns all fields necessary for context preloading from user $rec.
5891 * This helps with performance when dealing with hundreds of contexts.
5894 * @param string $tablealias context table alias in the query
5895 * @return array (table.column=>alias, ...)
5897 public static function get_preload_record_columns($tablealias) {
5899 "$tablealias.id" => "ctxid",
5900 "$tablealias.path" => "ctxpath",
5901 "$tablealias.depth" => "ctxdepth",
5902 "$tablealias.contextlevel" => "ctxlevel",
5903 "$tablealias.instanceid" => "ctxinstance",
5904 "$tablealias.locked" => "ctxlocked",
5909 * Returns all fields necessary for context preloading from user $rec.
5911 * This helps with performance when dealing with hundreds of contexts.
5914 * @param string $tablealias context table alias in the query
5917 public static function get_preload_record_columns_sql($tablealias) {
5918 return "$tablealias.id AS ctxid, " .
5919 "$tablealias.path AS ctxpath, " .
5920 "$tablealias.depth AS ctxdepth, " .
5921 "$tablealias.contextlevel AS ctxlevel, " .
5922 "$tablealias.instanceid AS ctxinstance, " .
5923 "$tablealias.locked AS ctxlocked";
5927 * Preloads context information from db record and strips the cached info.
5929 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5932 * @param stdClass $rec
5933 * @return void (modifies $rec)
5935 public static function preload_from_record(stdClass
$rec) {
5936 context
::preload_from_record($rec);
5940 * Preload a set of contexts using their contextid.
5942 * @param array $contextids
5944 public static function preload_contexts_by_id(array $contextids) {
5947 // Determine which contexts are not already cached.
5949 foreach ($contextids as $contextid) {
5950 if (!self
::cache_get_by_id($contextid)) {
5951 $tofetch[] = $contextid;
5955 if (count($tofetch) > 1) {
5956 // There are at least two to fetch.
5957 // There is no point only fetching a single context as this would be no more efficient than calling the existing code.
5958 list($insql, $inparams) = $DB->get_in_or_equal($tofetch, SQL_PARAMS_NAMED
);
5959 $ctxs = $DB->get_records_select('context', "id {$insql}", $inparams, '',
5960 \context_helper
::get_preload_record_columns_sql('{context}'));
5961 foreach ($ctxs as $ctx) {
5962 self
::preload_from_record($ctx);
5968 * Preload all contexts instances from course.
5970 * To be used if you expect multiple queries for course activities...
5973 * @param int $courseid
5975 public static function preload_course($courseid) {
5976 // Users can call this multiple times without doing any harm
5977 if (isset(context
::$cache_preloaded[$courseid])) {
5980 $coursecontext = context_course
::instance($courseid);
5981 $coursecontext->get_child_contexts();
5983 context
::$cache_preloaded[$courseid] = true;
5987 * Delete context instance
5990 * @param int $contextlevel
5991 * @param int $instanceid
5994 public static function delete_instance($contextlevel, $instanceid) {
5997 // double check the context still exists
5998 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5999 $context = context
::create_instance_from_record($record);
6002 // we should try to purge the cache anyway
6007 * Returns the name of specified context level
6010 * @param int $contextlevel
6011 * @return string name of the context level
6013 public static function get_level_name($contextlevel) {
6014 $classname = context_helper
::get_class_for_level($contextlevel);
6015 return $classname::get_level_name();
6021 public function get_url() {
6027 public function get_capabilities() {
6033 * System context class
6035 * @package core_access
6037 * @copyright Petr Skoda {@link http://skodak.org}
6038 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6041 class context_system
extends context
{
6043 * Please use context_system::instance() if you need the instance of context.
6045 * @param stdClass $record
6047 protected function __construct(stdClass
$record) {
6048 parent
::__construct($record);
6049 if ($record->contextlevel
!= CONTEXT_SYSTEM
) {
6050 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
6055 * Returns human readable context level name.
6058 * @return string the human readable context level name.
6060 public static function get_level_name() {
6061 return get_string('coresystem');
6065 * Returns human readable context identifier.
6067 * @param boolean $withprefix does not apply to system context
6068 * @param boolean $short does not apply to system context
6069 * @return string the human readable context name.
6071 public function get_context_name($withprefix = true, $short = false) {
6072 return self
::get_level_name();
6076 * Returns the most relevant URL for this context.
6078 * @return moodle_url
6080 public function get_url() {
6081 return new moodle_url('/');
6085 * Returns array of relevant context capability records.
6089 public function get_capabilities() {
6092 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6096 FROM {capabilities}";
6098 return $DB->get_records_sql($sql.' '.$sort, $params);
6102 * Create missing context instances at system context
6105 protected static function create_level_instances() {
6106 // nothing to do here, the system context is created automatically in installer
6111 * Returns system context instance.
6114 * @param int $instanceid should be 0
6115 * @param int $strictness
6116 * @param bool $cache
6117 * @return context_system context instance
6119 public static function instance($instanceid = 0, $strictness = MUST_EXIST
, $cache = true) {
6122 if ($instanceid != 0) {
6123 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
6126 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
6127 if (!isset(context
::$systemcontext)) {
6128 $record = new stdClass();
6129 $record->id
= SYSCONTEXTID
;
6130 $record->contextlevel
= CONTEXT_SYSTEM
;
6131 $record->instanceid
= 0;
6132 $record->path
= '/'.SYSCONTEXTID
;
6134 $record->locked
= 0;
6135 context
::$systemcontext = new context_system($record);
6137 return context
::$systemcontext;
6141 // We ignore the strictness completely because system context must exist except during install.
6142 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM
), '*', MUST_EXIST
);
6143 } catch (dml_exception
$e) {
6144 //table or record does not exist
6145 if (!during_initial_install()) {
6146 // do not mess with system context after install, it simply must exist
6153 $record = new stdClass();
6154 $record->contextlevel
= CONTEXT_SYSTEM
;
6155 $record->instanceid
= 0;
6157 $record->path
= null; // Not known before insert.
6158 $record->locked
= 0;
6161 if ($DB->count_records('context')) {
6162 // contexts already exist, this is very weird, system must be first!!!
6165 if (defined('SYSCONTEXTID')) {
6166 // this would happen only in unittest on sites that went through weird 1.7 upgrade
6167 $record->id
= SYSCONTEXTID
;
6168 $DB->import_record('context', $record);
6169 $DB->get_manager()->reset_sequence('context');
6171 $record->id
= $DB->insert_record('context', $record);
6173 } catch (dml_exception
$e) {
6174 // can not create context - table does not exist yet, sorry
6179 if ($record->instanceid
!= 0) {
6180 // this is very weird, somebody must be messing with context table
6181 debugging('Invalid system context detected');
6184 if ($record->depth
!= 1 or $record->path
!= '/'.$record->id
) {
6185 // fix path if necessary, initial install or path reset
6187 $record->path
= '/'.$record->id
;
6188 $DB->update_record('context', $record);
6191 if (empty($record->locked
)) {
6192 $record->locked
= 0;
6195 if (!defined('SYSCONTEXTID')) {
6196 define('SYSCONTEXTID', $record->id
);
6199 context
::$systemcontext = new context_system($record);
6200 return context
::$systemcontext;
6204 * Returns all site contexts except the system context, DO NOT call on production servers!!
6206 * Contexts are not cached.
6210 public function get_child_contexts() {
6213 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6215 // Just get all the contexts except for CONTEXT_SYSTEM level
6216 // and hope we don't OOM in the process - don't cache
6219 WHERE contextlevel > ".CONTEXT_SYSTEM
;
6220 $records = $DB->get_records_sql($sql);
6223 foreach ($records as $record) {
6224 $result[$record->id
] = context
::create_instance_from_record($record);
6231 * Returns sql necessary for purging of stale context instances.
6234 * @return string cleanup SQL
6236 protected static function get_cleanup_sql() {
6247 * Rebuild context paths and depths at system context level.
6250 * @param bool $force
6252 protected static function build_paths($force) {
6255 /* note: ignore $force here, we always do full test of system context */
6257 // exactly one record must exist
6258 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM
), '*', MUST_EXIST
);
6260 if ($record->instanceid
!= 0) {
6261 debugging('Invalid system context detected');
6264 if (defined('SYSCONTEXTID') and $record->id
!= SYSCONTEXTID
) {
6265 debugging('Invalid SYSCONTEXTID detected');
6268 if ($record->depth
!= 1 or $record->path
!= '/'.$record->id
) {
6269 // fix path if necessary, initial install or path reset
6271 $record->path
= '/'.$record->id
;
6272 $DB->update_record('context', $record);
6277 * Set whether this context has been locked or not.
6279 * @param bool $locked
6282 public function set_locked(bool $locked) {
6283 throw new \
coding_exception('It is not possible to lock the system context');
6291 * User context class
6293 * @package core_access
6295 * @copyright Petr Skoda {@link http://skodak.org}
6296 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6299 class context_user
extends context
{
6301 * Please use context_user::instance($userid) if you need the instance of context.
6302 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6304 * @param stdClass $record
6306 protected function __construct(stdClass
$record) {
6307 parent
::__construct($record);
6308 if ($record->contextlevel
!= CONTEXT_USER
) {
6309 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6314 * Returns human readable context level name.
6317 * @return string the human readable context level name.
6319 public static function get_level_name() {
6320 return get_string('user');
6324 * Returns human readable context identifier.
6326 * @param boolean $withprefix whether to prefix the name of the context with User
6327 * @param boolean $short does not apply to user context
6328 * @return string the human readable context name.
6330 public function get_context_name($withprefix = true, $short = false) {
6334 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid
, 'deleted'=>0))) {
6336 $name = get_string('user').': ';
6338 $name .= fullname($user);
6344 * Returns the most relevant URL for this context.
6346 * @return moodle_url
6348 public function get_url() {
6351 if ($COURSE->id
== SITEID
) {
6352 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid
));
6354 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid
, 'courseid'=>$COURSE->id
));
6360 * Returns array of relevant context capability records.
6364 public function get_capabilities() {
6367 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6369 $extracaps = array('moodle/grade:viewall');
6370 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED
, 'cap');
6373 WHERE contextlevel = ".CONTEXT_USER
."
6376 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6380 * Returns user context instance.
6383 * @param int $userid id from {user} table
6384 * @param int $strictness
6385 * @return context_user context instance
6387 public static function instance($userid, $strictness = MUST_EXIST
) {
6390 if ($context = context
::cache_get(CONTEXT_USER
, $userid)) {
6394 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER
, 'instanceid' => $userid))) {
6395 if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6396 $record = context
::insert_context_record(CONTEXT_USER
, $user->id
, '/'.SYSCONTEXTID
, 0);
6401 $context = new context_user($record);
6402 context
::cache_add($context);
6410 * Create missing context instances at user context level
6413 protected static function create_level_instances() {
6416 $sql = "SELECT ".CONTEXT_USER
.", u.id
6419 AND NOT EXISTS (SELECT 'x'
6421 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER
.")";
6422 $contextdata = $DB->get_recordset_sql($sql);
6423 foreach ($contextdata as $context) {
6424 context
::insert_context_record(CONTEXT_USER
, $context->id
, null);
6426 $contextdata->close();
6430 * Returns sql necessary for purging of stale context instances.
6433 * @return string cleanup SQL
6435 protected static function get_cleanup_sql() {
6439 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6440 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER
."
6447 * Rebuild context paths and depths at user context level.
6450 * @param bool $force
6452 protected static function build_paths($force) {
6455 // First update normal users.
6456 $path = $DB->sql_concat('?', 'id');
6457 $pathstart = '/' . SYSCONTEXTID
. '/';
6458 $params = array($pathstart);
6461 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6462 $params[] = $pathstart;
6464 $where = "depth = 0 OR path IS NULL";
6467 $sql = "UPDATE {context}
6470 WHERE contextlevel = " . CONTEXT_USER
. "
6472 $DB->execute($sql, $params);
6478 * Course category context class
6480 * @package core_access
6482 * @copyright Petr Skoda {@link http://skodak.org}
6483 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6486 class context_coursecat
extends context
{
6488 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6489 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6491 * @param stdClass $record
6493 protected function __construct(stdClass
$record) {
6494 parent
::__construct($record);
6495 if ($record->contextlevel
!= CONTEXT_COURSECAT
) {
6496 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6501 * Returns human readable context level name.
6504 * @return string the human readable context level name.
6506 public static function get_level_name() {
6507 return get_string('category');
6511 * Returns human readable context identifier.
6513 * @param boolean $withprefix whether to prefix the name of the context with Category
6514 * @param boolean $short does not apply to course categories
6515 * @return string the human readable context name.
6517 public function get_context_name($withprefix = true, $short = false) {
6521 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid
))) {
6523 $name = get_string('category').': ';
6525 $name .= format_string($category->name
, true, array('context' => $this));
6531 * Returns the most relevant URL for this context.
6533 * @return moodle_url
6535 public function get_url() {
6536 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid
));
6540 * Returns array of relevant context capability records.
6544 public function get_capabilities() {
6547 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6552 WHERE contextlevel IN (".CONTEXT_COURSECAT
.",".CONTEXT_COURSE
.",".CONTEXT_MODULE
.",".CONTEXT_BLOCK
.")";
6554 return $DB->get_records_sql($sql.' '.$sort, $params);
6558 * Returns course category context instance.
6561 * @param int $categoryid id from {course_categories} table
6562 * @param int $strictness
6563 * @return context_coursecat context instance
6565 public static function instance($categoryid, $strictness = MUST_EXIST
) {
6568 if ($context = context
::cache_get(CONTEXT_COURSECAT
, $categoryid)) {
6572 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT
, 'instanceid' => $categoryid))) {
6573 if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6574 if ($category->parent
) {
6575 $parentcontext = context_coursecat
::instance($category->parent
);
6576 $record = context
::insert_context_record(CONTEXT_COURSECAT
, $category->id
, $parentcontext->path
);
6578 $record = context
::insert_context_record(CONTEXT_COURSECAT
, $category->id
, '/'.SYSCONTEXTID
, 0);
6584 $context = new context_coursecat($record);
6585 context
::cache_add($context);
6593 * Returns immediate child contexts of category and all subcategories,
6594 * children of subcategories and courses are not returned.
6598 public function get_child_contexts() {
6601 if (empty($this->_path
) or empty($this->_depth
)) {
6602 debugging('Can not find child contexts of context '.$this->_id
.' try rebuilding of context paths');
6606 $sql = "SELECT ctx.*
6608 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6609 $params = array($this->_path
.'/%', $this->depth+
1, CONTEXT_COURSECAT
);
6610 $records = $DB->get_records_sql($sql, $params);
6613 foreach ($records as $record) {
6614 $result[$record->id
] = context
::create_instance_from_record($record);
6621 * Create missing context instances at course category context level
6624 protected static function create_level_instances() {
6627 $sql = "SELECT ".CONTEXT_COURSECAT
.", cc.id
6628 FROM {course_categories} cc
6629 WHERE NOT EXISTS (SELECT 'x'
6631 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT
.")";
6632 $contextdata = $DB->get_recordset_sql($sql);
6633 foreach ($contextdata as $context) {
6634 context
::insert_context_record(CONTEXT_COURSECAT
, $context->id
, null);
6636 $contextdata->close();
6640 * Returns sql necessary for purging of stale context instances.
6643 * @return string cleanup SQL
6645 protected static function get_cleanup_sql() {
6649 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6650 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT
."
6657 * Rebuild context paths and depths at course category context level.
6660 * @param bool $force
6662 protected static function build_paths($force) {
6665 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT
." AND (depth = 0 OR path IS NULL)")) {
6667 $ctxemptyclause = $emptyclause = '';
6669 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6670 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6673 $base = '/'.SYSCONTEXTID
;
6675 // Normal top level categories
6676 $sql = "UPDATE {context}
6678 path=".$DB->sql_concat("'$base/'", 'id')."
6679 WHERE contextlevel=".CONTEXT_COURSECAT
."
6680 AND EXISTS (SELECT 'x'
6681 FROM {course_categories} cc
6682 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6686 // Deeper categories - one query per depthlevel
6687 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6688 for ($n=2; $n<=$maxdepth; $n++
) {
6689 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
6690 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
6692 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT
." AND cc.depth = $n)
6693 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT
.")
6694 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6696 $trans = $DB->start_delegated_transaction();
6697 $DB->delete_records('context_temp');
6699 context
::merge_context_temp_table();
6700 $DB->delete_records('context_temp');
6701 $trans->allow_commit();
6710 * Course context class
6712 * @package core_access
6714 * @copyright Petr Skoda {@link http://skodak.org}
6715 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6718 class context_course
extends context
{
6720 * Please use context_course::instance($courseid) if you need the instance of context.
6721 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6723 * @param stdClass $record
6725 protected function __construct(stdClass
$record) {
6726 parent
::__construct($record);
6727 if ($record->contextlevel
!= CONTEXT_COURSE
) {
6728 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6733 * Returns human readable context level name.
6736 * @return string the human readable context level name.
6738 public static function get_level_name() {
6739 return get_string('course');
6743 * Returns human readable context identifier.
6745 * @param boolean $withprefix whether to prefix the name of the context with Course
6746 * @param boolean $short whether to use the short name of the thing.
6747 * @return string the human readable context name.
6749 public function get_context_name($withprefix = true, $short = false) {
6753 if ($this->_instanceid
== SITEID
) {
6754 $name = get_string('frontpage', 'admin');
6756 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid
))) {
6758 $name = get_string('course').': ';
6761 $name .= format_string($course->shortname
, true, array('context' => $this));
6763 $name .= format_string(get_course_display_name_for_list($course));
6771 * Returns the most relevant URL for this context.
6773 * @return moodle_url
6775 public function get_url() {
6776 if ($this->_instanceid
!= SITEID
) {
6777 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid
));
6780 return new moodle_url('/');
6784 * Returns array of relevant context capability records.
6788 public function get_capabilities() {
6791 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6796 WHERE contextlevel IN (".CONTEXT_COURSE
.",".CONTEXT_MODULE
.",".CONTEXT_BLOCK
.")";
6798 return $DB->get_records_sql($sql.' '.$sort, $params);
6802 * Is this context part of any course? If yes return course context.
6804 * @param bool $strict true means throw exception if not found, false means return false if not found
6805 * @return context_course context of the enclosing course, null if not found or exception
6807 public function get_course_context($strict = true) {
6812 * Returns course context instance.
6815 * @param int $courseid id from {course} table
6816 * @param int $strictness
6817 * @return context_course context instance
6819 public static function instance($courseid, $strictness = MUST_EXIST
) {
6822 if ($context = context
::cache_get(CONTEXT_COURSE
, $courseid)) {
6826 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE
, 'instanceid' => $courseid))) {
6827 if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
6828 if ($course->category
) {
6829 $parentcontext = context_coursecat
::instance($course->category
);
6830 $record = context
::insert_context_record(CONTEXT_COURSE
, $course->id
, $parentcontext->path
);
6832 $record = context
::insert_context_record(CONTEXT_COURSE
, $course->id
, '/'.SYSCONTEXTID
, 0);
6838 $context = new context_course($record);
6839 context
::cache_add($context);
6847 * Create missing context instances at course context level
6850 protected static function create_level_instances() {
6853 $sql = "SELECT ".CONTEXT_COURSE
.", c.id
6855 WHERE NOT EXISTS (SELECT 'x'
6857 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE
.")";
6858 $contextdata = $DB->get_recordset_sql($sql);
6859 foreach ($contextdata as $context) {
6860 context
::insert_context_record(CONTEXT_COURSE
, $context->id
, null);
6862 $contextdata->close();
6866 * Returns sql necessary for purging of stale context instances.
6869 * @return string cleanup SQL
6871 protected static function get_cleanup_sql() {
6875 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6876 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE
."
6883 * Rebuild context paths and depths at course context level.
6886 * @param bool $force
6888 protected static function build_paths($force) {
6891 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE
." AND (depth = 0 OR path IS NULL)")) {
6893 $ctxemptyclause = $emptyclause = '';
6895 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6896 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6899 $base = '/'.SYSCONTEXTID
;
6901 // Standard frontpage
6902 $sql = "UPDATE {context}
6904 path = ".$DB->sql_concat("'$base/'", 'id')."
6905 WHERE contextlevel = ".CONTEXT_COURSE
."
6906 AND EXISTS (SELECT 'x'
6908 WHERE c.id = {context}.instanceid AND c.category = 0)
6913 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
6914 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
6916 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE
." AND c.category <> 0)
6917 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT
.")
6918 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6920 $trans = $DB->start_delegated_transaction();
6921 $DB->delete_records('context_temp');
6923 context
::merge_context_temp_table();
6924 $DB->delete_records('context_temp');
6925 $trans->allow_commit();
6932 * Course module context class
6934 * @package core_access
6936 * @copyright Petr Skoda {@link http://skodak.org}
6937 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6940 class context_module
extends context
{
6942 * Please use context_module::instance($cmid) if you need the instance of context.
6943 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6945 * @param stdClass $record
6947 protected function __construct(stdClass
$record) {
6948 parent
::__construct($record);
6949 if ($record->contextlevel
!= CONTEXT_MODULE
) {
6950 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6955 * Returns human readable context level name.
6958 * @return string the human readable context level name.
6960 public static function get_level_name() {
6961 return get_string('activitymodule');
6965 * Returns human readable context identifier.
6967 * @param boolean $withprefix whether to prefix the name of the context with the
6968 * module name, e.g. Forum, Glossary, etc.
6969 * @param boolean $short does not apply to module context
6970 * @return string the human readable context name.
6972 public function get_context_name($withprefix = true, $short = false) {
6976 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6977 FROM {course_modules} cm
6978 JOIN {modules} md ON md.id = cm.module
6979 WHERE cm.id = ?", array($this->_instanceid
))) {
6980 if ($mod = $DB->get_record($cm->modname
, array('id' => $cm->instance
))) {
6982 $name = get_string('modulename', $cm->modname
).': ';
6984 $name .= format_string($mod->name
, true, array('context' => $this));
6991 * Returns the most relevant URL for this context.
6993 * @return moodle_url
6995 public function get_url() {
6998 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6999 FROM {course_modules} cm
7000 JOIN {modules} md ON md.id = cm.module
7001 WHERE cm.id = ?", array($this->_instanceid
))) {
7002 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid
));
7005 return new moodle_url('/');
7009 * Returns array of relevant context capability records.
7013 public function get_capabilities() {
7016 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7018 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid
));
7019 $module = $DB->get_record('modules', array('id'=>$cm->module
));
7022 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
7023 if (file_exists($subpluginsfile)) {
7024 $subplugins = array(); // should be redefined in the file
7025 include($subpluginsfile);
7026 if (!empty($subplugins)) {
7027 foreach (array_keys($subplugins) as $subplugintype) {
7028 foreach (array_keys(core_component
::get_plugin_list($subplugintype)) as $subpluginname) {
7029 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
7035 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
7036 $extracaps = array();
7037 if (file_exists($modfile)) {
7038 include_once($modfile);
7039 $modfunction = $module->name
.'_get_extra_capabilities';
7040 if (function_exists($modfunction)) {
7041 $extracaps = $modfunction();
7045 $extracaps = array_merge($subcaps, $extracaps);
7047 list($extra, $params) = $DB->get_in_or_equal(
7048 $extracaps, SQL_PARAMS_NAMED
, 'cap0', true, '');
7049 if (!empty($extra)) {
7050 $extra = "OR name $extra";
7053 // Fetch the list of modules, and remove this one.
7054 $components = \core_component
::get_component_list();
7055 $componentnames = $components['mod'];
7056 unset($componentnames["mod_{$module->name}"]);
7057 $componentnames = array_keys($componentnames);
7059 // Exclude all other modules.
7060 list($notcompsql, $notcompparams) = $DB->get_in_or_equal($componentnames, SQL_PARAMS_NAMED
, 'notcomp', false);
7061 $params = array_merge($params, $notcompparams);
7064 // Exclude other component submodules.
7066 $ignorecomponents = [];
7067 foreach ($componentnames as $mod) {
7068 if ($subplugins = \core_component
::get_subplugins($mod)) {
7069 foreach (array_keys($subplugins) as $subplugintype) {
7070 $paramname = "notlike{$i}";
7071 $ignorecomponents[] = $DB->sql_like('component', ":{$paramname}", true, true, true);
7072 $params[$paramname] = "{$subplugintype}_%";
7077 $notlikesql = "(" . implode(' AND ', $ignorecomponents) . ")";
7081 WHERE (contextlevel = ".CONTEXT_MODULE
."
7082 AND component {$notcompsql}
7086 return $DB->get_records_sql($sql.' '.$sort, $params);
7090 * Is this context part of any course? If yes return course context.
7092 * @param bool $strict true means throw exception if not found, false means return false if not found
7093 * @return context_course context of the enclosing course, null if not found or exception
7095 public function get_course_context($strict = true) {
7096 return $this->get_parent_context();
7100 * Returns module context instance.
7103 * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
7104 * @param int $strictness
7105 * @return context_module context instance
7107 public static function instance($cmid, $strictness = MUST_EXIST
) {
7110 if ($context = context
::cache_get(CONTEXT_MODULE
, $cmid)) {
7114 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE
, 'instanceid' => $cmid))) {
7115 if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
7116 $parentcontext = context_course
::instance($cm->course
);
7117 $record = context
::insert_context_record(CONTEXT_MODULE
, $cm->id
, $parentcontext->path
);
7122 $context = new context_module($record);
7123 context
::cache_add($context);
7131 * Create missing context instances at module context level
7134 protected static function create_level_instances() {
7137 $sql = "SELECT ".CONTEXT_MODULE
.", cm.id
7138 FROM {course_modules} cm
7139 WHERE NOT EXISTS (SELECT 'x'
7141 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE
.")";
7142 $contextdata = $DB->get_recordset_sql($sql);
7143 foreach ($contextdata as $context) {
7144 context
::insert_context_record(CONTEXT_MODULE
, $context->id
, null);
7146 $contextdata->close();
7150 * Returns sql necessary for purging of stale context instances.
7153 * @return string cleanup SQL
7155 protected static function get_cleanup_sql() {
7159 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
7160 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE
."
7167 * Rebuild context paths and depths at module context level.
7170 * @param bool $force
7172 protected static function build_paths($force) {
7175 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE
." AND (depth = 0 OR path IS NULL)")) {
7177 $ctxemptyclause = '';
7179 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7182 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7183 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7185 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE
.")
7186 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE
.")
7187 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7189 $trans = $DB->start_delegated_transaction();
7190 $DB->delete_records('context_temp');
7192 context
::merge_context_temp_table();
7193 $DB->delete_records('context_temp');
7194 $trans->allow_commit();
7201 * Block context class
7203 * @package core_access
7205 * @copyright Petr Skoda {@link http://skodak.org}
7206 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7209 class context_block
extends context
{
7211 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
7212 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7214 * @param stdClass $record
7216 protected function __construct(stdClass
$record) {
7217 parent
::__construct($record);
7218 if ($record->contextlevel
!= CONTEXT_BLOCK
) {
7219 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
7224 * Returns human readable context level name.
7227 * @return string the human readable context level name.
7229 public static function get_level_name() {
7230 return get_string('block');
7234 * Returns human readable context identifier.
7236 * @param boolean $withprefix whether to prefix the name of the context with Block
7237 * @param boolean $short does not apply to block context
7238 * @return string the human readable context name.
7240 public function get_context_name($withprefix = true, $short = false) {
7244 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid
))) {
7246 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7247 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7248 $blockname = "block_$blockinstance->blockname";
7249 if ($blockobject = new $blockname()) {
7251 $name = get_string('block').': ';
7253 $name .= $blockobject->title
;
7261 * Returns the most relevant URL for this context.
7263 * @return moodle_url
7265 public function get_url() {
7266 $parentcontexts = $this->get_parent_context();
7267 return $parentcontexts->get_url();
7271 * Returns array of relevant context capability records.
7275 public function get_capabilities() {
7278 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7281 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid
));
7284 $extracaps = block_method_result($bi->blockname
, 'get_extra_capabilities');
7286 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED
, 'cap');
7287 $extra = "OR name $extra";
7292 WHERE (contextlevel = ".CONTEXT_BLOCK
."
7293 AND component = :component)
7295 $params['component'] = 'block_' . $bi->blockname
;
7297 return $DB->get_records_sql($sql.' '.$sort, $params);
7301 * Is this context part of any course? If yes return course context.
7303 * @param bool $strict true means throw exception if not found, false means return false if not found
7304 * @return context_course context of the enclosing course, null if not found or exception
7306 public function get_course_context($strict = true) {
7307 $parentcontext = $this->get_parent_context();
7308 return $parentcontext->get_course_context($strict);
7312 * Returns block context instance.
7315 * @param int $blockinstanceid id from {block_instances} table.
7316 * @param int $strictness
7317 * @return context_block context instance
7319 public static function instance($blockinstanceid, $strictness = MUST_EXIST
) {
7322 if ($context = context
::cache_get(CONTEXT_BLOCK
, $blockinstanceid)) {
7326 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK
, 'instanceid' => $blockinstanceid))) {
7327 if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
7328 $parentcontext = context
::instance_by_id($bi->parentcontextid
);
7329 $record = context
::insert_context_record(CONTEXT_BLOCK
, $bi->id
, $parentcontext->path
);
7334 $context = new context_block($record);
7335 context
::cache_add($context);
7343 * Block do not have child contexts...
7346 public function get_child_contexts() {
7351 * Create missing context instances at block context level
7354 protected static function create_level_instances() {
7357 $sql = "SELECT ".CONTEXT_BLOCK
.", bi.id
7358 FROM {block_instances} bi
7359 WHERE NOT EXISTS (SELECT 'x'
7361 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK
.")";
7362 $contextdata = $DB->get_recordset_sql($sql);
7363 foreach ($contextdata as $context) {
7364 context
::insert_context_record(CONTEXT_BLOCK
, $context->id
, null);
7366 $contextdata->close();
7370 * Returns sql necessary for purging of stale context instances.
7373 * @return string cleanup SQL
7375 protected static function get_cleanup_sql() {
7379 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7380 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK
."
7387 * Rebuild context paths and depths at block context level.
7390 * @param bool $force
7392 protected static function build_paths($force) {
7395 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK
." AND (depth = 0 OR path IS NULL)")) {
7397 $ctxemptyclause = '';
7399 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7402 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7403 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7404 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7406 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK
.")
7407 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7408 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7410 $trans = $DB->start_delegated_transaction();
7411 $DB->delete_records('context_temp');
7413 context
::merge_context_temp_table();
7414 $DB->delete_records('context_temp');
7415 $trans->allow_commit();
7421 // ============== DEPRECATED FUNCTIONS ==========================================
7422 // Old context related functions were deprecated in 2.0, it is recommended
7423 // to use context classes in new code. Old function can be used when
7424 // creating patches that are supposed to be backported to older stable branches.
7425 // These deprecated functions will not be removed in near future,
7426 // before removing devs will be warned with a debugging message first,
7427 // then we will add error message and only after that we can remove the functions
7431 * Runs get_records select on context table and returns the result
7432 * Does get_records_select on the context table, and returns the results ordered
7433 * by contextlevel, and then the natural sort order within each level.
7434 * for the purpose of $select, you need to know that the context table has been
7435 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7437 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7438 * @param array $params any parameters required by $select.
7439 * @return array the requested context records.
7441 function get_sorted_contexts($select, $params = array()) {
7443 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7447 $select = 'WHERE ' . $select;
7449 return $DB->get_records_sql("
7452 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER
. " AND u.id = ctx.instanceid
7453 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT
. " AND cat.id = ctx.instanceid
7454 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE
. " AND c.id = ctx.instanceid
7455 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE
. " AND cm.id = ctx.instanceid
7456 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK
. " AND bi.id = ctx.instanceid
7458 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7463 * Given context and array of users, returns array of users whose enrolment status is suspended,
7464 * or enrolment has expired or has not started. Also removes those users from the given array
7466 * @param context $context context in which suspended users should be extracted.
7467 * @param array $users list of users.
7468 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7469 * @return array list of suspended users.
7471 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7474 // Get active enrolled users.
7475 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7476 $activeusers = $DB->get_records_sql($sql, $params);
7478 // Move suspended users to a separate array & remove from the initial one.
7480 if (sizeof($activeusers)) {
7481 foreach ($users as $userid => $user) {
7482 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7483 $susers[$userid] = $user;
7484 unset($users[$userid]);
7492 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7493 * or enrolment has expired or not started.
7495 * @param context $context context in which user enrolment is checked.
7496 * @param bool $usecache Enable or disable (default) the request cache
7497 * @return array list of suspended user id's.
7499 function get_suspended_userids(context
$context, $usecache = false) {
7503 $cache = cache
::make('core', 'suspended_userids');
7504 $susers = $cache->get($context->id
);
7505 if ($susers !== false) {
7510 $coursecontext = $context->get_course_context();
7513 // Front page users are always enrolled, so suspended list is empty.
7514 if ($coursecontext->instanceid
!= SITEID
) {
7515 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7516 $susers = $DB->get_fieldset_sql($sql, $params);
7517 $susers = array_combine($susers, $susers);
7520 // Cache results for the remainder of this request.
7522 $cache->set($context->id
, $susers);
7529 * Gets sql for finding users with capability in the given context
7531 * @param context $context
7532 * @param string|array $capability Capability name or array of names.
7533 * If an array is provided then this is the equivalent of a logical 'OR',
7534 * i.e. the user needs to have one of these capabilities.
7535 * @return array($sql, $params)
7537 function get_with_capability_sql(context
$context, $capability) {
7540 $prefix = 'cu' . $i . '_';
7542 $capjoin = get_with_capability_join($context, $capability, $prefix . 'u.id');
7544 $sql = "SELECT DISTINCT {$prefix}u.id
7545 FROM {user} {$prefix}u
7547 WHERE {$prefix}u.deleted = 0 AND $capjoin->wheres";
7549 return array($sql, $capjoin->params
);
7553 * Gets sql joins for finding users with capability in the given context
7555 * @param context $context Context for the join
7556 * @param string|array $capability Capability name or array of names.
7557 * If an array is provided then this is the equivalent of a logical 'OR',
7558 * i.e. the user needs to have one of these capabilities.
7559 * @param string $useridcolumn e.g. 'u.id'
7560 * @return \core\dml\sql_join Contains joins, wheres, params
7562 function get_with_capability_join(context
$context, $capability, $useridcolumn) {
7565 // Use unique prefix just in case somebody makes some SQL magic with the result.
7568 $prefix = 'eu' . $i . '_';
7570 // First find the course context.
7571 $coursecontext = $context->get_course_context();
7573 $isfrontpage = ($coursecontext->instanceid
== SITEID
);
7579 list($contextids, $contextpaths) = get_context_info_list($context);
7581 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED
, 'ctx');
7583 list($incaps, $capsparams) = $DB->get_in_or_equal($capability, SQL_PARAMS_NAMED
, 'cap');
7585 // Check whether context locking is enabled.
7586 // Filter out any write capability if this is the case.
7587 $excludelockedcaps = '';
7588 $excludelockedcapsparams = [];
7589 if (!empty($CFG->contextlocking
) && $context->locked
) {
7590 $excludelockedcaps = 'AND (cap.captype = :capread OR cap.name = :managelockscap)';
7591 $excludelockedcapsparams['capread'] = 'read';
7592 $excludelockedcapsparams['managelockscap'] = 'moodle/site:managecontextlocks';
7596 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
7597 FROM {role_capabilities} rc
7598 JOIN {capabilities} cap ON rc.capability = cap.name
7599 JOIN {context} ctx on rc.contextid = ctx.id
7600 WHERE rc.contextid $incontexts AND rc.capability $incaps $excludelockedcaps";
7601 $rcs = $DB->get_records_sql($sql, array_merge($cparams, $capsparams, $excludelockedcapsparams));
7602 foreach ($rcs as $rc) {
7603 $defs[$rc->path
][$rc->roleid
] = $rc->permission
;
7607 if (!empty($defs)) {
7608 foreach ($contextpaths as $path) {
7609 if (empty($defs[$path])) {
7612 foreach ($defs[$path] as $roleid => $perm) {
7613 if ($perm == CAP_PROHIBIT
) {
7614 $access[$roleid] = CAP_PROHIBIT
;
7617 if (!isset($access[$roleid])) {
7618 $access[$roleid] = (int) $perm;
7626 // Make lists of roles that are needed and prohibited.
7627 $needed = array(); // One of these is enough.
7628 $prohibited = array(); // Must not have any of these.
7629 foreach ($access as $roleid => $perm) {
7630 if ($perm == CAP_PROHIBIT
) {
7631 unset($needed[$roleid]);
7632 $prohibited[$roleid] = true;
7634 if ($perm == CAP_ALLOW
and empty($prohibited[$roleid])) {
7635 $needed[$roleid] = true;
7640 $defaultuserroleid = isset($CFG->defaultuserroleid
) ?
$CFG->defaultuserroleid
: 0;
7641 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid
) ?
$CFG->defaultfrontpageroleid
: 0;
7646 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
7649 if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
7650 // Everybody not having prohibit has the capability.
7653 if (empty($needed)) {
7659 if (!empty($prohibited[$defaultuserroleid])) {
7662 if (!empty($needed[$defaultuserroleid])) {
7663 // Everybody not having prohibit has the capability.
7666 if (empty($needed)) {
7674 // Nobody can match so return some SQL that does not return any results.
7675 $wheres[] = "1 = 2";
7680 $ctxids = implode(',', $contextids);
7681 $roleids = implode(',', array_keys($needed));
7682 $joins[] = "JOIN {role_assignments} {$prefix}ra3
7683 ON ({$prefix}ra3.userid = $useridcolumn
7684 AND {$prefix}ra3.roleid IN ($roleids)
7685 AND {$prefix}ra3.contextid IN ($ctxids))";
7689 $ctxids = implode(',', $contextids);
7690 $roleids = implode(',', array_keys($prohibited));
7691 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4
7692 ON ({$prefix}ra4.userid = $useridcolumn
7693 AND {$prefix}ra4.roleid IN ($roleids)
7694 AND {$prefix}ra4.contextid IN ($ctxids))";
7695 $wheres[] = "{$prefix}ra4.id IS NULL";
7700 $wheres[] = "$useridcolumn <> :{$prefix}guestid";
7701 $params["{$prefix}guestid"] = $CFG->siteguest
;
7703 $joins = implode("\n", $joins);
7704 $wheres = "(" . implode(" AND ", $wheres) . ")";
7706 return new \core\dml\
sql_join($joins, $wheres, $params);