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>
68 * Access control data is held in the "accessdata" array
69 * which - for the logged-in user, will be in $USER->access
71 * For other users can be generated and passed around (but may also be cached
72 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser).
74 * $accessdata is a multidimensional array, holding
75 * role assignments (RAs), role-capabilities-perm sets
76 * (role defs) and a list of courses we have loaded
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->accessdatabyuser
= array(); // Holds the cache of $accessdata structure for users (including $USER)
188 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
190 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
191 * accesslib's private caches. You need to do this before setting up test data,
192 * and also at the end of the tests.
197 function accesslib_clear_all_caches_for_unit_testing() {
200 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
203 accesslib_clear_all_caches(true);
205 unset($USER->access
);
209 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
211 * This reset does not touch global $USER.
214 * @param bool $resetcontexts
217 function accesslib_clear_all_caches($resetcontexts) {
218 global $ACCESSLIB_PRIVATE;
220 $ACCESSLIB_PRIVATE->dirtycontexts
= null;
221 $ACCESSLIB_PRIVATE->accessdatabyuser
= array();
222 $ACCESSLIB_PRIVATE->cacheroledefs
= array();
224 $cache = cache
::make('core', 'roledefs');
227 if ($resetcontexts) {
228 context_helper
::reset_caches();
233 * Clears accesslib's private cache of a specific role or roles. ONLY BE USED FROM THIS LIBRARY FILE!
235 * This reset does not touch global $USER.
238 * @param int|array $roles
241 function accesslib_clear_role_cache($roles) {
242 global $ACCESSLIB_PRIVATE;
244 if (!is_array($roles)) {
248 foreach ($roles as $role) {
249 if (isset($ACCESSLIB_PRIVATE->cacheroledefs
[$role])) {
250 unset($ACCESSLIB_PRIVATE->cacheroledefs
[$role]);
254 $cache = cache
::make('core', 'roledefs');
255 $cache->delete_many($roles);
259 * Role is assigned at system context.
265 function get_role_access($roleid) {
266 $accessdata = get_empty_accessdata();
267 $accessdata['ra']['/'.SYSCONTEXTID
] = array((int)$roleid => (int)$roleid);
272 * Fetch raw "site wide" role definitions.
273 * Even MUC static acceleration cache appears a bit slow for this.
274 * Important as can be hit hundreds of times per page.
276 * @param array $roleids List of role ids to fetch definitions for.
277 * @return array Complete definition for each requested role.
279 function get_role_definitions(array $roleids) {
280 global $ACCESSLIB_PRIVATE;
282 if (empty($roleids)) {
286 // Grab all keys we have not yet got in our static cache.
287 if ($uncached = array_diff($roleids, array_keys($ACCESSLIB_PRIVATE->cacheroledefs
))) {
288 $cache = cache
::make('core', 'roledefs');
289 foreach ($cache->get_many($uncached) as $roleid => $cachedroledef) {
290 if (is_array($cachedroledef)) {
291 $ACCESSLIB_PRIVATE->cacheroledefs
[$roleid] = $cachedroledef;
295 // Check we have the remaining keys from the MUC.
296 if ($uncached = array_diff($roleids, array_keys($ACCESSLIB_PRIVATE->cacheroledefs
))) {
297 $uncached = get_role_definitions_uncached($uncached);
298 $ACCESSLIB_PRIVATE->cacheroledefs +
= $uncached;
299 $cache->set_many($uncached);
303 // Return just the roles we need.
304 return array_intersect_key($ACCESSLIB_PRIVATE->cacheroledefs
, array_flip($roleids));
308 * Query raw "site wide" role definitions.
310 * @param array $roleids List of role ids to fetch definitions for.
311 * @return array Complete definition for each requested role.
313 function get_role_definitions_uncached(array $roleids) {
316 if (empty($roleids)) {
320 // Create a blank results array: even if a role has no capabilities,
321 // we need to ensure it is included in the results to show we have
322 // loaded all the capabilities that there are.
324 foreach ($roleids as $roleid) {
325 $rdefs[$roleid] = array();
328 // Load all the capabilities for these roles in all contexts.
329 list($sql, $params) = $DB->get_in_or_equal($roleids);
330 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
331 FROM {role_capabilities} rc
332 JOIN {context} ctx ON rc.contextid = ctx.id
333 WHERE rc.roleid $sql";
334 $rs = $DB->get_recordset_sql($sql, $params);
336 // Store the capabilities into the expected data structure.
337 foreach ($rs as $rd) {
338 if (!isset($rdefs[$rd->roleid
][$rd->path
])) {
339 $rdefs[$rd->roleid
][$rd->path
] = array();
341 $rdefs[$rd->roleid
][$rd->path
][$rd->capability
] = (int) $rd->permission
;
346 // Sometimes (e.g. get_user_capability_course_helper::get_capability_info_at_each_context)
347 // we process role definitinons in a way that requires we see parent contexts
348 // before child contexts. This sort ensures that works (and is faster than
349 // sorting in the SQL query).
350 foreach ($rdefs as $roleid => $rdef) {
351 ksort($rdefs[$roleid]);
358 * Get the default guest role, this is used for guest account,
359 * search engine spiders, etc.
361 * @return stdClass role record
363 function get_guest_role() {
366 if (empty($CFG->guestroleid
)) {
367 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
368 $guestrole = array_shift($roles); // Pick the first one
369 set_config('guestroleid', $guestrole->id
);
372 debugging('Can not find any guest role!');
376 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid
))) {
379 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
380 set_config('guestroleid', '');
381 return get_guest_role();
387 * Check whether a user has a particular capability in a given context.
390 * $context = context_module::instance($cm->id);
391 * has_capability('mod/forum:replypost', $context)
393 * By default checks the capabilities of the current user, but you can pass a
394 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
396 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
397 * or capabilities with XSS, config or data loss risks.
401 * @param string $capability the name of the capability to check. For example mod/forum:view
402 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
403 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
404 * @param boolean $doanything If false, ignores effect of admin role assignment
405 * @return boolean true if the user has this capability. Otherwise false.
407 function has_capability($capability, context
$context, $user = null, $doanything = true) {
408 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
410 if (during_initial_install()) {
411 if ($SCRIPT === "/$CFG->admin/index.php"
412 or $SCRIPT === "/$CFG->admin/cli/install.php"
413 or $SCRIPT === "/$CFG->admin/cli/install_database.php"
414 or (defined('BEHAT_UTIL') and BEHAT_UTIL
)
415 or (defined('PHPUNIT_UTIL') and PHPUNIT_UTIL
)) {
416 // we are in an installer - roles can not work yet
423 if (strpos($capability, 'moodle/legacy:') === 0) {
424 throw new coding_exception('Legacy capabilities can not be used any more!');
427 if (!is_bool($doanything)) {
428 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
431 // capability must exist
432 if (!$capinfo = get_capability_info($capability)) {
433 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
437 if (!isset($USER->id
)) {
438 // should never happen
440 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER
);
443 // make sure there is a real user specified
444 if ($user === null) {
447 $userid = is_object($user) ?
$user->id
: $user;
450 // make sure forcelogin cuts off not-logged-in users if enabled
451 if (!empty($CFG->forcelogin
) and $userid == 0) {
455 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
456 if (($capinfo->captype
=== 'write') or ($capinfo->riskbitmask
& (RISK_XSS | RISK_CONFIG | RISK_DATALOSS
))) {
457 if (isguestuser($userid) or $userid == 0) {
462 // somehow make sure the user is not deleted and actually exists
464 if ($userid == $USER->id
and isset($USER->deleted
)) {
465 // this prevents one query per page, it is a bit of cheating,
466 // but hopefully session is terminated properly once user is deleted
467 if ($USER->deleted
) {
471 if (!context_user
::instance($userid, IGNORE_MISSING
)) {
472 // no user context == invalid userid
478 // context path/depth must be valid
479 if (empty($context->path
) or $context->depth
== 0) {
480 // this should not happen often, each upgrade tries to rebuild the context paths
481 debugging('Context id '.$context->id
.' does not have valid path, please use context_helper::build_all_paths()');
482 if (is_siteadmin($userid)) {
489 // Find out if user is admin - it is not possible to override the doanything in any way
490 // and it is not possible to switch to admin role either.
492 if (is_siteadmin($userid)) {
493 if ($userid != $USER->id
) {
496 // make sure switchrole is not used in this context
497 if (empty($USER->access
['rsw'])) {
500 $parts = explode('/', trim($context->path
, '/'));
503 foreach ($parts as $part) {
504 $path .= '/' . $part;
505 if (!empty($USER->access
['rsw'][$path])) {
513 //ok, admin switched role in this context, let's use normal access control rules
517 // Careful check for staleness...
518 $context->reload_if_dirty();
520 if ($USER->id
== $userid) {
521 if (!isset($USER->access
)) {
522 load_all_capabilities();
524 $access =& $USER->access
;
527 // make sure user accessdata is really loaded
528 get_user_accessdata($userid, true);
529 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser
[$userid];
532 return has_capability_in_accessdata($capability, $context, $access);
536 * Check if the user has any one of several capabilities from a list.
538 * This is just a utility method that calls has_capability in a loop. Try to put
539 * the capabilities that most users are likely to have first in the list for best
543 * @see has_capability()
545 * @param array $capabilities an array of capability names.
546 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
547 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
548 * @param boolean $doanything If false, ignore effect of admin role assignment
549 * @return boolean true if the user has any of these capabilities. Otherwise false.
551 function has_any_capability(array $capabilities, context
$context, $user = null, $doanything = true) {
552 foreach ($capabilities as $capability) {
553 if (has_capability($capability, $context, $user, $doanything)) {
561 * Check if the user has all the capabilities in a list.
563 * This is just a utility method that calls has_capability in a loop. Try to put
564 * the capabilities that fewest users are likely to have first in the list for best
568 * @see has_capability()
570 * @param array $capabilities an array of capability names.
571 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
572 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
573 * @param boolean $doanything If false, ignore effect of admin role assignment
574 * @return boolean true if the user has all of these capabilities. Otherwise false.
576 function has_all_capabilities(array $capabilities, context
$context, $user = null, $doanything = true) {
577 foreach ($capabilities as $capability) {
578 if (!has_capability($capability, $context, $user, $doanything)) {
586 * Is course creator going to have capability in a new course?
588 * This is intended to be used in enrolment plugins before or during course creation,
589 * do not use after the course is fully created.
593 * @param string $capability the name of the capability to check.
594 * @param context $context course or category context where is course going to be created
595 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
596 * @return boolean true if the user will have this capability.
598 * @throws coding_exception if different type of context submitted
600 function guess_if_creator_will_have_course_capability($capability, context
$context, $user = null) {
603 if ($context->contextlevel
!= CONTEXT_COURSE
and $context->contextlevel
!= CONTEXT_COURSECAT
) {
604 throw new coding_exception('Only course or course category context expected');
607 if (has_capability($capability, $context, $user)) {
608 // User already has the capability, it could be only removed if CAP_PROHIBIT
609 // was involved here, but we ignore that.
613 if (!has_capability('moodle/course:create', $context, $user)) {
617 if (!enrol_is_enabled('manual')) {
621 if (empty($CFG->creatornewroleid
)) {
625 if ($context->contextlevel
== CONTEXT_COURSE
) {
626 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
630 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
635 // Most likely they will be enrolled after the course creation is finished,
636 // does the new role have the required capability?
637 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
638 return isset($neededroles[$CFG->creatornewroleid
]);
642 * Check if the user is an admin at the site level.
644 * Please note that use of proper capabilities is always encouraged,
645 * this function is supposed to be used from core or for temporary hacks.
649 * @param int|stdClass $user_or_id user id or user object
650 * @return bool true if user is one of the administrators, false otherwise
652 function is_siteadmin($user_or_id = null) {
655 if ($user_or_id === null) {
659 if (empty($user_or_id)) {
662 if (!empty($user_or_id->id
)) {
663 $userid = $user_or_id->id
;
665 $userid = $user_or_id;
668 // Because this script is called many times (150+ for course page) with
669 // the same parameters, it is worth doing minor optimisations. This static
670 // cache stores the value for a single userid, saving about 2ms from course
671 // page load time without using significant memory. As the static cache
672 // also includes the value it depends on, this cannot break unit tests.
673 static $knownid, $knownresult, $knownsiteadmins;
674 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins
) {
678 $knownsiteadmins = $CFG->siteadmins
;
680 $siteadmins = explode(',', $CFG->siteadmins
);
681 $knownresult = in_array($userid, $siteadmins);
686 * Returns true if user has at least one role assign
687 * of 'coursecontact' role (is potentially listed in some course descriptions).
692 function has_coursecontact_role($userid) {
695 if (empty($CFG->coursecontact
)) {
699 FROM {role_assignments}
700 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
701 return $DB->record_exists_sql($sql, array('userid'=>$userid));
705 * Does the user have a capability to do something?
707 * Walk the accessdata array and return true/false.
708 * Deals with prohibits, role switching, aggregating
711 * The main feature of here is being FAST and with no
716 * Switch Role merges with default role
717 * ------------------------------------
718 * If you are a teacher in course X, you have at least
719 * teacher-in-X + defaultloggedinuser-sitewide. So in the
720 * course you'll have techer+defaultloggedinuser.
721 * We try to mimic that in switchrole.
723 * Permission evaluation
724 * ---------------------
725 * Originally there was an extremely complicated way
726 * to determine the user access that dealt with
727 * "locality" or role assignments and role overrides.
728 * Now we simply evaluate access for each role separately
729 * and then verify if user has at least one role with allow
730 * and at the same time no role with prohibit.
733 * @param string $capability
734 * @param context $context
735 * @param array $accessdata
738 function has_capability_in_accessdata($capability, context
$context, array &$accessdata) {
741 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
742 $path = $context->path
;
743 $paths = array($path);
744 while($path = rtrim($path, '0123456789')) {
745 $path = rtrim($path, '/');
753 $switchedrole = false;
755 // Find out if role switched
756 if (!empty($accessdata['rsw'])) {
757 // From the bottom up...
758 foreach ($paths as $path) {
759 if (isset($accessdata['rsw'][$path])) {
760 // Found a switchrole assignment - check for that role _plus_ the default user role
761 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid
=>null);
762 $switchedrole = true;
768 if (!$switchedrole) {
769 // get all users roles in this context and above
770 foreach ($paths as $path) {
771 if (isset($accessdata['ra'][$path])) {
772 foreach ($accessdata['ra'][$path] as $roleid) {
773 $roles[$roleid] = null;
779 // Now find out what access is given to each role, going bottom-->up direction
780 $rdefs = get_role_definitions(array_keys($roles));
783 foreach ($roles as $roleid => $ignored) {
784 foreach ($paths as $path) {
785 if (isset($rdefs[$roleid][$path][$capability])) {
786 $perm = (int)$rdefs[$roleid][$path][$capability];
787 if ($perm === CAP_PROHIBIT
) {
788 // any CAP_PROHIBIT found means no permission for the user
791 if (is_null($roles[$roleid])) {
792 $roles[$roleid] = $perm;
796 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
797 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW
);
804 * A convenience function that tests has_capability, and displays an error if
805 * the user does not have that capability.
807 * NOTE before Moodle 2.0, this function attempted to make an appropriate
808 * require_login call before checking the capability. This is no longer the case.
809 * You must call require_login (or one of its variants) if you want to check the
810 * user is logged in, before you call this function.
812 * @see has_capability()
814 * @param string $capability the name of the capability to check. For example mod/forum:view
815 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
816 * @param int $userid A user id. By default (null) checks the permissions of the current user.
817 * @param bool $doanything If false, ignore effect of admin role assignment
818 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
819 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
820 * @return void terminates with an error if the user does not have the given capability.
822 function require_capability($capability, context
$context, $userid = null, $doanything = true,
823 $errormessage = 'nopermissions', $stringfile = '') {
824 if (!has_capability($capability, $context, $userid, $doanything)) {
825 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
830 * Return a nested array showing all role assignments for the user.
831 * [ra] => [contextpath][roleid] = roleid
834 * @param int $userid - the id of the user
835 * @return array access info array
837 function get_user_roles_sitewide_accessdata($userid) {
840 $accessdata = get_empty_accessdata();
842 // start with the default role
843 if (!empty($CFG->defaultuserroleid
)) {
844 $syscontext = context_system
::instance();
845 $accessdata['ra'][$syscontext->path
][(int)$CFG->defaultuserroleid
] = (int)$CFG->defaultuserroleid
;
848 // load the "default frontpage role"
849 if (!empty($CFG->defaultfrontpageroleid
)) {
850 $frontpagecontext = context_course
::instance(get_site()->id
);
851 if ($frontpagecontext->path
) {
852 $accessdata['ra'][$frontpagecontext->path
][(int)$CFG->defaultfrontpageroleid
] = (int)$CFG->defaultfrontpageroleid
;
856 // Preload every assigned role.
857 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
858 FROM {role_assignments} ra
859 JOIN {context} ctx ON ctx.id = ra.contextid
860 WHERE ra.userid = :userid";
862 $rs = $DB->get_recordset_sql($sql, array('userid' => $userid));
864 foreach ($rs as $ra) {
865 // RAs leafs are arrays to support multi-role assignments...
866 $accessdata['ra'][$ra->path
][(int)$ra->roleid
] = (int)$ra->roleid
;
875 * Returns empty accessdata structure.
878 * @return array empt accessdata
880 function get_empty_accessdata() {
881 $accessdata = array(); // named list
882 $accessdata['ra'] = array();
883 $accessdata['time'] = time();
884 $accessdata['rsw'] = array();
890 * Get accessdata for a given user.
894 * @param bool $preloadonly true means do not return access array
895 * @return array accessdata
897 function get_user_accessdata($userid, $preloadonly=false) {
898 global $CFG, $ACCESSLIB_PRIVATE, $USER;
900 if (isset($USER->access
)) {
901 $ACCESSLIB_PRIVATE->accessdatabyuser
[$USER->id
] = $USER->access
;
904 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser
[$userid])) {
905 if (empty($userid)) {
906 if (!empty($CFG->notloggedinroleid
)) {
907 $accessdata = get_role_access($CFG->notloggedinroleid
);
910 return get_empty_accessdata();
913 } else if (isguestuser($userid)) {
914 if ($guestrole = get_guest_role()) {
915 $accessdata = get_role_access($guestrole->id
);
918 return get_empty_accessdata();
922 // Includes default role and frontpage role.
923 $accessdata = get_user_roles_sitewide_accessdata($userid);
926 $ACCESSLIB_PRIVATE->accessdatabyuser
[$userid] = $accessdata;
932 return $ACCESSLIB_PRIVATE->accessdatabyuser
[$userid];
937 * A convenience function to completely load all the capabilities
938 * for the current user. It is called from has_capability() and functions change permissions.
940 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
941 * @see check_enrolment_plugins()
946 function load_all_capabilities() {
949 // roles not installed yet - we are in the middle of installation
950 if (during_initial_install()) {
954 if (!isset($USER->id
)) {
955 // this should not happen
959 unset($USER->access
);
960 $USER->access
= get_user_accessdata($USER->id
);
962 // Clear to force a refresh
963 unset($USER->mycourses
);
965 // init/reset internal enrol caches - active course enrolments and temp access
966 $USER->enrol
= array('enrolled'=>array(), 'tempguest'=>array());
970 * A convenience function to completely reload all the capabilities
971 * for the current user when roles have been updated in a relevant
972 * context -- but PRESERVING switchroles and loginas.
973 * This function resets all accesslib and context caches.
975 * That is - completely transparent to the user.
977 * Note: reloads $USER->access completely.
982 function reload_all_capabilities() {
983 global $USER, $DB, $ACCESSLIB_PRIVATE;
987 if (!empty($USER->access
['rsw'])) {
988 $sw = $USER->access
['rsw'];
991 accesslib_clear_all_caches(true);
992 unset($USER->access
);
993 $ACCESSLIB_PRIVATE->dirtycontexts
= array(); // prevent dirty flags refetching on this page
995 load_all_capabilities();
997 foreach ($sw as $path => $roleid) {
998 if ($record = $DB->get_record('context', array('path'=>$path))) {
999 $context = context
::instance_by_id($record->id
);
1000 role_switch($roleid, $context);
1006 * Adds a temp role to current USER->access array.
1008 * Useful for the "temporary guest" access we grant to logged-in users.
1009 * This is useful for enrol plugins only.
1012 * @param context_course $coursecontext
1013 * @param int $roleid
1016 function load_temp_course_role(context_course
$coursecontext, $roleid) {
1017 global $USER, $SITE;
1019 if (empty($roleid)) {
1020 debugging('invalid role specified in load_temp_course_role()');
1024 if ($coursecontext->instanceid
== $SITE->id
) {
1025 debugging('Can not use temp roles on the frontpage');
1029 if (!isset($USER->access
)) {
1030 load_all_capabilities();
1033 $coursecontext->reload_if_dirty();
1035 if (isset($USER->access
['ra'][$coursecontext->path
][$roleid])) {
1039 $USER->access
['ra'][$coursecontext->path
][(int)$roleid] = (int)$roleid;
1043 * Removes any extra guest roles from current USER->access array.
1044 * This is useful for enrol plugins only.
1047 * @param context_course $coursecontext
1050 function remove_temp_course_roles(context_course
$coursecontext) {
1051 global $DB, $USER, $SITE;
1053 if ($coursecontext->instanceid
== $SITE->id
) {
1054 debugging('Can not use temp roles on the frontpage');
1058 if (empty($USER->access
['ra'][$coursecontext->path
])) {
1059 //no roles here, weird
1063 $sql = "SELECT DISTINCT ra.roleid AS id
1064 FROM {role_assignments} ra
1065 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1066 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id
, 'userid'=>$USER->id
));
1068 $USER->access
['ra'][$coursecontext->path
] = array();
1069 foreach($ras as $r) {
1070 $USER->access
['ra'][$coursecontext->path
][(int)$r->id
] = (int)$r->id
;
1075 * Returns array of all role archetypes.
1079 function get_role_archetypes() {
1081 'manager' => 'manager',
1082 'coursecreator' => 'coursecreator',
1083 'editingteacher' => 'editingteacher',
1084 'teacher' => 'teacher',
1085 'student' => 'student',
1088 'frontpage' => 'frontpage'
1093 * Assign the defaults found in this capability definition to roles that have
1094 * the corresponding legacy capabilities assigned to them.
1096 * @param string $capability
1097 * @param array $legacyperms an array in the format (example):
1098 * 'guest' => CAP_PREVENT,
1099 * 'student' => CAP_ALLOW,
1100 * 'teacher' => CAP_ALLOW,
1101 * 'editingteacher' => CAP_ALLOW,
1102 * 'coursecreator' => CAP_ALLOW,
1103 * 'manager' => CAP_ALLOW
1104 * @return boolean success or failure.
1106 function assign_legacy_capabilities($capability, $legacyperms) {
1108 $archetypes = get_role_archetypes();
1110 foreach ($legacyperms as $type => $perm) {
1112 $systemcontext = context_system
::instance();
1113 if ($type === 'admin') {
1114 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1118 if (!array_key_exists($type, $archetypes)) {
1119 print_error('invalidlegacy', '', '', $type);
1122 if ($roles = get_archetype_roles($type)) {
1123 foreach ($roles as $role) {
1124 // Assign a site level capability.
1125 if (!assign_capability($capability, $perm, $role->id
, $systemcontext->id
)) {
1135 * Verify capability risks.
1137 * @param stdClass $capability a capability - a row from the capabilities table.
1138 * @return boolean whether this capability is safe - that is, whether people with the
1139 * safeoverrides capability should be allowed to change it.
1141 function is_safe_capability($capability) {
1142 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL
) & $capability->riskbitmask
);
1146 * Get the local override (if any) for a given capability in a role in a context
1148 * @param int $roleid
1149 * @param int $contextid
1150 * @param string $capability
1151 * @return stdClass local capability override
1153 function get_local_override($roleid, $contextid, $capability) {
1155 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1159 * Returns context instance plus related course and cm instances
1161 * @param int $contextid
1162 * @return array of ($context, $course, $cm)
1164 function get_context_info_array($contextid) {
1167 $context = context
::instance_by_id($contextid, MUST_EXIST
);
1171 if ($context->contextlevel
== CONTEXT_COURSE
) {
1172 $course = $DB->get_record('course', array('id'=>$context->instanceid
), '*', MUST_EXIST
);
1174 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
1175 $cm = get_coursemodule_from_id('', $context->instanceid
, 0, false, MUST_EXIST
);
1176 $course = $DB->get_record('course', array('id'=>$cm->course
), '*', MUST_EXIST
);
1178 } else if ($context->contextlevel
== CONTEXT_BLOCK
) {
1179 $parent = $context->get_parent_context();
1181 if ($parent->contextlevel
== CONTEXT_COURSE
) {
1182 $course = $DB->get_record('course', array('id'=>$parent->instanceid
), '*', MUST_EXIST
);
1183 } else if ($parent->contextlevel
== CONTEXT_MODULE
) {
1184 $cm = get_coursemodule_from_id('', $parent->instanceid
, 0, false, MUST_EXIST
);
1185 $course = $DB->get_record('course', array('id'=>$cm->course
), '*', MUST_EXIST
);
1189 return array($context, $course, $cm);
1193 * Function that creates a role
1195 * @param string $name role name
1196 * @param string $shortname role short name
1197 * @param string $description role description
1198 * @param string $archetype
1199 * @return int id or dml_exception
1201 function create_role($name, $shortname, $description, $archetype = '') {
1204 if (strpos($archetype, 'moodle/legacy:') !== false) {
1205 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1208 // verify role archetype actually exists
1209 $archetypes = get_role_archetypes();
1210 if (empty($archetypes[$archetype])) {
1214 // Insert the role record.
1215 $role = new stdClass();
1216 $role->name
= $name;
1217 $role->shortname
= $shortname;
1218 $role->description
= $description;
1219 $role->archetype
= $archetype;
1221 //find free sortorder number
1222 $role->sortorder
= $DB->get_field('role', 'MAX(sortorder) + 1', array());
1223 if (empty($role->sortorder
)) {
1224 $role->sortorder
= 1;
1226 $id = $DB->insert_record('role', $role);
1232 * Function that deletes a role and cleanups up after it
1234 * @param int $roleid id of role to delete
1235 * @return bool always true
1237 function delete_role($roleid) {
1240 // first unssign all users
1241 role_unassign_all(array('roleid'=>$roleid));
1243 // cleanup all references to this role, ignore errors
1244 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1245 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1246 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1247 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1248 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1249 $DB->delete_records('role_names', array('roleid'=>$roleid));
1250 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1252 // Get role record before it's deleted.
1253 $role = $DB->get_record('role', array('id'=>$roleid));
1255 // Finally delete the role itself.
1256 $DB->delete_records('role', array('id'=>$roleid));
1259 $event = \core\event\role_deleted
::create(
1261 'context' => context_system
::instance(),
1262 'objectid' => $roleid,
1265 'shortname' => $role->shortname
,
1266 'description' => $role->description
,
1267 'archetype' => $role->archetype
1271 $event->add_record_snapshot('role', $role);
1274 // Reset any cache of this role, including MUC.
1275 accesslib_clear_role_cache($roleid);
1281 * Function to write context specific overrides, or default capabilities.
1283 * NOTE: use $context->mark_dirty() after this
1285 * @param string $capability string name
1286 * @param int $permission CAP_ constants
1287 * @param int $roleid role id
1288 * @param int|context $contextid context id
1289 * @param bool $overwrite
1290 * @return bool always true or exception
1292 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1295 if ($contextid instanceof context
) {
1296 $context = $contextid;
1298 $context = context
::instance_by_id($contextid);
1301 if (empty($permission) ||
$permission == CAP_INHERIT
) { // if permission is not set
1302 unassign_capability($capability, $roleid, $context->id
);
1306 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id
, 'roleid'=>$roleid, 'capability'=>$capability));
1308 if ($existing and !$overwrite) { // We want to keep whatever is there already
1312 $cap = new stdClass();
1313 $cap->contextid
= $context->id
;
1314 $cap->roleid
= $roleid;
1315 $cap->capability
= $capability;
1316 $cap->permission
= $permission;
1317 $cap->timemodified
= time();
1318 $cap->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
1321 $cap->id
= $existing->id
;
1322 $DB->update_record('role_capabilities', $cap);
1324 if ($DB->record_exists('context', array('id'=>$context->id
))) {
1325 $DB->insert_record('role_capabilities', $cap);
1329 // Reset any cache of this role, including MUC.
1330 accesslib_clear_role_cache($roleid);
1336 * Unassign a capability from a role.
1338 * NOTE: use $context->mark_dirty() after this
1340 * @param string $capability the name of the capability
1341 * @param int $roleid the role id
1342 * @param int|context $contextid null means all contexts
1343 * @return boolean true or exception
1345 function unassign_capability($capability, $roleid, $contextid = null) {
1348 if (!empty($contextid)) {
1349 if ($contextid instanceof context
) {
1350 $context = $contextid;
1352 $context = context
::instance_by_id($contextid);
1354 // delete from context rel, if this is the last override in this context
1355 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id
));
1357 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1360 // Reset any cache of this role, including MUC.
1361 accesslib_clear_role_cache($roleid);
1367 * Get the roles that have a given capability assigned to it
1369 * This function does not resolve the actual permission of the capability.
1370 * It just checks for permissions and overrides.
1371 * Use get_roles_with_cap_in_context() if resolution is required.
1373 * @param string $capability capability name (string)
1374 * @param string $permission optional, the permission defined for this capability
1375 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1376 * @param stdClass $context null means any
1377 * @return array of role records
1379 function get_roles_with_capability($capability, $permission = null, $context = null) {
1383 $contexts = $context->get_parent_context_ids(true);
1384 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED
, 'ctx');
1385 $contextsql = "AND rc.contextid $insql";
1392 $permissionsql = " AND rc.permission = :permission";
1393 $params['permission'] = $permission;
1395 $permissionsql = '';
1400 WHERE r.id IN (SELECT rc.roleid
1401 FROM {role_capabilities} rc
1402 WHERE rc.capability = :capname
1405 $params['capname'] = $capability;
1408 return $DB->get_records_sql($sql, $params);
1412 * This function makes a role-assignment (a role for a user in a particular context)
1414 * @param int $roleid the role of the id
1415 * @param int $userid userid
1416 * @param int|context $contextid id of the context
1417 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1418 * @param int $itemid id of enrolment/auth plugin
1419 * @param string $timemodified defaults to current time
1420 * @return int new/existing id of the assignment
1422 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1425 // first of all detect if somebody is using old style parameters
1426 if ($contextid === 0 or is_numeric($component)) {
1427 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1430 // now validate all parameters
1431 if (empty($roleid)) {
1432 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1435 if (empty($userid)) {
1436 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1440 if (strpos($component, '_') === false) {
1441 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1445 if ($component !== '' and strpos($component, '_') === false) {
1446 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1450 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1451 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1454 if ($contextid instanceof context
) {
1455 $context = $contextid;
1457 $context = context
::instance_by_id($contextid, MUST_EXIST
);
1460 if (!$timemodified) {
1461 $timemodified = time();
1464 // Check for existing entry
1465 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id
, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1468 // role already assigned - this should not happen
1469 if (count($ras) > 1) {
1470 // very weird - remove all duplicates!
1471 $ra = array_shift($ras);
1472 foreach ($ras as $r) {
1473 $DB->delete_records('role_assignments', array('id'=>$r->id
));
1479 // actually there is no need to update, reset anything or trigger any event, so just return
1483 // Create a new entry
1484 $ra = new stdClass();
1485 $ra->roleid
= $roleid;
1486 $ra->contextid
= $context->id
;
1487 $ra->userid
= $userid;
1488 $ra->component
= $component;
1489 $ra->itemid
= $itemid;
1490 $ra->timemodified
= $timemodified;
1491 $ra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
1494 $ra->id
= $DB->insert_record('role_assignments', $ra);
1496 // mark context as dirty - again expensive, but needed
1497 $context->mark_dirty();
1499 if (!empty($USER->id
) && $USER->id
== $userid) {
1500 // If the user is the current user, then do full reload of capabilities too.
1501 reload_all_capabilities();
1504 core_course_category
::role_assignment_changed($roleid, $context);
1506 $event = \core\event\role_assigned
::create(array(
1507 'context' => $context,
1508 'objectid' => $ra->roleid
,
1509 'relateduserid' => $ra->userid
,
1512 'component' => $ra->component
,
1513 'itemid' => $ra->itemid
1516 $event->add_record_snapshot('role_assignments', $ra);
1523 * Removes one role assignment
1525 * @param int $roleid
1526 * @param int $userid
1527 * @param int $contextid
1528 * @param string $component
1529 * @param int $itemid
1532 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1533 // first make sure the params make sense
1534 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1535 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1539 if (strpos($component, '_') === false) {
1540 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1544 if ($component !== '' and strpos($component, '_') === false) {
1545 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1549 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1553 * Removes multiple role assignments, parameters may contain:
1554 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1556 * @param array $params role assignment parameters
1557 * @param bool $subcontexts unassign in subcontexts too
1558 * @param bool $includemanual include manual role assignments too
1561 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1562 global $USER, $CFG, $DB;
1565 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1568 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1569 foreach ($params as $key=>$value) {
1570 if (!in_array($key, $allowed)) {
1571 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1575 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1576 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1579 if ($includemanual) {
1580 if (!isset($params['component']) or $params['component'] === '') {
1581 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1586 if (empty($params['contextid'])) {
1587 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1591 $ras = $DB->get_records('role_assignments', $params);
1592 foreach($ras as $ra) {
1593 $DB->delete_records('role_assignments', array('id'=>$ra->id
));
1594 if ($context = context
::instance_by_id($ra->contextid
, IGNORE_MISSING
)) {
1595 // this is a bit expensive but necessary
1596 $context->mark_dirty();
1597 // If the user is the current user, then do full reload of capabilities too.
1598 if (!empty($USER->id
) && $USER->id
== $ra->userid
) {
1599 reload_all_capabilities();
1601 $event = \core\event\role_unassigned
::create(array(
1602 'context' => $context,
1603 'objectid' => $ra->roleid
,
1604 'relateduserid' => $ra->userid
,
1607 'component' => $ra->component
,
1608 'itemid' => $ra->itemid
1611 $event->add_record_snapshot('role_assignments', $ra);
1613 core_course_category
::role_assignment_changed($ra->roleid
, $context);
1618 // process subcontexts
1619 if ($subcontexts and $context = context
::instance_by_id($params['contextid'], IGNORE_MISSING
)) {
1620 if ($params['contextid'] instanceof context
) {
1621 $context = $params['contextid'];
1623 $context = context
::instance_by_id($params['contextid'], IGNORE_MISSING
);
1627 $contexts = $context->get_child_contexts();
1629 foreach($contexts as $context) {
1630 $mparams['contextid'] = $context->id
;
1631 $ras = $DB->get_records('role_assignments', $mparams);
1632 foreach($ras as $ra) {
1633 $DB->delete_records('role_assignments', array('id'=>$ra->id
));
1634 // this is a bit expensive but necessary
1635 $context->mark_dirty();
1636 // If the user is the current user, then do full reload of capabilities too.
1637 if (!empty($USER->id
) && $USER->id
== $ra->userid
) {
1638 reload_all_capabilities();
1640 $event = \core\event\role_unassigned
::create(
1641 array('context'=>$context, 'objectid'=>$ra->roleid
, 'relateduserid'=>$ra->userid
,
1642 'other'=>array('id'=>$ra->id
, 'component'=>$ra->component
, 'itemid'=>$ra->itemid
)));
1643 $event->add_record_snapshot('role_assignments', $ra);
1645 core_course_category
::role_assignment_changed($ra->roleid
, $context);
1651 // do this once more for all manual role assignments
1652 if ($includemanual) {
1653 $params['component'] = '';
1654 role_unassign_all($params, $subcontexts, false);
1659 * Determines if a user is currently logged in
1665 function isloggedin() {
1668 return (!empty($USER->id
));
1672 * Determines if a user is logged in as real guest user with username 'guest'.
1676 * @param int|object $user mixed user object or id, $USER if not specified
1677 * @return bool true if user is the real guest user, false if not logged in or other user
1679 function isguestuser($user = null) {
1680 global $USER, $DB, $CFG;
1682 // make sure we have the user id cached in config table, because we are going to use it a lot
1683 if (empty($CFG->siteguest
)) {
1684 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id
))) {
1685 // guest does not exist yet, weird
1688 set_config('siteguest', $guestid);
1690 if ($user === null) {
1694 if ($user === null) {
1695 // happens when setting the $USER
1698 } else if (is_numeric($user)) {
1699 return ($CFG->siteguest
== $user);
1701 } else if (is_object($user)) {
1702 if (empty($user->id
)) {
1703 return false; // not logged in means is not be guest
1705 return ($CFG->siteguest
== $user->id
);
1709 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1714 * Does user have a (temporary or real) guest access to course?
1718 * @param context $context
1719 * @param stdClass|int $user
1722 function is_guest(context
$context, $user = null) {
1725 // first find the course context
1726 $coursecontext = $context->get_course_context();
1728 // make sure there is a real user specified
1729 if ($user === null) {
1730 $userid = isset($USER->id
) ?
$USER->id
: 0;
1732 $userid = is_object($user) ?
$user->id
: $user;
1735 if (isguestuser($userid)) {
1736 // can not inspect or be enrolled
1740 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1741 // viewing users appear out of nowhere, they are neither guests nor participants
1745 // consider only real active enrolments here
1746 if (is_enrolled($coursecontext, $user, '', true)) {
1754 * Returns true if the user has moodle/course:view capability in the course,
1755 * this is intended for admins, managers (aka small admins), inspectors, etc.
1759 * @param context $context
1760 * @param int|stdClass $user if null $USER is used
1761 * @param string $withcapability extra capability name
1764 function is_viewing(context
$context, $user = null, $withcapability = '') {
1765 // first find the course context
1766 $coursecontext = $context->get_course_context();
1768 if (isguestuser($user)) {
1773 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1774 // admins are allowed to inspect courses
1778 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1779 // site admins always have the capability, but the enrolment above blocks
1787 * Returns true if the user is able to access the course.
1789 * This function is in no way, shape, or form a substitute for require_login.
1790 * It should only be used in circumstances where it is not possible to call require_login
1791 * such as the navigation.
1793 * This function checks many of the methods of access to a course such as the view
1794 * capability, enrollments, and guest access. It also makes use of the cache
1795 * generated by require_login for guest access.
1797 * The flags within the $USER object that are used here should NEVER be used outside
1798 * of this function can_access_course and require_login. Doing so WILL break future
1801 * @param stdClass $course record
1802 * @param stdClass|int|null $user user record or id, current user if null
1803 * @param string $withcapability Check for this capability as well.
1804 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1805 * @return boolean Returns true if the user is able to access the course
1807 function can_access_course(stdClass
$course, $user = null, $withcapability = '', $onlyactive = false) {
1810 // this function originally accepted $coursecontext parameter
1811 if ($course instanceof context
) {
1812 if ($course instanceof context_course
) {
1813 debugging('deprecated context parameter, please use $course record');
1814 $coursecontext = $course;
1815 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid
));
1817 debugging('Invalid context parameter, please use $course record');
1821 $coursecontext = context_course
::instance($course->id
);
1824 if (!isset($USER->id
)) {
1825 // should never happen
1827 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER
);
1830 // make sure there is a user specified
1831 if ($user === null) {
1832 $userid = $USER->id
;
1834 $userid = is_object($user) ?
$user->id
: $user;
1838 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
1842 if ($userid == $USER->id
) {
1843 if (!empty($USER->access
['rsw'][$coursecontext->path
])) {
1844 // the fact that somebody switched role means they can access the course no matter to what role they switched
1849 if (!$course->visible
and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
1853 if (is_viewing($coursecontext, $userid)) {
1857 if ($userid != $USER->id
) {
1858 // for performance reasons we do not verify temporary guest access for other users, sorry...
1859 return is_enrolled($coursecontext, $userid, '', $onlyactive);
1862 // === from here we deal only with $USER ===
1864 $coursecontext->reload_if_dirty();
1866 if (isset($USER->enrol
['enrolled'][$course->id
])) {
1867 if ($USER->enrol
['enrolled'][$course->id
] > time()) {
1871 if (isset($USER->enrol
['tempguest'][$course->id
])) {
1872 if ($USER->enrol
['tempguest'][$course->id
] > time()) {
1877 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
1881 // if not enrolled try to gain temporary guest access
1882 $instances = $DB->get_records('enrol', array('courseid'=>$course->id
, 'status'=>ENROL_INSTANCE_ENABLED
), 'sortorder, id ASC');
1883 $enrols = enrol_get_plugins(true);
1884 foreach($instances as $instance) {
1885 if (!isset($enrols[$instance->enrol
])) {
1888 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
1889 $until = $enrols[$instance->enrol
]->try_guestaccess($instance);
1890 if ($until !== false and $until > time()) {
1891 $USER->enrol
['tempguest'][$course->id
] = $until;
1895 if (isset($USER->enrol
['tempguest'][$course->id
])) {
1896 unset($USER->enrol
['tempguest'][$course->id
]);
1897 remove_temp_course_roles($coursecontext);
1904 * Loads the capability definitions for the component (from file).
1906 * Loads the capability definitions for the component (from file). If no
1907 * capabilities are defined for the component, we simply return an empty array.
1910 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
1911 * @return array array of capabilities
1913 function load_capability_def($component) {
1914 $defpath = core_component
::get_component_directory($component).'/db/access.php';
1916 $capabilities = array();
1917 if (file_exists($defpath)) {
1919 if (!empty($
{$component.'_capabilities'})) {
1920 // BC capability array name
1921 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
1922 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
1923 $capabilities = $
{$component.'_capabilities'};
1927 return $capabilities;
1931 * Gets the capabilities that have been cached in the database for this component.
1934 * @param string $component - examples: 'moodle', 'mod_forum'
1935 * @return array array of capabilities
1937 function get_cached_capabilities($component = 'moodle') {
1939 $caps = get_all_capabilities();
1940 $componentcaps = array();
1941 foreach ($caps as $cap) {
1942 if ($cap['component'] == $component) {
1943 $componentcaps[] = (object) $cap;
1946 return $componentcaps;
1950 * Returns default capabilities for given role archetype.
1952 * @param string $archetype role archetype
1955 function get_default_capabilities($archetype) {
1963 $defaults = array();
1964 $components = array();
1965 $allcaps = get_all_capabilities();
1967 foreach ($allcaps as $cap) {
1968 if (!in_array($cap['component'], $components)) {
1969 $components[] = $cap['component'];
1970 $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
1973 foreach($alldefs as $name=>$def) {
1974 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
1975 if (isset($def['archetypes'])) {
1976 if (isset($def['archetypes'][$archetype])) {
1977 $defaults[$name] = $def['archetypes'][$archetype];
1979 // 'legacy' is for backward compatibility with 1.9 access.php
1981 if (isset($def['legacy'][$archetype])) {
1982 $defaults[$name] = $def['legacy'][$archetype];
1991 * Return default roles that can be assigned, overridden or switched
1992 * by give role archetype.
1994 * @param string $type assign|override|switch|view
1995 * @param string $archetype
1996 * @return array of role ids
1998 function get_default_role_archetype_allows($type, $archetype) {
2001 if (empty($archetype)) {
2005 $roles = $DB->get_records('role');
2006 $archetypemap = array();
2007 foreach ($roles as $role) {
2008 if ($role->archetype
) {
2009 $archetypemap[$role->archetype
][$role->id
] = $role->id
;
2015 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2016 'coursecreator' => array(),
2017 'editingteacher' => array('teacher', 'student'),
2018 'teacher' => array(),
2019 'student' => array(),
2022 'frontpage' => array(),
2024 'override' => array(
2025 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2026 'coursecreator' => array(),
2027 'editingteacher' => array('teacher', 'student', 'guest'),
2028 'teacher' => array(),
2029 'student' => array(),
2032 'frontpage' => array(),
2035 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2036 'coursecreator' => array(),
2037 'editingteacher' => array('teacher', 'student', 'guest'),
2038 'teacher' => array('student', 'guest'),
2039 'student' => array(),
2042 'frontpage' => array(),
2045 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2046 'coursecreator' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2047 'editingteacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2048 'teacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2049 'student' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2052 'frontpage' => array(),
2056 if (!isset($defaults[$type][$archetype])) {
2057 debugging("Unknown type '$type'' or archetype '$archetype''");
2062 foreach ($defaults[$type][$archetype] as $at) {
2063 if (isset($archetypemap[$at])) {
2064 foreach ($archetypemap[$at] as $roleid) {
2065 $return[$roleid] = $roleid;
2074 * Reset role capabilities to default according to selected role archetype.
2075 * If no archetype selected, removes all capabilities.
2077 * This applies to capabilities that are assigned to the role (that you could
2078 * edit in the 'define roles' interface), and not to any capability overrides
2079 * in different locations.
2081 * @param int $roleid ID of role to reset capabilities for
2083 function reset_role_capabilities($roleid) {
2086 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST
);
2087 $defaultcaps = get_default_capabilities($role->archetype
);
2089 $systemcontext = context_system
::instance();
2091 $DB->delete_records('role_capabilities',
2092 array('roleid' => $roleid, 'contextid' => $systemcontext->id
));
2094 foreach($defaultcaps as $cap=>$permission) {
2095 assign_capability($cap, $permission, $roleid, $systemcontext->id
);
2098 // Reset any cache of this role, including MUC.
2099 accesslib_clear_role_cache($roleid);
2101 // Mark the system context dirty.
2102 context_system
::instance()->mark_dirty();
2106 * Updates the capabilities table with the component capability definitions.
2107 * If no parameters are given, the function updates the core moodle
2110 * Note that the absence of the db/access.php capabilities definition file
2111 * will cause any stored capabilities for the component to be removed from
2115 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2116 * @return boolean true if success, exception in case of any problems
2118 function update_capabilities($component = 'moodle') {
2119 global $DB, $OUTPUT;
2121 $storedcaps = array();
2123 $filecaps = load_capability_def($component);
2124 foreach($filecaps as $capname=>$unused) {
2125 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2126 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2130 // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2131 // So ensure our updating is based on fresh data.
2132 cache
::make('core', 'capabilities')->delete('core_capabilities');
2134 $cachedcaps = get_cached_capabilities($component);
2136 foreach ($cachedcaps as $cachedcap) {
2137 array_push($storedcaps, $cachedcap->name
);
2138 // update risk bitmasks and context levels in existing capabilities if needed
2139 if (array_key_exists($cachedcap->name
, $filecaps)) {
2140 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name
])) {
2141 $filecaps[$cachedcap->name
]['riskbitmask'] = 0; // no risk if not specified
2143 if ($cachedcap->captype
!= $filecaps[$cachedcap->name
]['captype']) {
2144 $updatecap = new stdClass();
2145 $updatecap->id
= $cachedcap->id
;
2146 $updatecap->captype
= $filecaps[$cachedcap->name
]['captype'];
2147 $DB->update_record('capabilities', $updatecap);
2149 if ($cachedcap->riskbitmask
!= $filecaps[$cachedcap->name
]['riskbitmask']) {
2150 $updatecap = new stdClass();
2151 $updatecap->id
= $cachedcap->id
;
2152 $updatecap->riskbitmask
= $filecaps[$cachedcap->name
]['riskbitmask'];
2153 $DB->update_record('capabilities', $updatecap);
2156 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name
])) {
2157 $filecaps[$cachedcap->name
]['contextlevel'] = 0; // no context level defined
2159 if ($cachedcap->contextlevel
!= $filecaps[$cachedcap->name
]['contextlevel']) {
2160 $updatecap = new stdClass();
2161 $updatecap->id
= $cachedcap->id
;
2162 $updatecap->contextlevel
= $filecaps[$cachedcap->name
]['contextlevel'];
2163 $DB->update_record('capabilities', $updatecap);
2169 // Flush the cached again, as we have changed DB.
2170 cache
::make('core', 'capabilities')->delete('core_capabilities');
2172 // Are there new capabilities in the file definition?
2175 foreach ($filecaps as $filecap => $def) {
2177 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2178 if (!array_key_exists('riskbitmask', $def)) {
2179 $def['riskbitmask'] = 0; // no risk if not specified
2181 $newcaps[$filecap] = $def;
2184 // Add new capabilities to the stored definition.
2185 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2186 foreach ($newcaps as $capname => $capdef) {
2187 $capability = new stdClass();
2188 $capability->name
= $capname;
2189 $capability->captype
= $capdef['captype'];
2190 $capability->contextlevel
= $capdef['contextlevel'];
2191 $capability->component
= $component;
2192 $capability->riskbitmask
= $capdef['riskbitmask'];
2194 $DB->insert_record('capabilities', $capability, false);
2196 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2197 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2198 foreach ($rolecapabilities as $rolecapability){
2199 //assign_capability will update rather than insert if capability exists
2200 if (!assign_capability($capname, $rolecapability->permission
,
2201 $rolecapability->roleid
, $rolecapability->contextid
, true)){
2202 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2206 // we ignore archetype key if we have cloned permissions
2207 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2208 assign_legacy_capabilities($capname, $capdef['archetypes']);
2209 // 'legacy' is for backward compatibility with 1.9 access.php
2210 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2211 assign_legacy_capabilities($capname, $capdef['legacy']);
2214 // Are there any capabilities that have been removed from the file
2215 // definition that we need to delete from the stored capabilities and
2216 // role assignments?
2217 capabilities_cleanup($component, $filecaps);
2219 // reset static caches
2220 accesslib_clear_all_caches(false);
2222 // Flush the cached again, as we have changed DB.
2223 cache
::make('core', 'capabilities')->delete('core_capabilities');
2229 * Deletes cached capabilities that are no longer needed by the component.
2230 * Also unassigns these capabilities from any roles that have them.
2231 * NOTE: this function is called from lib/db/upgrade.php
2234 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2235 * @param array $newcapdef array of the new capability definitions that will be
2236 * compared with the cached capabilities
2237 * @return int number of deprecated capabilities that have been removed
2239 function capabilities_cleanup($component, $newcapdef = null) {
2244 if ($cachedcaps = get_cached_capabilities($component)) {
2245 foreach ($cachedcaps as $cachedcap) {
2246 if (empty($newcapdef) ||
2247 array_key_exists($cachedcap->name
, $newcapdef) === false) {
2249 // Remove from capabilities cache.
2250 $DB->delete_records('capabilities', array('name'=>$cachedcap->name
));
2252 // Delete from roles.
2253 if ($roles = get_roles_with_capability($cachedcap->name
)) {
2254 foreach($roles as $role) {
2255 if (!unassign_capability($cachedcap->name
, $role->id
)) {
2256 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name
, 'role'=>$role->name
));
2263 if ($removedcount) {
2264 cache
::make('core', 'capabilities')->delete('core_capabilities');
2266 return $removedcount;
2270 * Returns an array of all the known types of risk
2271 * The array keys can be used, for example as CSS class names, or in calls to
2272 * print_risk_icon. The values are the corresponding RISK_ constants.
2274 * @return array all the known types of risk.
2276 function get_all_risks() {
2278 'riskmanagetrust' => RISK_MANAGETRUST
,
2279 'riskconfig' => RISK_CONFIG
,
2280 'riskxss' => RISK_XSS
,
2281 'riskpersonal' => RISK_PERSONAL
,
2282 'riskspam' => RISK_SPAM
,
2283 'riskdataloss' => RISK_DATALOSS
,
2288 * Return a link to moodle docs for a given capability name
2290 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2291 * @return string the human-readable capability name as a link to Moodle Docs.
2293 function get_capability_docs_link($capability) {
2294 $url = get_docs_url('Capabilities/' . $capability->name
);
2295 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name
) . '</a>';
2299 * This function pulls out all the resolved capabilities (overrides and
2300 * defaults) of a role used in capability overrides in contexts at a given
2303 * @param int $roleid
2304 * @param context $context
2305 * @param string $cap capability, optional, defaults to ''
2306 * @return array Array of capabilities
2308 function role_context_capabilities($roleid, context
$context, $cap = '') {
2311 $contexts = $context->get_parent_context_ids(true);
2312 $contexts = '('.implode(',', $contexts).')';
2314 $params = array($roleid);
2317 $search = " AND rc.capability = ? ";
2324 FROM {role_capabilities} rc, {context} c
2325 WHERE rc.contextid in $contexts
2327 AND rc.contextid = c.id $search
2328 ORDER BY c.contextlevel DESC, rc.capability DESC";
2330 $capabilities = array();
2332 if ($records = $DB->get_records_sql($sql, $params)) {
2333 // We are traversing via reverse order.
2334 foreach ($records as $record) {
2335 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2336 if (!isset($capabilities[$record->capability
]) ||
$record->permission
<-500) {
2337 $capabilities[$record->capability
] = $record->permission
;
2341 return $capabilities;
2345 * Constructs array with contextids as first parameter and context paths,
2346 * in both cases bottom top including self.
2349 * @param context $context
2352 function get_context_info_list(context
$context) {
2353 $contextids = explode('/', ltrim($context->path
, '/'));
2354 $contextpaths = array();
2355 $contextids2 = $contextids;
2356 while ($contextids2) {
2357 $contextpaths[] = '/' . implode('/', $contextids2);
2358 array_pop($contextids2);
2360 return array($contextids, $contextpaths);
2364 * Check if context is the front page context or a context inside it
2366 * Returns true if this context is the front page context, or a context inside it,
2369 * @param context $context a context object.
2372 function is_inside_frontpage(context
$context) {
2373 $frontpagecontext = context_course
::instance(SITEID
);
2374 return strpos($context->path
. '/', $frontpagecontext->path
. '/') === 0;
2378 * Returns capability information (cached)
2380 * @param string $capabilityname
2381 * @return stdClass or null if capability not found
2383 function get_capability_info($capabilityname) {
2384 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2386 $caps = get_all_capabilities();
2388 if (!isset($caps[$capabilityname])) {
2392 return (object) $caps[$capabilityname];
2396 * Returns all capabilitiy records, preferably from MUC and not database.
2398 * @return array All capability records indexed by capability name
2400 function get_all_capabilities() {
2402 $cache = cache
::make('core', 'capabilities');
2403 if (!$allcaps = $cache->get('core_capabilities')) {
2404 $rs = $DB->get_recordset('capabilities');
2406 foreach ($rs as $capability) {
2407 $capability->riskbitmask
= (int) $capability->riskbitmask
;
2408 $allcaps[$capability->name
] = (array) $capability;
2411 $cache->set('core_capabilities', $allcaps);
2417 * Returns the human-readable, translated version of the capability.
2418 * Basically a big switch statement.
2420 * @param string $capabilityname e.g. mod/choice:readresponses
2423 function get_capability_string($capabilityname) {
2425 // Typical capability name is 'plugintype/pluginname:capabilityname'
2426 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2428 if ($type === 'moodle') {
2429 $component = 'core_role';
2430 } else if ($type === 'quizreport') {
2432 $component = 'quiz_'.$name;
2434 $component = $type.'_'.$name;
2437 $stringname = $name.':'.$capname;
2439 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2440 return get_string($stringname, $component);
2443 $dir = core_component
::get_component_directory($component);
2444 if (!file_exists($dir)) {
2445 // plugin broken or does not exist, do not bother with printing of debug message
2446 return $capabilityname.' ???';
2449 // something is wrong in plugin, better print debug
2450 return get_string($stringname, $component);
2454 * This gets the mod/block/course/core etc strings.
2456 * @param string $component
2457 * @param int $contextlevel
2458 * @return string|bool String is success, false if failed
2460 function get_component_string($component, $contextlevel) {
2462 if ($component === 'moodle' or $component === 'core') {
2463 switch ($contextlevel) {
2464 // TODO MDL-46123: this should probably use context level names instead
2465 case CONTEXT_SYSTEM
: return get_string('coresystem');
2466 case CONTEXT_USER
: return get_string('users');
2467 case CONTEXT_COURSECAT
: return get_string('categories');
2468 case CONTEXT_COURSE
: return get_string('course');
2469 case CONTEXT_MODULE
: return get_string('activities');
2470 case CONTEXT_BLOCK
: return get_string('block');
2471 default: print_error('unknowncontext');
2475 list($type, $name) = core_component
::normalize_component($component);
2476 $dir = core_component
::get_plugin_directory($type, $name);
2477 if (!file_exists($dir)) {
2478 // plugin not installed, bad luck, there is no way to find the name
2479 return $component.' ???';
2483 // TODO MDL-46123: this is really hacky and should be improved.
2484 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2485 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2486 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2487 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2488 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2489 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2490 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2492 if (get_string_manager()->string_exists('pluginname', $component)) {
2493 return get_string('activity').': '.get_string('pluginname', $component);
2495 return get_string('activity').': '.get_string('modulename', $component);
2497 default: return get_string('pluginname', $component);
2502 * Gets the list of roles assigned to this context and up (parents)
2503 * from the aggregation of:
2504 * a) the list of roles that are visible on user profile page and participants page (profileroles setting) and;
2505 * b) if applicable, those roles that are assigned in the context.
2507 * @param context $context
2510 function get_profile_roles(context
$context) {
2512 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2513 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2514 if (has_capability('moodle/role:assign', $context)) {
2515 $rolesinscope = array_keys(get_all_roles($context));
2517 $rolesinscope = empty($CFG->profileroles
) ?
[] : array_map('trim', explode(',', $CFG->profileroles
));
2520 if (empty($rolesinscope)) {
2524 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED
, 'a');
2525 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'p');
2526 $params = array_merge($params, $cparams);
2528 if ($coursecontext = $context->get_course_context(false)) {
2529 $params['coursecontext'] = $coursecontext->id
;
2531 $params['coursecontext'] = 0;
2534 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2535 FROM {role_assignments} ra, {role} r
2536 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2537 WHERE r.id = ra.roleid
2538 AND ra.contextid $contextlist
2540 ORDER BY r.sortorder ASC";
2542 return $DB->get_records_sql($sql, $params);
2546 * Gets the list of roles assigned to this context and up (parents)
2548 * @param context $context
2549 * @param boolean $includeparents, false means without parents.
2552 function get_roles_used_in_context(context
$context, $includeparents = true) {
2555 if ($includeparents === true) {
2556 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'cl');
2558 list($contextlist, $params) = $DB->get_in_or_equal($context->id
, SQL_PARAMS_NAMED
, 'cl');
2561 if ($coursecontext = $context->get_course_context(false)) {
2562 $params['coursecontext'] = $coursecontext->id
;
2564 $params['coursecontext'] = 0;
2567 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2568 FROM {role_assignments} ra, {role} r
2569 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2570 WHERE r.id = ra.roleid
2571 AND ra.contextid $contextlist
2572 ORDER BY r.sortorder ASC";
2574 return $DB->get_records_sql($sql, $params);
2578 * This function is used to print roles column in user profile page.
2579 * It is using the CFG->profileroles to limit the list to only interesting roles.
2580 * (The permission tab has full details of user role assignments.)
2582 * @param int $userid
2583 * @param int $courseid
2586 function get_user_roles_in_course($userid, $courseid) {
2588 if ($courseid == SITEID
) {
2589 $context = context_system
::instance();
2591 $context = context_course
::instance($courseid);
2593 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2594 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2595 if (has_capability('moodle/role:assign', $context)) {
2596 $rolesinscope = array_keys(get_all_roles($context));
2598 $rolesinscope = empty($CFG->profileroles
) ?
[] : array_map('trim', explode(',', $CFG->profileroles
));
2600 if (empty($rolesinscope)) {
2604 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED
, 'a');
2605 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'p');
2606 $params = array_merge($params, $cparams);
2608 if ($coursecontext = $context->get_course_context(false)) {
2609 $params['coursecontext'] = $coursecontext->id
;
2611 $params['coursecontext'] = 0;
2614 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2615 FROM {role_assignments} ra, {role} r
2616 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2617 WHERE r.id = ra.roleid
2618 AND ra.contextid $contextlist
2620 AND ra.userid = :userid
2621 ORDER BY r.sortorder ASC";
2622 $params['userid'] = $userid;
2626 if ($roles = $DB->get_records_sql($sql, $params)) {
2627 $viewableroles = get_viewable_roles($context, $userid);
2629 $rolenames = array();
2630 foreach ($roles as $roleid => $unused) {
2631 if (isset($viewableroles[$roleid])) {
2632 $url = new moodle_url('/user/index.php', ['contextid' => $context->id
, 'roleid' => $roleid]);
2633 $rolenames[] = '<a href="' . $url . '">' . $viewableroles[$roleid] . '</a>';
2636 $rolestring = implode(',', $rolenames);
2643 * Checks if a user can assign users to a particular role in this context
2645 * @param context $context
2646 * @param int $targetroleid - the id of the role you want to assign users to
2649 function user_can_assign(context
$context, $targetroleid) {
2652 // First check to see if the user is a site administrator.
2653 if (is_siteadmin()) {
2657 // Check if user has override capability.
2658 // If not return false.
2659 if (!has_capability('moodle/role:assign', $context)) {
2662 // pull out all active roles of this user from this context(or above)
2663 if ($userroles = get_user_roles($context)) {
2664 foreach ($userroles as $userrole) {
2665 // if any in the role_allow_override table, then it's ok
2666 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid
, 'allowassign'=>$targetroleid))) {
2676 * Returns all site roles in correct sort order.
2678 * Note: this method does not localise role names or descriptions,
2679 * use role_get_names() if you need role names.
2681 * @param context $context optional context for course role name aliases
2682 * @return array of role records with optional coursealias property
2684 function get_all_roles(context
$context = null) {
2687 if (!$context or !$coursecontext = $context->get_course_context(false)) {
2688 $coursecontext = null;
2691 if ($coursecontext) {
2692 $sql = "SELECT r.*, rn.name AS coursealias
2694 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2695 ORDER BY r.sortorder ASC";
2696 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id
));
2699 return $DB->get_records('role', array(), 'sortorder ASC');
2704 * Returns roles of a specified archetype
2706 * @param string $archetype
2707 * @return array of full role records
2709 function get_archetype_roles($archetype) {
2711 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2715 * Gets all the user roles assigned in this context, or higher contexts for a list of users.
2717 * If you try using the combination $userids = [], $checkparentcontexts = true then this is likely
2718 * to cause an out-of-memory error on large Moodle sites, so this combination is deprecated and
2719 * outputs a warning, even though it is the default.
2721 * @param context $context
2722 * @param array $userids. An empty list means fetch all role assignments for the context.
2723 * @param bool $checkparentcontexts defaults to true
2724 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2727 function get_users_roles(context
$context, $userids = [], $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2730 if (!$userids && $checkparentcontexts) {
2731 debugging('Please do not call get_users_roles() with $checkparentcontexts = true ' .
2732 'and $userids array not set. This combination causes large Moodle sites ' .
2733 'with lots of site-wide role assignemnts to run out of memory.', DEBUG_DEVELOPER
);
2736 if ($checkparentcontexts) {
2737 $contextids = $context->get_parent_context_ids();
2739 $contextids = array();
2741 $contextids[] = $context->id
;
2743 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED
, 'con');
2745 // If userids was passed as an empty array, we fetch all role assignments for the course.
2746 if (empty($userids)) {
2747 $useridlist = ' IS NOT NULL ';
2750 list($useridlist, $uparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED
, 'uids');
2753 $sql = "SELECT ra.*, r.name, r.shortname, ra.userid
2754 FROM {role_assignments} ra, {role} r, {context} c
2755 WHERE ra.userid $useridlist
2756 AND ra.roleid = r.id
2757 AND ra.contextid = c.id
2758 AND ra.contextid $contextids
2761 $all = $DB->get_records_sql($sql , array_merge($params, $uparams));
2763 // Return results grouped by userid.
2765 foreach ($all as $id => $record) {
2766 if (!isset($result[$record->userid
])) {
2767 $result[$record->userid
] = [];
2769 $result[$record->userid
][$record->id
] = $record;
2772 // Make sure all requested users are included in the result, even if they had no role assignments.
2773 foreach ($userids as $id) {
2774 if (!isset($result[$id])) {
2784 * Gets all the user roles assigned in this context, or higher contexts
2785 * this is mainly used when checking if a user can assign a role, or overriding a role
2786 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2787 * allow_override tables
2789 * @param context $context
2790 * @param int $userid
2791 * @param bool $checkparentcontexts defaults to true
2792 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2795 function get_user_roles(context
$context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2798 if (empty($userid)) {
2799 if (empty($USER->id
)) {
2802 $userid = $USER->id
;
2805 if ($checkparentcontexts) {
2806 $contextids = $context->get_parent_context_ids();
2808 $contextids = array();
2810 $contextids[] = $context->id
;
2812 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM
);
2814 array_unshift($params, $userid);
2816 $sql = "SELECT ra.*, r.name, r.shortname
2817 FROM {role_assignments} ra, {role} r, {context} c
2819 AND ra.roleid = r.id
2820 AND ra.contextid = c.id
2821 AND ra.contextid $contextids
2824 return $DB->get_records_sql($sql ,$params);
2828 * Like get_user_roles, but adds in the authenticated user role, and the front
2829 * page roles, if applicable.
2831 * @param context $context the context.
2832 * @param int $userid optional. Defaults to $USER->id
2833 * @return array of objects with fields ->userid, ->contextid and ->roleid.
2835 function get_user_roles_with_special(context
$context, $userid = 0) {
2838 if (empty($userid)) {
2839 if (empty($USER->id
)) {
2842 $userid = $USER->id
;
2845 $ras = get_user_roles($context, $userid);
2847 // Add front-page role if relevant.
2848 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid
) ?
$CFG->defaultfrontpageroleid
: 0;
2849 $isfrontpage = ($context->contextlevel
== CONTEXT_COURSE
&& $context->instanceid
== SITEID
) ||
2850 is_inside_frontpage($context);
2851 if ($defaultfrontpageroleid && $isfrontpage) {
2852 $frontpagecontext = context_course
::instance(SITEID
);
2853 $ra = new stdClass();
2854 $ra->userid
= $userid;
2855 $ra->contextid
= $frontpagecontext->id
;
2856 $ra->roleid
= $defaultfrontpageroleid;
2860 // Add authenticated user role if relevant.
2861 $defaultuserroleid = isset($CFG->defaultuserroleid
) ?
$CFG->defaultuserroleid
: 0;
2862 if ($defaultuserroleid && !isguestuser($userid)) {
2863 $systemcontext = context_system
::instance();
2864 $ra = new stdClass();
2865 $ra->userid
= $userid;
2866 $ra->contextid
= $systemcontext->id
;
2867 $ra->roleid
= $defaultuserroleid;
2875 * Creates a record in the role_allow_override table
2877 * @param int $fromroleid source roleid
2878 * @param int $targetroleid target roleid
2881 function core_role_set_override_allowed($fromroleid, $targetroleid) {
2884 $record = new stdClass();
2885 $record->roleid
= $fromroleid;
2886 $record->allowoverride
= $targetroleid;
2887 $DB->insert_record('role_allow_override', $record);
2891 * Creates a record in the role_allow_assign table
2893 * @param int $fromroleid source roleid
2894 * @param int $targetroleid target roleid
2897 function core_role_set_assign_allowed($fromroleid, $targetroleid) {
2900 $record = new stdClass();
2901 $record->roleid
= $fromroleid;
2902 $record->allowassign
= $targetroleid;
2903 $DB->insert_record('role_allow_assign', $record);
2907 * Creates a record in the role_allow_switch table
2909 * @param int $fromroleid source roleid
2910 * @param int $targetroleid target roleid
2913 function core_role_set_switch_allowed($fromroleid, $targetroleid) {
2916 $record = new stdClass();
2917 $record->roleid
= $fromroleid;
2918 $record->allowswitch
= $targetroleid;
2919 $DB->insert_record('role_allow_switch', $record);
2923 * Creates a record in the role_allow_view table
2925 * @param int $fromroleid source roleid
2926 * @param int $targetroleid target roleid
2929 function core_role_set_view_allowed($fromroleid, $targetroleid) {
2932 $record = new stdClass();
2933 $record->roleid
= $fromroleid;
2934 $record->allowview
= $targetroleid;
2935 $DB->insert_record('role_allow_view', $record);
2939 * Gets a list of roles that this user can assign in this context
2941 * @param context $context the context.
2942 * @param int $rolenamedisplay the type of role name to display. One of the
2943 * ROLENAME_X constants. Default ROLENAME_ALIAS.
2944 * @param bool $withusercounts if true, count the number of users with each role.
2945 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
2946 * @return array if $withusercounts is false, then an array $roleid => $rolename.
2947 * if $withusercounts is true, returns a list of three arrays,
2948 * $rolenames, $rolecounts, and $nameswithcounts.
2950 function get_assignable_roles(context
$context, $rolenamedisplay = ROLENAME_ALIAS
, $withusercounts = false, $user = null) {
2953 // make sure there is a real user specified
2954 if ($user === null) {
2955 $userid = isset($USER->id
) ?
$USER->id
: 0;
2957 $userid = is_object($user) ?
$user->id
: $user;
2960 if (!has_capability('moodle/role:assign', $context, $userid)) {
2961 if ($withusercounts) {
2962 return array(array(), array(), array());
2971 if ($withusercounts) {
2972 $extrafields = ', (SELECT count(u.id)
2973 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
2974 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
2976 $params['conid'] = $context->id
;
2979 if (is_siteadmin($userid)) {
2980 // show all roles allowed in this context to admins
2981 $assignrestriction = "";
2983 $parents = $context->get_parent_context_ids(true);
2984 $contexts = implode(',' , $parents);
2985 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
2986 FROM {role_allow_assign} raa
2987 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
2988 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
2989 ) ar ON ar.id = r.id";
2990 $params['userid'] = $userid;
2992 $params['contextlevel'] = $context->contextlevel
;
2994 if ($coursecontext = $context->get_course_context(false)) {
2995 $params['coursecontext'] = $coursecontext->id
;
2997 $params['coursecontext'] = 0; // no course aliases
2998 $coursecontext = null;
3000 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3003 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3004 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3005 ORDER BY r.sortorder ASC";
3006 $roles = $DB->get_records_sql($sql, $params);
3008 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3010 if (!$withusercounts) {
3014 $rolecounts = array();
3015 $nameswithcounts = array();
3016 foreach ($roles as $role) {
3017 $nameswithcounts[$role->id
] = $rolenames[$role->id
] . ' (' . $roles[$role->id
]->usercount
. ')';
3018 $rolecounts[$role->id
] = $roles[$role->id
]->usercount
;
3020 return array($rolenames, $rolecounts, $nameswithcounts);
3024 * Gets a list of roles that this user can switch to in a context
3026 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3027 * This function just process the contents of the role_allow_switch table. You also need to
3028 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3030 * @param context $context a context.
3031 * @return array an array $roleid => $rolename.
3033 function get_switchable_roles(context
$context) {
3036 // You can't switch roles without this capability.
3037 if (!has_capability('moodle/role:switchroles', $context)) {
3044 if (!is_siteadmin()) {
3045 // Admins are allowed to switch to any role with.
3046 // Others are subject to the additional constraint that the switch-to role must be allowed by
3047 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3048 $parents = $context->get_parent_context_ids(true);
3049 $contexts = implode(',' , $parents);
3051 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3052 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3053 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3054 $params['userid'] = $USER->id
;
3057 if ($coursecontext = $context->get_course_context(false)) {
3058 $params['coursecontext'] = $coursecontext->id
;
3060 $params['coursecontext'] = 0; // no course aliases
3061 $coursecontext = null;
3065 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3066 FROM (SELECT DISTINCT rc.roleid
3067 FROM {role_capabilities} rc
3070 JOIN {role} r ON r.id = idlist.roleid
3071 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3072 ORDER BY r.sortorder";
3073 $roles = $DB->get_records_sql($query, $params);
3075 return role_fix_names($roles, $context, ROLENAME_ALIAS
, true);
3079 * Gets a list of roles that this user can view in a context
3081 * @param context $context a context.
3082 * @param int $userid id of user.
3083 * @return array an array $roleid => $rolename.
3085 function get_viewable_roles(context
$context, $userid = null) {
3088 if ($userid == null) {
3089 $userid = $USER->id
;
3095 if (!is_siteadmin()) {
3096 // Admins are allowed to view any role.
3097 // Others are subject to the additional constraint that the view role must be allowed by
3098 // 'role_allow_view' for some role they have assigned in this context or any parent.
3099 $contexts = $context->get_parent_context_ids(true);
3100 list($insql, $inparams) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED
);
3102 $extrajoins = "JOIN {role_allow_view} ras ON ras.allowview = r.id
3103 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3104 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid $insql";
3106 $params +
= $inparams;
3107 $params['userid'] = $userid;
3110 if ($coursecontext = $context->get_course_context(false)) {
3111 $params['coursecontext'] = $coursecontext->id
;
3113 $params['coursecontext'] = 0; // No course aliases.
3114 $coursecontext = null;
3118 SELECT r.id, r.name, r.shortname, rn.name AS coursealias, r.sortorder
3121 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3123 GROUP BY r.id, r.name, r.shortname, rn.name, r.sortorder
3124 ORDER BY r.sortorder";
3125 $roles = $DB->get_records_sql($query, $params);
3127 return role_fix_names($roles, $context, ROLENAME_ALIAS
, true);
3131 * Gets a list of roles that this user can override in this context.
3133 * @param context $context the context.
3134 * @param int $rolenamedisplay the type of role name to display. One of the
3135 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3136 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3137 * @return array if $withcounts is false, then an array $roleid => $rolename.
3138 * if $withusercounts is true, returns a list of three arrays,
3139 * $rolenames, $rolecounts, and $nameswithcounts.
3141 function get_overridable_roles(context
$context, $rolenamedisplay = ROLENAME_ALIAS
, $withcounts = false) {
3144 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3146 return array(array(), array(), array());
3152 $parents = $context->get_parent_context_ids(true);
3153 $contexts = implode(',' , $parents);
3158 $params['userid'] = $USER->id
;
3160 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3161 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3162 $params['conid'] = $context->id
;
3165 if ($coursecontext = $context->get_course_context(false)) {
3166 $params['coursecontext'] = $coursecontext->id
;
3168 $params['coursecontext'] = 0; // no course aliases
3169 $coursecontext = null;
3172 if (is_siteadmin()) {
3173 // show all roles to admins
3174 $roles = $DB->get_records_sql("
3175 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3177 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3178 ORDER BY ro.sortorder ASC", $params);
3181 $roles = $DB->get_records_sql("
3182 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3184 JOIN (SELECT DISTINCT r.id
3186 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3187 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3188 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3189 ) inline_view ON ro.id = inline_view.id
3190 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3191 ORDER BY ro.sortorder ASC", $params);
3194 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3200 $rolecounts = array();
3201 $nameswithcounts = array();
3202 foreach ($roles as $role) {
3203 $nameswithcounts[$role->id
] = $rolenames[$role->id
] . ' (' . $roles[$role->id
]->overridecount
. ')';
3204 $rolecounts[$role->id
] = $roles[$role->id
]->overridecount
;
3206 return array($rolenames, $rolecounts, $nameswithcounts);
3210 * Create a role menu suitable for default role selection in enrol plugins.
3212 * @package core_enrol
3214 * @param context $context
3215 * @param int $addroleid current or default role - always added to list
3216 * @return array roleid=>localised role name
3218 function get_default_enrol_roles(context
$context, $addroleid = null) {
3221 $params = array('contextlevel'=>CONTEXT_COURSE
);
3223 if ($coursecontext = $context->get_course_context(false)) {
3224 $params['coursecontext'] = $coursecontext->id
;
3226 $params['coursecontext'] = 0; // no course names
3227 $coursecontext = null;
3231 $addrole = "OR r.id = :addroleid";
3232 $params['addroleid'] = $addroleid;
3237 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3239 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3240 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3241 WHERE rcl.id IS NOT NULL $addrole
3242 ORDER BY sortorder DESC";
3244 $roles = $DB->get_records_sql($sql, $params);
3246 return role_fix_names($roles, $context, ROLENAME_BOTH
, true);
3250 * Return context levels where this role is assignable.
3252 * @param integer $roleid the id of a role.
3253 * @return array list of the context levels at which this role may be assigned.
3255 function get_role_contextlevels($roleid) {
3257 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3258 'contextlevel', 'id,contextlevel');
3262 * Return roles suitable for assignment at the specified context level.
3264 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3266 * @param integer $contextlevel a contextlevel.
3267 * @return array list of role ids that are assignable at this context level.
3269 function get_roles_for_contextlevels($contextlevel) {
3271 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3276 * Returns default context levels where roles can be assigned.
3278 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3279 * from the array returned by get_role_archetypes();
3280 * @return array list of the context levels at which this type of role may be assigned by default.
3282 function get_default_contextlevels($rolearchetype) {
3283 static $defaults = array(
3284 'manager' => array(CONTEXT_SYSTEM
, CONTEXT_COURSECAT
, CONTEXT_COURSE
),
3285 'coursecreator' => array(CONTEXT_SYSTEM
, CONTEXT_COURSECAT
),
3286 'editingteacher' => array(CONTEXT_COURSE
, CONTEXT_MODULE
),
3287 'teacher' => array(CONTEXT_COURSE
, CONTEXT_MODULE
),
3288 'student' => array(CONTEXT_COURSE
, CONTEXT_MODULE
),
3291 'frontpage' => array());
3293 if (isset($defaults[$rolearchetype])) {
3294 return $defaults[$rolearchetype];
3301 * Set the context levels at which a particular role can be assigned.
3302 * Throws exceptions in case of error.
3304 * @param integer $roleid the id of a role.
3305 * @param array $contextlevels the context levels at which this role should be assignable,
3306 * duplicate levels are removed.
3309 function set_role_contextlevels($roleid, array $contextlevels) {
3311 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3312 $rcl = new stdClass();
3313 $rcl->roleid
= $roleid;
3314 $contextlevels = array_unique($contextlevels);
3315 foreach ($contextlevels as $level) {
3316 $rcl->contextlevel
= $level;
3317 $DB->insert_record('role_context_levels', $rcl, false, true);
3322 * Who has this capability in this context?
3324 * This can be a very expensive call - use sparingly and keep
3325 * the results if you are going to need them again soon.
3327 * Note if $fields is empty this function attempts to get u.*
3328 * which can get rather large - and has a serious perf impact
3331 * @param context $context
3332 * @param string|array $capability - capability name(s)
3333 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3334 * @param string $sort - the sort order. Default is lastaccess time.
3335 * @param mixed $limitfrom - number of records to skip (offset)
3336 * @param mixed $limitnum - number of records to fetch
3337 * @param string|array $groups - single group or array of groups - only return
3338 * users who are in one of these group(s).
3339 * @param string|array $exceptions - list of users to exclude, comma separated or array
3340 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3341 * @param bool $view_ignored - use get_enrolled_sql() instead
3342 * @param bool $useviewallgroups if $groups is set the return users who
3343 * have capability both $capability and moodle/site:accessallgroups
3344 * in this context, as well as users who have $capability and who are
3346 * @return array of user records
3348 function get_users_by_capability(context
$context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3349 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3352 $defaultuserroleid = isset($CFG->defaultuserroleid
) ?
$CFG->defaultuserroleid
: 0;
3353 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid
) ?
$CFG->defaultfrontpageroleid
: 0;
3355 $ctxids = trim($context->path
, '/');
3356 $ctxids = str_replace('/', ',', $ctxids);
3358 // Context is the frontpage
3359 $iscoursepage = false; // coursepage other than fp
3360 $isfrontpage = false;
3361 if ($context->contextlevel
== CONTEXT_COURSE
) {
3362 if ($context->instanceid
== SITEID
) {
3363 $isfrontpage = true;
3365 $iscoursepage = true;
3368 $isfrontpage = ($isfrontpage ||
is_inside_frontpage($context));
3370 $caps = (array)$capability;
3372 // construct list of context paths bottom-->top
3373 list($contextids, $paths) = get_context_info_list($context);
3375 // we need to find out all roles that have these capabilities either in definition or in overrides
3377 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED
, 'con');
3378 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED
, 'cap');
3379 $params = array_merge($params, $params2);
3380 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3381 FROM {role_capabilities} rc
3382 JOIN {context} ctx on rc.contextid = ctx.id
3383 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3385 $rcs = $DB->get_records_sql($sql, $params);
3386 foreach ($rcs as $rc) {
3387 $defs[$rc->capability
][$rc->path
][$rc->roleid
] = $rc->permission
;
3390 // go through the permissions bottom-->top direction to evaluate the current permission,
3391 // first one wins (prohibit is an exception that always wins)
3393 foreach ($caps as $cap) {
3394 foreach ($paths as $path) {
3395 if (empty($defs[$cap][$path])) {
3398 foreach($defs[$cap][$path] as $roleid => $perm) {
3399 if ($perm == CAP_PROHIBIT
) {
3400 $access[$cap][$roleid] = CAP_PROHIBIT
;
3403 if (!isset($access[$cap][$roleid])) {
3404 $access[$cap][$roleid] = (int)$perm;
3410 // make lists of roles that are needed and prohibited in this context
3411 $needed = array(); // one of these is enough
3412 $prohibited = array(); // must not have any of these
3413 foreach ($caps as $cap) {
3414 if (empty($access[$cap])) {
3417 foreach ($access[$cap] as $roleid => $perm) {
3418 if ($perm == CAP_PROHIBIT
) {
3419 unset($needed[$cap][$roleid]);
3420 $prohibited[$cap][$roleid] = true;
3421 } else if ($perm == CAP_ALLOW
and empty($prohibited[$cap][$roleid])) {
3422 $needed[$cap][$roleid] = true;
3425 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3426 // easy, nobody has the permission
3427 unset($needed[$cap]);
3428 unset($prohibited[$cap]);
3429 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3430 // everybody is disqualified on the frontpage
3431 unset($needed[$cap]);
3432 unset($prohibited[$cap]);
3434 if (empty($prohibited[$cap])) {
3435 unset($prohibited[$cap]);
3439 if (empty($needed)) {
3440 // there can not be anybody if no roles match this request
3444 if (empty($prohibited)) {
3445 // we can compact the needed roles
3447 foreach ($needed as $cap) {
3448 foreach ($cap as $roleid=>$unused) {
3452 $needed = array('any'=>$n);
3456 // ***** Set up default fields ******
3457 if (empty($fields)) {
3458 if ($iscoursepage) {
3459 $fields = 'u.*, ul.timeaccess AS lastaccess';
3464 if ($CFG->debugdeveloper
&& strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3465 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER
);
3469 // Set up default sort
3470 if (empty($sort)) { // default to course lastaccess or just lastaccess
3471 if ($iscoursepage) {
3472 $sort = 'ul.timeaccess';
3474 $sort = 'u.lastaccess';
3478 // Prepare query clauses
3479 $wherecond = array();
3483 // User lastaccess JOIN
3484 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3485 // user_lastaccess is not required MDL-13810
3487 if ($iscoursepage) {
3488 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3490 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3494 // We never return deleted users or guest account.
3495 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3496 $params['guestid'] = $CFG->siteguest
;
3500 $groups = (array)$groups;
3501 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED
, 'grp');
3502 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3503 $params = array_merge($params, $grpparams);
3505 if ($useviewallgroups) {
3506 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3507 if (!empty($viewallgroupsusers)) {
3508 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3510 $wherecond[] = "($grouptest)";
3513 $wherecond[] = "($grouptest)";
3518 if (!empty($exceptions)) {
3519 $exceptions = (array)$exceptions;
3520 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED
, 'exc', false);
3521 $params = array_merge($params, $exparams);
3522 $wherecond[] = "u.id $exsql";
3525 // now add the needed and prohibited roles conditions as joins
3526 if (!empty($needed['any'])) {
3527 // simple case - there are no prohibits involved
3528 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3531 $joins[] = "JOIN (SELECT DISTINCT userid
3532 FROM {role_assignments}
3533 WHERE contextid IN ($ctxids)
3534 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3535 ) ra ON ra.userid = u.id";
3540 foreach ($needed as $cap=>$unused) {
3541 if (empty($prohibited[$cap])) {
3542 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3546 $unions[] = "SELECT userid
3547 FROM {role_assignments}
3548 WHERE contextid IN ($ctxids)
3549 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3552 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3553 // nobody can have this cap because it is prevented in default roles
3556 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3557 // everybody except the prohibitted - hiding does not matter
3558 $unions[] = "SELECT id AS userid
3560 WHERE id NOT IN (SELECT userid
3561 FROM {role_assignments}
3562 WHERE contextid IN ($ctxids)
3563 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3566 $unions[] = "SELECT userid
3567 FROM {role_assignments}
3568 WHERE contextid IN ($ctxids) AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3571 FROM {role_assignments}
3572 WHERE contextid IN ($ctxids)
3573 AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . ")
3580 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3582 // only prohibits found - nobody can be matched
3583 $wherecond[] = "1 = 2";
3588 // Collect WHERE conditions and needed joins
3589 $where = implode(' AND ', $wherecond);
3590 if ($where !== '') {
3591 $where = 'WHERE ' . $where;
3593 $joins = implode("\n", $joins);
3595 // Ok, let's get the users!
3596 $sql = "SELECT $fields
3602 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3606 * Re-sort a users array based on a sorting policy
3608 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3609 * based on a sorting policy. This is to support the odd practice of
3610 * sorting teachers by 'authority', where authority was "lowest id of the role
3613 * Will execute 1 database query. Only suitable for small numbers of users, as it
3614 * uses an u.id IN() clause.
3616 * Notes about the sorting criteria.
3618 * As a default, we cannot rely on role.sortorder because then
3619 * admins/coursecreators will always win. That is why the sane
3620 * rule "is locality matters most", with sortorder as 2nd
3623 * If you want role.sortorder, use the 'sortorder' policy, and
3624 * name explicitly what roles you want to cover. It's probably
3625 * a good idea to see what roles have the capabilities you want
3626 * (array_diff() them against roiles that have 'can-do-anything'
3627 * to weed out admin-ish roles. Or fetch a list of roles from
3628 * variables like $CFG->coursecontact .
3630 * @param array $users Users array, keyed on userid
3631 * @param context $context
3632 * @param array $roles ids of the roles to include, optional
3633 * @param string $sortpolicy defaults to locality, more about
3634 * @return array sorted copy of the array
3636 function sort_by_roleassignment_authority($users, context
$context, $roles = array(), $sortpolicy = 'locality') {
3639 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3640 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path
, 1)).')';
3641 if (empty($roles)) {
3644 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3647 $sql = "SELECT ra.userid
3648 FROM {role_assignments} ra
3652 ON ra.contextid=ctx.id
3657 // Default 'locality' policy -- read PHPDoc notes
3658 // about sort policies...
3659 $orderby = 'ORDER BY '
3660 .'ctx.depth DESC, ' /* locality wins */
3661 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3662 .'ra.id'; /* role assignment order tie-breaker */
3663 if ($sortpolicy === 'sortorder') {
3664 $orderby = 'ORDER BY '
3665 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3666 .'ra.id'; /* role assignment order tie-breaker */
3669 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3670 $sortedusers = array();
3673 foreach ($sortedids as $id) {
3675 if (isset($seen[$id])) {
3681 $sortedusers[$id] = $users[$id];
3683 return $sortedusers;
3687 * Gets all the users assigned this role in this context or higher
3689 * Note that moodle is based on capabilities and it is usually better
3690 * to check permissions than to check role ids as the capabilities
3691 * system is more flexible. If you really need, you can to use this
3692 * function but consider has_capability() as a possible substitute.
3694 * All $sort fields are added into $fields if not present there yet.
3696 * If $roleid is an array or is empty (all roles) you need to set $fields
3697 * (and $sort by extension) params according to it, as the first field
3698 * returned by the database should be unique (ra.id is the best candidate).
3700 * @param int $roleid (can also be an array of ints!)
3701 * @param context $context
3702 * @param bool $parent if true, get list of users assigned in higher context too
3703 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3704 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3705 * null => use default sort from users_order_by_sql.
3706 * @param bool $all true means all, false means limit to enrolled users
3707 * @param string $group defaults to ''
3708 * @param mixed $limitfrom defaults to ''
3709 * @param mixed $limitnum defaults to ''
3710 * @param string $extrawheretest defaults to ''
3711 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3714 function get_role_users($roleid, context
$context, $parent = false, $fields = '',
3715 $sort = null, $all = true, $group = '',
3716 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3719 if (empty($fields)) {
3720 $allnames = get_all_user_name_fields(true, 'u');
3721 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
3722 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3723 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3724 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3725 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3728 // Prevent wrong function uses.
3729 if ((empty($roleid) ||
is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
3730 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
3731 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
3733 if (!empty($roleid)) {
3734 // Solving partially the issue when specifying multiple roles.
3736 foreach ($roleid as $id) {
3737 // Ignoring duplicated keys keeping the first user appearance.
3738 $users = $users +
get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
3739 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
3745 $parentcontexts = '';
3747 $parentcontexts = substr($context->path
, 1); // kill leading slash
3748 $parentcontexts = str_replace('/', ',', $parentcontexts);
3749 if ($parentcontexts !== '') {
3750 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3755 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED
, 'r');
3756 $roleselect = "AND ra.roleid $rids";
3762 if ($coursecontext = $context->get_course_context(false)) {
3763 $params['coursecontext'] = $coursecontext->id
;
3765 $params['coursecontext'] = 0;
3769 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3770 $groupselect = " AND gm.groupid = :groupid ";
3771 $params['groupid'] = $group;
3777 $params['contextid'] = $context->id
;
3779 if ($extrawheretest) {
3780 $extrawheretest = ' AND ' . $extrawheretest;
3783 if ($whereorsortparams) {
3784 $params = array_merge($params, $whereorsortparams);
3788 list($sort, $sortparams) = users_order_by_sql('u');
3789 $params = array_merge($params, $sortparams);
3792 // Adding the fields from $sort that are not present in $fields.
3793 $sortarray = preg_split('/,\s*/', $sort);
3794 $fieldsarray = preg_split('/,\s*/', $fields);
3796 // Discarding aliases from the fields.
3797 $fieldnames = array();
3798 foreach ($fieldsarray as $key => $field) {
3799 list($fieldnames[$key]) = explode(' ', $field);
3802 $addedfields = array();
3803 foreach ($sortarray as $sortfield) {
3804 // Throw away any additional arguments to the sort (e.g. ASC/DESC).
3805 list($sortfield) = explode(' ', $sortfield);
3806 list($tableprefix) = explode('.', $sortfield);
3807 $fieldpresent = false;
3808 foreach ($fieldnames as $fieldname) {
3809 if ($fieldname === $sortfield ||
$fieldname === $tableprefix.'.*') {
3810 $fieldpresent = true;
3815 if (!$fieldpresent) {
3816 $fieldsarray[] = $sortfield;
3817 $addedfields[] = $sortfield;
3821 $fields = implode(', ', $fieldsarray);
3822 if (!empty($addedfields)) {
3823 $addedfields = implode(', ', $addedfields);
3824 debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
3827 if ($all === null) {
3828 // Previously null was used to indicate that parameter was not used.
3831 if (!$all and $coursecontext) {
3832 // Do not use get_enrolled_sql() here for performance reasons.
3833 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
3834 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
3835 $params['ecourseid'] = $coursecontext->instanceid
;
3840 $sql = "SELECT DISTINCT $fields, ra.roleid
3841 FROM {role_assignments} ra
3842 JOIN {user} u ON u.id = ra.userid
3843 JOIN {role} r ON ra.roleid = r.id
3845 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3847 WHERE (ra.contextid = :contextid $parentcontexts)
3851 ORDER BY $sort"; // join now so that we can just use fullname() later
3853 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3857 * Counts all the users assigned this role in this context or higher
3859 * @param int|array $roleid either int or an array of ints
3860 * @param context $context
3861 * @param bool $parent if true, get list of users assigned in higher context too
3862 * @return int Returns the result count
3864 function count_role_users($roleid, context
$context, $parent = false) {
3868 if ($contexts = $context->get_parent_context_ids()) {
3869 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3871 $parentcontexts = '';
3874 $parentcontexts = '';
3878 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM
);
3879 $roleselect = "AND r.roleid $rids";
3885 array_unshift($params, $context->id
);
3887 $sql = "SELECT COUNT(DISTINCT u.id)
3888 FROM {role_assignments} r
3889 JOIN {user} u ON u.id = r.userid
3890 WHERE (r.contextid = ? $parentcontexts)
3894 return $DB->count_records_sql($sql, $params);
3898 * This function gets the list of courses that this user has a particular capability in.
3900 * It is now reasonably efficient, but bear in mind that if there are users who have the capability
3901 * everywhere, it may return an array of all courses.
3903 * @param string $capability Capability in question
3904 * @param int $userid User ID or null for current user
3905 * @param bool $doanything True if 'doanything' is permitted (default)
3906 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3907 * otherwise use a comma-separated list of the fields you require, not including id.
3908 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
3909 * @param string $orderby If set, use a comma-separated list of fields from course
3910 * table with sql modifiers (DESC) if needed
3911 * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
3912 * @return array|bool Array of courses, if none found false is returned.
3914 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '',
3918 // Default to current user.
3920 $userid = $USER->id
;
3923 if ($doanything && is_siteadmin($userid)) {
3924 // If the user is a site admin and $doanything is enabled then there is no need to restrict
3925 // the list of courses.
3926 $contextlimitsql = '';
3927 $contextlimitparams = [];
3929 // Gets SQL to limit contexts ('x' table) to those where the user has this capability.
3930 list ($contextlimitsql, $contextlimitparams) = \core\access\get_user_capability_course_helper
::get_sql(
3931 $userid, $capability);
3932 if (!$contextlimitsql) {
3933 // If the does not have this capability in any context, return false without querying.
3937 $contextlimitsql = 'WHERE' . $contextlimitsql;
3940 // Convert fields list and ordering
3942 if ($fieldsexceptid) {
3943 $fields = array_map('trim', explode(',', $fieldsexceptid));
3944 foreach($fields as $field) {
3945 // Context fields have a different alias.
3946 if (strpos($field, 'ctx') === 0) {
3949 $realfield = 'contextlevel';
3951 case 'ctxinstance' :
3952 $realfield = 'instanceid';
3955 $realfield = substr($field, 3);
3958 $fieldlist .= ',x.' . $realfield . ' AS ' . $field;
3960 $fieldlist .= ',c.'.$field;
3965 $fields = explode(',', $orderby);
3967 foreach($fields as $field) {
3971 $orderby .= 'c.'.$field;
3973 $orderby = 'ORDER BY '.$orderby;
3977 $rs = $DB->get_recordset_sql("
3978 SELECT c.id $fieldlist
3980 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
3982 $orderby", array_merge([CONTEXT_COURSE
], $contextlimitparams));
3983 foreach ($rs as $course) {
3984 $courses[] = $course;
3991 return empty($courses) ?
false : $courses;
3995 * Switches the current user to another role for the current session and only
3996 * in the given context.
3998 * The caller *must* check
3999 * - that this op is allowed
4000 * - that the requested role can be switched to in this context (use get_switchable_roles)
4001 * - that the requested role is NOT $CFG->defaultuserroleid
4003 * To "unswitch" pass 0 as the roleid.
4005 * This function *will* modify $USER->access - beware
4007 * @param integer $roleid the role to switch to.
4008 * @param context $context the context in which to perform the switch.
4009 * @return bool success or failure.
4011 function role_switch($roleid, context
$context) {
4014 // Add the ghost RA to $USER->access as $USER->access['rsw'][$path] = $roleid.
4015 // To un-switch just unset($USER->access['rsw'][$path]).
4017 // Note: it is not possible to switch to roles that do not have course:view
4019 if (!isset($USER->access
)) {
4020 load_all_capabilities();
4023 // Add the switch RA
4025 unset($USER->access
['rsw'][$context->path
]);
4029 $USER->access
['rsw'][$context->path
] = $roleid;
4035 * Checks if the user has switched roles within the given course.
4037 * Note: You can only switch roles within the course, hence it takes a course id
4038 * rather than a context. On that note Petr volunteered to implement this across
4039 * all other contexts, all requests for this should be forwarded to him ;)
4041 * @param int $courseid The id of the course to check
4042 * @return bool True if the user has switched roles within the course.
4044 function is_role_switched($courseid) {
4046 $context = context_course
::instance($courseid, MUST_EXIST
);
4047 return (!empty($USER->access
['rsw'][$context->path
]));
4051 * Get any role that has an override on exact context
4053 * @param context $context The context to check
4054 * @return array An array of roles
4056 function get_roles_with_override_on_context(context
$context) {
4059 return $DB->get_records_sql("SELECT r.*
4060 FROM {role_capabilities} rc, {role} r
4061 WHERE rc.roleid = r.id AND rc.contextid = ?",
4062 array($context->id
));
4066 * Get all capabilities for this role on this context (overrides)
4068 * @param stdClass $role
4069 * @param context $context
4072 function get_capabilities_from_role_on_context($role, context
$context) {
4075 return $DB->get_records_sql("SELECT *
4076 FROM {role_capabilities}
4077 WHERE contextid = ? AND roleid = ?",
4078 array($context->id
, $role->id
));
4082 * Find all user assignment of users for this role, on this context
4084 * @param stdClass $role
4085 * @param context $context
4088 function get_users_from_role_on_context($role, context
$context) {
4091 return $DB->get_records_sql("SELECT *
4092 FROM {role_assignments}
4093 WHERE contextid = ? AND roleid = ?",
4094 array($context->id
, $role->id
));
4098 * Simple function returning a boolean true if user has roles
4099 * in context or parent contexts, otherwise false.
4101 * @param int $userid
4102 * @param int $roleid
4103 * @param int $contextid empty means any context
4106 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4110 if (!$context = context
::instance_by_id($contextid, IGNORE_MISSING
)) {
4113 $parents = $context->get_parent_context_ids(true);
4114 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED
, 'r');
4115 $params['userid'] = $userid;
4116 $params['roleid'] = $roleid;
4118 $sql = "SELECT COUNT(ra.id)
4119 FROM {role_assignments} ra
4120 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4122 $count = $DB->get_field_sql($sql, $params);
4123 return ($count > 0);
4126 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4131 * Get localised role name or alias if exists and format the text.
4133 * @param stdClass $role role object
4134 * - optional 'coursealias' property should be included for performance reasons if course context used
4135 * - description property is not required here
4136 * @param context|bool $context empty means system context
4137 * @param int $rolenamedisplay type of role name
4138 * @return string localised role name or course role name alias
4140 function role_get_name(stdClass
$role, $context = null, $rolenamedisplay = ROLENAME_ALIAS
) {
4143 if ($rolenamedisplay == ROLENAME_SHORT
) {
4144 return $role->shortname
;
4147 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4148 $coursecontext = null;
4151 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS
or $rolenamedisplay == ROLENAME_BOTH
or $rolenamedisplay == ROLENAME_ALIAS_RAW
)) {
4152 $role = clone($role); // Do not modify parameters.
4153 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id
, 'contextid'=>$coursecontext->id
))) {
4154 $role->coursealias
= $r->name
;
4156 $role->coursealias
= null;
4160 if ($rolenamedisplay == ROLENAME_ALIAS_RAW
) {
4161 if ($coursecontext) {
4162 return $role->coursealias
;
4168 if (trim($role->name
) !== '') {
4169 // For filtering always use context where was the thing defined - system for roles here.
4170 $original = format_string($role->name
, true, array('context'=>context_system
::instance()));
4173 // Empty role->name means we want to see localised role name based on shortname,
4174 // only default roles are supposed to be localised.
4175 switch ($role->shortname
) {
4176 case 'manager': $original = get_string('manager', 'role'); break;
4177 case 'coursecreator': $original = get_string('coursecreators'); break;
4178 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4179 case 'teacher': $original = get_string('noneditingteacher'); break;
4180 case 'student': $original = get_string('defaultcoursestudent'); break;
4181 case 'guest': $original = get_string('guest'); break;
4182 case 'user': $original = get_string('authenticateduser'); break;
4183 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4184 // We should not get here, the role UI should require the name for custom roles!
4185 default: $original = $role->shortname
; break;
4189 if ($rolenamedisplay == ROLENAME_ORIGINAL
) {
4193 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT
) {
4194 return "$original ($role->shortname)";
4197 if ($rolenamedisplay == ROLENAME_ALIAS
) {
4198 if ($coursecontext and trim($role->coursealias
) !== '') {
4199 return format_string($role->coursealias
, true, array('context'=>$coursecontext));
4205 if ($rolenamedisplay == ROLENAME_BOTH
) {
4206 if ($coursecontext and trim($role->coursealias
) !== '') {
4207 return format_string($role->coursealias
, true, array('context'=>$coursecontext)) . " ($original)";
4213 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4217 * Returns localised role description if available.
4218 * If the name is empty it tries to find the default role name using
4219 * hardcoded list of default role names or other methods in the future.
4221 * @param stdClass $role
4222 * @return string localised role name
4224 function role_get_description(stdClass
$role) {
4225 if (!html_is_blank($role->description
)) {
4226 return format_text($role->description
, FORMAT_HTML
, array('context'=>context_system
::instance()));
4229 switch ($role->shortname
) {
4230 case 'manager': return get_string('managerdescription', 'role');
4231 case 'coursecreator': return get_string('coursecreatorsdescription');
4232 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4233 case 'teacher': return get_string('noneditingteacherdescription');
4234 case 'student': return get_string('defaultcoursestudentdescription');
4235 case 'guest': return get_string('guestdescription');
4236 case 'user': return get_string('authenticateduserdescription');
4237 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4243 * Get all the localised role names for a context.
4245 * In new installs default roles have empty names, this function
4246 * add localised role names using current language pack.
4248 * @param context $context the context, null means system context
4249 * @param array of role objects with a ->localname field containing the context-specific role name.
4250 * @param int $rolenamedisplay
4251 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4252 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4254 function role_get_names(context
$context = null, $rolenamedisplay = ROLENAME_ALIAS
, $returnmenu = null) {
4255 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4259 * Prepare list of roles for display, apply aliases and localise default role names.
4261 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4262 * @param context $context the context, null means system context
4263 * @param int $rolenamedisplay
4264 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4265 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4267 function role_fix_names($roleoptions, context
$context = null, $rolenamedisplay = ROLENAME_ALIAS
, $returnmenu = null) {
4270 if (empty($roleoptions)) {
4274 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4275 $coursecontext = null;
4278 // We usually need all role columns...
4279 $first = reset($roleoptions);
4280 if ($returnmenu === null) {
4281 $returnmenu = !is_object($first);
4284 if (!is_object($first) or !property_exists($first, 'shortname')) {
4285 $allroles = get_all_roles($context);
4286 foreach ($roleoptions as $rid => $unused) {
4287 $roleoptions[$rid] = $allroles[$rid];
4291 // Inject coursealias if necessary.
4292 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW
or $rolenamedisplay == ROLENAME_ALIAS
or $rolenamedisplay == ROLENAME_BOTH
)) {
4293 $first = reset($roleoptions);
4294 if (!property_exists($first, 'coursealias')) {
4295 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id
));
4296 foreach ($aliasnames as $alias) {
4297 if (isset($roleoptions[$alias->roleid
])) {
4298 $roleoptions[$alias->roleid
]->coursealias
= $alias->name
;
4304 // Add localname property.
4305 foreach ($roleoptions as $rid => $role) {
4306 $roleoptions[$rid]->localname
= role_get_name($role, $coursecontext, $rolenamedisplay);
4310 return $roleoptions;
4314 foreach ($roleoptions as $rid => $role) {
4315 $menu[$rid] = $role->localname
;
4322 * Aids in detecting if a new line is required when reading a new capability
4324 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4325 * when we read in a new capability.
4326 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4327 * but when we are in grade, all reports/import/export capabilities should be together
4329 * @param string $cap component string a
4330 * @param string $comp component string b
4331 * @param int $contextlevel
4332 * @return bool whether 2 component are in different "sections"
4334 function component_level_changed($cap, $comp, $contextlevel) {
4336 if (strstr($cap->component
, '/') && strstr($comp, '/')) {
4337 $compsa = explode('/', $cap->component
);
4338 $compsb = explode('/', $comp);
4340 // list of system reports
4341 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4345 // we are in gradebook, still
4346 if (($compsa[0] == 'gradeexport' ||
$compsa[0] == 'gradeimport' ||
$compsa[0] == 'gradereport') &&
4347 ($compsb[0] == 'gradeexport' ||
$compsb[0] == 'gradeimport' ||
$compsb[0] == 'gradereport')) {
4351 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4356 return ($cap->component
!= $comp ||
$cap->contextlevel
!= $contextlevel);
4360 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4361 * and return an array of roleids in order.
4363 * @param array $allroles array of roles, as returned by get_all_roles();
4364 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4366 function fix_role_sortorder($allroles) {
4369 $rolesort = array();
4371 foreach ($allroles as $role) {
4372 $rolesort[$i] = $role->id
;
4373 if ($role->sortorder
!= $i) {
4374 $r = new stdClass();
4377 $DB->update_record('role', $r);
4378 $allroles[$role->id
]->sortorder
= $i;
4386 * Switch the sort order of two roles (used in admin/roles/manage.php).
4388 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4389 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4390 * @return boolean success or failure
4392 function switch_roles($first, $second) {
4394 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4395 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder
));
4396 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder
, array('sortorder' => $second->sortorder
));
4397 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder
, array('sortorder' => $temp));
4402 * Duplicates all the base definitions of a role
4404 * @param stdClass $sourcerole role to copy from
4405 * @param int $targetrole id of role to copy to
4407 function role_cap_duplicate($sourcerole, $targetrole) {
4410 $systemcontext = context_system
::instance();
4411 $caps = $DB->get_records_sql("SELECT *
4412 FROM {role_capabilities}
4413 WHERE roleid = ? AND contextid = ?",
4414 array($sourcerole->id
, $systemcontext->id
));
4415 // adding capabilities
4416 foreach ($caps as $cap) {
4418 $cap->roleid
= $targetrole;
4419 $DB->insert_record('role_capabilities', $cap);
4422 // Reset any cache of this role, including MUC.
4423 accesslib_clear_role_cache($targetrole);
4427 * Returns two lists, this can be used to find out if user has capability.
4428 * Having any needed role and no forbidden role in this context means
4429 * user has this capability in this context.
4430 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4432 * @param stdClass $context
4433 * @param string $capability
4434 * @return array($neededroles, $forbiddenroles)
4436 function get_roles_with_cap_in_context($context, $capability) {
4439 $ctxids = trim($context->path
, '/'); // kill leading slash
4440 $ctxids = str_replace('/', ',', $ctxids);
4442 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4443 FROM {role_capabilities} rc
4444 JOIN {context} ctx ON ctx.id = rc.contextid
4445 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4446 ORDER BY rc.roleid ASC, ctx.depth DESC";
4447 $params = array('cap'=>$capability);
4449 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4450 // no cap definitions --> no capability
4451 return array(array(), array());
4454 $forbidden = array();
4456 foreach($capdefs as $def) {
4457 if (isset($forbidden[$def->roleid
])) {
4460 if ($def->permission
== CAP_PROHIBIT
) {
4461 $forbidden[$def->roleid
] = $def->roleid
;
4462 unset($needed[$def->roleid
]);
4465 if (!isset($needed[$def->roleid
])) {
4466 if ($def->permission
== CAP_ALLOW
) {
4467 $needed[$def->roleid
] = true;
4468 } else if ($def->permission
== CAP_PREVENT
) {
4469 $needed[$def->roleid
] = false;
4475 // remove all those roles not allowing
4476 foreach($needed as $key=>$value) {
4478 unset($needed[$key]);
4480 $needed[$key] = $key;
4484 return array($needed, $forbidden);
4488 * Returns an array of role IDs that have ALL of the the supplied capabilities
4489 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4491 * @param stdClass $context
4492 * @param array $capabilities An array of capabilities
4493 * @return array of roles with all of the required capabilities
4495 function get_roles_with_caps_in_context($context, $capabilities) {
4496 $neededarr = array();
4497 $forbiddenarr = array();
4498 foreach($capabilities as $caprequired) {
4499 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4502 $rolesthatcanrate = array();
4503 if (!empty($neededarr)) {
4504 foreach ($neededarr as $needed) {
4505 if (empty($rolesthatcanrate)) {
4506 $rolesthatcanrate = $needed;
4508 //only want roles that have all caps
4509 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4513 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4514 foreach ($forbiddenarr as $forbidden) {
4515 //remove any roles that are forbidden any of the caps
4516 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4519 return $rolesthatcanrate;
4523 * Returns an array of role names that have ALL of the the supplied capabilities
4524 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4526 * @param stdClass $context
4527 * @param array $capabilities An array of capabilities
4528 * @return array of roles with all of the required capabilities
4530 function get_role_names_with_caps_in_context($context, $capabilities) {
4533 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4534 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4537 foreach ($rolesthatcanrate as $r) {
4538 $roles[$r] = $allroles[$r];
4541 return role_fix_names($roles, $context, ROLENAME_ALIAS
, true);
4545 * This function verifies the prohibit comes from this context
4546 * and there are no more prohibits in parent contexts.
4548 * @param int $roleid
4549 * @param context $context
4550 * @param string $capability name
4553 function prohibit_is_removable($roleid, context
$context, $capability) {
4556 $ctxids = trim($context->path
, '/'); // kill leading slash
4557 $ctxids = str_replace('/', ',', $ctxids);
4559 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT
);
4561 $sql = "SELECT ctx.id
4562 FROM {role_capabilities} rc
4563 JOIN {context} ctx ON ctx.id = rc.contextid
4564 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4565 ORDER BY ctx.depth DESC";
4567 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4568 // no prohibits == nothing to remove
4572 if (count($prohibits) > 1) {
4573 // more prohibits can not be removed
4577 return !empty($prohibits[$context->id
]);
4581 * More user friendly role permission changing,
4582 * it should produce as few overrides as possible.
4584 * @param int $roleid
4585 * @param stdClass $context
4586 * @param string $capname capability name
4587 * @param int $permission
4590 function role_change_permission($roleid, $context, $capname, $permission) {
4593 if ($permission == CAP_INHERIT
) {
4594 unassign_capability($capname, $roleid, $context->id
);
4595 $context->mark_dirty();
4599 $ctxids = trim($context->path
, '/'); // kill leading slash
4600 $ctxids = str_replace('/', ',', $ctxids);
4602 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4604 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4605 FROM {role_capabilities} rc
4606 JOIN {context} ctx ON ctx.id = rc.contextid
4607 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4608 ORDER BY ctx.depth DESC";
4610 if ($existing = $DB->get_records_sql($sql, $params)) {
4611 foreach($existing as $e) {
4612 if ($e->permission
== CAP_PROHIBIT
) {
4613 // prohibit can not be overridden, no point in changing anything
4617 $lowest = array_shift($existing);
4618 if ($lowest->permission
== $permission) {
4619 // permission already set in this context or parent - nothing to do
4623 $parent = array_shift($existing);
4624 if ($parent->permission
== $permission) {
4625 // permission already set in parent context or parent - just unset in this context
4626 // we do this because we want as few overrides as possible for performance reasons
4627 unassign_capability($capname, $roleid, $context->id
);
4628 $context->mark_dirty();
4634 if ($permission == CAP_PREVENT
) {
4635 // nothing means role does not have permission
4640 // assign the needed capability
4641 assign_capability($capname, $permission, $roleid, $context->id
, true);
4643 // force cap reloading
4644 $context->mark_dirty();
4649 * Basic moodle context abstraction class.
4651 * Google confirms that no other important framework is using "context" class,
4652 * we could use something else like mcontext or moodle_context, but we need to type
4653 * this very often which would be annoying and it would take too much space...
4655 * This class is derived from stdClass for backwards compatibility with
4656 * odl $context record that was returned from DML $DB->get_record()
4658 * @package core_access
4660 * @copyright Petr Skoda {@link http://skodak.org}
4661 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4664 * @property-read int $id context id
4665 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4666 * @property-read int $instanceid id of related instance in each context
4667 * @property-read string $path path to context, starts with system context
4668 * @property-read int $depth
4670 abstract class context
extends stdClass
implements IteratorAggregate
{
4674 * Can be accessed publicly through $context->id
4681 * Can be accessed publicly through $context->contextlevel
4682 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4684 protected $_contextlevel;
4687 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4688 * Can be accessed publicly through $context->instanceid
4691 protected $_instanceid;
4694 * The path to the context always starting from the system context
4695 * Can be accessed publicly through $context->path
4701 * The depth of the context in relation to parent contexts
4702 * Can be accessed publicly through $context->depth
4708 * @var array Context caching info
4710 private static $cache_contextsbyid = array();
4713 * @var array Context caching info
4715 private static $cache_contexts = array();
4719 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4722 protected static $cache_count = 0;
4725 * @var array Context caching info
4727 protected static $cache_preloaded = array();
4730 * @var context_system The system context once initialised
4732 protected static $systemcontext = null;
4735 * Resets the cache to remove all data.
4738 protected static function reset_caches() {
4739 self
::$cache_contextsbyid = array();
4740 self
::$cache_contexts = array();
4741 self
::$cache_count = 0;
4742 self
::$cache_preloaded = array();
4744 self
::$systemcontext = null;
4748 * Adds a context to the cache. If the cache is full, discards a batch of
4752 * @param context $context New context to add
4755 protected static function cache_add(context
$context) {
4756 if (isset(self
::$cache_contextsbyid[$context->id
])) {
4757 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4761 if (self
::$cache_count >= CONTEXT_CACHE_MAX_SIZE
) {
4763 foreach(self
::$cache_contextsbyid as $ctx) {
4766 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4769 if ($i > (CONTEXT_CACHE_MAX_SIZE
/ 3)) {
4770 // we remove oldest third of the contexts to make room for more contexts
4773 unset(self
::$cache_contextsbyid[$ctx->id
]);
4774 unset(self
::$cache_contexts[$ctx->contextlevel
][$ctx->instanceid
]);
4775 self
::$cache_count--;
4779 self
::$cache_contexts[$context->contextlevel
][$context->instanceid
] = $context;
4780 self
::$cache_contextsbyid[$context->id
] = $context;
4781 self
::$cache_count++
;
4785 * Removes a context from the cache.
4788 * @param context $context Context object to remove
4791 protected static function cache_remove(context
$context) {
4792 if (!isset(self
::$cache_contextsbyid[$context->id
])) {
4793 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4796 unset(self
::$cache_contexts[$context->contextlevel
][$context->instanceid
]);
4797 unset(self
::$cache_contextsbyid[$context->id
]);
4799 self
::$cache_count--;
4801 if (self
::$cache_count < 0) {
4802 self
::$cache_count = 0;
4807 * Gets a context from the cache.
4810 * @param int $contextlevel Context level
4811 * @param int $instance Instance ID
4812 * @return context|bool Context or false if not in cache
4814 protected static function cache_get($contextlevel, $instance) {
4815 if (isset(self
::$cache_contexts[$contextlevel][$instance])) {
4816 return self
::$cache_contexts[$contextlevel][$instance];
4822 * Gets a context from the cache based on its id.
4825 * @param int $id Context ID
4826 * @return context|bool Context or false if not in cache
4828 protected static function cache_get_by_id($id) {
4829 if (isset(self
::$cache_contextsbyid[$id])) {
4830 return self
::$cache_contextsbyid[$id];
4836 * Preloads context information from db record and strips the cached info.
4839 * @param stdClass $rec
4840 * @return void (modifies $rec)
4842 protected static function preload_from_record(stdClass
$rec) {
4843 if (empty($rec->ctxid
) or empty($rec->ctxlevel
) or !isset($rec->ctxinstance
) or empty($rec->ctxpath
) or empty($rec->ctxdepth
)) {
4844 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4848 // note: in PHP5 the objects are passed by reference, no need to return $rec
4849 $record = new stdClass();
4850 $record->id
= $rec->ctxid
; unset($rec->ctxid
);
4851 $record->contextlevel
= $rec->ctxlevel
; unset($rec->ctxlevel
);
4852 $record->instanceid
= $rec->ctxinstance
; unset($rec->ctxinstance
);
4853 $record->path
= $rec->ctxpath
; unset($rec->ctxpath
);
4854 $record->depth
= $rec->ctxdepth
; unset($rec->ctxdepth
);
4856 return context
::create_instance_from_record($record);
4860 // ====== magic methods =======
4863 * Magic setter method, we do not want anybody to modify properties from the outside
4864 * @param string $name
4865 * @param mixed $value
4867 public function __set($name, $value) {
4868 debugging('Can not change context instance properties!');
4872 * Magic method getter, redirects to read only values.
4873 * @param string $name
4876 public function __get($name) {
4878 case 'id': return $this->_id
;
4879 case 'contextlevel': return $this->_contextlevel
;
4880 case 'instanceid': return $this->_instanceid
;
4881 case 'path': return $this->_path
;
4882 case 'depth': return $this->_depth
;
4885 debugging('Invalid context property accessed! '.$name);
4891 * Full support for isset on our magic read only properties.
4892 * @param string $name
4895 public function __isset($name) {
4897 case 'id': return isset($this->_id
);
4898 case 'contextlevel': return isset($this->_contextlevel
);
4899 case 'instanceid': return isset($this->_instanceid
);
4900 case 'path': return isset($this->_path
);
4901 case 'depth': return isset($this->_depth
);
4903 default: return false;
4909 * ALl properties are read only, sorry.
4910 * @param string $name
4912 public function __unset($name) {
4913 debugging('Can not unset context instance properties!');
4916 // ====== implementing method from interface IteratorAggregate ======
4919 * Create an iterator because magic vars can't be seen by 'foreach'.
4921 * Now we can convert context object to array using convert_to_array(),
4922 * and feed it properly to json_encode().
4924 public function getIterator() {
4927 'contextlevel' => $this->contextlevel
,
4928 'instanceid' => $this->instanceid
,
4929 'path' => $this->path
,
4930 'depth' => $this->depth
4932 return new ArrayIterator($ret);
4935 // ====== general context methods ======
4938 * Constructor is protected so that devs are forced to
4939 * use context_xxx::instance() or context::instance_by_id().
4941 * @param stdClass $record
4943 protected function __construct(stdClass
$record) {
4944 $this->_id
= (int)$record->id
;
4945 $this->_contextlevel
= (int)$record->contextlevel
;
4946 $this->_instanceid
= $record->instanceid
;
4947 $this->_path
= $record->path
;
4948 $this->_depth
= $record->depth
;
4952 * This function is also used to work around 'protected' keyword problems in context_helper.
4954 * @param stdClass $record
4955 * @return context instance
4957 protected static function create_instance_from_record(stdClass
$record) {
4958 $classname = context_helper
::get_class_for_level($record->contextlevel
);
4960 if ($context = context
::cache_get_by_id($record->id
)) {
4964 $context = new $classname($record);
4965 context
::cache_add($context);
4971 * Copy prepared new contexts from temp table to context table,
4972 * we do this in db specific way for perf reasons only.
4975 protected static function merge_context_temp_table() {
4979 * - mysql does not allow to use FROM in UPDATE statements
4980 * - using two tables after UPDATE works in mysql, but might give unexpected
4981 * results in pg 8 (depends on configuration)
4982 * - using table alias in UPDATE does not work in pg < 8.2
4984 * Different code for each database - mostly for performance reasons
4987 $dbfamily = $DB->get_dbfamily();
4988 if ($dbfamily == 'mysql') {
4989 $updatesql = "UPDATE {context} ct, {context_temp} temp
4990 SET ct.path = temp.path,
4991 ct.depth = temp.depth
4992 WHERE ct.id = temp.id";
4993 } else if ($dbfamily == 'oracle') {
4994 $updatesql = "UPDATE {context} ct
4995 SET (ct.path, ct.depth) =
4996 (SELECT temp.path, temp.depth
4997 FROM {context_temp} temp
4998 WHERE temp.id=ct.id)
4999 WHERE EXISTS (SELECT 'x'
5000 FROM {context_temp} temp
5001 WHERE temp.id = ct.id)";
5002 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5003 $updatesql = "UPDATE {context}
5004 SET path = temp.path,
5006 FROM {context_temp} temp
5007 WHERE temp.id={context}.id";
5009 // sqlite and others
5010 $updatesql = "UPDATE {context}
5011 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5012 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5013 WHERE id IN (SELECT id FROM {context_temp})";
5016 $DB->execute($updatesql);
5020 * Get a context instance as an object, from a given context id.
5023 * @param int $id context id
5024 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5025 * MUST_EXIST means throw exception if no record found
5026 * @return context|bool the context object or false if not found
5028 public static function instance_by_id($id, $strictness = MUST_EXIST
) {
5031 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5032 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5033 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5036 if ($id == SYSCONTEXTID
) {
5037 return context_system
::instance(0, $strictness);
5040 if (is_array($id) or is_object($id) or empty($id)) {
5041 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5044 if ($context = context
::cache_get_by_id($id)) {
5048 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5049 return context
::create_instance_from_record($record);
5056 * Update context info after moving context in the tree structure.
5058 * @param context $newparent
5061 public function update_moved(context
$newparent) {
5064 $frompath = $this->_path
;
5065 $newpath = $newparent->path
. '/' . $this->_id
;
5067 $trans = $DB->start_delegated_transaction();
5069 $this->mark_dirty();
5072 if (($newparent->depth +
1) != $this->_depth
) {
5073 $diff = $newparent->depth
- $this->_depth +
1;
5074 $setdepth = ", depth = depth + $diff";
5076 $sql = "UPDATE {context}
5080 $params = array($newpath, $this->_id
);
5081 $DB->execute($sql, $params);
5083 $this->_path
= $newpath;
5084 $this->_depth
= $newparent->depth +
1;
5086 $sql = "UPDATE {context}
5087 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+
1))."
5090 $params = array($newpath, "{$frompath}/%");
5091 $DB->execute($sql, $params);
5093 $this->mark_dirty();
5095 context
::reset_caches();
5097 $trans->allow_commit();
5101 * Remove all context path info and optionally rebuild it.
5103 * @param bool $rebuild
5106 public function reset_paths($rebuild = true) {
5110 $this->mark_dirty();
5112 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5113 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5114 if ($this->_contextlevel
!= CONTEXT_SYSTEM
) {
5115 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id
));
5116 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id
));
5118 $this->_path
= null;
5122 context_helper
::build_all_paths(false);
5125 context
::reset_caches();
5129 * Delete all data linked to content, do not delete the context record itself
5131 public function delete_content() {
5134 blocks_delete_all_for_context($this->_id
);
5135 filter_delete_all_for_context($this->_id
);
5137 require_once($CFG->dirroot
. '/comment/lib.php');
5138 comment
::delete_comments(array('contextid'=>$this->_id
));
5140 require_once($CFG->dirroot
.'/rating/lib.php');
5141 $delopt = new stdclass();
5142 $delopt->contextid
= $this->_id
;
5143 $rm = new rating_manager();
5144 $rm->delete_ratings($delopt);
5146 // delete all files attached to this context
5147 $fs = get_file_storage();
5148 $fs->delete_area_files($this->_id
);
5150 // Delete all repository instances attached to this context.
5151 require_once($CFG->dirroot
. '/repository/lib.php');
5152 repository
::delete_all_for_context($this->_id
);
5154 // delete all advanced grading data attached to this context
5155 require_once($CFG->dirroot
.'/grade/grading/lib.php');
5156 grading_manager
::delete_all_for_context($this->_id
);
5158 $ids = $DB->get_fieldset_select('role_capabilities', 'DISTINCT roleid', 'contextid = ?', array($this->_id
));
5160 // now delete stuff from role related tables, role_unassign_all
5161 // and unenrol should be called earlier to do proper cleanup
5162 $DB->delete_records('role_assignments', array('contextid'=>$this->_id
));
5163 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id
));
5164 $DB->delete_records('role_names', array('contextid'=>$this->_id
));
5167 // Reset any cache of these roles, including MUC.
5168 accesslib_clear_role_cache($ids);
5173 * Delete the context content and the context record itself
5175 public function delete() {
5178 if ($this->_contextlevel
<= CONTEXT_SYSTEM
) {
5179 throw new coding_exception('Cannot delete system context');
5182 // double check the context still exists
5183 if (!$DB->record_exists('context', array('id'=>$this->_id
))) {
5184 context
::cache_remove($this);
5188 $this->delete_content();
5189 $DB->delete_records('context', array('id'=>$this->_id
));
5190 // purge static context cache if entry present
5191 context
::cache_remove($this);
5193 // do not mark dirty contexts if parents unknown
5194 if (!is_null($this->_path
) and $this->_depth
> 0) {
5195 $this->mark_dirty();
5199 // ====== context level related methods ======
5202 * Utility method for context creation
5205 * @param int $contextlevel
5206 * @param int $instanceid
5207 * @param string $parentpath
5208 * @return stdClass context record
5210 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5213 $record = new stdClass();
5214 $record->contextlevel
= $contextlevel;
5215 $record->instanceid
= $instanceid;
5217 $record->path
= null; //not known before insert
5219 $record->id
= $DB->insert_record('context', $record);
5221 // now add path if known - it can be added later
5222 if (!is_null($parentpath)) {
5223 $record->path
= $parentpath.'/'.$record->id
;
5224 $record->depth
= substr_count($record->path
, '/');
5225 $DB->update_record('context', $record);
5232 * Returns human readable context identifier.
5234 * @param boolean $withprefix whether to prefix the name of the context with the
5235 * type of context, e.g. User, Course, Forum, etc.
5236 * @param boolean $short whether to use the short name of the thing. Only applies
5237 * to course contexts
5238 * @return string the human readable context name.
5240 public function get_context_name($withprefix = true, $short = false) {
5241 // must be implemented in all context levels
5242 throw new coding_exception('can not get name of abstract context');
5246 * Returns the most relevant URL for this context.
5248 * @return moodle_url
5250 public abstract function get_url();
5253 * Returns array of relevant context capability records.
5257 public abstract function get_capabilities();
5260 * Recursive function which, given a context, find all its children context ids.
5262 * For course category contexts it will return immediate children and all subcategory contexts.
5263 * It will NOT recurse into courses or subcategories categories.
5264 * If you want to do that, call it on the returned courses/categories.
5266 * When called for a course context, it will return the modules and blocks
5267 * displayed in the course page and blocks displayed on the module pages.
5269 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5272 * @return array Array of child records
5274 public function get_child_contexts() {
5277 if (empty($this->_path
) or empty($this->_depth
)) {
5278 debugging('Can not find child contexts of context '.$this->_id
.' try rebuilding of context paths');
5282 $sql = "SELECT ctx.*
5284 WHERE ctx.path LIKE ?";
5285 $params = array($this->_path
.'/%');
5286 $records = $DB->get_records_sql($sql, $params);
5289 foreach ($records as $record) {
5290 $result[$record->id
] = context
::create_instance_from_record($record);
5297 * Returns parent contexts of this context in reversed order, i.e. parent first,
5298 * then grand parent, etc.
5300 * @param bool $includeself tre means include self too
5301 * @return array of context instances
5303 public function get_parent_contexts($includeself = false) {
5304 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5309 foreach ($contextids as $contextid) {
5310 $parent = context
::instance_by_id($contextid, MUST_EXIST
);
5311 $result[$parent->id
] = $parent;
5318 * Returns parent contexts of this context in reversed order, i.e. parent first,
5319 * then grand parent, etc.
5321 * @param bool $includeself tre means include self too
5322 * @return array of context ids
5324 public function get_parent_context_ids($includeself = false) {
5325 if (empty($this->_path
)) {
5329 $parentcontexts = trim($this->_path
, '/'); // kill leading slash
5330 $parentcontexts = explode('/', $parentcontexts);
5331 if (!$includeself) {
5332 array_pop($parentcontexts); // and remove its own id
5335 return array_reverse($parentcontexts);
5339 * Returns parent context
5343 public function get_parent_context() {
5344 if (empty($this->_path
) or $this->_id
== SYSCONTEXTID
) {
5348 $parentcontexts = trim($this->_path
, '/'); // kill leading slash
5349 $parentcontexts = explode('/', $parentcontexts);
5350 array_pop($parentcontexts); // self
5351 $contextid = array_pop($parentcontexts); // immediate parent
5353 return context
::instance_by_id($contextid, MUST_EXIST
);
5357 * Is this context part of any course? If yes return course context.
5359 * @param bool $strict true means throw exception if not found, false means return false if not found
5360 * @return context_course context of the enclosing course, null if not found or exception
5362 public function get_course_context($strict = true) {
5364 throw new coding_exception('Context does not belong to any course.');
5371 * Returns sql necessary for purging of stale context instances.
5374 * @return string cleanup SQL
5376 protected static function get_cleanup_sql() {
5377 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5381 * Rebuild context paths and depths at context level.
5384 * @param bool $force
5387 protected static function build_paths($force) {
5388 throw new coding_exception('build_paths() method must be implemented in all context levels');
5392 * Create missing context instances at given level
5397 protected static function create_level_instances() {
5398 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5402 * Reset all cached permissions and definitions if the necessary.
5405 public function reload_if_dirty() {
5406 global $ACCESSLIB_PRIVATE, $USER;
5408 // Load dirty contexts list if needed
5410 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts
)) {
5411 // we do not load dirty flags in CLI and cron
5412 $ACCESSLIB_PRIVATE->dirtycontexts
= array();
5415 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts
)) {
5416 if (!isset($USER->access
['time'])) {
5417 // nothing was loaded yet, we do not need to check dirty contexts now
5420 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5421 $ACCESSLIB_PRIVATE->dirtycontexts
= get_cache_flags('accesslib/dirtycontexts', $USER->access
['time']-2);
5425 foreach ($ACCESSLIB_PRIVATE->dirtycontexts
as $path=>$unused) {
5426 if ($path === $this->_path
or strpos($this->_path
, $path.'/') === 0) {
5427 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5428 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5429 reload_all_capabilities();
5436 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5438 public function mark_dirty() {
5439 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5441 if (during_initial_install()) {
5445 // only if it is a non-empty string
5446 if (is_string($this->_path
) && $this->_path
!== '') {
5447 set_cache_flag('accesslib/dirtycontexts', $this->_path
, 1, time()+
$CFG->sessiontimeout
);
5448 if (isset($ACCESSLIB_PRIVATE->dirtycontexts
)) {
5449 $ACCESSLIB_PRIVATE->dirtycontexts
[$this->_path
] = 1;
5452 $ACCESSLIB_PRIVATE->dirtycontexts
= array($this->_path
=> 1);
5454 if (isset($USER->access
['time'])) {
5455 $ACCESSLIB_PRIVATE->dirtycontexts
= get_cache_flags('accesslib/dirtycontexts', $USER->access
['time']-2);
5457 $ACCESSLIB_PRIVATE->dirtycontexts
= array($this->_path
=> 1);
5459 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5468 * Context maintenance and helper methods.
5470 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5471 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5472 * level implementation from the rest of code, the code completion returns what developers need.
5474 * Thank you Tim Hunt for helping me with this nasty trick.
5476 * @package core_access
5478 * @copyright Petr Skoda {@link http://skodak.org}
5479 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5482 class context_helper
extends context
{
5485 * @var array An array mapping context levels to classes
5487 private static $alllevels;
5490 * Instance does not make sense here, only static use
5492 protected function __construct() {
5496 * Reset internal context levels array.
5498 public static function reset_levels() {
5499 self
::$alllevels = null;
5503 * Initialise context levels, call before using self::$alllevels.
5505 private static function init_levels() {
5508 if (isset(self
::$alllevels)) {
5511 self
::$alllevels = array(
5512 CONTEXT_SYSTEM
=> 'context_system',
5513 CONTEXT_USER
=> 'context_user',
5514 CONTEXT_COURSECAT
=> 'context_coursecat',
5515 CONTEXT_COURSE
=> 'context_course',
5516 CONTEXT_MODULE
=> 'context_module',
5517 CONTEXT_BLOCK
=> 'context_block',
5520 if (empty($CFG->custom_context_classes
)) {
5524 $levels = $CFG->custom_context_classes
;
5525 if (!is_array($levels)) {
5526 $levels = @unserialize
($levels);
5528 if (!is_array($levels)) {
5529 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER
);
5533 // Unsupported custom levels, use with care!!!
5534 foreach ($levels as $level => $classname) {
5535 self
::$alllevels[$level] = $classname;
5537 ksort(self
::$alllevels);
5541 * Returns a class name of the context level class
5544 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5545 * @return string class name of the context class
5547 public static function get_class_for_level($contextlevel) {
5548 self
::init_levels();
5549 if (isset(self
::$alllevels[$contextlevel])) {
5550 return self
::$alllevels[$contextlevel];
5552 throw new coding_exception('Invalid context level specified');
5557 * Returns a list of all context levels
5560 * @return array int=>string (level=>level class name)
5562 public static function get_all_levels() {
5563 self
::init_levels();
5564 return self
::$alllevels;
5568 * Remove stale contexts that belonged to deleted instances.
5569 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5574 public static function cleanup_instances() {
5576 self
::init_levels();
5579 foreach (self
::$alllevels as $level=>$classname) {
5580 $sqls[] = $classname::get_cleanup_sql();
5583 $sql = implode(" UNION ", $sqls);
5585 // it is probably better to use transactions, it might be faster too
5586 $transaction = $DB->start_delegated_transaction();
5588 $rs = $DB->get_recordset_sql($sql);
5589 foreach ($rs as $record) {
5590 $context = context
::create_instance_from_record($record);
5595 $transaction->allow_commit();
5599 * Create all context instances at the given level and above.
5602 * @param int $contextlevel null means all levels
5603 * @param bool $buildpaths
5606 public static function create_instances($contextlevel = null, $buildpaths = true) {
5607 self
::init_levels();
5608 foreach (self
::$alllevels as $level=>$classname) {
5609 if ($contextlevel and $level > $contextlevel) {
5610 // skip potential sub-contexts
5613 $classname::create_level_instances();
5615 $classname::build_paths(false);
5621 * Rebuild paths and depths in all context levels.
5624 * @param bool $force false means add missing only
5627 public static function build_all_paths($force = false) {
5628 self
::init_levels();
5629 foreach (self
::$alllevels as $classname) {
5630 $classname::build_paths($force);
5633 // reset static course cache - it might have incorrect cached data
5634 accesslib_clear_all_caches(true);
5638 * Resets the cache to remove all data.
5641 public static function reset_caches() {
5642 context
::reset_caches();
5646 * Returns all fields necessary for context preloading from user $rec.
5648 * This helps with performance when dealing with hundreds of contexts.
5651 * @param string $tablealias context table alias in the query
5652 * @return array (table.column=>alias, ...)
5654 public static function get_preload_record_columns($tablealias) {
5655 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5659 * Returns all fields necessary for context preloading from user $rec.
5661 * This helps with performance when dealing with hundreds of contexts.
5664 * @param string $tablealias context table alias in the query
5667 public static function get_preload_record_columns_sql($tablealias) {
5668 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5672 * Preloads context information from db record and strips the cached info.
5674 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5677 * @param stdClass $rec
5678 * @return void (modifies $rec)
5680 public static function preload_from_record(stdClass
$rec) {
5681 context
::preload_from_record($rec);
5685 * Preload all contexts instances from course.
5687 * To be used if you expect multiple queries for course activities...
5690 * @param int $courseid
5692 public static function preload_course($courseid) {
5693 // Users can call this multiple times without doing any harm
5694 if (isset(context
::$cache_preloaded[$courseid])) {
5697 $coursecontext = context_course
::instance($courseid);
5698 $coursecontext->get_child_contexts();
5700 context
::$cache_preloaded[$courseid] = true;
5704 * Delete context instance
5707 * @param int $contextlevel
5708 * @param int $instanceid
5711 public static function delete_instance($contextlevel, $instanceid) {
5714 // double check the context still exists
5715 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5716 $context = context
::create_instance_from_record($record);
5719 // we should try to purge the cache anyway
5724 * Returns the name of specified context level
5727 * @param int $contextlevel
5728 * @return string name of the context level
5730 public static function get_level_name($contextlevel) {
5731 $classname = context_helper
::get_class_for_level($contextlevel);
5732 return $classname::get_level_name();
5738 public function get_url() {
5744 public function get_capabilities() {
5750 * System context class
5752 * @package core_access
5754 * @copyright Petr Skoda {@link http://skodak.org}
5755 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5758 class context_system
extends context
{
5760 * Please use context_system::instance() if you need the instance of context.
5762 * @param stdClass $record
5764 protected function __construct(stdClass
$record) {
5765 parent
::__construct($record);
5766 if ($record->contextlevel
!= CONTEXT_SYSTEM
) {
5767 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5772 * Returns human readable context level name.
5775 * @return string the human readable context level name.
5777 public static function get_level_name() {
5778 return get_string('coresystem');
5782 * Returns human readable context identifier.
5784 * @param boolean $withprefix does not apply to system context
5785 * @param boolean $short does not apply to system context
5786 * @return string the human readable context name.
5788 public function get_context_name($withprefix = true, $short = false) {
5789 return self
::get_level_name();
5793 * Returns the most relevant URL for this context.
5795 * @return moodle_url
5797 public function get_url() {
5798 return new moodle_url('/');
5802 * Returns array of relevant context capability records.
5806 public function get_capabilities() {
5809 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5813 FROM {capabilities}";
5815 return $DB->get_records_sql($sql.' '.$sort, $params);
5819 * Create missing context instances at system context
5822 protected static function create_level_instances() {
5823 // nothing to do here, the system context is created automatically in installer
5828 * Returns system context instance.
5831 * @param int $instanceid should be 0
5832 * @param int $strictness
5833 * @param bool $cache
5834 * @return context_system context instance
5836 public static function instance($instanceid = 0, $strictness = MUST_EXIST
, $cache = true) {
5839 if ($instanceid != 0) {
5840 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5843 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5844 if (!isset(context
::$systemcontext)) {
5845 $record = new stdClass();
5846 $record->id
= SYSCONTEXTID
;
5847 $record->contextlevel
= CONTEXT_SYSTEM
;
5848 $record->instanceid
= 0;
5849 $record->path
= '/'.SYSCONTEXTID
;
5851 context
::$systemcontext = new context_system($record);
5853 return context
::$systemcontext;
5858 // We ignore the strictness completely because system context must exist except during install.
5859 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM
), '*', MUST_EXIST
);
5860 } catch (dml_exception
$e) {
5861 //table or record does not exist
5862 if (!during_initial_install()) {
5863 // do not mess with system context after install, it simply must exist
5870 $record = new stdClass();
5871 $record->contextlevel
= CONTEXT_SYSTEM
;
5872 $record->instanceid
= 0;
5874 $record->path
= null; //not known before insert
5877 if ($DB->count_records('context')) {
5878 // contexts already exist, this is very weird, system must be first!!!
5881 if (defined('SYSCONTEXTID')) {
5882 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5883 $record->id
= SYSCONTEXTID
;
5884 $DB->import_record('context', $record);
5885 $DB->get_manager()->reset_sequence('context');
5887 $record->id
= $DB->insert_record('context', $record);
5889 } catch (dml_exception
$e) {
5890 // can not create context - table does not exist yet, sorry
5895 if ($record->instanceid
!= 0) {
5896 // this is very weird, somebody must be messing with context table
5897 debugging('Invalid system context detected');
5900 if ($record->depth
!= 1 or $record->path
!= '/'.$record->id
) {
5901 // fix path if necessary, initial install or path reset
5903 $record->path
= '/'.$record->id
;
5904 $DB->update_record('context', $record);
5907 if (!defined('SYSCONTEXTID')) {
5908 define('SYSCONTEXTID', $record->id
);
5911 context
::$systemcontext = new context_system($record);
5912 return context
::$systemcontext;
5916 * Returns all site contexts except the system context, DO NOT call on production servers!!
5918 * Contexts are not cached.
5922 public function get_child_contexts() {
5925 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
5927 // Just get all the contexts except for CONTEXT_SYSTEM level
5928 // and hope we don't OOM in the process - don't cache
5931 WHERE contextlevel > ".CONTEXT_SYSTEM
;
5932 $records = $DB->get_records_sql($sql);
5935 foreach ($records as $record) {
5936 $result[$record->id
] = context
::create_instance_from_record($record);
5943 * Returns sql necessary for purging of stale context instances.
5946 * @return string cleanup SQL
5948 protected static function get_cleanup_sql() {
5959 * Rebuild context paths and depths at system context level.
5962 * @param bool $force
5964 protected static function build_paths($force) {
5967 /* note: ignore $force here, we always do full test of system context */
5969 // exactly one record must exist
5970 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM
), '*', MUST_EXIST
);
5972 if ($record->instanceid
!= 0) {
5973 debugging('Invalid system context detected');
5976 if (defined('SYSCONTEXTID') and $record->id
!= SYSCONTEXTID
) {
5977 debugging('Invalid SYSCONTEXTID detected');
5980 if ($record->depth
!= 1 or $record->path
!= '/'.$record->id
) {
5981 // fix path if necessary, initial install or path reset
5983 $record->path
= '/'.$record->id
;
5984 $DB->update_record('context', $record);
5991 * User context class
5993 * @package core_access
5995 * @copyright Petr Skoda {@link http://skodak.org}
5996 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5999 class context_user
extends context
{
6001 * Please use context_user::instance($userid) if you need the instance of context.
6002 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6004 * @param stdClass $record
6006 protected function __construct(stdClass
$record) {
6007 parent
::__construct($record);
6008 if ($record->contextlevel
!= CONTEXT_USER
) {
6009 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6014 * Returns human readable context level name.
6017 * @return string the human readable context level name.
6019 public static function get_level_name() {
6020 return get_string('user');
6024 * Returns human readable context identifier.
6026 * @param boolean $withprefix whether to prefix the name of the context with User
6027 * @param boolean $short does not apply to user context
6028 * @return string the human readable context name.
6030 public function get_context_name($withprefix = true, $short = false) {
6034 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid
, 'deleted'=>0))) {
6036 $name = get_string('user').': ';
6038 $name .= fullname($user);
6044 * Returns the most relevant URL for this context.
6046 * @return moodle_url
6048 public function get_url() {
6051 if ($COURSE->id
== SITEID
) {
6052 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid
));
6054 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid
, 'courseid'=>$COURSE->id
));
6060 * Returns array of relevant context capability records.
6064 public function get_capabilities() {
6067 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6069 $extracaps = array('moodle/grade:viewall');
6070 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED
, 'cap');
6073 WHERE contextlevel = ".CONTEXT_USER
."
6076 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6080 * Returns user context instance.
6083 * @param int $userid id from {user} table
6084 * @param int $strictness
6085 * @return context_user context instance
6087 public static function instance($userid, $strictness = MUST_EXIST
) {
6090 if ($context = context
::cache_get(CONTEXT_USER
, $userid)) {
6094 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER
, 'instanceid' => $userid))) {
6095 if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6096 $record = context
::insert_context_record(CONTEXT_USER
, $user->id
, '/'.SYSCONTEXTID
, 0);
6101 $context = new context_user($record);
6102 context
::cache_add($context);
6110 * Create missing context instances at user context level
6113 protected static function create_level_instances() {
6116 $sql = "SELECT ".CONTEXT_USER
.", u.id
6119 AND NOT EXISTS (SELECT 'x'
6121 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER
.")";
6122 $contextdata = $DB->get_recordset_sql($sql);
6123 foreach ($contextdata as $context) {
6124 context
::insert_context_record(CONTEXT_USER
, $context->id
, null);
6126 $contextdata->close();
6130 * Returns sql necessary for purging of stale context instances.
6133 * @return string cleanup SQL
6135 protected static function get_cleanup_sql() {
6139 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6140 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER
."
6147 * Rebuild context paths and depths at user context level.
6150 * @param bool $force
6152 protected static function build_paths($force) {
6155 // First update normal users.
6156 $path = $DB->sql_concat('?', 'id');
6157 $pathstart = '/' . SYSCONTEXTID
. '/';
6158 $params = array($pathstart);
6161 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6162 $params[] = $pathstart;
6164 $where = "depth = 0 OR path IS NULL";
6167 $sql = "UPDATE {context}
6170 WHERE contextlevel = " . CONTEXT_USER
. "
6172 $DB->execute($sql, $params);
6178 * Course category context class
6180 * @package core_access
6182 * @copyright Petr Skoda {@link http://skodak.org}
6183 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6186 class context_coursecat
extends context
{
6188 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6189 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6191 * @param stdClass $record
6193 protected function __construct(stdClass
$record) {
6194 parent
::__construct($record);
6195 if ($record->contextlevel
!= CONTEXT_COURSECAT
) {
6196 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6201 * Returns human readable context level name.
6204 * @return string the human readable context level name.
6206 public static function get_level_name() {
6207 return get_string('category');
6211 * Returns human readable context identifier.
6213 * @param boolean $withprefix whether to prefix the name of the context with Category
6214 * @param boolean $short does not apply to course categories
6215 * @return string the human readable context name.
6217 public function get_context_name($withprefix = true, $short = false) {
6221 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid
))) {
6223 $name = get_string('category').': ';
6225 $name .= format_string($category->name
, true, array('context' => $this));
6231 * Returns the most relevant URL for this context.
6233 * @return moodle_url
6235 public function get_url() {
6236 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid
));
6240 * Returns array of relevant context capability records.
6244 public function get_capabilities() {
6247 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6252 WHERE contextlevel IN (".CONTEXT_COURSECAT
.",".CONTEXT_COURSE
.",".CONTEXT_MODULE
.",".CONTEXT_BLOCK
.")";
6254 return $DB->get_records_sql($sql.' '.$sort, $params);
6258 * Returns course category context instance.
6261 * @param int $categoryid id from {course_categories} table
6262 * @param int $strictness
6263 * @return context_coursecat context instance
6265 public static function instance($categoryid, $strictness = MUST_EXIST
) {
6268 if ($context = context
::cache_get(CONTEXT_COURSECAT
, $categoryid)) {
6272 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT
, 'instanceid' => $categoryid))) {
6273 if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6274 if ($category->parent
) {
6275 $parentcontext = context_coursecat
::instance($category->parent
);
6276 $record = context
::insert_context_record(CONTEXT_COURSECAT
, $category->id
, $parentcontext->path
);
6278 $record = context
::insert_context_record(CONTEXT_COURSECAT
, $category->id
, '/'.SYSCONTEXTID
, 0);
6284 $context = new context_coursecat($record);
6285 context
::cache_add($context);
6293 * Returns immediate child contexts of category and all subcategories,
6294 * children of subcategories and courses are not returned.
6298 public function get_child_contexts() {
6301 if (empty($this->_path
) or empty($this->_depth
)) {
6302 debugging('Can not find child contexts of context '.$this->_id
.' try rebuilding of context paths');
6306 $sql = "SELECT ctx.*
6308 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6309 $params = array($this->_path
.'/%', $this->depth+
1, CONTEXT_COURSECAT
);
6310 $records = $DB->get_records_sql($sql, $params);
6313 foreach ($records as $record) {
6314 $result[$record->id
] = context
::create_instance_from_record($record);
6321 * Create missing context instances at course category context level
6324 protected static function create_level_instances() {
6327 $sql = "SELECT ".CONTEXT_COURSECAT
.", cc.id
6328 FROM {course_categories} cc
6329 WHERE NOT EXISTS (SELECT 'x'
6331 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT
.")";
6332 $contextdata = $DB->get_recordset_sql($sql);
6333 foreach ($contextdata as $context) {
6334 context
::insert_context_record(CONTEXT_COURSECAT
, $context->id
, null);
6336 $contextdata->close();
6340 * Returns sql necessary for purging of stale context instances.
6343 * @return string cleanup SQL
6345 protected static function get_cleanup_sql() {
6349 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6350 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT
."
6357 * Rebuild context paths and depths at course category context level.
6360 * @param bool $force
6362 protected static function build_paths($force) {
6365 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT
." AND (depth = 0 OR path IS NULL)")) {
6367 $ctxemptyclause = $emptyclause = '';
6369 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6370 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6373 $base = '/'.SYSCONTEXTID
;
6375 // Normal top level categories
6376 $sql = "UPDATE {context}
6378 path=".$DB->sql_concat("'$base/'", 'id')."
6379 WHERE contextlevel=".CONTEXT_COURSECAT
."
6380 AND EXISTS (SELECT 'x'
6381 FROM {course_categories} cc
6382 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6386 // Deeper categories - one query per depthlevel
6387 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6388 for ($n=2; $n<=$maxdepth; $n++
) {
6389 $sql = "INSERT INTO {context_temp} (id, path, depth)
6390 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6392 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT
." AND cc.depth = $n)
6393 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT
.")
6394 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6396 $trans = $DB->start_delegated_transaction();
6397 $DB->delete_records('context_temp');
6399 context
::merge_context_temp_table();
6400 $DB->delete_records('context_temp');
6401 $trans->allow_commit();
6410 * Course context class
6412 * @package core_access
6414 * @copyright Petr Skoda {@link http://skodak.org}
6415 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6418 class context_course
extends context
{
6420 * Please use context_course::instance($courseid) if you need the instance of context.
6421 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6423 * @param stdClass $record
6425 protected function __construct(stdClass
$record) {
6426 parent
::__construct($record);
6427 if ($record->contextlevel
!= CONTEXT_COURSE
) {
6428 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6433 * Returns human readable context level name.
6436 * @return string the human readable context level name.
6438 public static function get_level_name() {
6439 return get_string('course');
6443 * Returns human readable context identifier.
6445 * @param boolean $withprefix whether to prefix the name of the context with Course
6446 * @param boolean $short whether to use the short name of the thing.
6447 * @return string the human readable context name.
6449 public function get_context_name($withprefix = true, $short = false) {
6453 if ($this->_instanceid
== SITEID
) {
6454 $name = get_string('frontpage', 'admin');
6456 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid
))) {
6458 $name = get_string('course').': ';
6461 $name .= format_string($course->shortname
, true, array('context' => $this));
6463 $name .= format_string(get_course_display_name_for_list($course));
6471 * Returns the most relevant URL for this context.
6473 * @return moodle_url
6475 public function get_url() {
6476 if ($this->_instanceid
!= SITEID
) {
6477 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid
));
6480 return new moodle_url('/');
6484 * Returns array of relevant context capability records.
6488 public function get_capabilities() {
6491 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6496 WHERE contextlevel IN (".CONTEXT_COURSE
.",".CONTEXT_MODULE
.",".CONTEXT_BLOCK
.")";
6498 return $DB->get_records_sql($sql.' '.$sort, $params);
6502 * Is this context part of any course? If yes return course context.
6504 * @param bool $strict true means throw exception if not found, false means return false if not found
6505 * @return context_course context of the enclosing course, null if not found or exception
6507 public function get_course_context($strict = true) {
6512 * Returns course context instance.
6515 * @param int $courseid id from {course} table
6516 * @param int $strictness
6517 * @return context_course context instance
6519 public static function instance($courseid, $strictness = MUST_EXIST
) {
6522 if ($context = context
::cache_get(CONTEXT_COURSE
, $courseid)) {
6526 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE
, 'instanceid' => $courseid))) {
6527 if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
6528 if ($course->category
) {
6529 $parentcontext = context_coursecat
::instance($course->category
);
6530 $record = context
::insert_context_record(CONTEXT_COURSE
, $course->id
, $parentcontext->path
);
6532 $record = context
::insert_context_record(CONTEXT_COURSE
, $course->id
, '/'.SYSCONTEXTID
, 0);
6538 $context = new context_course($record);
6539 context
::cache_add($context);
6547 * Create missing context instances at course context level
6550 protected static function create_level_instances() {
6553 $sql = "SELECT ".CONTEXT_COURSE
.", c.id
6555 WHERE NOT EXISTS (SELECT 'x'
6557 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE
.")";
6558 $contextdata = $DB->get_recordset_sql($sql);
6559 foreach ($contextdata as $context) {
6560 context
::insert_context_record(CONTEXT_COURSE
, $context->id
, null);
6562 $contextdata->close();
6566 * Returns sql necessary for purging of stale context instances.
6569 * @return string cleanup SQL
6571 protected static function get_cleanup_sql() {
6575 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6576 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE
."
6583 * Rebuild context paths and depths at course context level.
6586 * @param bool $force
6588 protected static function build_paths($force) {
6591 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE
." AND (depth = 0 OR path IS NULL)")) {
6593 $ctxemptyclause = $emptyclause = '';
6595 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6596 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6599 $base = '/'.SYSCONTEXTID
;
6601 // Standard frontpage
6602 $sql = "UPDATE {context}
6604 path = ".$DB->sql_concat("'$base/'", 'id')."
6605 WHERE contextlevel = ".CONTEXT_COURSE
."
6606 AND EXISTS (SELECT 'x'
6608 WHERE c.id = {context}.instanceid AND c.category = 0)
6613 $sql = "INSERT INTO {context_temp} (id, path, depth)
6614 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6616 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE
." AND c.category <> 0)
6617 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT
.")
6618 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6620 $trans = $DB->start_delegated_transaction();
6621 $DB->delete_records('context_temp');
6623 context
::merge_context_temp_table();
6624 $DB->delete_records('context_temp');
6625 $trans->allow_commit();
6632 * Course module context class
6634 * @package core_access
6636 * @copyright Petr Skoda {@link http://skodak.org}
6637 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6640 class context_module
extends context
{
6642 * Please use context_module::instance($cmid) if you need the instance of context.
6643 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6645 * @param stdClass $record
6647 protected function __construct(stdClass
$record) {
6648 parent
::__construct($record);
6649 if ($record->contextlevel
!= CONTEXT_MODULE
) {
6650 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6655 * Returns human readable context level name.
6658 * @return string the human readable context level name.
6660 public static function get_level_name() {
6661 return get_string('activitymodule');
6665 * Returns human readable context identifier.
6667 * @param boolean $withprefix whether to prefix the name of the context with the
6668 * module name, e.g. Forum, Glossary, etc.
6669 * @param boolean $short does not apply to module context
6670 * @return string the human readable context name.
6672 public function get_context_name($withprefix = true, $short = false) {
6676 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6677 FROM {course_modules} cm
6678 JOIN {modules} md ON md.id = cm.module
6679 WHERE cm.id = ?", array($this->_instanceid
))) {
6680 if ($mod = $DB->get_record($cm->modname
, array('id' => $cm->instance
))) {
6682 $name = get_string('modulename', $cm->modname
).': ';
6684 $name .= format_string($mod->name
, true, array('context' => $this));
6691 * Returns the most relevant URL for this context.
6693 * @return moodle_url
6695 public function get_url() {
6698 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6699 FROM {course_modules} cm
6700 JOIN {modules} md ON md.id = cm.module
6701 WHERE cm.id = ?", array($this->_instanceid
))) {
6702 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid
));
6705 return new moodle_url('/');
6709 * Returns array of relevant context capability records.
6713 public function get_capabilities() {
6716 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6718 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid
));
6719 $module = $DB->get_record('modules', array('id'=>$cm->module
));
6722 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6723 if (file_exists($subpluginsfile)) {
6724 $subplugins = array(); // should be redefined in the file
6725 include($subpluginsfile);
6726 if (!empty($subplugins)) {
6727 foreach (array_keys($subplugins) as $subplugintype) {
6728 foreach (array_keys(core_component
::get_plugin_list($subplugintype)) as $subpluginname) {
6729 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6735 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6736 $extracaps = array();
6737 if (file_exists($modfile)) {
6738 include_once($modfile);
6739 $modfunction = $module->name
.'_get_extra_capabilities';
6740 if (function_exists($modfunction)) {
6741 $extracaps = $modfunction();
6745 $extracaps = array_merge($subcaps, $extracaps);
6747 list($extra, $params) = $DB->get_in_or_equal(
6748 $extracaps, SQL_PARAMS_NAMED
, 'cap0', true, '');
6749 if (!empty($extra)) {
6750 $extra = "OR name $extra";
6754 WHERE (contextlevel = ".CONTEXT_MODULE
."
6755 AND (component = :component OR component = 'moodle'))
6757 $params['component'] = "mod_$module->name";
6759 return $DB->get_records_sql($sql.' '.$sort, $params);
6763 * Is this context part of any course? If yes return course context.
6765 * @param bool $strict true means throw exception if not found, false means return false if not found
6766 * @return context_course context of the enclosing course, null if not found or exception
6768 public function get_course_context($strict = true) {
6769 return $this->get_parent_context();
6773 * Returns module context instance.
6776 * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
6777 * @param int $strictness
6778 * @return context_module context instance
6780 public static function instance($cmid, $strictness = MUST_EXIST
) {
6783 if ($context = context
::cache_get(CONTEXT_MODULE
, $cmid)) {
6787 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE
, 'instanceid' => $cmid))) {
6788 if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
6789 $parentcontext = context_course
::instance($cm->course
);
6790 $record = context
::insert_context_record(CONTEXT_MODULE
, $cm->id
, $parentcontext->path
);
6795 $context = new context_module($record);
6796 context
::cache_add($context);
6804 * Create missing context instances at module context level
6807 protected static function create_level_instances() {
6810 $sql = "SELECT ".CONTEXT_MODULE
.", cm.id
6811 FROM {course_modules} cm
6812 WHERE NOT EXISTS (SELECT 'x'
6814 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE
.")";
6815 $contextdata = $DB->get_recordset_sql($sql);
6816 foreach ($contextdata as $context) {
6817 context
::insert_context_record(CONTEXT_MODULE
, $context->id
, null);
6819 $contextdata->close();
6823 * Returns sql necessary for purging of stale context instances.
6826 * @return string cleanup SQL
6828 protected static function get_cleanup_sql() {
6832 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6833 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE
."
6840 * Rebuild context paths and depths at module context level.
6843 * @param bool $force
6845 protected static function build_paths($force) {
6848 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE
." AND (depth = 0 OR path IS NULL)")) {
6850 $ctxemptyclause = '';
6852 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6855 $sql = "INSERT INTO {context_temp} (id, path, depth)
6856 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6858 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE
.")
6859 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE
.")
6860 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6862 $trans = $DB->start_delegated_transaction();
6863 $DB->delete_records('context_temp');
6865 context
::merge_context_temp_table();
6866 $DB->delete_records('context_temp');
6867 $trans->allow_commit();
6874 * Block context class
6876 * @package core_access
6878 * @copyright Petr Skoda {@link http://skodak.org}
6879 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6882 class context_block
extends context
{
6884 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6885 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6887 * @param stdClass $record
6889 protected function __construct(stdClass
$record) {
6890 parent
::__construct($record);
6891 if ($record->contextlevel
!= CONTEXT_BLOCK
) {
6892 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6897 * Returns human readable context level name.
6900 * @return string the human readable context level name.
6902 public static function get_level_name() {
6903 return get_string('block');
6907 * Returns human readable context identifier.
6909 * @param boolean $withprefix whether to prefix the name of the context with Block
6910 * @param boolean $short does not apply to block context
6911 * @return string the human readable context name.
6913 public function get_context_name($withprefix = true, $short = false) {
6917 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid
))) {
6919 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
6920 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
6921 $blockname = "block_$blockinstance->blockname";
6922 if ($blockobject = new $blockname()) {
6924 $name = get_string('block').': ';
6926 $name .= $blockobject->title
;
6934 * Returns the most relevant URL for this context.
6936 * @return moodle_url
6938 public function get_url() {
6939 $parentcontexts = $this->get_parent_context();
6940 return $parentcontexts->get_url();
6944 * Returns array of relevant context capability records.
6948 public function get_capabilities() {
6951 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6954 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid
));
6957 $extracaps = block_method_result($bi->blockname
, 'get_extra_capabilities');
6959 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED
, 'cap');
6960 $extra = "OR name $extra";
6965 WHERE (contextlevel = ".CONTEXT_BLOCK
."
6966 AND component = :component)
6968 $params['component'] = 'block_' . $bi->blockname
;
6970 return $DB->get_records_sql($sql.' '.$sort, $params);
6974 * Is this context part of any course? If yes return course context.
6976 * @param bool $strict true means throw exception if not found, false means return false if not found
6977 * @return context_course context of the enclosing course, null if not found or exception
6979 public function get_course_context($strict = true) {
6980 $parentcontext = $this->get_parent_context();
6981 return $parentcontext->get_course_context($strict);
6985 * Returns block context instance.
6988 * @param int $blockinstanceid id from {block_instances} table.
6989 * @param int $strictness
6990 * @return context_block context instance
6992 public static function instance($blockinstanceid, $strictness = MUST_EXIST
) {
6995 if ($context = context
::cache_get(CONTEXT_BLOCK
, $blockinstanceid)) {
6999 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK
, 'instanceid' => $blockinstanceid))) {
7000 if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
7001 $parentcontext = context
::instance_by_id($bi->parentcontextid
);
7002 $record = context
::insert_context_record(CONTEXT_BLOCK
, $bi->id
, $parentcontext->path
);
7007 $context = new context_block($record);
7008 context
::cache_add($context);
7016 * Block do not have child contexts...
7019 public function get_child_contexts() {
7024 * Create missing context instances at block context level
7027 protected static function create_level_instances() {
7030 $sql = "SELECT ".CONTEXT_BLOCK
.", bi.id
7031 FROM {block_instances} bi
7032 WHERE NOT EXISTS (SELECT 'x'
7034 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK
.")";
7035 $contextdata = $DB->get_recordset_sql($sql);
7036 foreach ($contextdata as $context) {
7037 context
::insert_context_record(CONTEXT_BLOCK
, $context->id
, null);
7039 $contextdata->close();
7043 * Returns sql necessary for purging of stale context instances.
7046 * @return string cleanup SQL
7048 protected static function get_cleanup_sql() {
7052 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7053 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK
."
7060 * Rebuild context paths and depths at block context level.
7063 * @param bool $force
7065 protected static function build_paths($force) {
7068 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK
." AND (depth = 0 OR path IS NULL)")) {
7070 $ctxemptyclause = '';
7072 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7075 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7076 $sql = "INSERT INTO {context_temp} (id, path, depth)
7077 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7079 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK
.")
7080 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7081 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7083 $trans = $DB->start_delegated_transaction();
7084 $DB->delete_records('context_temp');
7086 context
::merge_context_temp_table();
7087 $DB->delete_records('context_temp');
7088 $trans->allow_commit();
7094 // ============== DEPRECATED FUNCTIONS ==========================================
7095 // Old context related functions were deprecated in 2.0, it is recommended
7096 // to use context classes in new code. Old function can be used when
7097 // creating patches that are supposed to be backported to older stable branches.
7098 // These deprecated functions will not be removed in near future,
7099 // before removing devs will be warned with a debugging message first,
7100 // then we will add error message and only after that we can remove the functions
7104 * Runs get_records select on context table and returns the result
7105 * Does get_records_select on the context table, and returns the results ordered
7106 * by contextlevel, and then the natural sort order within each level.
7107 * for the purpose of $select, you need to know that the context table has been
7108 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7110 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7111 * @param array $params any parameters required by $select.
7112 * @return array the requested context records.
7114 function get_sorted_contexts($select, $params = array()) {
7116 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7120 $select = 'WHERE ' . $select;
7122 return $DB->get_records_sql("
7125 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER
. " AND u.id = ctx.instanceid
7126 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT
. " AND cat.id = ctx.instanceid
7127 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE
. " AND c.id = ctx.instanceid
7128 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE
. " AND cm.id = ctx.instanceid
7129 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK
. " AND bi.id = ctx.instanceid
7131 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7136 * Given context and array of users, returns array of users whose enrolment status is suspended,
7137 * or enrolment has expired or has not started. Also removes those users from the given array
7139 * @param context $context context in which suspended users should be extracted.
7140 * @param array $users list of users.
7141 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7142 * @return array list of suspended users.
7144 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7147 // Get active enrolled users.
7148 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7149 $activeusers = $DB->get_records_sql($sql, $params);
7151 // Move suspended users to a separate array & remove from the initial one.
7153 if (sizeof($activeusers)) {
7154 foreach ($users as $userid => $user) {
7155 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7156 $susers[$userid] = $user;
7157 unset($users[$userid]);
7165 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7166 * or enrolment has expired or not started.
7168 * @param context $context context in which user enrolment is checked.
7169 * @param bool $usecache Enable or disable (default) the request cache
7170 * @return array list of suspended user id's.
7172 function get_suspended_userids(context
$context, $usecache = false) {
7176 $cache = cache
::make('core', 'suspended_userids');
7177 $susers = $cache->get($context->id
);
7178 if ($susers !== false) {
7183 $coursecontext = $context->get_course_context();
7186 // Front page users are always enrolled, so suspended list is empty.
7187 if ($coursecontext->instanceid
!= SITEID
) {
7188 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7189 $susers = $DB->get_fieldset_sql($sql, $params);
7190 $susers = array_combine($susers, $susers);
7193 // Cache results for the remainder of this request.
7195 $cache->set($context->id
, $susers);
7202 * Gets sql for finding users with capability in the given context
7204 * @param context $context
7205 * @param string|array $capability Capability name or array of names.
7206 * If an array is provided then this is the equivalent of a logical 'OR',
7207 * i.e. the user needs to have one of these capabilities.
7208 * @return array($sql, $params)
7210 function get_with_capability_sql(context
$context, $capability) {
7213 $prefix = 'cu' . $i . '_';
7215 $capjoin = get_with_capability_join($context, $capability, $prefix . 'u.id');
7217 $sql = "SELECT DISTINCT {$prefix}u.id
7218 FROM {user} {$prefix}u
7220 WHERE {$prefix}u.deleted = 0 AND $capjoin->wheres";
7222 return array($sql, $capjoin->params
);
7226 * Gets sql joins for finding users with capability in the given context
7228 * @param context $context Context for the join
7229 * @param string|array $capability Capability name or array of names.
7230 * If an array is provided then this is the equivalent of a logical 'OR',
7231 * i.e. the user needs to have one of these capabilities.
7232 * @param string $useridcolumn e.g. 'u.id'
7233 * @return \core\dml\sql_join Contains joins, wheres, params
7235 function get_with_capability_join(context
$context, $capability, $useridcolumn) {
7238 // Use unique prefix just in case somebody makes some SQL magic with the result.
7241 $prefix = 'eu' . $i . '_';
7243 // First find the course context.
7244 $coursecontext = $context->get_course_context();
7246 $isfrontpage = ($coursecontext->instanceid
== SITEID
);
7252 list($contextids, $contextpaths) = get_context_info_list($context);
7254 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED
, 'ctx');
7256 list($incaps, $capsparams) = $DB->get_in_or_equal($capability, SQL_PARAMS_NAMED
, 'cap');
7259 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
7260 FROM {role_capabilities} rc
7261 JOIN {context} ctx on rc.contextid = ctx.id
7262 WHERE rc.contextid $incontexts AND rc.capability $incaps";
7263 $rcs = $DB->get_records_sql($sql, array_merge($cparams, $capsparams));
7264 foreach ($rcs as $rc) {
7265 $defs[$rc->path
][$rc->roleid
] = $rc->permission
;
7269 if (!empty($defs)) {
7270 foreach ($contextpaths as $path) {
7271 if (empty($defs[$path])) {
7274 foreach ($defs[$path] as $roleid => $perm) {
7275 if ($perm == CAP_PROHIBIT
) {
7276 $access[$roleid] = CAP_PROHIBIT
;
7279 if (!isset($access[$roleid])) {
7280 $access[$roleid] = (int) $perm;
7288 // Make lists of roles that are needed and prohibited.
7289 $needed = array(); // One of these is enough.
7290 $prohibited = array(); // Must not have any of these.
7291 foreach ($access as $roleid => $perm) {
7292 if ($perm == CAP_PROHIBIT
) {
7293 unset($needed[$roleid]);
7294 $prohibited[$roleid] = true;
7296 if ($perm == CAP_ALLOW
and empty($prohibited[$roleid])) {
7297 $needed[$roleid] = true;
7302 $defaultuserroleid = isset($CFG->defaultuserroleid
) ?
$CFG->defaultuserroleid
: 0;
7303 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid
) ?
$CFG->defaultfrontpageroleid
: 0;
7308 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
7311 if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
7312 // Everybody not having prohibit has the capability.
7315 if (empty($needed)) {
7321 if (!empty($prohibited[$defaultuserroleid])) {
7324 if (!empty($needed[$defaultuserroleid])) {
7325 // Everybody not having prohibit has the capability.
7328 if (empty($needed)) {
7336 // Nobody can match so return some SQL that does not return any results.
7337 $wheres[] = "1 = 2";
7342 $ctxids = implode(',', $contextids);
7343 $roleids = implode(',', array_keys($needed));
7344 $joins[] = "JOIN {role_assignments} {$prefix}ra3
7345 ON ({$prefix}ra3.userid = $useridcolumn
7346 AND {$prefix}ra3.roleid IN ($roleids)
7347 AND {$prefix}ra3.contextid IN ($ctxids))";
7351 $ctxids = implode(',', $contextids);
7352 $roleids = implode(',', array_keys($prohibited));
7353 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4
7354 ON ({$prefix}ra4.userid = $useridcolumn
7355 AND {$prefix}ra4.roleid IN ($roleids)
7356 AND {$prefix}ra4.contextid IN ($ctxids))";
7357 $wheres[] = "{$prefix}ra4.id IS NULL";
7362 $wheres[] = "$useridcolumn <> :{$prefix}guestid";
7363 $params["{$prefix}guestid"] = $CFG->siteguest
;
7365 $joins = implode("\n", $joins);
7366 $wheres = "(" . implode(" AND ", $wheres) . ")";
7368 return new \core\dml\
sql_join($joins, $wheres, $params);