Merge branch 'MDL-76905-master' of https://github.com/ferranrecio/moodle
[moodle.git] / lib / accesslib.php
blob9ea453a07c25231ec88e864c2ac28464d5c718ce
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
18 * This file contains functions for managing user access
20 * <b>Public API vs internals</b>
22 * General users probably only care about
24 * Context handling
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...
31 * - has_capability()
32 * - has_any_capability()
33 * - has_all_capabilities()
34 * - require_capability()
35 * - require_login() (from moodlelib)
36 * - is_enrolled()
37 * - is_viewing()
38 * - is_guest()
39 * - is_siteadmin()
40 * - isguestuser()
41 * - isloggedin()
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
50 * Modify roles
51 * - role_assign()
52 * - role_unassign()
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()
60 * - etc.
62 * <b>Name conventions</b>
64 * "ctx" means context
65 * "ra" means role assignment
66 * "rdef" means role definition
68 * <b>accessdata</b>
70 * Access control data is held in the "accessdata" array
71 * which - for the logged-in user, will be in $USER->access
73 * For other users can be generated and passed around (but may also be cached
74 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser).
76 * $accessdata is a multidimensional array, holding
77 * role assignments (RAs), role switches and initialization time.
79 * Things are keyed on "contextpaths" (the path field of
80 * the context table) for fast walking up/down the tree.
81 * <code>
82 * $accessdata['ra'][$contextpath] = array($roleid=>$roleid)
83 * [$contextpath] = array($roleid=>$roleid)
84 * [$contextpath] = array($roleid=>$roleid)
85 * </code>
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);
169 /** Performance hint for assign_capability: the contextid is known to exist */
170 define('ACCESSLIB_HINT_CONTEXT_EXISTS', 'contextexists');
171 /** Performance hint for assign_capability: there is no existing entry in role_capabilities */
172 define('ACCESSLIB_HINT_NO_EXISTING', 'notexists');
175 * Although this looks like a global variable, it isn't really.
177 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
178 * It is used to cache various bits of data between function calls for performance reasons.
179 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
180 * as methods of a class, instead of functions.
182 * @access private
183 * @global stdClass $ACCESSLIB_PRIVATE
184 * @name $ACCESSLIB_PRIVATE
186 global $ACCESSLIB_PRIVATE;
187 $ACCESSLIB_PRIVATE = new stdClass();
188 $ACCESSLIB_PRIVATE->cacheroledefs = array(); // Holds site-wide role definitions.
189 $ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache, loaded from DB once per page
190 $ACCESSLIB_PRIVATE->dirtyusers = null; // Dirty users cache, loaded from DB once per $USER->id
191 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
194 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
196 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
197 * accesslib's private caches. You need to do this before setting up test data,
198 * and also at the end of the tests.
200 * @access private
201 * @return void
203 function accesslib_clear_all_caches_for_unit_testing() {
204 global $USER;
205 if (!PHPUNIT_TEST) {
206 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
209 accesslib_clear_all_caches(true);
210 accesslib_reset_role_cache();
212 unset($USER->access);
216 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
218 * This reset does not touch global $USER.
220 * @access private
221 * @param bool $resetcontexts
222 * @return void
224 function accesslib_clear_all_caches($resetcontexts) {
225 global $ACCESSLIB_PRIVATE;
227 $ACCESSLIB_PRIVATE->dirtycontexts = null;
228 $ACCESSLIB_PRIVATE->dirtyusers = null;
229 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
231 if ($resetcontexts) {
232 context_helper::reset_caches();
237 * Full reset of accesslib's private role cache. ONLY TO BE USED FROM THIS LIBRARY FILE!
239 * This reset does not touch global $USER.
241 * Note: Only use this when the roles that need a refresh are unknown.
243 * @see accesslib_clear_role_cache()
245 * @access private
246 * @return void
248 function accesslib_reset_role_cache() {
249 global $ACCESSLIB_PRIVATE;
251 $ACCESSLIB_PRIVATE->cacheroledefs = array();
252 $cache = cache::make('core', 'roledefs');
253 $cache->purge();
257 * Clears accesslib's private cache of a specific role or roles. ONLY BE USED FROM THIS LIBRARY FILE!
259 * This reset does not touch global $USER.
261 * @access private
262 * @param int|array $roles
263 * @return void
265 function accesslib_clear_role_cache($roles) {
266 global $ACCESSLIB_PRIVATE;
268 if (!is_array($roles)) {
269 $roles = [$roles];
272 foreach ($roles as $role) {
273 if (isset($ACCESSLIB_PRIVATE->cacheroledefs[$role])) {
274 unset($ACCESSLIB_PRIVATE->cacheroledefs[$role]);
278 $cache = cache::make('core', 'roledefs');
279 $cache->delete_many($roles);
283 * Role is assigned at system context.
285 * @access private
286 * @param int $roleid
287 * @return array
289 function get_role_access($roleid) {
290 $accessdata = get_empty_accessdata();
291 $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
292 return $accessdata;
296 * Fetch raw "site wide" role definitions.
297 * Even MUC static acceleration cache appears a bit slow for this.
298 * Important as can be hit hundreds of times per page.
300 * @param array $roleids List of role ids to fetch definitions for.
301 * @return array Complete definition for each requested role.
303 function get_role_definitions(array $roleids) {
304 global $ACCESSLIB_PRIVATE;
306 if (empty($roleids)) {
307 return array();
310 // Grab all keys we have not yet got in our static cache.
311 if ($uncached = array_diff($roleids, array_keys($ACCESSLIB_PRIVATE->cacheroledefs))) {
312 $cache = cache::make('core', 'roledefs');
313 foreach ($cache->get_many($uncached) as $roleid => $cachedroledef) {
314 if (is_array($cachedroledef)) {
315 $ACCESSLIB_PRIVATE->cacheroledefs[$roleid] = $cachedroledef;
319 // Check we have the remaining keys from the MUC.
320 if ($uncached = array_diff($roleids, array_keys($ACCESSLIB_PRIVATE->cacheroledefs))) {
321 $uncached = get_role_definitions_uncached($uncached);
322 $ACCESSLIB_PRIVATE->cacheroledefs += $uncached;
323 $cache->set_many($uncached);
327 // Return just the roles we need.
328 return array_intersect_key($ACCESSLIB_PRIVATE->cacheroledefs, array_flip($roleids));
332 * Query raw "site wide" role definitions.
334 * @param array $roleids List of role ids to fetch definitions for.
335 * @return array Complete definition for each requested role.
337 function get_role_definitions_uncached(array $roleids) {
338 global $DB;
340 if (empty($roleids)) {
341 return array();
344 // Create a blank results array: even if a role has no capabilities,
345 // we need to ensure it is included in the results to show we have
346 // loaded all the capabilities that there are.
347 $rdefs = array();
348 foreach ($roleids as $roleid) {
349 $rdefs[$roleid] = array();
352 // Load all the capabilities for these roles in all contexts.
353 list($sql, $params) = $DB->get_in_or_equal($roleids);
354 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
355 FROM {role_capabilities} rc
356 JOIN {context} ctx ON rc.contextid = ctx.id
357 JOIN {capabilities} cap ON rc.capability = cap.name
358 WHERE rc.roleid $sql";
359 $rs = $DB->get_recordset_sql($sql, $params);
361 // Store the capabilities into the expected data structure.
362 foreach ($rs as $rd) {
363 if (!isset($rdefs[$rd->roleid][$rd->path])) {
364 $rdefs[$rd->roleid][$rd->path] = array();
366 $rdefs[$rd->roleid][$rd->path][$rd->capability] = (int) $rd->permission;
369 $rs->close();
371 // Sometimes (e.g. get_user_capability_course_helper::get_capability_info_at_each_context)
372 // we process role definitinons in a way that requires we see parent contexts
373 // before child contexts. This sort ensures that works (and is faster than
374 // sorting in the SQL query).
375 foreach ($rdefs as $roleid => $rdef) {
376 ksort($rdefs[$roleid]);
379 return $rdefs;
383 * Get the default guest role, this is used for guest account,
384 * search engine spiders, etc.
386 * @return stdClass role record
388 function get_guest_role() {
389 global $CFG, $DB;
391 if (empty($CFG->guestroleid)) {
392 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
393 $guestrole = array_shift($roles); // Pick the first one
394 set_config('guestroleid', $guestrole->id);
395 return $guestrole;
396 } else {
397 debugging('Can not find any guest role!');
398 return false;
400 } else {
401 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
402 return $guestrole;
403 } else {
404 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
405 set_config('guestroleid', '');
406 return get_guest_role();
412 * Check whether a user has a particular capability in a given context.
414 * For example:
415 * $context = context_module::instance($cm->id);
416 * has_capability('mod/forum:replypost', $context)
418 * By default checks the capabilities of the current user, but you can pass a
419 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
421 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
422 * or capabilities with XSS, config or data loss risks.
424 * @category access
426 * @param string $capability the name of the capability to check. For example mod/forum:view
427 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
428 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
429 * @param boolean $doanything If false, ignores effect of admin role assignment
430 * @return boolean true if the user has this capability. Otherwise false.
432 function has_capability($capability, context $context, $user = null, $doanything = true) {
433 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
435 if (during_initial_install()) {
436 if ($SCRIPT === "/$CFG->admin/index.php"
437 or $SCRIPT === "/$CFG->admin/cli/install.php"
438 or $SCRIPT === "/$CFG->admin/cli/install_database.php"
439 or (defined('BEHAT_UTIL') and BEHAT_UTIL)
440 or (defined('PHPUNIT_UTIL') and PHPUNIT_UTIL)) {
441 // we are in an installer - roles can not work yet
442 return true;
443 } else {
444 return false;
448 if (strpos($capability, 'moodle/legacy:') === 0) {
449 throw new coding_exception('Legacy capabilities can not be used any more!');
452 if (!is_bool($doanything)) {
453 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
456 // capability must exist
457 if (!$capinfo = get_capability_info($capability)) {
458 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
459 return false;
462 if (!isset($USER->id)) {
463 // should never happen
464 $USER->id = 0;
465 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER);
468 // make sure there is a real user specified
469 if ($user === null) {
470 $userid = $USER->id;
471 } else {
472 $userid = is_object($user) ? $user->id : $user;
475 // make sure forcelogin cuts off not-logged-in users if enabled
476 if (!empty($CFG->forcelogin) and $userid == 0) {
477 return false;
480 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
481 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
482 if (isguestuser($userid) or $userid == 0) {
483 return false;
487 // Check whether context locking is enabled.
488 if (!empty($CFG->contextlocking)) {
489 if ($capinfo->captype === 'write' && $context->locked) {
490 // Context locking applies to any write capability in a locked context.
491 // It does not apply to moodle/site:managecontextlocks - this is to allow context locking to be unlocked.
492 if ($capinfo->name !== 'moodle/site:managecontextlocks') {
493 // It applies to all users who are not site admins.
494 // It also applies to site admins when contextlockappliestoadmin is set.
495 if (!is_siteadmin($userid) || !empty($CFG->contextlockappliestoadmin)) {
496 return false;
502 // somehow make sure the user is not deleted and actually exists
503 if ($userid != 0) {
504 if ($userid == $USER->id and isset($USER->deleted)) {
505 // this prevents one query per page, it is a bit of cheating,
506 // but hopefully session is terminated properly once user is deleted
507 if ($USER->deleted) {
508 return false;
510 } else {
511 if (!context_user::instance($userid, IGNORE_MISSING)) {
512 // no user context == invalid userid
513 return false;
518 // context path/depth must be valid
519 if (empty($context->path) or $context->depth == 0) {
520 // this should not happen often, each upgrade tries to rebuild the context paths
521 debugging('Context id '.$context->id.' does not have valid path, please use context_helper::build_all_paths()');
522 if (is_siteadmin($userid)) {
523 return true;
524 } else {
525 return false;
529 if (!empty($USER->loginascontext)) {
530 // The current user is logged in as another user and can assume their identity at or below the `loginascontext`
531 // defined in the USER session.
532 // The user may not assume their identity at any other location.
533 if (!$USER->loginascontext->is_parent_of($context, true)) {
534 // The context being checked is not the specified context, or one of its children.
535 return false;
539 // Find out if user is admin - it is not possible to override the doanything in any way
540 // and it is not possible to switch to admin role either.
541 if ($doanything) {
542 if (is_siteadmin($userid)) {
543 if ($userid != $USER->id) {
544 return true;
546 // make sure switchrole is not used in this context
547 if (empty($USER->access['rsw'])) {
548 return true;
550 $parts = explode('/', trim($context->path, '/'));
551 $path = '';
552 $switched = false;
553 foreach ($parts as $part) {
554 $path .= '/' . $part;
555 if (!empty($USER->access['rsw'][$path])) {
556 $switched = true;
557 break;
560 if (!$switched) {
561 return true;
563 //ok, admin switched role in this context, let's use normal access control rules
567 // Careful check for staleness...
568 $context->reload_if_dirty();
570 if ($USER->id == $userid) {
571 if (!isset($USER->access)) {
572 load_all_capabilities();
574 $access =& $USER->access;
576 } else {
577 // make sure user accessdata is really loaded
578 get_user_accessdata($userid, true);
579 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
582 return has_capability_in_accessdata($capability, $context, $access);
586 * Check if the user has any one of several capabilities from a list.
588 * This is just a utility method that calls has_capability in a loop. Try to put
589 * the capabilities that most users are likely to have first in the list for best
590 * performance.
592 * @category access
593 * @see has_capability()
595 * @param array $capabilities an array of capability names.
596 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
597 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
598 * @param boolean $doanything If false, ignore effect of admin role assignment
599 * @return boolean true if the user has any of these capabilities. Otherwise false.
601 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
602 foreach ($capabilities as $capability) {
603 if (has_capability($capability, $context, $user, $doanything)) {
604 return true;
607 return false;
611 * Check if the user has all the capabilities in a list.
613 * This is just a utility method that calls has_capability in a loop. Try to put
614 * the capabilities that fewest users are likely to have first in the list for best
615 * performance.
617 * @category access
618 * @see has_capability()
620 * @param array $capabilities an array of capability names.
621 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
622 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
623 * @param boolean $doanything If false, ignore effect of admin role assignment
624 * @return boolean true if the user has all of these capabilities. Otherwise false.
626 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
627 foreach ($capabilities as $capability) {
628 if (!has_capability($capability, $context, $user, $doanything)) {
629 return false;
632 return true;
636 * Is course creator going to have capability in a new course?
638 * This is intended to be used in enrolment plugins before or during course creation,
639 * do not use after the course is fully created.
641 * @category access
643 * @param string $capability the name of the capability to check.
644 * @param context $context course or category context where is course going to be created
645 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
646 * @return boolean true if the user will have this capability.
648 * @throws coding_exception if different type of context submitted
650 function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) {
651 global $CFG;
653 if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) {
654 throw new coding_exception('Only course or course category context expected');
657 if (has_capability($capability, $context, $user)) {
658 // User already has the capability, it could be only removed if CAP_PROHIBIT
659 // was involved here, but we ignore that.
660 return true;
663 if (!has_capability('moodle/course:create', $context, $user)) {
664 return false;
667 if (!enrol_is_enabled('manual')) {
668 return false;
671 if (empty($CFG->creatornewroleid)) {
672 return false;
675 if ($context->contextlevel == CONTEXT_COURSE) {
676 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
677 return false;
679 } else {
680 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
681 return false;
685 // Most likely they will be enrolled after the course creation is finished,
686 // does the new role have the required capability?
687 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
688 return isset($neededroles[$CFG->creatornewroleid]);
692 * Check if the user is an admin at the site level.
694 * Please note that use of proper capabilities is always encouraged,
695 * this function is supposed to be used from core or for temporary hacks.
697 * @category access
699 * @param int|stdClass $user_or_id user id or user object
700 * @return bool true if user is one of the administrators, false otherwise
702 function is_siteadmin($user_or_id = null) {
703 global $CFG, $USER;
705 if ($user_or_id === null) {
706 $user_or_id = $USER;
709 if (empty($user_or_id)) {
710 return false;
712 if (!empty($user_or_id->id)) {
713 $userid = $user_or_id->id;
714 } else {
715 $userid = $user_or_id;
718 // Because this script is called many times (150+ for course page) with
719 // the same parameters, it is worth doing minor optimisations. This static
720 // cache stores the value for a single userid, saving about 2ms from course
721 // page load time without using significant memory. As the static cache
722 // also includes the value it depends on, this cannot break unit tests.
723 static $knownid, $knownresult, $knownsiteadmins;
724 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
725 return $knownresult;
727 $knownid = $userid;
728 $knownsiteadmins = $CFG->siteadmins;
730 $siteadmins = explode(',', $CFG->siteadmins);
731 $knownresult = in_array($userid, $siteadmins);
732 return $knownresult;
736 * Returns true if user has at least one role assign
737 * of 'coursecontact' role (is potentially listed in some course descriptions).
739 * @param int $userid
740 * @return bool
742 function has_coursecontact_role($userid) {
743 global $DB, $CFG;
745 if (empty($CFG->coursecontact)) {
746 return false;
748 $sql = "SELECT 1
749 FROM {role_assignments}
750 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
751 return $DB->record_exists_sql($sql, array('userid'=>$userid));
755 * Does the user have a capability to do something?
757 * Walk the accessdata array and return true/false.
758 * Deals with prohibits, role switching, aggregating
759 * capabilities, etc.
761 * The main feature of here is being FAST and with no
762 * side effects.
764 * Notes:
766 * Switch Role merges with default role
767 * ------------------------------------
768 * If you are a teacher in course X, you have at least
769 * teacher-in-X + defaultloggedinuser-sitewide. So in the
770 * course you'll have techer+defaultloggedinuser.
771 * We try to mimic that in switchrole.
773 * Permission evaluation
774 * ---------------------
775 * Originally there was an extremely complicated way
776 * to determine the user access that dealt with
777 * "locality" or role assignments and role overrides.
778 * Now we simply evaluate access for each role separately
779 * and then verify if user has at least one role with allow
780 * and at the same time no role with prohibit.
782 * @access private
783 * @param string $capability
784 * @param context $context
785 * @param array $accessdata
786 * @return bool
788 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
789 global $CFG;
791 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
792 $path = $context->path;
793 $paths = array($path);
794 while ($path = rtrim($path, '0123456789')) {
795 $path = rtrim($path, '/');
796 if ($path === '') {
797 break;
799 $paths[] = $path;
802 $roles = array();
803 $switchedrole = false;
805 // Find out if role switched
806 if (!empty($accessdata['rsw'])) {
807 // From the bottom up...
808 foreach ($paths as $path) {
809 if (isset($accessdata['rsw'][$path])) {
810 // Found a switchrole assignment - check for that role _plus_ the default user role
811 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
812 $switchedrole = true;
813 break;
818 if (!$switchedrole) {
819 // get all users roles in this context and above
820 foreach ($paths as $path) {
821 if (isset($accessdata['ra'][$path])) {
822 foreach ($accessdata['ra'][$path] as $roleid) {
823 $roles[$roleid] = null;
829 // Now find out what access is given to each role, going bottom-->up direction
830 $rdefs = get_role_definitions(array_keys($roles));
831 $allowed = false;
833 foreach ($roles as $roleid => $ignored) {
834 foreach ($paths as $path) {
835 if (isset($rdefs[$roleid][$path][$capability])) {
836 $perm = (int)$rdefs[$roleid][$path][$capability];
837 if ($perm === CAP_PROHIBIT) {
838 // any CAP_PROHIBIT found means no permission for the user
839 return false;
841 if (is_null($roles[$roleid])) {
842 $roles[$roleid] = $perm;
846 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
847 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
850 return $allowed;
854 * A convenience function that tests has_capability, and displays an error if
855 * the user does not have that capability.
857 * NOTE before Moodle 2.0, this function attempted to make an appropriate
858 * require_login call before checking the capability. This is no longer the case.
859 * You must call require_login (or one of its variants) if you want to check the
860 * user is logged in, before you call this function.
862 * @see has_capability()
864 * @param string $capability the name of the capability to check. For example mod/forum:view
865 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
866 * @param int $userid A user id. By default (null) checks the permissions of the current user.
867 * @param bool $doanything If false, ignore effect of admin role assignment
868 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
869 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
870 * @return void terminates with an error if the user does not have the given capability.
872 function require_capability($capability, context $context, $userid = null, $doanything = true,
873 $errormessage = 'nopermissions', $stringfile = '') {
874 if (!has_capability($capability, $context, $userid, $doanything)) {
875 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
880 * A convenience function that tests has_capability for a list of capabilities, and displays an error if
881 * the user does not have that capability.
883 * This is just a utility method that calls has_capability in a loop. Try to put
884 * the capabilities that fewest users are likely to have first in the list for best
885 * performance.
887 * @category access
888 * @see has_capability()
890 * @param array $capabilities an array of capability names.
891 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
892 * @param int $userid A user id. By default (null) checks the permissions of the current user.
893 * @param bool $doanything If false, ignore effect of admin role assignment
894 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
895 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
896 * @return void terminates with an error if the user does not have the given capability.
898 function require_all_capabilities(array $capabilities, context $context, $userid = null, $doanything = true,
899 $errormessage = 'nopermissions', $stringfile = ''): void {
900 foreach ($capabilities as $capability) {
901 if (!has_capability($capability, $context, $userid, $doanything)) {
902 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
908 * Return a nested array showing all role assignments for the user.
909 * [ra] => [contextpath][roleid] = roleid
911 * @access private
912 * @param int $userid - the id of the user
913 * @return array access info array
915 function get_user_roles_sitewide_accessdata($userid) {
916 global $CFG, $DB;
918 $accessdata = get_empty_accessdata();
920 // start with the default role
921 if (!empty($CFG->defaultuserroleid)) {
922 $syscontext = context_system::instance();
923 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
926 // load the "default frontpage role"
927 if (!empty($CFG->defaultfrontpageroleid)) {
928 $frontpagecontext = context_course::instance(get_site()->id);
929 if ($frontpagecontext->path) {
930 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
934 // Preload every assigned role.
935 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
936 FROM {role_assignments} ra
937 JOIN {context} ctx ON ctx.id = ra.contextid
938 WHERE ra.userid = :userid";
940 $rs = $DB->get_recordset_sql($sql, array('userid' => $userid));
942 foreach ($rs as $ra) {
943 // RAs leafs are arrays to support multi-role assignments...
944 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
947 $rs->close();
949 return $accessdata;
953 * Returns empty accessdata structure.
955 * @access private
956 * @return array empt accessdata
958 function get_empty_accessdata() {
959 $accessdata = array(); // named list
960 $accessdata['ra'] = array();
961 $accessdata['time'] = time();
962 $accessdata['rsw'] = array();
964 return $accessdata;
968 * Get accessdata for a given user.
970 * @access private
971 * @param int $userid
972 * @param bool $preloadonly true means do not return access array
973 * @return array accessdata
975 function get_user_accessdata($userid, $preloadonly=false) {
976 global $CFG, $ACCESSLIB_PRIVATE, $USER;
978 if (isset($USER->access)) {
979 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->access;
982 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
983 if (empty($userid)) {
984 if (!empty($CFG->notloggedinroleid)) {
985 $accessdata = get_role_access($CFG->notloggedinroleid);
986 } else {
987 // weird
988 return get_empty_accessdata();
991 } else if (isguestuser($userid)) {
992 if ($guestrole = get_guest_role()) {
993 $accessdata = get_role_access($guestrole->id);
994 } else {
995 //weird
996 return get_empty_accessdata();
999 } else {
1000 // Includes default role and frontpage role.
1001 $accessdata = get_user_roles_sitewide_accessdata($userid);
1004 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1007 if ($preloadonly) {
1008 return;
1009 } else {
1010 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1015 * A convenience function to completely load all the capabilities
1016 * for the current user. It is called from has_capability() and functions change permissions.
1018 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1019 * @see check_enrolment_plugins()
1021 * @access private
1022 * @return void
1024 function load_all_capabilities() {
1025 global $USER;
1027 // roles not installed yet - we are in the middle of installation
1028 if (during_initial_install()) {
1029 return;
1032 if (!isset($USER->id)) {
1033 // this should not happen
1034 $USER->id = 0;
1037 unset($USER->access);
1038 $USER->access = get_user_accessdata($USER->id);
1040 // Clear to force a refresh
1041 unset($USER->mycourses);
1043 // init/reset internal enrol caches - active course enrolments and temp access
1044 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1048 * A convenience function to completely reload all the capabilities
1049 * for the current user when roles have been updated in a relevant
1050 * context -- but PRESERVING switchroles and loginas.
1051 * This function resets all accesslib and context caches.
1053 * That is - completely transparent to the user.
1055 * Note: reloads $USER->access completely.
1057 * @access private
1058 * @return void
1060 function reload_all_capabilities() {
1061 global $USER, $DB, $ACCESSLIB_PRIVATE;
1063 // copy switchroles
1064 $sw = array();
1065 if (!empty($USER->access['rsw'])) {
1066 $sw = $USER->access['rsw'];
1069 accesslib_clear_all_caches(true);
1070 unset($USER->access);
1072 // Prevent dirty flags refetching on this page.
1073 $ACCESSLIB_PRIVATE->dirtycontexts = array();
1074 $ACCESSLIB_PRIVATE->dirtyusers = array($USER->id => false);
1076 load_all_capabilities();
1078 foreach ($sw as $path => $roleid) {
1079 if ($record = $DB->get_record('context', array('path'=>$path))) {
1080 $context = context::instance_by_id($record->id);
1081 if (has_capability('moodle/role:switchroles', $context)) {
1082 role_switch($roleid, $context);
1089 * Adds a temp role to current USER->access array.
1091 * Useful for the "temporary guest" access we grant to logged-in users.
1092 * This is useful for enrol plugins only.
1094 * @since Moodle 2.2
1095 * @param context_course $coursecontext
1096 * @param int $roleid
1097 * @return void
1099 function load_temp_course_role(context_course $coursecontext, $roleid) {
1100 global $USER, $SITE;
1102 if (empty($roleid)) {
1103 debugging('invalid role specified in load_temp_course_role()');
1104 return;
1107 if ($coursecontext->instanceid == $SITE->id) {
1108 debugging('Can not use temp roles on the frontpage');
1109 return;
1112 if (!isset($USER->access)) {
1113 load_all_capabilities();
1116 $coursecontext->reload_if_dirty();
1118 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1119 return;
1122 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1126 * Removes any extra guest roles from current USER->access array.
1127 * This is useful for enrol plugins only.
1129 * @since Moodle 2.2
1130 * @param context_course $coursecontext
1131 * @return void
1133 function remove_temp_course_roles(context_course $coursecontext) {
1134 global $DB, $USER, $SITE;
1136 if ($coursecontext->instanceid == $SITE->id) {
1137 debugging('Can not use temp roles on the frontpage');
1138 return;
1141 if (empty($USER->access['ra'][$coursecontext->path])) {
1142 //no roles here, weird
1143 return;
1146 $sql = "SELECT DISTINCT ra.roleid AS id
1147 FROM {role_assignments} ra
1148 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1149 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1151 $USER->access['ra'][$coursecontext->path] = array();
1152 foreach ($ras as $r) {
1153 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1158 * Returns array of all role archetypes.
1160 * @return array
1162 function get_role_archetypes() {
1163 return array(
1164 'manager' => 'manager',
1165 'coursecreator' => 'coursecreator',
1166 'editingteacher' => 'editingteacher',
1167 'teacher' => 'teacher',
1168 'student' => 'student',
1169 'guest' => 'guest',
1170 'user' => 'user',
1171 'frontpage' => 'frontpage'
1176 * Assign the defaults found in this capability definition to roles that have
1177 * the corresponding legacy capabilities assigned to them.
1179 * @param string $capability
1180 * @param array $legacyperms an array in the format (example):
1181 * 'guest' => CAP_PREVENT,
1182 * 'student' => CAP_ALLOW,
1183 * 'teacher' => CAP_ALLOW,
1184 * 'editingteacher' => CAP_ALLOW,
1185 * 'coursecreator' => CAP_ALLOW,
1186 * 'manager' => CAP_ALLOW
1187 * @return boolean success or failure.
1189 function assign_legacy_capabilities($capability, $legacyperms) {
1191 $archetypes = get_role_archetypes();
1193 foreach ($legacyperms as $type => $perm) {
1195 $systemcontext = context_system::instance();
1196 if ($type === 'admin') {
1197 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1198 $type = 'manager';
1201 if (!array_key_exists($type, $archetypes)) {
1202 throw new \moodle_exception('invalidlegacy', '', '', $type);
1205 if ($roles = get_archetype_roles($type)) {
1206 foreach ($roles as $role) {
1207 // Assign a site level capability.
1208 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1209 return false;
1214 return true;
1218 * Verify capability risks.
1220 * @param stdClass $capability a capability - a row from the capabilities table.
1221 * @return boolean whether this capability is safe - that is, whether people with the
1222 * safeoverrides capability should be allowed to change it.
1224 function is_safe_capability($capability) {
1225 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1229 * Get the local override (if any) for a given capability in a role in a context
1231 * @param int $roleid
1232 * @param int $contextid
1233 * @param string $capability
1234 * @return stdClass local capability override
1236 function get_local_override($roleid, $contextid, $capability) {
1237 global $DB;
1239 return $DB->get_record_sql("
1240 SELECT rc.*
1241 FROM {role_capabilities} rc
1242 JOIN {capability} cap ON rc.capability = cap.name
1243 WHERE rc.roleid = :roleid AND rc.capability = :capability AND rc.contextid = :contextid", [
1244 'roleid' => $roleid,
1245 'contextid' => $contextid,
1246 'capability' => $capability,
1252 * Returns context instance plus related course and cm instances
1254 * @param int $contextid
1255 * @return array of ($context, $course, $cm)
1257 function get_context_info_array($contextid) {
1258 global $DB;
1260 $context = context::instance_by_id($contextid, MUST_EXIST);
1261 $course = null;
1262 $cm = null;
1264 if ($context->contextlevel == CONTEXT_COURSE) {
1265 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1267 } else if ($context->contextlevel == CONTEXT_MODULE) {
1268 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1269 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1271 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1272 $parent = $context->get_parent_context();
1274 if ($parent->contextlevel == CONTEXT_COURSE) {
1275 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1276 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1277 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1278 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1282 return array($context, $course, $cm);
1286 * Function that creates a role
1288 * @param string $name role name
1289 * @param string $shortname role short name
1290 * @param string $description role description
1291 * @param string $archetype
1292 * @return int id or dml_exception
1294 function create_role($name, $shortname, $description, $archetype = '') {
1295 global $DB;
1297 if (strpos($archetype, 'moodle/legacy:') !== false) {
1298 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1301 // verify role archetype actually exists
1302 $archetypes = get_role_archetypes();
1303 if (empty($archetypes[$archetype])) {
1304 $archetype = '';
1307 // Insert the role record.
1308 $role = new stdClass();
1309 $role->name = $name;
1310 $role->shortname = $shortname;
1311 $role->description = $description;
1312 $role->archetype = $archetype;
1314 //find free sortorder number
1315 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1316 if (empty($role->sortorder)) {
1317 $role->sortorder = 1;
1319 $role->id = $DB->insert_record('role', $role);
1320 $event = \core\event\role_created::create([
1321 'objectid' => $role->id,
1322 'context' => context_system::instance(),
1323 'other' => [
1324 'name' => $role->name,
1325 'shortname' => $role->shortname,
1326 'archetype' => $role->archetype,
1330 $event->add_record_snapshot('role', $role);
1331 $event->trigger();
1333 return $role->id;
1337 * Function that deletes a role and cleanups up after it
1339 * @param int $roleid id of role to delete
1340 * @return bool always true
1342 function delete_role($roleid) {
1343 global $DB;
1345 // first unssign all users
1346 role_unassign_all(array('roleid'=>$roleid));
1348 // cleanup all references to this role, ignore errors
1349 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1350 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1351 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1352 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1353 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1354 $DB->delete_records('role_names', array('roleid'=>$roleid));
1355 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1357 // Get role record before it's deleted.
1358 $role = $DB->get_record('role', array('id'=>$roleid));
1360 // Finally delete the role itself.
1361 $DB->delete_records('role', array('id'=>$roleid));
1363 // Trigger event.
1364 $event = \core\event\role_deleted::create(
1365 array(
1366 'context' => context_system::instance(),
1367 'objectid' => $roleid,
1368 'other' =>
1369 array(
1370 'shortname' => $role->shortname,
1371 'description' => $role->description,
1372 'archetype' => $role->archetype
1376 $event->add_record_snapshot('role', $role);
1377 $event->trigger();
1379 // Reset any cache of this role, including MUC.
1380 accesslib_clear_role_cache($roleid);
1382 return true;
1386 * Function to write context specific overrides, or default capabilities.
1388 * The $performancehints array can currently contain two values intended to make this faster when
1389 * this function is being called in a loop, if you have already checked certain details:
1390 * 'contextexists' - if we already know the contextid exists in context table
1391 * ASSIGN_HINT_NO_EXISTING - if we already know there is no entry in role_capabilities matching
1392 * contextid, roleid, and capability
1394 * @param string $capability string name
1395 * @param int $permission CAP_ constants
1396 * @param int $roleid role id
1397 * @param int|context $contextid context id
1398 * @param bool $overwrite
1399 * @param string[] $performancehints Performance hints - leave blank unless needed
1400 * @return bool always true or exception
1402 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false, array $performancehints = []) {
1403 global $USER, $DB;
1405 if ($contextid instanceof context) {
1406 $context = $contextid;
1407 } else {
1408 $context = context::instance_by_id($contextid);
1411 // Capability must exist.
1412 if (!$capinfo = get_capability_info($capability)) {
1413 throw new coding_exception("Capability '{$capability}' was not found! This has to be fixed in code.");
1416 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1417 unassign_capability($capability, $roleid, $context->id);
1418 return true;
1421 if (in_array(ACCESSLIB_HINT_NO_EXISTING, $performancehints)) {
1422 $existing = false;
1423 } else {
1424 $existing = $DB->get_record('role_capabilities',
1425 ['contextid' => $context->id, 'roleid' => $roleid, 'capability' => $capability]);
1428 if ($existing and !$overwrite) { // We want to keep whatever is there already
1429 return true;
1432 $cap = new stdClass();
1433 $cap->contextid = $context->id;
1434 $cap->roleid = $roleid;
1435 $cap->capability = $capability;
1436 $cap->permission = $permission;
1437 $cap->timemodified = time();
1438 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1440 if ($existing) {
1441 $cap->id = $existing->id;
1442 $DB->update_record('role_capabilities', $cap);
1443 } else {
1444 if (in_array(ACCESSLIB_HINT_CONTEXT_EXISTS, $performancehints) ||
1445 $DB->record_exists('context', ['id' => $context->id])) {
1446 $DB->insert_record('role_capabilities', $cap);
1450 // Trigger capability_assigned event.
1451 \core\event\capability_assigned::create([
1452 'userid' => $cap->modifierid,
1453 'context' => $context,
1454 'objectid' => $roleid,
1455 'other' => [
1456 'capability' => $capability,
1457 'oldpermission' => $existing->permission ?? CAP_INHERIT,
1458 'permission' => $permission
1460 ])->trigger();
1462 // Reset any cache of this role, including MUC.
1463 accesslib_clear_role_cache($roleid);
1465 return true;
1469 * Unassign a capability from a role.
1471 * @param string $capability the name of the capability
1472 * @param int $roleid the role id
1473 * @param int|context $contextid null means all contexts
1474 * @return boolean true or exception
1476 function unassign_capability($capability, $roleid, $contextid = null) {
1477 global $DB, $USER;
1479 // Capability must exist.
1480 if (!$capinfo = get_capability_info($capability)) {
1481 throw new coding_exception("Capability '{$capability}' was not found! This has to be fixed in code.");
1484 if (!empty($contextid)) {
1485 if ($contextid instanceof context) {
1486 $context = $contextid;
1487 } else {
1488 $context = context::instance_by_id($contextid);
1490 // delete from context rel, if this is the last override in this context
1491 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1492 } else {
1493 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1496 // Trigger capability_assigned event.
1497 \core\event\capability_unassigned::create([
1498 'userid' => $USER->id,
1499 'context' => $context ?? context_system::instance(),
1500 'objectid' => $roleid,
1501 'other' => [
1502 'capability' => $capability,
1504 ])->trigger();
1506 // Reset any cache of this role, including MUC.
1507 accesslib_clear_role_cache($roleid);
1509 return true;
1513 * Get the roles that have a given capability assigned to it
1515 * This function does not resolve the actual permission of the capability.
1516 * It just checks for permissions and overrides.
1517 * Use get_roles_with_cap_in_context() if resolution is required.
1519 * @param string $capability capability name (string)
1520 * @param string $permission optional, the permission defined for this capability
1521 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1522 * @param stdClass $context null means any
1523 * @return array of role records
1525 function get_roles_with_capability($capability, $permission = null, $context = null) {
1526 global $DB;
1528 if ($context) {
1529 $contexts = $context->get_parent_context_ids(true);
1530 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1531 $contextsql = "AND rc.contextid $insql";
1532 } else {
1533 $params = array();
1534 $contextsql = '';
1537 if ($permission) {
1538 $permissionsql = " AND rc.permission = :permission";
1539 $params['permission'] = $permission;
1540 } else {
1541 $permissionsql = '';
1544 $sql = "SELECT r.*
1545 FROM {role} r
1546 WHERE r.id IN (SELECT rc.roleid
1547 FROM {role_capabilities} rc
1548 JOIN {capabilities} cap ON rc.capability = cap.name
1549 WHERE rc.capability = :capname
1550 $contextsql
1551 $permissionsql)";
1552 $params['capname'] = $capability;
1555 return $DB->get_records_sql($sql, $params);
1559 * This function makes a role-assignment (a role for a user in a particular context)
1561 * @param int $roleid the role of the id
1562 * @param int $userid userid
1563 * @param int|context $contextid id of the context
1564 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1565 * @param int $itemid id of enrolment/auth plugin
1566 * @param string $timemodified defaults to current time
1567 * @return int new/existing id of the assignment
1569 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1570 global $USER, $DB;
1572 // first of all detect if somebody is using old style parameters
1573 if ($contextid === 0 or is_numeric($component)) {
1574 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1577 // now validate all parameters
1578 if (empty($roleid)) {
1579 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1582 if (empty($userid)) {
1583 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1586 if ($itemid) {
1587 if (strpos($component, '_') === false) {
1588 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1590 } else {
1591 $itemid = 0;
1592 if ($component !== '' and strpos($component, '_') === false) {
1593 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1597 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1598 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1601 if ($contextid instanceof context) {
1602 $context = $contextid;
1603 } else {
1604 $context = context::instance_by_id($contextid, MUST_EXIST);
1607 if (!$timemodified) {
1608 $timemodified = time();
1611 // Check for existing entry
1612 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1614 if ($ras) {
1615 // role already assigned - this should not happen
1616 if (count($ras) > 1) {
1617 // very weird - remove all duplicates!
1618 $ra = array_shift($ras);
1619 foreach ($ras as $r) {
1620 $DB->delete_records('role_assignments', array('id'=>$r->id));
1622 } else {
1623 $ra = reset($ras);
1626 // actually there is no need to update, reset anything or trigger any event, so just return
1627 return $ra->id;
1630 // Create a new entry
1631 $ra = new stdClass();
1632 $ra->roleid = $roleid;
1633 $ra->contextid = $context->id;
1634 $ra->userid = $userid;
1635 $ra->component = $component;
1636 $ra->itemid = $itemid;
1637 $ra->timemodified = $timemodified;
1638 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1639 $ra->sortorder = 0;
1641 $ra->id = $DB->insert_record('role_assignments', $ra);
1643 // Role assignments have changed, so mark user as dirty.
1644 mark_user_dirty($userid);
1646 core_course_category::role_assignment_changed($roleid, $context);
1648 $event = \core\event\role_assigned::create(array(
1649 'context' => $context,
1650 'objectid' => $ra->roleid,
1651 'relateduserid' => $ra->userid,
1652 'other' => array(
1653 'id' => $ra->id,
1654 'component' => $ra->component,
1655 'itemid' => $ra->itemid
1658 $event->add_record_snapshot('role_assignments', $ra);
1659 $event->trigger();
1661 return $ra->id;
1665 * Removes one role assignment
1667 * @param int $roleid
1668 * @param int $userid
1669 * @param int $contextid
1670 * @param string $component
1671 * @param int $itemid
1672 * @return void
1674 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1675 // first make sure the params make sense
1676 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1677 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1680 if ($itemid) {
1681 if (strpos($component, '_') === false) {
1682 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1684 } else {
1685 $itemid = 0;
1686 if ($component !== '' and strpos($component, '_') === false) {
1687 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1691 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1695 * Removes multiple role assignments, parameters may contain:
1696 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1698 * @param array $params role assignment parameters
1699 * @param bool $subcontexts unassign in subcontexts too
1700 * @param bool $includemanual include manual role assignments too
1701 * @return void
1703 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1704 global $USER, $CFG, $DB;
1706 if (!$params) {
1707 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1710 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1711 foreach ($params as $key=>$value) {
1712 if (!in_array($key, $allowed)) {
1713 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1717 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1718 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1721 if ($includemanual) {
1722 if (!isset($params['component']) or $params['component'] === '') {
1723 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1727 if ($subcontexts) {
1728 if (empty($params['contextid'])) {
1729 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1733 $ras = $DB->get_records('role_assignments', $params);
1734 foreach ($ras as $ra) {
1735 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1736 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1737 // Role assignments have changed, so mark user as dirty.
1738 mark_user_dirty($ra->userid);
1740 $event = \core\event\role_unassigned::create(array(
1741 'context' => $context,
1742 'objectid' => $ra->roleid,
1743 'relateduserid' => $ra->userid,
1744 'other' => array(
1745 'id' => $ra->id,
1746 'component' => $ra->component,
1747 'itemid' => $ra->itemid
1750 $event->add_record_snapshot('role_assignments', $ra);
1751 $event->trigger();
1752 core_course_category::role_assignment_changed($ra->roleid, $context);
1755 unset($ras);
1757 // process subcontexts
1758 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1759 if ($params['contextid'] instanceof context) {
1760 $context = $params['contextid'];
1761 } else {
1762 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1765 if ($context) {
1766 $contexts = $context->get_child_contexts();
1767 $mparams = $params;
1768 foreach ($contexts as $context) {
1769 $mparams['contextid'] = $context->id;
1770 $ras = $DB->get_records('role_assignments', $mparams);
1771 foreach ($ras as $ra) {
1772 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1773 // Role assignments have changed, so mark user as dirty.
1774 mark_user_dirty($ra->userid);
1776 $event = \core\event\role_unassigned::create(
1777 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1778 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1779 $event->add_record_snapshot('role_assignments', $ra);
1780 $event->trigger();
1781 core_course_category::role_assignment_changed($ra->roleid, $context);
1787 // do this once more for all manual role assignments
1788 if ($includemanual) {
1789 $params['component'] = '';
1790 role_unassign_all($params, $subcontexts, false);
1795 * Mark a user as dirty (with timestamp) so as to force reloading of the user session.
1797 * @param int $userid
1798 * @return void
1800 function mark_user_dirty($userid) {
1801 global $CFG, $ACCESSLIB_PRIVATE;
1803 if (during_initial_install()) {
1804 return;
1807 // Throw exception if invalid userid is provided.
1808 if (empty($userid)) {
1809 throw new coding_exception('Invalid user parameter supplied for mark_user_dirty() function!');
1812 // Set dirty flag in database, set dirty field locally, and clear local accessdata cache.
1813 set_cache_flag('accesslib/dirtyusers', $userid, 1, time() + $CFG->sessiontimeout);
1814 $ACCESSLIB_PRIVATE->dirtyusers[$userid] = 1;
1815 unset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
1819 * Determines if a user is currently logged in
1821 * @category access
1823 * @return bool
1825 function isloggedin() {
1826 global $USER;
1828 return (!empty($USER->id));
1832 * Determines if a user is logged in as real guest user with username 'guest'.
1834 * @category access
1836 * @param int|object $user mixed user object or id, $USER if not specified
1837 * @return bool true if user is the real guest user, false if not logged in or other user
1839 function isguestuser($user = null) {
1840 global $USER, $DB, $CFG;
1842 // make sure we have the user id cached in config table, because we are going to use it a lot
1843 if (empty($CFG->siteguest)) {
1844 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1845 // guest does not exist yet, weird
1846 return false;
1848 set_config('siteguest', $guestid);
1850 if ($user === null) {
1851 $user = $USER;
1854 if ($user === null) {
1855 // happens when setting the $USER
1856 return false;
1858 } else if (is_numeric($user)) {
1859 return ($CFG->siteguest == $user);
1861 } else if (is_object($user)) {
1862 if (empty($user->id)) {
1863 return false; // not logged in means is not be guest
1864 } else {
1865 return ($CFG->siteguest == $user->id);
1868 } else {
1869 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1874 * Does user have a (temporary or real) guest access to course?
1876 * @category access
1878 * @param context $context
1879 * @param stdClass|int $user
1880 * @return bool
1882 function is_guest(context $context, $user = null) {
1883 global $USER;
1885 // first find the course context
1886 $coursecontext = $context->get_course_context();
1888 // make sure there is a real user specified
1889 if ($user === null) {
1890 $userid = isset($USER->id) ? $USER->id : 0;
1891 } else {
1892 $userid = is_object($user) ? $user->id : $user;
1895 if (isguestuser($userid)) {
1896 // can not inspect or be enrolled
1897 return true;
1900 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1901 // viewing users appear out of nowhere, they are neither guests nor participants
1902 return false;
1905 // consider only real active enrolments here
1906 if (is_enrolled($coursecontext, $user, '', true)) {
1907 return false;
1910 return true;
1914 * Returns true if the user has moodle/course:view capability in the course,
1915 * this is intended for admins, managers (aka small admins), inspectors, etc.
1917 * @category access
1919 * @param context $context
1920 * @param int|stdClass $user if null $USER is used
1921 * @param string $withcapability extra capability name
1922 * @return bool
1924 function is_viewing(context $context, $user = null, $withcapability = '') {
1925 // first find the course context
1926 $coursecontext = $context->get_course_context();
1928 if (isguestuser($user)) {
1929 // can not inspect
1930 return false;
1933 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1934 // admins are allowed to inspect courses
1935 return false;
1938 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1939 // site admins always have the capability, but the enrolment above blocks
1940 return false;
1943 return true;
1947 * Returns true if the user is able to access the course.
1949 * This function is in no way, shape, or form a substitute for require_login.
1950 * It should only be used in circumstances where it is not possible to call require_login
1951 * such as the navigation.
1953 * This function checks many of the methods of access to a course such as the view
1954 * capability, enrollments, and guest access. It also makes use of the cache
1955 * generated by require_login for guest access.
1957 * The flags within the $USER object that are used here should NEVER be used outside
1958 * of this function can_access_course and require_login. Doing so WILL break future
1959 * versions.
1961 * @param stdClass $course record
1962 * @param stdClass|int|null $user user record or id, current user if null
1963 * @param string $withcapability Check for this capability as well.
1964 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1965 * @return boolean Returns true if the user is able to access the course
1967 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
1968 global $DB, $USER;
1970 // this function originally accepted $coursecontext parameter
1971 if ($course instanceof context) {
1972 if ($course instanceof context_course) {
1973 debugging('deprecated context parameter, please use $course record');
1974 $coursecontext = $course;
1975 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
1976 } else {
1977 debugging('Invalid context parameter, please use $course record');
1978 return false;
1980 } else {
1981 $coursecontext = context_course::instance($course->id);
1984 if (!isset($USER->id)) {
1985 // should never happen
1986 $USER->id = 0;
1987 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
1990 // make sure there is a user specified
1991 if ($user === null) {
1992 $userid = $USER->id;
1993 } else {
1994 $userid = is_object($user) ? $user->id : $user;
1996 unset($user);
1998 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
1999 return false;
2002 if ($userid == $USER->id) {
2003 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2004 // the fact that somebody switched role means they can access the course no matter to what role they switched
2005 return true;
2009 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2010 return false;
2013 if (is_viewing($coursecontext, $userid)) {
2014 return true;
2017 if ($userid != $USER->id) {
2018 // for performance reasons we do not verify temporary guest access for other users, sorry...
2019 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2022 // === from here we deal only with $USER ===
2024 $coursecontext->reload_if_dirty();
2026 if (isset($USER->enrol['enrolled'][$course->id])) {
2027 if ($USER->enrol['enrolled'][$course->id] > time()) {
2028 return true;
2031 if (isset($USER->enrol['tempguest'][$course->id])) {
2032 if ($USER->enrol['tempguest'][$course->id] > time()) {
2033 return true;
2037 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2038 return true;
2041 if (!core_course_category::can_view_course_info($course)) {
2042 // No guest access if user does not have capability to browse courses.
2043 return false;
2046 // if not enrolled try to gain temporary guest access
2047 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2048 $enrols = enrol_get_plugins(true);
2049 foreach ($instances as $instance) {
2050 if (!isset($enrols[$instance->enrol])) {
2051 continue;
2053 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2054 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2055 if ($until !== false and $until > time()) {
2056 $USER->enrol['tempguest'][$course->id] = $until;
2057 return true;
2060 if (isset($USER->enrol['tempguest'][$course->id])) {
2061 unset($USER->enrol['tempguest'][$course->id]);
2062 remove_temp_course_roles($coursecontext);
2065 return false;
2069 * Loads the capability definitions for the component (from file).
2071 * Loads the capability definitions for the component (from file). If no
2072 * capabilities are defined for the component, we simply return an empty array.
2074 * @access private
2075 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2076 * @return array array of capabilities
2078 function load_capability_def($component) {
2079 $defpath = core_component::get_component_directory($component).'/db/access.php';
2081 $capabilities = array();
2082 if (file_exists($defpath)) {
2083 require($defpath);
2084 if (!empty(${$component.'_capabilities'})) {
2085 // BC capability array name
2086 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2087 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2088 $capabilities = ${$component.'_capabilities'};
2092 return $capabilities;
2096 * Gets the capabilities that have been cached in the database for this component.
2098 * @access private
2099 * @param string $component - examples: 'moodle', 'mod_forum'
2100 * @return array array of capabilities
2102 function get_cached_capabilities($component = 'moodle') {
2103 global $DB;
2104 $caps = get_all_capabilities();
2105 $componentcaps = array();
2106 foreach ($caps as $cap) {
2107 if ($cap['component'] == $component) {
2108 $componentcaps[] = (object) $cap;
2111 return $componentcaps;
2115 * Returns default capabilities for given role archetype.
2117 * @param string $archetype role archetype
2118 * @return array
2120 function get_default_capabilities($archetype) {
2121 global $DB;
2123 if (!$archetype) {
2124 return array();
2127 $alldefs = array();
2128 $defaults = array();
2129 $components = array();
2130 $allcaps = get_all_capabilities();
2132 foreach ($allcaps as $cap) {
2133 if (!in_array($cap['component'], $components)) {
2134 $components[] = $cap['component'];
2135 $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
2138 foreach ($alldefs as $name=>$def) {
2139 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2140 if (isset($def['archetypes'])) {
2141 if (isset($def['archetypes'][$archetype])) {
2142 $defaults[$name] = $def['archetypes'][$archetype];
2144 // 'legacy' is for backward compatibility with 1.9 access.php
2145 } else {
2146 if (isset($def['legacy'][$archetype])) {
2147 $defaults[$name] = $def['legacy'][$archetype];
2152 return $defaults;
2156 * Return default roles that can be assigned, overridden or switched
2157 * by give role archetype.
2159 * @param string $type assign|override|switch|view
2160 * @param string $archetype
2161 * @return array of role ids
2163 function get_default_role_archetype_allows($type, $archetype) {
2164 global $DB;
2166 if (empty($archetype)) {
2167 return array();
2170 $roles = $DB->get_records('role');
2171 $archetypemap = array();
2172 foreach ($roles as $role) {
2173 if ($role->archetype) {
2174 $archetypemap[$role->archetype][$role->id] = $role->id;
2178 $defaults = array(
2179 'assign' => array(
2180 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2181 'coursecreator' => array(),
2182 'editingteacher' => array('teacher', 'student'),
2183 'teacher' => array(),
2184 'student' => array(),
2185 'guest' => array(),
2186 'user' => array(),
2187 'frontpage' => array(),
2189 'override' => array(
2190 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2191 'coursecreator' => array(),
2192 'editingteacher' => array('teacher', 'student', 'guest'),
2193 'teacher' => array(),
2194 'student' => array(),
2195 'guest' => array(),
2196 'user' => array(),
2197 'frontpage' => array(),
2199 'switch' => array(
2200 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2201 'coursecreator' => array(),
2202 'editingteacher' => array('teacher', 'student', 'guest'),
2203 'teacher' => array('student', 'guest'),
2204 'student' => array(),
2205 'guest' => array(),
2206 'user' => array(),
2207 'frontpage' => array(),
2209 'view' => array(
2210 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2211 'coursecreator' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2212 'editingteacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2213 'teacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2214 'student' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2215 'guest' => array(),
2216 'user' => array(),
2217 'frontpage' => array(),
2221 if (!isset($defaults[$type][$archetype])) {
2222 debugging("Unknown type '$type'' or archetype '$archetype''");
2223 return array();
2226 $return = array();
2227 foreach ($defaults[$type][$archetype] as $at) {
2228 if (isset($archetypemap[$at])) {
2229 foreach ($archetypemap[$at] as $roleid) {
2230 $return[$roleid] = $roleid;
2235 return $return;
2239 * Reset role capabilities to default according to selected role archetype.
2240 * If no archetype selected, removes all capabilities.
2242 * This applies to capabilities that are assigned to the role (that you could
2243 * edit in the 'define roles' interface), and not to any capability overrides
2244 * in different locations.
2246 * @param int $roleid ID of role to reset capabilities for
2248 function reset_role_capabilities($roleid) {
2249 global $DB;
2251 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2252 $defaultcaps = get_default_capabilities($role->archetype);
2254 $systemcontext = context_system::instance();
2256 $DB->delete_records('role_capabilities',
2257 array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2259 foreach ($defaultcaps as $cap=>$permission) {
2260 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2263 // Reset any cache of this role, including MUC.
2264 accesslib_clear_role_cache($roleid);
2268 * Updates the capabilities table with the component capability definitions.
2269 * If no parameters are given, the function updates the core moodle
2270 * capabilities.
2272 * Note that the absence of the db/access.php capabilities definition file
2273 * will cause any stored capabilities for the component to be removed from
2274 * the database.
2276 * @access private
2277 * @param string $component examples: 'moodle', 'mod_forum', 'block_activity_results'
2278 * @return boolean true if success, exception in case of any problems
2280 function update_capabilities($component = 'moodle') {
2281 global $DB, $OUTPUT;
2283 // Allow temporary caches to be used during install, dramatically boosting performance.
2284 $token = new \core_cache\allow_temporary_caches();
2286 $storedcaps = array();
2288 $filecaps = load_capability_def($component);
2289 foreach ($filecaps as $capname=>$unused) {
2290 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2291 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2295 // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2296 // So ensure our updating is based on fresh data.
2297 cache::make('core', 'capabilities')->delete('core_capabilities');
2299 $cachedcaps = get_cached_capabilities($component);
2300 if ($cachedcaps) {
2301 foreach ($cachedcaps as $cachedcap) {
2302 array_push($storedcaps, $cachedcap->name);
2303 // update risk bitmasks and context levels in existing capabilities if needed
2304 if (array_key_exists($cachedcap->name, $filecaps)) {
2305 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2306 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2308 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2309 $updatecap = new stdClass();
2310 $updatecap->id = $cachedcap->id;
2311 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2312 $DB->update_record('capabilities', $updatecap);
2314 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2315 $updatecap = new stdClass();
2316 $updatecap->id = $cachedcap->id;
2317 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2318 $DB->update_record('capabilities', $updatecap);
2321 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2322 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2324 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2325 $updatecap = new stdClass();
2326 $updatecap->id = $cachedcap->id;
2327 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2328 $DB->update_record('capabilities', $updatecap);
2334 // Flush the cached again, as we have changed DB.
2335 cache::make('core', 'capabilities')->delete('core_capabilities');
2337 // Are there new capabilities in the file definition?
2338 $newcaps = array();
2340 foreach ($filecaps as $filecap => $def) {
2341 if (!$storedcaps ||
2342 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2343 if (!array_key_exists('riskbitmask', $def)) {
2344 $def['riskbitmask'] = 0; // no risk if not specified
2346 $newcaps[$filecap] = $def;
2349 // Add new capabilities to the stored definition.
2350 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2351 $capabilityobjects = [];
2352 foreach ($newcaps as $capname => $capdef) {
2353 $capability = new stdClass();
2354 $capability->name = $capname;
2355 $capability->captype = $capdef['captype'];
2356 $capability->contextlevel = $capdef['contextlevel'];
2357 $capability->component = $component;
2358 $capability->riskbitmask = $capdef['riskbitmask'];
2359 $capabilityobjects[] = $capability;
2361 $DB->insert_records('capabilities', $capabilityobjects);
2363 // Flush the cache, as we have changed DB.
2364 cache::make('core', 'capabilities')->delete('core_capabilities');
2366 foreach ($newcaps as $capname => $capdef) {
2367 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2368 if ($rolecapabilities = $DB->get_records_sql('
2369 SELECT rc.*,
2370 CASE WHEN EXISTS(SELECT 1
2371 FROM {role_capabilities} rc2
2372 WHERE rc2.capability = ?
2373 AND rc2.contextid = rc.contextid
2374 AND rc2.roleid = rc.roleid) THEN 1 ELSE 0 END AS entryexists,
2375 ' . context_helper::get_preload_record_columns_sql('x') .'
2376 FROM {role_capabilities} rc
2377 JOIN {context} x ON x.id = rc.contextid
2378 WHERE rc.capability = ?',
2379 [$capname, $capdef['clonepermissionsfrom']])) {
2380 foreach ($rolecapabilities as $rolecapability) {
2381 // Preload the context and add performance hints based on the SQL query above.
2382 context_helper::preload_from_record($rolecapability);
2383 $performancehints = [ACCESSLIB_HINT_CONTEXT_EXISTS];
2384 if (!$rolecapability->entryexists) {
2385 $performancehints[] = ACCESSLIB_HINT_NO_EXISTING;
2387 //assign_capability will update rather than insert if capability exists
2388 if (!assign_capability($capname, $rolecapability->permission,
2389 $rolecapability->roleid, $rolecapability->contextid, true, $performancehints)) {
2390 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2394 // we ignore archetype key if we have cloned permissions
2395 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2396 assign_legacy_capabilities($capname, $capdef['archetypes']);
2397 // 'legacy' is for backward compatibility with 1.9 access.php
2398 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2399 assign_legacy_capabilities($capname, $capdef['legacy']);
2402 // Are there any capabilities that have been removed from the file
2403 // definition that we need to delete from the stored capabilities and
2404 // role assignments?
2405 capabilities_cleanup($component, $filecaps);
2407 // reset static caches
2408 accesslib_reset_role_cache();
2410 // Flush the cached again, as we have changed DB.
2411 cache::make('core', 'capabilities')->delete('core_capabilities');
2413 return true;
2417 * Deletes cached capabilities that are no longer needed by the component.
2418 * Also unassigns these capabilities from any roles that have them.
2419 * NOTE: this function is called from lib/db/upgrade.php
2421 * @access private
2422 * @param string $component examples: 'moodle', 'mod_forum', 'block_activity_results'
2423 * @param array $newcapdef array of the new capability definitions that will be
2424 * compared with the cached capabilities
2425 * @return int number of deprecated capabilities that have been removed
2427 function capabilities_cleanup($component, $newcapdef = null) {
2428 global $DB;
2430 $removedcount = 0;
2432 if ($cachedcaps = get_cached_capabilities($component)) {
2433 foreach ($cachedcaps as $cachedcap) {
2434 if (empty($newcapdef) ||
2435 array_key_exists($cachedcap->name, $newcapdef) === false) {
2437 // Delete from roles.
2438 if ($roles = get_roles_with_capability($cachedcap->name)) {
2439 foreach ($roles as $role) {
2440 if (!unassign_capability($cachedcap->name, $role->id)) {
2441 throw new \moodle_exception('cannotunassigncap', 'error', '',
2442 (object)array('cap' => $cachedcap->name, 'role' => $role->name));
2447 // Remove from role_capabilities for any old ones.
2448 $DB->delete_records('role_capabilities', array('capability' => $cachedcap->name));
2450 // Remove from capabilities cache.
2451 $DB->delete_records('capabilities', array('name' => $cachedcap->name));
2452 $removedcount++;
2453 } // End if.
2456 if ($removedcount) {
2457 cache::make('core', 'capabilities')->delete('core_capabilities');
2459 return $removedcount;
2463 * Returns an array of all the known types of risk
2464 * The array keys can be used, for example as CSS class names, or in calls to
2465 * print_risk_icon. The values are the corresponding RISK_ constants.
2467 * @return array all the known types of risk.
2469 function get_all_risks() {
2470 return array(
2471 'riskmanagetrust' => RISK_MANAGETRUST,
2472 'riskconfig' => RISK_CONFIG,
2473 'riskxss' => RISK_XSS,
2474 'riskpersonal' => RISK_PERSONAL,
2475 'riskspam' => RISK_SPAM,
2476 'riskdataloss' => RISK_DATALOSS,
2481 * Return a link to moodle docs for a given capability name
2483 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2484 * @return string the human-readable capability name as a link to Moodle Docs.
2486 function get_capability_docs_link($capability) {
2487 $url = get_docs_url('Capabilities/' . $capability->name);
2488 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2492 * This function pulls out all the resolved capabilities (overrides and
2493 * defaults) of a role used in capability overrides in contexts at a given
2494 * context.
2496 * @param int $roleid
2497 * @param context $context
2498 * @param string $cap capability, optional, defaults to ''
2499 * @return array Array of capabilities
2501 function role_context_capabilities($roleid, context $context, $cap = '') {
2502 global $DB;
2504 $contexts = $context->get_parent_context_ids(true);
2505 $contexts = '('.implode(',', $contexts).')';
2507 $params = array($roleid);
2509 if ($cap) {
2510 $search = " AND rc.capability = ? ";
2511 $params[] = $cap;
2512 } else {
2513 $search = '';
2516 $sql = "SELECT rc.*
2517 FROM {role_capabilities} rc
2518 JOIN {context} c ON rc.contextid = c.id
2519 JOIN {capabilities} cap ON rc.capability = cap.name
2520 WHERE rc.contextid in $contexts
2521 AND rc.roleid = ?
2522 $search
2523 ORDER BY c.contextlevel DESC, rc.capability DESC";
2525 $capabilities = array();
2527 if ($records = $DB->get_records_sql($sql, $params)) {
2528 // We are traversing via reverse order.
2529 foreach ($records as $record) {
2530 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2531 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2532 $capabilities[$record->capability] = $record->permission;
2536 return $capabilities;
2540 * Constructs array with contextids as first parameter and context paths,
2541 * in both cases bottom top including self.
2543 * @access private
2544 * @param context $context
2545 * @return array
2547 function get_context_info_list(context $context) {
2548 $contextids = explode('/', ltrim($context->path, '/'));
2549 $contextpaths = array();
2550 $contextids2 = $contextids;
2551 while ($contextids2) {
2552 $contextpaths[] = '/' . implode('/', $contextids2);
2553 array_pop($contextids2);
2555 return array($contextids, $contextpaths);
2559 * Check if context is the front page context or a context inside it
2561 * Returns true if this context is the front page context, or a context inside it,
2562 * otherwise false.
2564 * @param context $context a context object.
2565 * @return bool
2567 function is_inside_frontpage(context $context) {
2568 $frontpagecontext = context_course::instance(SITEID);
2569 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2573 * Returns capability information (cached)
2575 * @param string $capabilityname
2576 * @return stdClass or null if capability not found
2578 function get_capability_info($capabilityname) {
2579 $caps = get_all_capabilities();
2581 // Check for deprecated capability.
2582 if ($deprecatedinfo = get_deprecated_capability_info($capabilityname)) {
2583 if (!empty($deprecatedinfo['replacement'])) {
2584 // Let's try again with this capability if it exists.
2585 if (isset($caps[$deprecatedinfo['replacement']])) {
2586 $capabilityname = $deprecatedinfo['replacement'];
2587 } else {
2588 debugging("Capability '{$capabilityname}' was supposed to be replaced with ".
2589 "'{$deprecatedinfo['replacement']}', which does not exist !");
2592 $fullmessage = $deprecatedinfo['fullmessage'];
2593 debugging($fullmessage, DEBUG_DEVELOPER);
2595 if (!isset($caps[$capabilityname])) {
2596 return null;
2599 return (object) $caps[$capabilityname];
2603 * Returns deprecation info for this particular capabilty (cached)
2605 * Do not use this function except in the get_capability_info
2607 * @param string $capabilityname
2608 * @return stdClass|null with deprecation message and potential replacement if not null
2610 function get_deprecated_capability_info($capabilityname) {
2611 // Here if we do like get_all_capabilities, we run into performance issues as the full array is unserialised each time.
2612 // We could have used an adhoc task but this also had performance issue. Last solution was to create a cache using
2613 // the official caches.php file. The performance issue shows in test_permission_evaluation.
2614 $cache = cache::make('core', 'deprecatedcapabilities');
2615 // Cache has not be initialised.
2616 if (!$cache->get('deprecated_capabilities_initialised')) {
2617 // Look for deprecated capabilities in each components.
2618 $allcaps = get_all_capabilities();
2619 $components = [];
2620 $alldeprecatedcaps = [];
2621 foreach ($allcaps as $cap) {
2622 if (!in_array($cap['component'], $components)) {
2623 $components[] = $cap['component'];
2624 $defpath = core_component::get_component_directory($cap['component']).'/db/access.php';
2625 if (file_exists($defpath)) {
2626 $deprecatedcapabilities = [];
2627 require($defpath);
2628 if (!empty($deprecatedcapabilities)) {
2629 foreach ($deprecatedcapabilities as $cname => $cdef) {
2630 $cache->set($cname, $cdef);
2636 $cache->set('deprecated_capabilities_initialised', true);
2638 if (!$cache->has($capabilityname)) {
2639 return null;
2641 $deprecatedinfo = $cache->get($capabilityname);
2642 $deprecatedinfo['fullmessage'] = "The capability '{$capabilityname}' is deprecated.";
2643 if (!empty($deprecatedinfo['message'])) {
2644 $deprecatedinfo['fullmessage'] .= $deprecatedinfo['message'];
2646 if (!empty($deprecatedinfo['replacement'])) {
2647 $deprecatedinfo['fullmessage'] .=
2648 "It will be replaced by '{$deprecatedinfo['replacement']}'.";
2650 return $deprecatedinfo;
2654 * Returns all capabilitiy records, preferably from MUC and not database.
2656 * @return array All capability records indexed by capability name
2658 function get_all_capabilities() {
2659 global $DB;
2660 $cache = cache::make('core', 'capabilities');
2661 if (!$allcaps = $cache->get('core_capabilities')) {
2662 $rs = $DB->get_recordset('capabilities');
2663 $allcaps = array();
2664 foreach ($rs as $capability) {
2665 $capability->riskbitmask = (int) $capability->riskbitmask;
2666 $allcaps[$capability->name] = (array) $capability;
2668 $rs->close();
2669 $cache->set('core_capabilities', $allcaps);
2671 return $allcaps;
2675 * Returns the human-readable, translated version of the capability.
2676 * Basically a big switch statement.
2678 * @param string $capabilityname e.g. mod/choice:readresponses
2679 * @return string
2681 function get_capability_string($capabilityname) {
2683 // Typical capability name is 'plugintype/pluginname:capabilityname'
2684 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2686 if ($type === 'moodle') {
2687 $component = 'core_role';
2688 } else if ($type === 'quizreport') {
2689 //ugly hack!!
2690 $component = 'quiz_'.$name;
2691 } else {
2692 $component = $type.'_'.$name;
2695 $stringname = $name.':'.$capname;
2697 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2698 return get_string($stringname, $component);
2701 $dir = core_component::get_component_directory($component);
2702 if (!file_exists($dir)) {
2703 // plugin broken or does not exist, do not bother with printing of debug message
2704 return $capabilityname.' ???';
2707 // something is wrong in plugin, better print debug
2708 return get_string($stringname, $component);
2712 * This gets the mod/block/course/core etc strings.
2714 * @param string $component
2715 * @param int $contextlevel
2716 * @return string|bool String is success, false if failed
2718 function get_component_string($component, $contextlevel) {
2720 if ($component === 'moodle' || $component === 'core') {
2721 return context_helper::get_level_name($contextlevel);
2724 list($type, $name) = core_component::normalize_component($component);
2725 $dir = core_component::get_plugin_directory($type, $name);
2726 if (!file_exists($dir)) {
2727 // plugin not installed, bad luck, there is no way to find the name
2728 return $component . ' ???';
2731 // Some plugin types need an extra prefix to make the name easy to understand.
2732 switch ($type) {
2733 case 'quiz':
2734 $prefix = get_string('quizreport', 'quiz') . ': ';
2735 break;
2736 case 'repository':
2737 $prefix = get_string('repository', 'repository') . ': ';
2738 break;
2739 case 'gradeimport':
2740 $prefix = get_string('gradeimport', 'grades') . ': ';
2741 break;
2742 case 'gradeexport':
2743 $prefix = get_string('gradeexport', 'grades') . ': ';
2744 break;
2745 case 'gradereport':
2746 $prefix = get_string('gradereport', 'grades') . ': ';
2747 break;
2748 case 'webservice':
2749 $prefix = get_string('webservice', 'webservice') . ': ';
2750 break;
2751 case 'block':
2752 $prefix = get_string('block') . ': ';
2753 break;
2754 case 'mod':
2755 $prefix = get_string('activity') . ': ';
2756 break;
2758 // Default case, just use the plugin name.
2759 default:
2760 $prefix = '';
2762 return $prefix . get_string('pluginname', $component);
2766 * Gets the list of roles assigned to this context and up (parents)
2767 * from the aggregation of:
2768 * a) the list of roles that are visible on user profile page and participants page (profileroles setting) and;
2769 * b) if applicable, those roles that are assigned in the context.
2771 * @param context $context
2772 * @return array
2774 function get_profile_roles(context $context) {
2775 global $CFG, $DB;
2776 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2777 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2778 if (has_capability('moodle/role:assign', $context)) {
2779 $rolesinscope = array_keys(get_all_roles($context));
2780 } else {
2781 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2784 if (empty($rolesinscope)) {
2785 return [];
2788 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2789 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2790 $params = array_merge($params, $cparams);
2792 if ($coursecontext = $context->get_course_context(false)) {
2793 $params['coursecontext'] = $coursecontext->id;
2794 } else {
2795 $params['coursecontext'] = 0;
2798 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2799 FROM {role_assignments} ra, {role} r
2800 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2801 WHERE r.id = ra.roleid
2802 AND ra.contextid $contextlist
2803 AND r.id $rallowed
2804 ORDER BY r.sortorder ASC";
2806 return $DB->get_records_sql($sql, $params);
2810 * Gets the list of roles assigned to this context and up (parents)
2812 * @param context $context
2813 * @param boolean $includeparents, false means without parents.
2814 * @return array
2816 function get_roles_used_in_context(context $context, $includeparents = true) {
2817 global $DB;
2819 if ($includeparents === true) {
2820 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2821 } else {
2822 list($contextlist, $params) = $DB->get_in_or_equal($context->id, SQL_PARAMS_NAMED, 'cl');
2825 if ($coursecontext = $context->get_course_context(false)) {
2826 $params['coursecontext'] = $coursecontext->id;
2827 } else {
2828 $params['coursecontext'] = 0;
2831 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2832 FROM {role_assignments} ra, {role} r
2833 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2834 WHERE r.id = ra.roleid
2835 AND ra.contextid $contextlist
2836 ORDER BY r.sortorder ASC";
2838 return $DB->get_records_sql($sql, $params);
2842 * This function is used to print roles column in user profile page.
2843 * It is using the CFG->profileroles to limit the list to only interesting roles.
2844 * (The permission tab has full details of user role assignments.)
2846 * @param int $userid
2847 * @param int $courseid
2848 * @return string
2850 function get_user_roles_in_course($userid, $courseid) {
2851 global $CFG, $DB;
2852 if ($courseid == SITEID) {
2853 $context = context_system::instance();
2854 } else {
2855 $context = context_course::instance($courseid);
2857 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2858 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2859 if (has_capability('moodle/role:assign', $context)) {
2860 $rolesinscope = array_keys(get_all_roles($context));
2861 } else {
2862 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2864 if (empty($rolesinscope)) {
2865 return '';
2868 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2869 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2870 $params = array_merge($params, $cparams);
2872 if ($coursecontext = $context->get_course_context(false)) {
2873 $params['coursecontext'] = $coursecontext->id;
2874 } else {
2875 $params['coursecontext'] = 0;
2878 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2879 FROM {role_assignments} ra, {role} r
2880 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2881 WHERE r.id = ra.roleid
2882 AND ra.contextid $contextlist
2883 AND r.id $rallowed
2884 AND ra.userid = :userid
2885 ORDER BY r.sortorder ASC";
2886 $params['userid'] = $userid;
2888 $rolestring = '';
2890 if ($roles = $DB->get_records_sql($sql, $params)) {
2891 $viewableroles = get_viewable_roles($context, $userid);
2893 $rolenames = array();
2894 foreach ($roles as $roleid => $unused) {
2895 if (isset($viewableroles[$roleid])) {
2896 $url = new moodle_url('/user/index.php', ['contextid' => $context->id, 'roleid' => $roleid]);
2897 $rolenames[] = '<a href="' . $url . '">' . $viewableroles[$roleid] . '</a>';
2900 $rolestring = implode(', ', $rolenames);
2903 return $rolestring;
2907 * Checks if a user can assign users to a particular role in this context
2909 * @param context $context
2910 * @param int $targetroleid - the id of the role you want to assign users to
2911 * @return boolean
2913 function user_can_assign(context $context, $targetroleid) {
2914 global $DB;
2916 // First check to see if the user is a site administrator.
2917 if (is_siteadmin()) {
2918 return true;
2921 // Check if user has override capability.
2922 // If not return false.
2923 if (!has_capability('moodle/role:assign', $context)) {
2924 return false;
2926 // pull out all active roles of this user from this context(or above)
2927 if ($userroles = get_user_roles($context)) {
2928 foreach ($userroles as $userrole) {
2929 // if any in the role_allow_override table, then it's ok
2930 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2931 return true;
2936 return false;
2940 * Returns all site roles in correct sort order.
2942 * Note: this method does not localise role names or descriptions,
2943 * use role_get_names() if you need role names.
2945 * @param context $context optional context for course role name aliases
2946 * @return array of role records with optional coursealias property
2948 function get_all_roles(context $context = null) {
2949 global $DB;
2951 if (!$context or !$coursecontext = $context->get_course_context(false)) {
2952 $coursecontext = null;
2955 if ($coursecontext) {
2956 $sql = "SELECT r.*, rn.name AS coursealias
2957 FROM {role} r
2958 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2959 ORDER BY r.sortorder ASC";
2960 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
2962 } else {
2963 return $DB->get_records('role', array(), 'sortorder ASC');
2968 * Returns roles of a specified archetype
2970 * @param string $archetype
2971 * @return array of full role records
2973 function get_archetype_roles($archetype) {
2974 global $DB;
2975 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2979 * Gets all the user roles assigned in this context, or higher contexts for a list of users.
2981 * If you try using the combination $userids = [], $checkparentcontexts = true then this is likely
2982 * to cause an out-of-memory error on large Moodle sites, so this combination is deprecated and
2983 * outputs a warning, even though it is the default.
2985 * @param context $context
2986 * @param array $userids. An empty list means fetch all role assignments for the context.
2987 * @param bool $checkparentcontexts defaults to true
2988 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2989 * @return array
2991 function get_users_roles(context $context, $userids = [], $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2992 global $DB;
2994 if (!$userids && $checkparentcontexts) {
2995 debugging('Please do not call get_users_roles() with $checkparentcontexts = true ' .
2996 'and $userids array not set. This combination causes large Moodle sites ' .
2997 'with lots of site-wide role assignemnts to run out of memory.', DEBUG_DEVELOPER);
3000 if ($checkparentcontexts) {
3001 $contextids = $context->get_parent_context_ids();
3002 } else {
3003 $contextids = array();
3005 $contextids[] = $context->id;
3007 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3009 // If userids was passed as an empty array, we fetch all role assignments for the course.
3010 if (empty($userids)) {
3011 $useridlist = ' IS NOT NULL ';
3012 $uparams = [];
3013 } else {
3014 list($useridlist, $uparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'uids');
3017 $sql = "SELECT ra.*, r.name, r.shortname, ra.userid
3018 FROM {role_assignments} ra, {role} r, {context} c
3019 WHERE ra.userid $useridlist
3020 AND ra.roleid = r.id
3021 AND ra.contextid = c.id
3022 AND ra.contextid $contextids
3023 ORDER BY $order";
3025 $all = $DB->get_records_sql($sql , array_merge($params, $uparams));
3027 // Return results grouped by userid.
3028 $result = [];
3029 foreach ($all as $id => $record) {
3030 if (!isset($result[$record->userid])) {
3031 $result[$record->userid] = [];
3033 $result[$record->userid][$record->id] = $record;
3036 // Make sure all requested users are included in the result, even if they had no role assignments.
3037 foreach ($userids as $id) {
3038 if (!isset($result[$id])) {
3039 $result[$id] = [];
3043 return $result;
3048 * Gets all the user roles assigned in this context, or higher contexts
3049 * this is mainly used when checking if a user can assign a role, or overriding a role
3050 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3051 * allow_override tables
3053 * @param context $context
3054 * @param int $userid
3055 * @param bool $checkparentcontexts defaults to true
3056 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
3057 * @return array
3059 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
3060 global $USER, $DB;
3062 if (empty($userid)) {
3063 if (empty($USER->id)) {
3064 return array();
3066 $userid = $USER->id;
3069 if ($checkparentcontexts) {
3070 $contextids = $context->get_parent_context_ids();
3071 } else {
3072 $contextids = array();
3074 $contextids[] = $context->id;
3076 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3078 array_unshift($params, $userid);
3080 $sql = "SELECT ra.*, r.name, r.shortname
3081 FROM {role_assignments} ra, {role} r, {context} c
3082 WHERE ra.userid = ?
3083 AND ra.roleid = r.id
3084 AND ra.contextid = c.id
3085 AND ra.contextid $contextids
3086 ORDER BY $order";
3088 return $DB->get_records_sql($sql ,$params);
3092 * Like get_user_roles, but adds in the authenticated user role, and the front
3093 * page roles, if applicable.
3095 * @param context $context the context.
3096 * @param int $userid optional. Defaults to $USER->id
3097 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3099 function get_user_roles_with_special(context $context, $userid = 0) {
3100 global $CFG, $USER;
3102 if (empty($userid)) {
3103 if (empty($USER->id)) {
3104 return array();
3106 $userid = $USER->id;
3109 $ras = get_user_roles($context, $userid);
3111 // Add front-page role if relevant.
3112 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3113 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3114 is_inside_frontpage($context);
3115 if ($defaultfrontpageroleid && $isfrontpage) {
3116 $frontpagecontext = context_course::instance(SITEID);
3117 $ra = new stdClass();
3118 $ra->userid = $userid;
3119 $ra->contextid = $frontpagecontext->id;
3120 $ra->roleid = $defaultfrontpageroleid;
3121 $ras[] = $ra;
3124 // Add authenticated user role if relevant.
3125 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3126 if ($defaultuserroleid && !isguestuser($userid)) {
3127 $systemcontext = context_system::instance();
3128 $ra = new stdClass();
3129 $ra->userid = $userid;
3130 $ra->contextid = $systemcontext->id;
3131 $ra->roleid = $defaultuserroleid;
3132 $ras[] = $ra;
3135 return $ras;
3139 * Creates a record in the role_allow_override table
3141 * @param int $fromroleid source roleid
3142 * @param int $targetroleid target roleid
3143 * @return void
3145 function core_role_set_override_allowed($fromroleid, $targetroleid) {
3146 global $DB;
3148 $record = new stdClass();
3149 $record->roleid = $fromroleid;
3150 $record->allowoverride = $targetroleid;
3151 $DB->insert_record('role_allow_override', $record);
3155 * Creates a record in the role_allow_assign table
3157 * @param int $fromroleid source roleid
3158 * @param int $targetroleid target roleid
3159 * @return void
3161 function core_role_set_assign_allowed($fromroleid, $targetroleid) {
3162 global $DB;
3164 $record = new stdClass();
3165 $record->roleid = $fromroleid;
3166 $record->allowassign = $targetroleid;
3167 $DB->insert_record('role_allow_assign', $record);
3171 * Creates a record in the role_allow_switch table
3173 * @param int $fromroleid source roleid
3174 * @param int $targetroleid target roleid
3175 * @return void
3177 function core_role_set_switch_allowed($fromroleid, $targetroleid) {
3178 global $DB;
3180 $record = new stdClass();
3181 $record->roleid = $fromroleid;
3182 $record->allowswitch = $targetroleid;
3183 $DB->insert_record('role_allow_switch', $record);
3187 * Creates a record in the role_allow_view table
3189 * @param int $fromroleid source roleid
3190 * @param int $targetroleid target roleid
3191 * @return void
3193 function core_role_set_view_allowed($fromroleid, $targetroleid) {
3194 global $DB;
3196 $record = new stdClass();
3197 $record->roleid = $fromroleid;
3198 $record->allowview = $targetroleid;
3199 $DB->insert_record('role_allow_view', $record);
3203 * Gets a list of roles that this user can assign in this context
3205 * @param context $context the context.
3206 * @param int $rolenamedisplay the type of role name to display. One of the
3207 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3208 * @param bool $withusercounts if true, count the number of users with each role.
3209 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3210 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3211 * if $withusercounts is true, returns a list of three arrays,
3212 * $rolenames, $rolecounts, and $nameswithcounts.
3214 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3215 global $USER, $DB;
3217 // make sure there is a real user specified
3218 if ($user === null) {
3219 $userid = isset($USER->id) ? $USER->id : 0;
3220 } else {
3221 $userid = is_object($user) ? $user->id : $user;
3224 if (!has_capability('moodle/role:assign', $context, $userid)) {
3225 if ($withusercounts) {
3226 return array(array(), array(), array());
3227 } else {
3228 return array();
3232 $params = array();
3233 $extrafields = '';
3235 if ($withusercounts) {
3236 $extrafields = ', (SELECT COUNT(DISTINCT u.id)
3237 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3238 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3239 ) AS usercount';
3240 $params['conid'] = $context->id;
3243 if (is_siteadmin($userid)) {
3244 // show all roles allowed in this context to admins
3245 $assignrestriction = "";
3246 } else {
3247 $parents = $context->get_parent_context_ids(true);
3248 $contexts = implode(',' , $parents);
3249 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3250 FROM {role_allow_assign} raa
3251 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3252 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3253 ) ar ON ar.id = r.id";
3254 $params['userid'] = $userid;
3256 $params['contextlevel'] = $context->contextlevel;
3258 if ($coursecontext = $context->get_course_context(false)) {
3259 $params['coursecontext'] = $coursecontext->id;
3260 } else {
3261 $params['coursecontext'] = 0; // no course aliases
3262 $coursecontext = null;
3264 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3265 FROM {role} r
3266 $assignrestriction
3267 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3268 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3269 ORDER BY r.sortorder ASC";
3270 $roles = $DB->get_records_sql($sql, $params);
3272 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3274 if (!$withusercounts) {
3275 return $rolenames;
3278 $rolecounts = array();
3279 $nameswithcounts = array();
3280 foreach ($roles as $role) {
3281 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3282 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3284 return array($rolenames, $rolecounts, $nameswithcounts);
3288 * Gets a list of roles that this user can switch to in a context
3290 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3291 * This function just process the contents of the role_allow_switch table. You also need to
3292 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3294 * @param context $context a context.
3295 * @param int $rolenamedisplay the type of role name to display. One of the
3296 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3297 * @return array an array $roleid => $rolename.
3299 function get_switchable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS) {
3300 global $USER, $DB;
3302 // You can't switch roles without this capability.
3303 if (!has_capability('moodle/role:switchroles', $context)) {
3304 return [];
3307 $params = array();
3308 $extrajoins = '';
3309 $extrawhere = '';
3310 if (!is_siteadmin()) {
3311 // Admins are allowed to switch to any role with.
3312 // Others are subject to the additional constraint that the switch-to role must be allowed by
3313 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3314 $parents = $context->get_parent_context_ids(true);
3315 $contexts = implode(',' , $parents);
3317 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3318 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3319 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3320 $params['userid'] = $USER->id;
3323 if ($coursecontext = $context->get_course_context(false)) {
3324 $params['coursecontext'] = $coursecontext->id;
3325 } else {
3326 $params['coursecontext'] = 0; // no course aliases
3327 $coursecontext = null;
3330 $query = "
3331 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3332 FROM (SELECT DISTINCT rc.roleid
3333 FROM {role_capabilities} rc
3335 $extrajoins
3336 $extrawhere) idlist
3337 JOIN {role} r ON r.id = idlist.roleid
3338 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3339 ORDER BY r.sortorder";
3340 $roles = $DB->get_records_sql($query, $params);
3342 return role_fix_names($roles, $context, $rolenamedisplay, true);
3346 * Gets a list of roles that this user can view in a context
3348 * @param context $context a context.
3349 * @param int $userid id of user.
3350 * @param int $rolenamedisplay the type of role name to display. One of the
3351 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3352 * @return array an array $roleid => $rolename.
3354 function get_viewable_roles(context $context, $userid = null, $rolenamedisplay = ROLENAME_ALIAS) {
3355 global $USER, $DB;
3357 if ($userid == null) {
3358 $userid = $USER->id;
3361 $params = array();
3362 $extrajoins = '';
3363 $extrawhere = '';
3364 if (!is_siteadmin()) {
3365 // Admins are allowed to view any role.
3366 // Others are subject to the additional constraint that the view role must be allowed by
3367 // 'role_allow_view' for some role they have assigned in this context or any parent.
3368 $contexts = $context->get_parent_context_ids(true);
3369 list($insql, $inparams) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED);
3371 $extrajoins = "JOIN {role_allow_view} ras ON ras.allowview = r.id
3372 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3373 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid $insql";
3375 $params += $inparams;
3376 $params['userid'] = $userid;
3379 if ($coursecontext = $context->get_course_context(false)) {
3380 $params['coursecontext'] = $coursecontext->id;
3381 } else {
3382 $params['coursecontext'] = 0; // No course aliases.
3383 $coursecontext = null;
3386 $query = "
3387 SELECT r.id, r.name, r.shortname, rn.name AS coursealias, r.sortorder
3388 FROM {role} r
3389 $extrajoins
3390 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3391 $extrawhere
3392 GROUP BY r.id, r.name, r.shortname, rn.name, r.sortorder
3393 ORDER BY r.sortorder";
3394 $roles = $DB->get_records_sql($query, $params);
3396 return role_fix_names($roles, $context, $rolenamedisplay, true);
3400 * Gets a list of roles that this user can override in this context.
3402 * @param context $context the context.
3403 * @param int $rolenamedisplay the type of role name to display. One of the
3404 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3405 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3406 * @return array if $withcounts is false, then an array $roleid => $rolename.
3407 * if $withusercounts is true, returns a list of three arrays,
3408 * $rolenames, $rolecounts, and $nameswithcounts.
3410 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3411 global $USER, $DB;
3413 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3414 if ($withcounts) {
3415 return array(array(), array(), array());
3416 } else {
3417 return array();
3421 $parents = $context->get_parent_context_ids(true);
3422 $contexts = implode(',' , $parents);
3424 $params = array();
3425 $extrafields = '';
3427 $params['userid'] = $USER->id;
3428 if ($withcounts) {
3429 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3430 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3431 $params['conid'] = $context->id;
3434 if ($coursecontext = $context->get_course_context(false)) {
3435 $params['coursecontext'] = $coursecontext->id;
3436 } else {
3437 $params['coursecontext'] = 0; // no course aliases
3438 $coursecontext = null;
3441 if (is_siteadmin()) {
3442 // show all roles to admins
3443 $roles = $DB->get_records_sql("
3444 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3445 FROM {role} ro
3446 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3447 ORDER BY ro.sortorder ASC", $params);
3449 } else {
3450 $roles = $DB->get_records_sql("
3451 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3452 FROM {role} ro
3453 JOIN (SELECT DISTINCT r.id
3454 FROM {role} r
3455 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3456 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3457 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3458 ) inline_view ON ro.id = inline_view.id
3459 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3460 ORDER BY ro.sortorder ASC", $params);
3463 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3465 if (!$withcounts) {
3466 return $rolenames;
3469 $rolecounts = array();
3470 $nameswithcounts = array();
3471 foreach ($roles as $role) {
3472 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3473 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3475 return array($rolenames, $rolecounts, $nameswithcounts);
3479 * Create a role menu suitable for default role selection in enrol plugins.
3481 * @package core_enrol
3483 * @param context $context
3484 * @param int $addroleid current or default role - always added to list
3485 * @return array roleid=>localised role name
3487 function get_default_enrol_roles(context $context, $addroleid = null) {
3488 global $DB;
3490 $params = array('contextlevel'=>CONTEXT_COURSE);
3492 if ($coursecontext = $context->get_course_context(false)) {
3493 $params['coursecontext'] = $coursecontext->id;
3494 } else {
3495 $params['coursecontext'] = 0; // no course names
3496 $coursecontext = null;
3499 if ($addroleid) {
3500 $addrole = "OR r.id = :addroleid";
3501 $params['addroleid'] = $addroleid;
3502 } else {
3503 $addrole = "";
3506 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3507 FROM {role} r
3508 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3509 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3510 WHERE rcl.id IS NOT NULL $addrole
3511 ORDER BY sortorder DESC";
3513 $roles = $DB->get_records_sql($sql, $params);
3515 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3519 * Return context levels where this role is assignable.
3521 * @param integer $roleid the id of a role.
3522 * @return array list of the context levels at which this role may be assigned.
3524 function get_role_contextlevels($roleid) {
3525 global $DB;
3526 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3527 'contextlevel', 'id,contextlevel');
3531 * Return roles suitable for assignment at the specified context level.
3533 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3535 * @param integer $contextlevel a contextlevel.
3536 * @return array list of role ids that are assignable at this context level.
3538 function get_roles_for_contextlevels($contextlevel) {
3539 global $DB;
3540 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3541 '', 'id,roleid');
3545 * Returns default context levels where roles can be assigned.
3547 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3548 * from the array returned by get_role_archetypes();
3549 * @return array list of the context levels at which this type of role may be assigned by default.
3551 function get_default_contextlevels($rolearchetype) {
3552 static $defaults = array(
3553 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3554 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3555 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3556 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3557 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3558 'guest' => array(),
3559 'user' => array(),
3560 'frontpage' => array());
3562 if (isset($defaults[$rolearchetype])) {
3563 return $defaults[$rolearchetype];
3564 } else {
3565 return array();
3570 * Set the context levels at which a particular role can be assigned.
3571 * Throws exceptions in case of error.
3573 * @param integer $roleid the id of a role.
3574 * @param array $contextlevels the context levels at which this role should be assignable,
3575 * duplicate levels are removed.
3576 * @return void
3578 function set_role_contextlevels($roleid, array $contextlevels) {
3579 global $DB;
3580 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3581 $rcl = new stdClass();
3582 $rcl->roleid = $roleid;
3583 $contextlevels = array_unique($contextlevels);
3584 foreach ($contextlevels as $level) {
3585 $rcl->contextlevel = $level;
3586 $DB->insert_record('role_context_levels', $rcl, false, true);
3591 * Gets sql joins for finding users with capability in the given context.
3593 * @param context $context Context for the join.
3594 * @param string|array $capability Capability name or array of names.
3595 * If an array is provided then this is the equivalent of a logical 'OR',
3596 * i.e. the user needs to have one of these capabilities.
3597 * @param string $useridcolumn e.g. 'u.id'.
3598 * @return \core\dml\sql_join Contains joins, wheres, params.
3599 * This function will set ->cannotmatchanyrows if applicable.
3600 * This may let you skip doing a DB query.
3602 function get_with_capability_join(context $context, $capability, $useridcolumn) {
3603 global $CFG, $DB;
3605 // Add a unique prefix to param names to ensure they are unique.
3606 static $i = 0;
3607 $i++;
3608 $paramprefix = 'eu' . $i . '_';
3610 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3611 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3613 $ctxids = trim($context->path, '/');
3614 $ctxids = str_replace('/', ',', $ctxids);
3616 // Context is the frontpage
3617 $isfrontpage = $context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID;
3618 $isfrontpage = $isfrontpage || is_inside_frontpage($context);
3620 $caps = (array) $capability;
3622 // Construct list of context paths bottom --> top.
3623 list($contextids, $paths) = get_context_info_list($context);
3625 // We need to find out all roles that have these capabilities either in definition or in overrides.
3626 $defs = [];
3627 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, $paramprefix . 'con');
3628 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, $paramprefix . 'cap');
3630 // Check whether context locking is enabled.
3631 // Filter out any write capability if this is the case.
3632 $excludelockedcaps = '';
3633 $excludelockedcapsparams = [];
3634 if (!empty($CFG->contextlocking) && $context->locked) {
3635 $excludelockedcaps = 'AND (cap.captype = :capread OR cap.name = :managelockscap)';
3636 $excludelockedcapsparams['capread'] = 'read';
3637 $excludelockedcapsparams['managelockscap'] = 'moodle/site:managecontextlocks';
3640 $params = array_merge($params, $params2, $excludelockedcapsparams);
3641 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3642 FROM {role_capabilities} rc
3643 JOIN {capabilities} cap ON rc.capability = cap.name
3644 JOIN {context} ctx on rc.contextid = ctx.id
3645 WHERE rc.contextid $incontexts AND rc.capability $incaps $excludelockedcaps";
3647 $rcs = $DB->get_records_sql($sql, $params);
3648 foreach ($rcs as $rc) {
3649 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3652 // Go through the permissions bottom-->top direction to evaluate the current permission,
3653 // first one wins (prohibit is an exception that always wins).
3654 $access = [];
3655 foreach ($caps as $cap) {
3656 foreach ($paths as $path) {
3657 if (empty($defs[$cap][$path])) {
3658 continue;
3660 foreach ($defs[$cap][$path] as $roleid => $perm) {
3661 if ($perm == CAP_PROHIBIT) {
3662 $access[$cap][$roleid] = CAP_PROHIBIT;
3663 continue;
3665 if (!isset($access[$cap][$roleid])) {
3666 $access[$cap][$roleid] = (int)$perm;
3672 // Make lists of roles that are needed and prohibited in this context.
3673 $needed = []; // One of these is enough.
3674 $prohibited = []; // Must not have any of these.
3675 foreach ($caps as $cap) {
3676 if (empty($access[$cap])) {
3677 continue;
3679 foreach ($access[$cap] as $roleid => $perm) {
3680 if ($perm == CAP_PROHIBIT) {
3681 unset($needed[$cap][$roleid]);
3682 $prohibited[$cap][$roleid] = true;
3683 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3684 $needed[$cap][$roleid] = true;
3687 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3688 // Easy, nobody has the permission.
3689 unset($needed[$cap]);
3690 unset($prohibited[$cap]);
3691 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3692 // Everybody is disqualified on the frontpage.
3693 unset($needed[$cap]);
3694 unset($prohibited[$cap]);
3696 if (empty($prohibited[$cap])) {
3697 unset($prohibited[$cap]);
3701 if (empty($needed)) {
3702 // There can not be anybody if no roles match this request.
3703 return new \core\dml\sql_join('', '1 = 2', [], true);
3706 if (empty($prohibited)) {
3707 // We can compact the needed roles.
3708 $n = [];
3709 foreach ($needed as $cap) {
3710 foreach ($cap as $roleid => $unused) {
3711 $n[$roleid] = true;
3714 $needed = ['any' => $n];
3715 unset($n);
3718 // Prepare query clauses.
3719 $wherecond = [];
3720 $params = [];
3721 $joins = [];
3722 $cannotmatchanyrows = false;
3724 // We never return deleted users or guest account.
3725 // Use a hack to get the deleted user column without an API change.
3726 $deletedusercolumn = substr($useridcolumn, 0, -2) . 'deleted';
3727 $wherecond[] = "$deletedusercolumn = 0 AND $useridcolumn <> :{$paramprefix}guestid";
3728 $params[$paramprefix . 'guestid'] = $CFG->siteguest;
3730 // Now add the needed and prohibited roles conditions as joins.
3731 if (!empty($needed['any'])) {
3732 // Simple case - there are no prohibits involved.
3733 if (!empty($needed['any'][$defaultuserroleid]) ||
3734 ($isfrontpage && !empty($needed['any'][$defaultfrontpageroleid]))) {
3735 // Everybody.
3736 } else {
3737 $joins[] = "JOIN (SELECT DISTINCT userid
3738 FROM {role_assignments}
3739 WHERE contextid IN ($ctxids)
3740 AND roleid IN (" . implode(',', array_keys($needed['any'])) . ")
3741 ) ra ON ra.userid = $useridcolumn";
3743 } else {
3744 $unions = [];
3745 $everybody = false;
3746 foreach ($needed as $cap => $unused) {
3747 if (empty($prohibited[$cap])) {
3748 if (!empty($needed[$cap][$defaultuserroleid]) ||
3749 ($isfrontpage && !empty($needed[$cap][$defaultfrontpageroleid]))) {
3750 $everybody = true;
3751 break;
3752 } else {
3753 $unions[] = "SELECT userid
3754 FROM {role_assignments}
3755 WHERE contextid IN ($ctxids)
3756 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3758 } else {
3759 if (!empty($prohibited[$cap][$defaultuserroleid]) ||
3760 ($isfrontpage && !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3761 // Nobody can have this cap because it is prohibited in default roles.
3762 continue;
3764 } else if (!empty($needed[$cap][$defaultuserroleid]) ||
3765 ($isfrontpage && !empty($needed[$cap][$defaultfrontpageroleid]))) {
3766 // Everybody except the prohibited - hiding does not matter.
3767 $unions[] = "SELECT id AS userid
3768 FROM {user}
3769 WHERE id NOT IN (SELECT userid
3770 FROM {role_assignments}
3771 WHERE contextid IN ($ctxids)
3772 AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . "))";
3774 } else {
3775 $unions[] = "SELECT userid
3776 FROM {role_assignments}
3777 WHERE contextid IN ($ctxids) AND roleid IN (" . implode(',', array_keys($needed[$cap])) . ")
3778 AND userid NOT IN (
3779 SELECT userid
3780 FROM {role_assignments}
3781 WHERE contextid IN ($ctxids)
3782 AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . "))";
3787 if (!$everybody) {
3788 if ($unions) {
3789 $joins[] = "JOIN (
3790 SELECT DISTINCT userid
3791 FROM (
3792 " . implode("\n UNION \n", $unions) . "
3793 ) us
3794 ) ra ON ra.userid = $useridcolumn";
3795 } else {
3796 // Only prohibits found - nobody can be matched.
3797 $wherecond[] = "1 = 2";
3798 $cannotmatchanyrows = true;
3803 return new \core\dml\sql_join(implode("\n", $joins), implode(" AND ", $wherecond), $params, $cannotmatchanyrows);
3807 * Who has this capability in this context?
3809 * This can be a very expensive call - use sparingly and keep
3810 * the results if you are going to need them again soon.
3812 * Note if $fields is empty this function attempts to get u.*
3813 * which can get rather large - and has a serious perf impact
3814 * on some DBs.
3816 * @param context $context
3817 * @param string|array $capability - capability name(s)
3818 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3819 * @param string $sort - the sort order. Default is lastaccess time.
3820 * @param mixed $limitfrom - number of records to skip (offset)
3821 * @param mixed $limitnum - number of records to fetch
3822 * @param string|array $groups - single group or array of groups - only return
3823 * users who are in one of these group(s).
3824 * @param string|array $exceptions - list of users to exclude, comma separated or array
3825 * @param bool $notuseddoanything not used any more, admin accounts are never returned
3826 * @param bool $notusedview - use get_enrolled_sql() instead
3827 * @param bool $useviewallgroups if $groups is set the return users who
3828 * have capability both $capability and moodle/site:accessallgroups
3829 * in this context, as well as users who have $capability and who are
3830 * in $groups.
3831 * @return array of user records
3833 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3834 $groups = '', $exceptions = '', $notuseddoanything = null, $notusedview = null, $useviewallgroups = false) {
3835 global $CFG, $DB;
3837 // Context is a course page other than the frontpage.
3838 $iscoursepage = $context->contextlevel == CONTEXT_COURSE && $context->instanceid != SITEID;
3840 // Set up default fields list if necessary.
3841 if (empty($fields)) {
3842 if ($iscoursepage) {
3843 $fields = 'u.*, ul.timeaccess AS lastaccess';
3844 } else {
3845 $fields = 'u.*';
3847 } else {
3848 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3849 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3853 // Set up default sort if necessary.
3854 if (empty($sort)) { // default to course lastaccess or just lastaccess
3855 if ($iscoursepage) {
3856 $sort = 'ul.timeaccess';
3857 } else {
3858 $sort = 'u.lastaccess';
3862 // Get the bits of SQL relating to capabilities.
3863 $sqljoin = get_with_capability_join($context, $capability, 'u.id');
3864 if ($sqljoin->cannotmatchanyrows) {
3865 return [];
3868 // Prepare query clauses.
3869 $wherecond = [$sqljoin->wheres];
3870 $params = $sqljoin->params;
3871 $joins = [$sqljoin->joins];
3873 // Add user lastaccess JOIN, if required.
3874 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3875 // Here user_lastaccess is not required MDL-13810.
3876 } else {
3877 if ($iscoursepage) {
3878 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3879 } else {
3880 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3884 // Groups.
3885 if ($groups) {
3886 $groups = (array)$groups;
3887 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3888 $joins[] = "LEFT OUTER JOIN (SELECT DISTINCT userid
3889 FROM {groups_members}
3890 WHERE groupid $grouptest
3891 ) gm ON gm.userid = u.id";
3893 $params = array_merge($params, $grpparams);
3895 $grouptest = 'gm.userid IS NOT NULL';
3896 if ($useviewallgroups) {
3897 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3898 if (!empty($viewallgroupsusers)) {
3899 $grouptest .= ' OR u.id IN (' . implode(',', array_keys($viewallgroupsusers)) . ')';
3902 $wherecond[] = "($grouptest)";
3905 // User exceptions.
3906 if (!empty($exceptions)) {
3907 $exceptions = (array)$exceptions;
3908 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3909 $params = array_merge($params, $exparams);
3910 $wherecond[] = "u.id $exsql";
3913 // Collect WHERE conditions and needed joins.
3914 $where = implode(' AND ', $wherecond);
3915 if ($where !== '') {
3916 $where = 'WHERE ' . $where;
3918 $joins = implode("\n", $joins);
3920 // Finally! we have all the bits, run the query.
3921 $sql = "SELECT $fields
3922 FROM {user} u
3923 $joins
3924 $where
3925 ORDER BY $sort";
3927 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3931 * Re-sort a users array based on a sorting policy
3933 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3934 * based on a sorting policy. This is to support the odd practice of
3935 * sorting teachers by 'authority', where authority was "lowest id of the role
3936 * assignment".
3938 * Will execute 1 database query. Only suitable for small numbers of users, as it
3939 * uses an u.id IN() clause.
3941 * Notes about the sorting criteria.
3943 * As a default, we cannot rely on role.sortorder because then
3944 * admins/coursecreators will always win. That is why the sane
3945 * rule "is locality matters most", with sortorder as 2nd
3946 * consideration.
3948 * If you want role.sortorder, use the 'sortorder' policy, and
3949 * name explicitly what roles you want to cover. It's probably
3950 * a good idea to see what roles have the capabilities you want
3951 * (array_diff() them against roiles that have 'can-do-anything'
3952 * to weed out admin-ish roles. Or fetch a list of roles from
3953 * variables like $CFG->coursecontact .
3955 * @param array $users Users array, keyed on userid
3956 * @param context $context
3957 * @param array $roles ids of the roles to include, optional
3958 * @param string $sortpolicy defaults to locality, more about
3959 * @return array sorted copy of the array
3961 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3962 global $DB;
3964 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3965 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3966 if (empty($roles)) {
3967 $roleswhere = '';
3968 } else {
3969 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3972 $sql = "SELECT ra.userid
3973 FROM {role_assignments} ra
3974 JOIN {role} r
3975 ON ra.roleid=r.id
3976 JOIN {context} ctx
3977 ON ra.contextid=ctx.id
3978 WHERE $userswhere
3979 $contextwhere
3980 $roleswhere";
3982 // Default 'locality' policy -- read PHPDoc notes
3983 // about sort policies...
3984 $orderby = 'ORDER BY '
3985 .'ctx.depth DESC, ' /* locality wins */
3986 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3987 .'ra.id'; /* role assignment order tie-breaker */
3988 if ($sortpolicy === 'sortorder') {
3989 $orderby = 'ORDER BY '
3990 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3991 .'ra.id'; /* role assignment order tie-breaker */
3994 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3995 $sortedusers = array();
3996 $seen = array();
3998 foreach ($sortedids as $id) {
3999 // Avoid duplicates
4000 if (isset($seen[$id])) {
4001 continue;
4003 $seen[$id] = true;
4005 // assign
4006 $sortedusers[$id] = $users[$id];
4008 return $sortedusers;
4012 * Gets all the users assigned this role in this context or higher
4014 * Note that moodle is based on capabilities and it is usually better
4015 * to check permissions than to check role ids as the capabilities
4016 * system is more flexible. If you really need, you can to use this
4017 * function but consider has_capability() as a possible substitute.
4019 * All $sort fields are added into $fields if not present there yet.
4021 * If $roleid is an array or is empty (all roles) you need to set $fields
4022 * (and $sort by extension) params according to it, as the first field
4023 * returned by the database should be unique (ra.id is the best candidate).
4025 * @param int $roleid (can also be an array of ints!)
4026 * @param context $context
4027 * @param bool $parent if true, get list of users assigned in higher context too
4028 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
4029 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
4030 * null => use default sort from users_order_by_sql.
4031 * @param bool $all true means all, false means limit to enrolled users
4032 * @param string $group defaults to ''
4033 * @param mixed $limitfrom defaults to ''
4034 * @param mixed $limitnum defaults to ''
4035 * @param string $extrawheretest defaults to ''
4036 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
4037 * @return array
4039 function get_role_users($roleid, context $context, $parent = false, $fields = '',
4040 $sort = null, $all = true, $group = '',
4041 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
4042 global $DB;
4044 if (empty($fields)) {
4045 $userfieldsapi = \core_user\fields::for_name();
4046 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
4047 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
4048 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
4049 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
4050 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
4051 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
4054 // Prevent wrong function uses.
4055 if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
4056 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
4057 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
4059 if (!empty($roleid)) {
4060 // Solving partially the issue when specifying multiple roles.
4061 $users = array();
4062 foreach ($roleid as $id) {
4063 // Ignoring duplicated keys keeping the first user appearance.
4064 $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
4065 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
4067 return $users;
4071 $parentcontexts = '';
4072 if ($parent) {
4073 $parentcontexts = substr($context->path, 1); // kill leading slash
4074 $parentcontexts = str_replace('/', ',', $parentcontexts);
4075 if ($parentcontexts !== '') {
4076 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4080 if ($roleid) {
4081 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
4082 $roleselect = "AND ra.roleid $rids";
4083 } else {
4084 $params = array();
4085 $roleselect = '';
4088 if ($coursecontext = $context->get_course_context(false)) {
4089 $params['coursecontext'] = $coursecontext->id;
4090 } else {
4091 $params['coursecontext'] = 0;
4094 if ($group) {
4095 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
4096 $groupselect = " AND gm.groupid = :groupid ";
4097 $params['groupid'] = $group;
4098 } else {
4099 $groupjoin = '';
4100 $groupselect = '';
4103 $params['contextid'] = $context->id;
4105 if ($extrawheretest) {
4106 $extrawheretest = ' AND ' . $extrawheretest;
4109 if ($whereorsortparams) {
4110 $params = array_merge($params, $whereorsortparams);
4113 if (!$sort) {
4114 list($sort, $sortparams) = users_order_by_sql('u');
4115 $params = array_merge($params, $sortparams);
4118 // Adding the fields from $sort that are not present in $fields.
4119 $sortarray = preg_split('/,\s*/', $sort);
4120 $fieldsarray = preg_split('/,\s*/', $fields);
4122 // Discarding aliases from the fields.
4123 $fieldnames = array();
4124 foreach ($fieldsarray as $key => $field) {
4125 list($fieldnames[$key]) = explode(' ', $field);
4128 $addedfields = array();
4129 foreach ($sortarray as $sortfield) {
4130 // Throw away any additional arguments to the sort (e.g. ASC/DESC).
4131 list($sortfield) = explode(' ', $sortfield);
4132 list($tableprefix) = explode('.', $sortfield);
4133 $fieldpresent = false;
4134 foreach ($fieldnames as $fieldname) {
4135 if ($fieldname === $sortfield || $fieldname === $tableprefix.'.*') {
4136 $fieldpresent = true;
4137 break;
4141 if (!$fieldpresent) {
4142 $fieldsarray[] = $sortfield;
4143 $addedfields[] = $sortfield;
4147 $fields = implode(', ', $fieldsarray);
4148 if (!empty($addedfields)) {
4149 $addedfields = implode(', ', $addedfields);
4150 debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
4153 if ($all === null) {
4154 // Previously null was used to indicate that parameter was not used.
4155 $all = true;
4157 if (!$all and $coursecontext) {
4158 // Do not use get_enrolled_sql() here for performance reasons.
4159 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
4160 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
4161 $params['ecourseid'] = $coursecontext->instanceid;
4162 } else {
4163 $ejoin = "";
4166 $sql = "SELECT DISTINCT $fields, ra.roleid
4167 FROM {role_assignments} ra
4168 JOIN {user} u ON u.id = ra.userid
4169 JOIN {role} r ON ra.roleid = r.id
4170 $ejoin
4171 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
4172 $groupjoin
4173 WHERE (ra.contextid = :contextid $parentcontexts)
4174 $roleselect
4175 $groupselect
4176 $extrawheretest
4177 ORDER BY $sort"; // join now so that we can just use fullname() later
4179 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
4183 * Counts all the users assigned this role in this context or higher
4185 * @param int|array $roleid either int or an array of ints
4186 * @param context $context
4187 * @param bool $parent if true, get list of users assigned in higher context too
4188 * @return int Returns the result count
4190 function count_role_users($roleid, context $context, $parent = false) {
4191 global $DB;
4193 if ($parent) {
4194 if ($contexts = $context->get_parent_context_ids()) {
4195 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4196 } else {
4197 $parentcontexts = '';
4199 } else {
4200 $parentcontexts = '';
4203 if ($roleid) {
4204 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
4205 $roleselect = "AND r.roleid $rids";
4206 } else {
4207 $params = array();
4208 $roleselect = '';
4211 array_unshift($params, $context->id);
4213 $sql = "SELECT COUNT(DISTINCT u.id)
4214 FROM {role_assignments} r
4215 JOIN {user} u ON u.id = r.userid
4216 WHERE (r.contextid = ? $parentcontexts)
4217 $roleselect
4218 AND u.deleted = 0";
4220 return $DB->count_records_sql($sql, $params);
4224 * This function gets the list of course and course category contexts that this user has a particular capability in.
4226 * It is now reasonably efficient, but bear in mind that if there are users who have the capability
4227 * everywhere, it may return an array of all contexts.
4229 * @param string $capability Capability in question
4230 * @param int $userid User ID or null for current user
4231 * @param bool $getcategories Wether to return also course_categories
4232 * @param bool $doanything True if 'doanything' is permitted (default)
4233 * @param string $coursefieldsexceptid Leave blank if you only need 'id' in the course records;
4234 * otherwise use a comma-separated list of the fields you require, not including id.
4235 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
4236 * @param string $categoryfieldsexceptid Leave blank if you only need 'id' in the course records;
4237 * otherwise use a comma-separated list of the fields you require, not including id.
4238 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
4239 * @param string $courseorderby If set, use a comma-separated list of fields from course
4240 * table with sql modifiers (DESC) if needed
4241 * @param string $categoryorderby If set, use a comma-separated list of fields from course_category
4242 * table with sql modifiers (DESC) if needed
4243 * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
4244 * @return array Array of categories and courses.
4246 function get_user_capability_contexts(string $capability, bool $getcategories, $userid = null, $doanything = true,
4247 $coursefieldsexceptid = '', $categoryfieldsexceptid = '', $courseorderby = '',
4248 $categoryorderby = '', $limit = 0): array {
4249 global $DB, $USER;
4251 // Default to current user.
4252 if (!$userid) {
4253 $userid = $USER->id;
4256 if (!$capinfo = get_capability_info($capability)) {
4257 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
4258 return [false, false];
4261 if ($doanything && is_siteadmin($userid)) {
4262 // If the user is a site admin and $doanything is enabled then there is no need to restrict
4263 // the list of courses.
4264 $contextlimitsql = '';
4265 $contextlimitparams = [];
4266 } else {
4267 // Gets SQL to limit contexts ('x' table) to those where the user has this capability.
4268 list ($contextlimitsql, $contextlimitparams) = \core\access\get_user_capability_course_helper::get_sql(
4269 $userid, $capinfo->name);
4270 if (!$contextlimitsql) {
4271 // If the does not have this capability in any context, return false without querying.
4272 return [false, false];
4275 $contextlimitsql = 'WHERE' . $contextlimitsql;
4278 $categories = [];
4279 if ($getcategories) {
4280 $fieldlist = \core\access\get_user_capability_course_helper::map_fieldnames($categoryfieldsexceptid);
4281 if ($categoryorderby) {
4282 $fields = explode(',', $categoryorderby);
4283 $orderby = '';
4284 foreach ($fields as $field) {
4285 if ($orderby) {
4286 $orderby .= ',';
4288 $orderby .= 'c.'.$field;
4290 $orderby = 'ORDER BY '.$orderby;
4292 $rs = $DB->get_recordset_sql("
4293 SELECT c.id $fieldlist
4294 FROM {course_categories} c
4295 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
4296 $contextlimitsql
4297 $orderby", array_merge([CONTEXT_COURSECAT], $contextlimitparams));
4298 $basedlimit = $limit;
4299 foreach ($rs as $category) {
4300 $categories[] = $category;
4301 $basedlimit--;
4302 if ($basedlimit == 0) {
4303 break;
4308 $courses = [];
4309 $fieldlist = \core\access\get_user_capability_course_helper::map_fieldnames($coursefieldsexceptid);
4310 if ($courseorderby) {
4311 $fields = explode(',', $courseorderby);
4312 $courseorderby = '';
4313 foreach ($fields as $field) {
4314 if ($courseorderby) {
4315 $courseorderby .= ',';
4317 $courseorderby .= 'c.'.$field;
4319 $courseorderby = 'ORDER BY '.$courseorderby;
4321 $rs = $DB->get_recordset_sql("
4322 SELECT c.id $fieldlist
4323 FROM {course} c
4324 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
4325 $contextlimitsql
4326 $courseorderby", array_merge([CONTEXT_COURSE], $contextlimitparams));
4327 foreach ($rs as $course) {
4328 $courses[] = $course;
4329 $limit--;
4330 if ($limit == 0) {
4331 break;
4334 $rs->close();
4335 return [$categories, $courses];
4339 * This function gets the list of courses that this user has a particular capability in.
4341 * It is now reasonably efficient, but bear in mind that if there are users who have the capability
4342 * everywhere, it may return an array of all courses.
4344 * @param string $capability Capability in question
4345 * @param int $userid User ID or null for current user
4346 * @param bool $doanything True if 'doanything' is permitted (default)
4347 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4348 * otherwise use a comma-separated list of the fields you require, not including id.
4349 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
4350 * @param string $orderby If set, use a comma-separated list of fields from course
4351 * table with sql modifiers (DESC) if needed
4352 * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
4353 * @return array|bool Array of courses, if none found false is returned.
4355 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '',
4356 $orderby = '', $limit = 0) {
4357 list($categories, $courses) = get_user_capability_contexts(
4358 $capability,
4359 false,
4360 $userid,
4361 $doanything,
4362 $fieldsexceptid,
4364 $orderby,
4366 $limit
4368 return $courses;
4372 * Switches the current user to another role for the current session and only
4373 * in the given context.
4375 * The caller *must* check
4376 * - that this op is allowed
4377 * - that the requested role can be switched to in this context (use get_switchable_roles)
4378 * - that the requested role is NOT $CFG->defaultuserroleid
4380 * To "unswitch" pass 0 as the roleid.
4382 * This function *will* modify $USER->access - beware
4384 * @param integer $roleid the role to switch to.
4385 * @param context $context the context in which to perform the switch.
4386 * @return bool success or failure.
4388 function role_switch($roleid, context $context) {
4389 global $USER;
4391 // Add the ghost RA to $USER->access as $USER->access['rsw'][$path] = $roleid.
4392 // To un-switch just unset($USER->access['rsw'][$path]).
4394 // Note: it is not possible to switch to roles that do not have course:view
4396 if (!isset($USER->access)) {
4397 load_all_capabilities();
4400 // Make sure that course index is refreshed.
4401 if ($coursecontext = $context->get_course_context()) {
4402 core_courseformat\base::session_cache_reset(get_course($coursecontext->instanceid));
4405 // Add the switch RA
4406 if ($roleid == 0) {
4407 unset($USER->access['rsw'][$context->path]);
4408 return true;
4411 $USER->access['rsw'][$context->path] = $roleid;
4413 return true;
4417 * Checks if the user has switched roles within the given course.
4419 * Note: You can only switch roles within the course, hence it takes a course id
4420 * rather than a context. On that note Petr volunteered to implement this across
4421 * all other contexts, all requests for this should be forwarded to him ;)
4423 * @param int $courseid The id of the course to check
4424 * @return bool True if the user has switched roles within the course.
4426 function is_role_switched($courseid) {
4427 global $USER;
4428 $context = context_course::instance($courseid, MUST_EXIST);
4429 return (!empty($USER->access['rsw'][$context->path]));
4433 * Get any role that has an override on exact context
4435 * @param context $context The context to check
4436 * @return array An array of roles
4438 function get_roles_with_override_on_context(context $context) {
4439 global $DB;
4441 return $DB->get_records_sql("SELECT r.*
4442 FROM {role_capabilities} rc, {role} r
4443 WHERE rc.roleid = r.id AND rc.contextid = ?",
4444 array($context->id));
4448 * Get all capabilities for this role on this context (overrides)
4450 * @param stdClass $role
4451 * @param context $context
4452 * @return array
4454 function get_capabilities_from_role_on_context($role, context $context) {
4455 global $DB;
4457 return $DB->get_records_sql("SELECT *
4458 FROM {role_capabilities}
4459 WHERE contextid = ? AND roleid = ?",
4460 array($context->id, $role->id));
4464 * Find all user assignment of users for this role, on this context
4466 * @param stdClass $role
4467 * @param context $context
4468 * @return array
4470 function get_users_from_role_on_context($role, context $context) {
4471 global $DB;
4473 return $DB->get_records_sql("SELECT *
4474 FROM {role_assignments}
4475 WHERE contextid = ? AND roleid = ?",
4476 array($context->id, $role->id));
4480 * Simple function returning a boolean true if user has roles
4481 * in context or parent contexts, otherwise false.
4483 * @param int $userid
4484 * @param int $roleid
4485 * @param int $contextid empty means any context
4486 * @return bool
4488 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4489 global $DB;
4491 if ($contextid) {
4492 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4493 return false;
4495 $parents = $context->get_parent_context_ids(true);
4496 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4497 $params['userid'] = $userid;
4498 $params['roleid'] = $roleid;
4500 $sql = "SELECT COUNT(ra.id)
4501 FROM {role_assignments} ra
4502 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4504 $count = $DB->get_field_sql($sql, $params);
4505 return ($count > 0);
4507 } else {
4508 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4513 * Get localised role name or alias if exists and format the text.
4515 * @param stdClass $role role object
4516 * - optional 'coursealias' property should be included for performance reasons if course context used
4517 * - description property is not required here
4518 * @param context|bool $context empty means system context
4519 * @param int $rolenamedisplay type of role name
4520 * @return string localised role name or course role name alias
4522 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4523 global $DB;
4525 if ($rolenamedisplay == ROLENAME_SHORT) {
4526 return $role->shortname;
4529 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4530 $coursecontext = null;
4533 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4534 $role = clone($role); // Do not modify parameters.
4535 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4536 $role->coursealias = $r->name;
4537 } else {
4538 $role->coursealias = null;
4542 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4543 if ($coursecontext) {
4544 return $role->coursealias;
4545 } else {
4546 return null;
4550 if (trim($role->name) !== '') {
4551 // For filtering always use context where was the thing defined - system for roles here.
4552 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4554 } else {
4555 // Empty role->name means we want to see localised role name based on shortname,
4556 // only default roles are supposed to be localised.
4557 switch ($role->shortname) {
4558 case 'manager': $original = get_string('manager', 'role'); break;
4559 case 'coursecreator': $original = get_string('coursecreators'); break;
4560 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4561 case 'teacher': $original = get_string('noneditingteacher'); break;
4562 case 'student': $original = get_string('defaultcoursestudent'); break;
4563 case 'guest': $original = get_string('guest'); break;
4564 case 'user': $original = get_string('authenticateduser'); break;
4565 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4566 // We should not get here, the role UI should require the name for custom roles!
4567 default: $original = $role->shortname; break;
4571 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4572 return $original;
4575 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4576 return "$original ($role->shortname)";
4579 if ($rolenamedisplay == ROLENAME_ALIAS) {
4580 if ($coursecontext && $role->coursealias && trim($role->coursealias) !== '') {
4581 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4582 } else {
4583 return $original;
4587 if ($rolenamedisplay == ROLENAME_BOTH) {
4588 if ($coursecontext && $role->coursealias && trim($role->coursealias) !== '') {
4589 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4590 } else {
4591 return $original;
4595 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4599 * Returns localised role description if available.
4600 * If the name is empty it tries to find the default role name using
4601 * hardcoded list of default role names or other methods in the future.
4603 * @param stdClass $role
4604 * @return string localised role name
4606 function role_get_description(stdClass $role) {
4607 if (!html_is_blank($role->description)) {
4608 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4611 switch ($role->shortname) {
4612 case 'manager': return get_string('managerdescription', 'role');
4613 case 'coursecreator': return get_string('coursecreatorsdescription');
4614 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4615 case 'teacher': return get_string('noneditingteacherdescription');
4616 case 'student': return get_string('defaultcoursestudentdescription');
4617 case 'guest': return get_string('guestdescription');
4618 case 'user': return get_string('authenticateduserdescription');
4619 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4620 default: return '';
4625 * Get all the localised role names for a context.
4627 * In new installs default roles have empty names, this function
4628 * add localised role names using current language pack.
4630 * @param context $context the context, null means system context
4631 * @param array of role objects with a ->localname field containing the context-specific role name.
4632 * @param int $rolenamedisplay
4633 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4634 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4636 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4637 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4641 * Prepare list of roles for display, apply aliases and localise default role names.
4643 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4644 * @param context $context the context, null means system context
4645 * @param int $rolenamedisplay
4646 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4647 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4649 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4650 global $DB;
4652 if (empty($roleoptions)) {
4653 return array();
4656 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4657 $coursecontext = null;
4660 // We usually need all role columns...
4661 $first = reset($roleoptions);
4662 if ($returnmenu === null) {
4663 $returnmenu = !is_object($first);
4666 if (!is_object($first) or !property_exists($first, 'shortname')) {
4667 $allroles = get_all_roles($context);
4668 foreach ($roleoptions as $rid => $unused) {
4669 $roleoptions[$rid] = $allroles[$rid];
4673 // Inject coursealias if necessary.
4674 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4675 $first = reset($roleoptions);
4676 if (!property_exists($first, 'coursealias')) {
4677 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4678 foreach ($aliasnames as $alias) {
4679 if (isset($roleoptions[$alias->roleid])) {
4680 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4686 // Add localname property.
4687 foreach ($roleoptions as $rid => $role) {
4688 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4691 if (!$returnmenu) {
4692 return $roleoptions;
4695 $menu = array();
4696 foreach ($roleoptions as $rid => $role) {
4697 $menu[$rid] = $role->localname;
4700 return $menu;
4704 * Aids in detecting if a new line is required when reading a new capability
4706 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4707 * when we read in a new capability.
4708 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4709 * but when we are in grade, all reports/import/export capabilities should be together
4711 * @param string $cap component string a
4712 * @param string $comp component string b
4713 * @param int $contextlevel
4714 * @return bool whether 2 component are in different "sections"
4716 function component_level_changed($cap, $comp, $contextlevel) {
4718 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4719 $compsa = explode('/', $cap->component);
4720 $compsb = explode('/', $comp);
4722 // list of system reports
4723 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4724 return false;
4727 // we are in gradebook, still
4728 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4729 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4730 return false;
4733 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4734 return false;
4738 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4742 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4743 * and return an array of roleids in order.
4745 * @param array $allroles array of roles, as returned by get_all_roles();
4746 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4748 function fix_role_sortorder($allroles) {
4749 global $DB;
4751 $rolesort = array();
4752 $i = 0;
4753 foreach ($allroles as $role) {
4754 $rolesort[$i] = $role->id;
4755 if ($role->sortorder != $i) {
4756 $r = new stdClass();
4757 $r->id = $role->id;
4758 $r->sortorder = $i;
4759 $DB->update_record('role', $r);
4760 $allroles[$role->id]->sortorder = $i;
4762 $i++;
4764 return $rolesort;
4768 * Switch the sort order of two roles (used in admin/roles/manage.php).
4770 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4771 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4772 * @return boolean success or failure
4774 function switch_roles($first, $second) {
4775 global $DB;
4776 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4777 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4778 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4779 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4780 return $result;
4784 * Duplicates all the base definitions of a role
4786 * @param stdClass $sourcerole role to copy from
4787 * @param int $targetrole id of role to copy to
4789 function role_cap_duplicate($sourcerole, $targetrole) {
4790 global $DB;
4792 $systemcontext = context_system::instance();
4793 $caps = $DB->get_records_sql("SELECT *
4794 FROM {role_capabilities}
4795 WHERE roleid = ? AND contextid = ?",
4796 array($sourcerole->id, $systemcontext->id));
4797 // adding capabilities
4798 foreach ($caps as $cap) {
4799 unset($cap->id);
4800 $cap->roleid = $targetrole;
4801 $DB->insert_record('role_capabilities', $cap);
4804 // Reset any cache of this role, including MUC.
4805 accesslib_clear_role_cache($targetrole);
4809 * Returns two lists, this can be used to find out if user has capability.
4810 * Having any needed role and no forbidden role in this context means
4811 * user has this capability in this context.
4812 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4814 * @param stdClass $context
4815 * @param string $capability
4816 * @return array($neededroles, $forbiddenroles)
4818 function get_roles_with_cap_in_context($context, $capability) {
4819 global $DB;
4821 $ctxids = trim($context->path, '/'); // kill leading slash
4822 $ctxids = str_replace('/', ',', $ctxids);
4824 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4825 FROM {role_capabilities} rc
4826 JOIN {context} ctx ON ctx.id = rc.contextid
4827 JOIN {capabilities} cap ON rc.capability = cap.name
4828 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4829 ORDER BY rc.roleid ASC, ctx.depth DESC";
4830 $params = array('cap'=>$capability);
4832 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4833 // no cap definitions --> no capability
4834 return array(array(), array());
4837 $forbidden = array();
4838 $needed = array();
4839 foreach ($capdefs as $def) {
4840 if (isset($forbidden[$def->roleid])) {
4841 continue;
4843 if ($def->permission == CAP_PROHIBIT) {
4844 $forbidden[$def->roleid] = $def->roleid;
4845 unset($needed[$def->roleid]);
4846 continue;
4848 if (!isset($needed[$def->roleid])) {
4849 if ($def->permission == CAP_ALLOW) {
4850 $needed[$def->roleid] = true;
4851 } else if ($def->permission == CAP_PREVENT) {
4852 $needed[$def->roleid] = false;
4856 unset($capdefs);
4858 // remove all those roles not allowing
4859 foreach ($needed as $key=>$value) {
4860 if (!$value) {
4861 unset($needed[$key]);
4862 } else {
4863 $needed[$key] = $key;
4867 return array($needed, $forbidden);
4871 * Returns an array of role IDs that have ALL of the the supplied capabilities
4872 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4874 * @param stdClass $context
4875 * @param array $capabilities An array of capabilities
4876 * @return array of roles with all of the required capabilities
4878 function get_roles_with_caps_in_context($context, $capabilities) {
4879 $neededarr = array();
4880 $forbiddenarr = array();
4881 foreach ($capabilities as $caprequired) {
4882 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4885 $rolesthatcanrate = array();
4886 if (!empty($neededarr)) {
4887 foreach ($neededarr as $needed) {
4888 if (empty($rolesthatcanrate)) {
4889 $rolesthatcanrate = $needed;
4890 } else {
4891 //only want roles that have all caps
4892 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4896 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4897 foreach ($forbiddenarr as $forbidden) {
4898 //remove any roles that are forbidden any of the caps
4899 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4902 return $rolesthatcanrate;
4906 * Returns an array of role names that have ALL of the the supplied capabilities
4907 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4909 * @param stdClass $context
4910 * @param array $capabilities An array of capabilities
4911 * @return array of roles with all of the required capabilities
4913 function get_role_names_with_caps_in_context($context, $capabilities) {
4914 global $DB;
4916 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4917 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4919 $roles = array();
4920 foreach ($rolesthatcanrate as $r) {
4921 $roles[$r] = $allroles[$r];
4924 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4928 * This function verifies the prohibit comes from this context
4929 * and there are no more prohibits in parent contexts.
4931 * @param int $roleid
4932 * @param context $context
4933 * @param string $capability name
4934 * @return bool
4936 function prohibit_is_removable($roleid, context $context, $capability) {
4937 global $DB;
4939 $ctxids = trim($context->path, '/'); // kill leading slash
4940 $ctxids = str_replace('/', ',', $ctxids);
4942 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4944 $sql = "SELECT ctx.id
4945 FROM {role_capabilities} rc
4946 JOIN {context} ctx ON ctx.id = rc.contextid
4947 JOIN {capabilities} cap ON rc.capability = cap.name
4948 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4949 ORDER BY ctx.depth DESC";
4951 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4952 // no prohibits == nothing to remove
4953 return true;
4956 if (count($prohibits) > 1) {
4957 // more prohibits can not be removed
4958 return false;
4961 return !empty($prohibits[$context->id]);
4965 * More user friendly role permission changing,
4966 * it should produce as few overrides as possible.
4968 * @param int $roleid
4969 * @param stdClass $context
4970 * @param string $capname capability name
4971 * @param int $permission
4972 * @return void
4974 function role_change_permission($roleid, $context, $capname, $permission) {
4975 global $DB;
4977 if ($permission == CAP_INHERIT) {
4978 unassign_capability($capname, $roleid, $context->id);
4979 return;
4982 $ctxids = trim($context->path, '/'); // kill leading slash
4983 $ctxids = str_replace('/', ',', $ctxids);
4985 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4987 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4988 FROM {role_capabilities} rc
4989 JOIN {context} ctx ON ctx.id = rc.contextid
4990 JOIN {capabilities} cap ON rc.capability = cap.name
4991 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4992 ORDER BY ctx.depth DESC";
4994 if ($existing = $DB->get_records_sql($sql, $params)) {
4995 foreach ($existing as $e) {
4996 if ($e->permission == CAP_PROHIBIT) {
4997 // prohibit can not be overridden, no point in changing anything
4998 return;
5001 $lowest = array_shift($existing);
5002 if ($lowest->permission == $permission) {
5003 // permission already set in this context or parent - nothing to do
5004 return;
5006 if ($existing) {
5007 $parent = array_shift($existing);
5008 if ($parent->permission == $permission) {
5009 // permission already set in parent context or parent - just unset in this context
5010 // we do this because we want as few overrides as possible for performance reasons
5011 unassign_capability($capname, $roleid, $context->id);
5012 return;
5016 } else {
5017 if ($permission == CAP_PREVENT) {
5018 // nothing means role does not have permission
5019 return;
5023 // assign the needed capability
5024 assign_capability($capname, $permission, $roleid, $context->id, true);
5029 * Basic moodle context abstraction class.
5031 * Google confirms that no other important framework is using "context" class,
5032 * we could use something else like mcontext or moodle_context, but we need to type
5033 * this very often which would be annoying and it would take too much space...
5035 * This class is derived from stdClass for backwards compatibility with
5036 * odl $context record that was returned from DML $DB->get_record()
5038 * @package core_access
5039 * @category access
5040 * @copyright Petr Skoda {@link http://skodak.org}
5041 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5042 * @since Moodle 2.2
5044 * @property-read int $id context id
5045 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
5046 * @property-read int $instanceid id of related instance in each context
5047 * @property-read string $path path to context, starts with system context
5048 * @property-read int $depth
5050 abstract class context extends stdClass implements IteratorAggregate {
5052 /** @var string Default sorting of capabilities in {@see get_capabilities} */
5053 protected const DEFAULT_CAPABILITY_SORT = 'contextlevel, component, name';
5056 * The context id
5057 * Can be accessed publicly through $context->id
5058 * @var int
5060 protected $_id;
5063 * The context level
5064 * Can be accessed publicly through $context->contextlevel
5065 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
5067 protected $_contextlevel;
5070 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
5071 * Can be accessed publicly through $context->instanceid
5072 * @var int
5074 protected $_instanceid;
5077 * The path to the context always starting from the system context
5078 * Can be accessed publicly through $context->path
5079 * @var string
5081 protected $_path;
5084 * The depth of the context in relation to parent contexts
5085 * Can be accessed publicly through $context->depth
5086 * @var int
5088 protected $_depth;
5091 * Whether this context is locked or not.
5093 * Can be accessed publicly through $context->locked.
5095 * @var int
5097 protected $_locked;
5100 * @var array Context caching info
5102 private static $cache_contextsbyid = array();
5105 * @var array Context caching info
5107 private static $cache_contexts = array();
5110 * Context count
5111 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
5112 * @var int
5114 protected static $cache_count = 0;
5117 * @var array Context caching info
5119 protected static $cache_preloaded = array();
5122 * @var context_system The system context once initialised
5124 protected static $systemcontext = null;
5127 * Resets the cache to remove all data.
5128 * @static
5130 protected static function reset_caches() {
5131 self::$cache_contextsbyid = array();
5132 self::$cache_contexts = array();
5133 self::$cache_count = 0;
5134 self::$cache_preloaded = array();
5136 self::$systemcontext = null;
5140 * Adds a context to the cache. If the cache is full, discards a batch of
5141 * older entries.
5143 * @static
5144 * @param context $context New context to add
5145 * @return void
5147 protected static function cache_add(context $context) {
5148 if (isset(self::$cache_contextsbyid[$context->id])) {
5149 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5150 return;
5153 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
5154 $i = 0;
5155 foreach (self::$cache_contextsbyid as $ctx) {
5156 $i++;
5157 if ($i <= 100) {
5158 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
5159 continue;
5161 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
5162 // we remove oldest third of the contexts to make room for more contexts
5163 break;
5165 unset(self::$cache_contextsbyid[$ctx->id]);
5166 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
5167 self::$cache_count--;
5171 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
5172 self::$cache_contextsbyid[$context->id] = $context;
5173 self::$cache_count++;
5177 * Removes a context from the cache.
5179 * @static
5180 * @param context $context Context object to remove
5181 * @return void
5183 protected static function cache_remove(context $context) {
5184 if (!isset(self::$cache_contextsbyid[$context->id])) {
5185 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5186 return;
5188 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
5189 unset(self::$cache_contextsbyid[$context->id]);
5191 self::$cache_count--;
5193 if (self::$cache_count < 0) {
5194 self::$cache_count = 0;
5199 * Gets a context from the cache.
5201 * @static
5202 * @param int $contextlevel Context level
5203 * @param int $instance Instance ID
5204 * @return context|bool Context or false if not in cache
5206 protected static function cache_get($contextlevel, $instance) {
5207 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
5208 return self::$cache_contexts[$contextlevel][$instance];
5210 return false;
5214 * Gets a context from the cache based on its id.
5216 * @static
5217 * @param int $id Context ID
5218 * @return context|bool Context or false if not in cache
5220 protected static function cache_get_by_id($id) {
5221 if (isset(self::$cache_contextsbyid[$id])) {
5222 return self::$cache_contextsbyid[$id];
5224 return false;
5228 * Preloads context information from db record and strips the cached info.
5230 * @static
5231 * @param stdClass $rec
5232 * @return void (modifies $rec)
5234 protected static function preload_from_record(stdClass $rec) {
5235 $notenoughdata = false;
5236 $notenoughdata = $notenoughdata || empty($rec->ctxid);
5237 $notenoughdata = $notenoughdata || empty($rec->ctxlevel);
5238 $notenoughdata = $notenoughdata || !isset($rec->ctxinstance);
5239 $notenoughdata = $notenoughdata || empty($rec->ctxpath);
5240 $notenoughdata = $notenoughdata || empty($rec->ctxdepth);
5241 $notenoughdata = $notenoughdata || !isset($rec->ctxlocked);
5242 if ($notenoughdata) {
5243 // The record does not have enough data, passed here repeatedly or context does not exist yet.
5244 if (isset($rec->ctxid) && !isset($rec->ctxlocked)) {
5245 debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER);
5247 return;
5250 $record = (object) [
5251 'id' => $rec->ctxid,
5252 'contextlevel' => $rec->ctxlevel,
5253 'instanceid' => $rec->ctxinstance,
5254 'path' => $rec->ctxpath,
5255 'depth' => $rec->ctxdepth,
5256 'locked' => $rec->ctxlocked,
5259 unset($rec->ctxid);
5260 unset($rec->ctxlevel);
5261 unset($rec->ctxinstance);
5262 unset($rec->ctxpath);
5263 unset($rec->ctxdepth);
5264 unset($rec->ctxlocked);
5266 return context::create_instance_from_record($record);
5270 // ====== magic methods =======
5273 * Magic setter method, we do not want anybody to modify properties from the outside
5274 * @param string $name
5275 * @param mixed $value
5277 public function __set($name, $value) {
5278 debugging('Can not change context instance properties!');
5282 * Magic method getter, redirects to read only values.
5283 * @param string $name
5284 * @return mixed
5286 public function __get($name) {
5287 switch ($name) {
5288 case 'id':
5289 return $this->_id;
5290 case 'contextlevel':
5291 return $this->_contextlevel;
5292 case 'instanceid':
5293 return $this->_instanceid;
5294 case 'path':
5295 return $this->_path;
5296 case 'depth':
5297 return $this->_depth;
5298 case 'locked':
5299 return $this->is_locked();
5301 default:
5302 debugging('Invalid context property accessed! '.$name);
5303 return null;
5308 * Full support for isset on our magic read only properties.
5309 * @param string $name
5310 * @return bool
5312 public function __isset($name) {
5313 switch ($name) {
5314 case 'id':
5315 return isset($this->_id);
5316 case 'contextlevel':
5317 return isset($this->_contextlevel);
5318 case 'instanceid':
5319 return isset($this->_instanceid);
5320 case 'path':
5321 return isset($this->_path);
5322 case 'depth':
5323 return isset($this->_depth);
5324 case 'locked':
5325 // Locked is always set.
5326 return true;
5327 default:
5328 return false;
5333 * All properties are read only, sorry.
5334 * @param string $name
5336 public function __unset($name) {
5337 debugging('Can not unset context instance properties!');
5340 // ====== implementing method from interface IteratorAggregate ======
5343 * Create an iterator because magic vars can't be seen by 'foreach'.
5345 * Now we can convert context object to array using convert_to_array(),
5346 * and feed it properly to json_encode().
5348 public function getIterator(): Traversable {
5349 $ret = array(
5350 'id' => $this->id,
5351 'contextlevel' => $this->contextlevel,
5352 'instanceid' => $this->instanceid,
5353 'path' => $this->path,
5354 'depth' => $this->depth,
5355 'locked' => $this->locked,
5357 return new ArrayIterator($ret);
5360 // ====== general context methods ======
5363 * Constructor is protected so that devs are forced to
5364 * use context_xxx::instance() or context::instance_by_id().
5366 * @param stdClass $record
5368 protected function __construct(stdClass $record) {
5369 $this->_id = (int)$record->id;
5370 $this->_contextlevel = (int)$record->contextlevel;
5371 $this->_instanceid = $record->instanceid;
5372 $this->_path = $record->path;
5373 $this->_depth = $record->depth;
5375 if (isset($record->locked)) {
5376 $this->_locked = $record->locked;
5377 } else if (!during_initial_install() && !moodle_needs_upgrading()) {
5378 debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER);
5383 * This function is also used to work around 'protected' keyword problems in context_helper.
5384 * @static
5385 * @param stdClass $record
5386 * @return context instance
5388 protected static function create_instance_from_record(stdClass $record) {
5389 $classname = context_helper::get_class_for_level($record->contextlevel);
5391 if ($context = context::cache_get_by_id($record->id)) {
5392 return $context;
5395 $context = new $classname($record);
5396 context::cache_add($context);
5398 return $context;
5402 * Copy prepared new contexts from temp table to context table,
5403 * we do this in db specific way for perf reasons only.
5404 * @static
5406 protected static function merge_context_temp_table() {
5407 global $DB;
5409 /* MDL-11347:
5410 * - mysql does not allow to use FROM in UPDATE statements
5411 * - using two tables after UPDATE works in mysql, but might give unexpected
5412 * results in pg 8 (depends on configuration)
5413 * - using table alias in UPDATE does not work in pg < 8.2
5415 * Different code for each database - mostly for performance reasons
5418 $dbfamily = $DB->get_dbfamily();
5419 if ($dbfamily == 'mysql') {
5420 $updatesql = "UPDATE {context} ct, {context_temp} temp
5421 SET ct.path = temp.path,
5422 ct.depth = temp.depth,
5423 ct.locked = temp.locked
5424 WHERE ct.id = temp.id";
5425 } else if ($dbfamily == 'oracle') {
5426 $updatesql = "UPDATE {context} ct
5427 SET (ct.path, ct.depth, ct.locked) =
5428 (SELECT temp.path, temp.depth, temp.locked
5429 FROM {context_temp} temp
5430 WHERE temp.id=ct.id)
5431 WHERE EXISTS (SELECT 'x'
5432 FROM {context_temp} temp
5433 WHERE temp.id = ct.id)";
5434 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5435 $updatesql = "UPDATE {context}
5436 SET path = temp.path,
5437 depth = temp.depth,
5438 locked = temp.locked
5439 FROM {context_temp} temp
5440 WHERE temp.id={context}.id";
5441 } else {
5442 // sqlite and others
5443 $updatesql = "UPDATE {context}
5444 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5445 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id),
5446 locked = (SELECT locked FROM {context_temp} WHERE id = {context}.id)
5447 WHERE id IN (SELECT id FROM {context_temp})";
5450 $DB->execute($updatesql);
5454 * Get a context instance as an object, from a given context id.
5456 * @static
5457 * @param int $id context id
5458 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5459 * MUST_EXIST means throw exception if no record found
5460 * @return context|bool the context object or false if not found
5462 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5463 global $DB;
5465 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5466 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5467 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5470 if ($id == SYSCONTEXTID) {
5471 return context_system::instance(0, $strictness);
5474 if (is_array($id) or is_object($id) or empty($id)) {
5475 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5478 if ($context = context::cache_get_by_id($id)) {
5479 return $context;
5482 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5483 return context::create_instance_from_record($record);
5486 return false;
5490 * Update context info after moving context in the tree structure.
5492 * @param context $newparent
5493 * @return void
5495 public function update_moved(context $newparent) {
5496 global $DB;
5498 $frompath = $this->_path;
5499 $newpath = $newparent->path . '/' . $this->_id;
5501 $trans = $DB->start_delegated_transaction();
5503 $setdepth = '';
5504 if (($newparent->depth +1) != $this->_depth) {
5505 $diff = $newparent->depth - $this->_depth + 1;
5506 $setdepth = ", depth = depth + $diff";
5508 $sql = "UPDATE {context}
5509 SET path = ?
5510 $setdepth
5511 WHERE id = ?";
5512 $params = array($newpath, $this->_id);
5513 $DB->execute($sql, $params);
5515 $this->_path = $newpath;
5516 $this->_depth = $newparent->depth + 1;
5518 $sql = "UPDATE {context}
5519 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5520 $setdepth
5521 WHERE path LIKE ?";
5522 $params = array($newpath, "{$frompath}/%");
5523 $DB->execute($sql, $params);
5525 $this->mark_dirty();
5527 context::reset_caches();
5529 $trans->allow_commit();
5533 * Set whether this context has been locked or not.
5535 * @param bool $locked
5536 * @return $this
5538 public function set_locked(bool $locked) {
5539 global $DB;
5541 if ($this->_locked == $locked) {
5542 return $this;
5545 $this->_locked = $locked;
5546 $DB->set_field('context', 'locked', (int) $locked, ['id' => $this->id]);
5547 $this->mark_dirty();
5549 if ($locked) {
5550 $eventname = '\\core\\event\\context_locked';
5551 } else {
5552 $eventname = '\\core\\event\\context_unlocked';
5554 $event = $eventname::create(['context' => $this, 'objectid' => $this->id]);
5555 $event->trigger();
5557 self::reset_caches();
5559 return $this;
5563 * Remove all context path info and optionally rebuild it.
5565 * @param bool $rebuild
5566 * @return void
5568 public function reset_paths($rebuild = true) {
5569 global $DB;
5571 if ($this->_path) {
5572 $this->mark_dirty();
5574 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5575 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5576 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5577 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5578 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5579 $this->_depth = 0;
5580 $this->_path = null;
5583 if ($rebuild) {
5584 context_helper::build_all_paths(false);
5587 context::reset_caches();
5591 * Delete all data linked to content, do not delete the context record itself
5593 public function delete_content() {
5594 global $CFG, $DB;
5596 blocks_delete_all_for_context($this->_id);
5597 filter_delete_all_for_context($this->_id);
5599 require_once($CFG->dirroot . '/comment/lib.php');
5600 comment::delete_comments(array('contextid'=>$this->_id));
5602 require_once($CFG->dirroot.'/rating/lib.php');
5603 $delopt = new stdclass();
5604 $delopt->contextid = $this->_id;
5605 $rm = new rating_manager();
5606 $rm->delete_ratings($delopt);
5608 // delete all files attached to this context
5609 $fs = get_file_storage();
5610 $fs->delete_area_files($this->_id);
5612 // Delete all repository instances attached to this context.
5613 require_once($CFG->dirroot . '/repository/lib.php');
5614 repository::delete_all_for_context($this->_id);
5616 // delete all advanced grading data attached to this context
5617 require_once($CFG->dirroot.'/grade/grading/lib.php');
5618 grading_manager::delete_all_for_context($this->_id);
5620 // now delete stuff from role related tables, role_unassign_all
5621 // and unenrol should be called earlier to do proper cleanup
5622 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5623 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5624 $this->delete_capabilities();
5628 * Unassign all capabilities from a context.
5630 public function delete_capabilities() {
5631 global $DB;
5633 $ids = $DB->get_fieldset_select('role_capabilities', 'DISTINCT roleid', 'contextid = ?', array($this->_id));
5634 if ($ids) {
5635 $DB->delete_records('role_capabilities', array('contextid' => $this->_id));
5637 // Reset any cache of these roles, including MUC.
5638 accesslib_clear_role_cache($ids);
5643 * Delete the context content and the context record itself
5645 public function delete() {
5646 global $DB;
5648 if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5649 throw new coding_exception('Cannot delete system context');
5652 // double check the context still exists
5653 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5654 context::cache_remove($this);
5655 return;
5658 $this->delete_content();
5659 $DB->delete_records('context', array('id'=>$this->_id));
5660 // purge static context cache if entry present
5661 context::cache_remove($this);
5663 // Inform search engine to delete data related to this context.
5664 \core_search\manager::context_deleted($this);
5667 // ====== context level related methods ======
5670 * Utility method for context creation
5672 * @static
5673 * @param int $contextlevel
5674 * @param int $instanceid
5675 * @param string $parentpath
5676 * @return stdClass context record
5678 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5679 global $DB;
5681 $record = new stdClass();
5682 $record->contextlevel = $contextlevel;
5683 $record->instanceid = $instanceid;
5684 $record->depth = 0;
5685 $record->path = null; //not known before insert
5686 $record->locked = 0;
5688 $record->id = $DB->insert_record('context', $record);
5690 // now add path if known - it can be added later
5691 if (!is_null($parentpath)) {
5692 $record->path = $parentpath.'/'.$record->id;
5693 $record->depth = substr_count($record->path, '/');
5694 $DB->update_record('context', $record);
5697 return $record;
5701 * Returns human readable context identifier.
5703 * @param boolean $withprefix whether to prefix the name of the context with the
5704 * type of context, e.g. User, Course, Forum, etc.
5705 * @param boolean $short whether to use the short name of the thing. Only applies
5706 * to course contexts
5707 * @param boolean $escape Whether the returned name of the thing is to be
5708 * HTML escaped or not.
5709 * @return string the human readable context name.
5711 public function get_context_name($withprefix = true, $short = false, $escape = true) {
5712 // must be implemented in all context levels
5713 throw new coding_exception('can not get name of abstract context');
5717 * Whether the current context is locked.
5719 * @return bool
5721 public function is_locked() {
5722 if ($this->_locked) {
5723 return true;
5726 if ($parent = $this->get_parent_context()) {
5727 return $parent->is_locked();
5730 return false;
5734 * Returns the most relevant URL for this context.
5736 * @return moodle_url
5738 public abstract function get_url();
5741 * Returns array of relevant context capability records.
5743 * @param string $sort SQL order by snippet for sorting returned capabilities sensibly for display
5744 * @return array
5746 public abstract function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT);
5749 * Recursive function which, given a context, find all its children context ids.
5751 * For course category contexts it will return immediate children and all subcategory contexts.
5752 * It will NOT recurse into courses or subcategories categories.
5753 * If you want to do that, call it on the returned courses/categories.
5755 * When called for a course context, it will return the modules and blocks
5756 * displayed in the course page and blocks displayed on the module pages.
5758 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5759 * contexts ;-)
5761 * @return array Array of child records
5763 public function get_child_contexts() {
5764 global $DB;
5766 if (empty($this->_path) or empty($this->_depth)) {
5767 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5768 return array();
5771 $sql = "SELECT ctx.*
5772 FROM {context} ctx
5773 WHERE ctx.path LIKE ?";
5774 $params = array($this->_path.'/%');
5775 $records = $DB->get_records_sql($sql, $params);
5777 $result = array();
5778 foreach ($records as $record) {
5779 $result[$record->id] = context::create_instance_from_record($record);
5782 return $result;
5786 * Determine if the current context is a parent of the possible child.
5788 * @param context $possiblechild
5789 * @param bool $includeself Whether to check the current context
5790 * @return bool
5792 public function is_parent_of(context $possiblechild, bool $includeself): bool {
5793 // A simple substring check is used on the context path.
5794 // The possible child's path is used as a haystack, with the current context as the needle.
5795 // The path is prefixed with '+' to ensure that the parent always starts at the top.
5796 // It is suffixed with '+' to ensure that parents are not included.
5797 // The needle always suffixes with a '/' to ensure that the contextid uses a complete match (i.e. 142/ instead of 14).
5798 // The haystack is suffixed with '/+' if $includeself is true to allow the current context to match.
5799 // The haystack is suffixed with '+' if $includeself is false to prevent the current context from matching.
5800 $haystacksuffix = $includeself ? '/+' : '+';
5802 $strpos = strpos(
5803 "+{$possiblechild->path}{$haystacksuffix}",
5804 "+{$this->path}/"
5806 return $strpos === 0;
5810 * Returns parent contexts of this context in reversed order, i.e. parent first,
5811 * then grand parent, etc.
5813 * @param bool $includeself true means include self too
5814 * @return array of context instances
5816 public function get_parent_contexts($includeself = false) {
5817 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5818 return array();
5821 // Preload the contexts to reduce DB calls.
5822 context_helper::preload_contexts_by_id($contextids);
5824 $result = array();
5825 foreach ($contextids as $contextid) {
5826 $parent = context::instance_by_id($contextid, MUST_EXIST);
5827 $result[$parent->id] = $parent;
5830 return $result;
5834 * Determine if the current context is a child of the possible parent.
5836 * @param context $possibleparent
5837 * @param bool $includeself Whether to check the current context
5838 * @return bool
5840 public function is_child_of(context $possibleparent, bool $includeself): bool {
5841 // A simple substring check is used on the context path.
5842 // The current context is used as a haystack, with the possible parent as the needle.
5843 // The path is prefixed with '+' to ensure that the parent always starts at the top.
5844 // It is suffixed with '+' to ensure that children are not included.
5845 // The needle always suffixes with a '/' to ensure that the contextid uses a complete match (i.e. 142/ instead of 14).
5846 // The haystack is suffixed with '/+' if $includeself is true to allow the current context to match.
5847 // The haystack is suffixed with '+' if $includeself is false to prevent the current context from matching.
5848 $haystacksuffix = $includeself ? '/+' : '+';
5850 $strpos = strpos(
5851 "+{$this->path}{$haystacksuffix}",
5852 "+{$possibleparent->path}/"
5854 return $strpos === 0;
5858 * Returns parent context ids of this context in reversed order, i.e. parent first,
5859 * then grand parent, etc.
5861 * @param bool $includeself true means include self too
5862 * @return array of context ids
5864 public function get_parent_context_ids($includeself = false) {
5865 if (empty($this->_path)) {
5866 return array();
5869 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5870 $parentcontexts = explode('/', $parentcontexts);
5871 if (!$includeself) {
5872 array_pop($parentcontexts); // and remove its own id
5875 return array_reverse($parentcontexts);
5879 * Returns parent context paths of this context.
5881 * @param bool $includeself true means include self too
5882 * @return array of context paths
5884 public function get_parent_context_paths($includeself = false) {
5885 if (empty($this->_path)) {
5886 return array();
5889 $contextids = explode('/', $this->_path);
5891 $path = '';
5892 $paths = array();
5893 foreach ($contextids as $contextid) {
5894 if ($contextid) {
5895 $path .= '/' . $contextid;
5896 $paths[$contextid] = $path;
5900 if (!$includeself) {
5901 unset($paths[$this->_id]);
5904 return $paths;
5908 * Returns parent context
5910 * @return context
5912 public function get_parent_context() {
5913 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5914 return false;
5917 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5918 $parentcontexts = explode('/', $parentcontexts);
5919 array_pop($parentcontexts); // self
5920 $contextid = array_pop($parentcontexts); // immediate parent
5922 return context::instance_by_id($contextid, MUST_EXIST);
5926 * Is this context part of any course? If yes return course context.
5928 * @param bool $strict true means throw exception if not found, false means return false if not found
5929 * @return context_course context of the enclosing course, null if not found or exception
5931 public function get_course_context($strict = true) {
5932 if ($strict) {
5933 throw new coding_exception('Context does not belong to any course.');
5934 } else {
5935 return false;
5940 * Returns sql necessary for purging of stale context instances.
5942 * @static
5943 * @return string cleanup SQL
5945 protected static function get_cleanup_sql() {
5946 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5950 * Rebuild context paths and depths at context level.
5952 * @static
5953 * @param bool $force
5954 * @return void
5956 protected static function build_paths($force) {
5957 throw new coding_exception('build_paths() method must be implemented in all context levels');
5961 * Create missing context instances at given level
5963 * @static
5964 * @return void
5966 protected static function create_level_instances() {
5967 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5971 * Reset all cached permissions and definitions if the necessary.
5972 * @return void
5974 public function reload_if_dirty() {
5975 global $ACCESSLIB_PRIVATE, $USER;
5977 // Load dirty contexts list if needed
5978 if (CLI_SCRIPT) {
5979 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5980 // we do not load dirty flags in CLI and cron
5981 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5983 } else {
5984 if (!isset($USER->access['time'])) {
5985 // Nothing has been loaded yet, so we do not need to check dirty flags now.
5986 return;
5989 // From skodak: No idea why -2 is there, server cluster time difference maybe...
5990 $changedsince = $USER->access['time'] - 2;
5992 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5993 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $changedsince);
5996 if (!isset($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
5997 $ACCESSLIB_PRIVATE->dirtyusers[$USER->id] = get_cache_flag('accesslib/dirtyusers', $USER->id, $changedsince);
6001 $dirty = false;
6003 if (!empty($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
6004 $dirty = true;
6005 } else if (!empty($ACCESSLIB_PRIVATE->dirtycontexts)) {
6006 $paths = $this->get_parent_context_paths(true);
6008 foreach ($paths as $path) {
6009 if (isset($ACCESSLIB_PRIVATE->dirtycontexts[$path])) {
6010 $dirty = true;
6011 break;
6016 if ($dirty) {
6017 // Reload all capabilities of USER and others - preserving loginas, roleswitches, etc.
6018 // Then cleanup any marks of dirtyness... at least from our short term memory!
6019 reload_all_capabilities();
6024 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
6026 public function mark_dirty() {
6027 global $CFG, $USER, $ACCESSLIB_PRIVATE;
6029 if (during_initial_install()) {
6030 return;
6033 // only if it is a non-empty string
6034 if (is_string($this->_path) && $this->_path !== '') {
6035 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
6036 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
6037 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
6038 } else {
6039 if (CLI_SCRIPT) {
6040 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
6041 } else {
6042 if (isset($USER->access['time'])) {
6043 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
6044 } else {
6045 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
6047 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
6056 * Context maintenance and helper methods.
6058 * This is "extends context" is a bloody hack that tires to work around the deficiencies
6059 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
6060 * level implementation from the rest of code, the code completion returns what developers need.
6062 * Thank you Tim Hunt for helping me with this nasty trick.
6064 * @package core_access
6065 * @category access
6066 * @copyright Petr Skoda {@link http://skodak.org}
6067 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6068 * @since Moodle 2.2
6070 class context_helper extends context {
6073 * @var array An array mapping context levels to classes
6075 private static $alllevels;
6078 * Instance does not make sense here, only static use
6080 protected function __construct() {
6084 * Reset internal context levels array.
6086 public static function reset_levels() {
6087 self::$alllevels = null;
6091 * Initialise context levels, call before using self::$alllevels.
6093 private static function init_levels() {
6094 global $CFG;
6096 if (isset(self::$alllevels)) {
6097 return;
6099 self::$alllevels = array(
6100 CONTEXT_SYSTEM => 'context_system',
6101 CONTEXT_USER => 'context_user',
6102 CONTEXT_COURSECAT => 'context_coursecat',
6103 CONTEXT_COURSE => 'context_course',
6104 CONTEXT_MODULE => 'context_module',
6105 CONTEXT_BLOCK => 'context_block',
6108 if (empty($CFG->custom_context_classes)) {
6109 return;
6112 $levels = $CFG->custom_context_classes;
6113 if (!is_array($levels)) {
6114 $levels = @unserialize($levels);
6116 if (!is_array($levels)) {
6117 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
6118 return;
6121 // Unsupported custom levels, use with care!!!
6122 foreach ($levels as $level => $classname) {
6123 self::$alllevels[$level] = $classname;
6125 ksort(self::$alllevels);
6129 * Returns a class name of the context level class
6131 * @static
6132 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
6133 * @return string class name of the context class
6135 public static function get_class_for_level($contextlevel) {
6136 self::init_levels();
6137 if (isset(self::$alllevels[$contextlevel])) {
6138 return self::$alllevels[$contextlevel];
6139 } else {
6140 throw new coding_exception('Invalid context level specified');
6145 * Returns a list of all context levels
6147 * @static
6148 * @return array int=>string (level=>level class name)
6150 public static function get_all_levels() {
6151 self::init_levels();
6152 return self::$alllevels;
6156 * Remove stale contexts that belonged to deleted instances.
6157 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
6159 * @static
6160 * @return void
6162 public static function cleanup_instances() {
6163 global $DB;
6164 self::init_levels();
6166 $sqls = array();
6167 foreach (self::$alllevels as $level=>$classname) {
6168 $sqls[] = $classname::get_cleanup_sql();
6171 $sql = implode(" UNION ", $sqls);
6173 // it is probably better to use transactions, it might be faster too
6174 $transaction = $DB->start_delegated_transaction();
6176 $rs = $DB->get_recordset_sql($sql);
6177 foreach ($rs as $record) {
6178 $context = context::create_instance_from_record($record);
6179 $context->delete();
6181 $rs->close();
6183 $transaction->allow_commit();
6187 * Create all context instances at the given level and above.
6189 * @static
6190 * @param int $contextlevel null means all levels
6191 * @param bool $buildpaths
6192 * @return void
6194 public static function create_instances($contextlevel = null, $buildpaths = true) {
6195 self::init_levels();
6196 foreach (self::$alllevels as $level=>$classname) {
6197 if ($contextlevel and $level > $contextlevel) {
6198 // skip potential sub-contexts
6199 continue;
6201 $classname::create_level_instances();
6202 if ($buildpaths) {
6203 $classname::build_paths(false);
6209 * Rebuild paths and depths in all context levels.
6211 * @static
6212 * @param bool $force false means add missing only
6213 * @return void
6215 public static function build_all_paths($force = false) {
6216 self::init_levels();
6217 foreach (self::$alllevels as $classname) {
6218 $classname::build_paths($force);
6221 // reset static course cache - it might have incorrect cached data
6222 accesslib_clear_all_caches(true);
6226 * Resets the cache to remove all data.
6227 * @static
6229 public static function reset_caches() {
6230 context::reset_caches();
6234 * Returns all fields necessary for context preloading from user $rec.
6236 * This helps with performance when dealing with hundreds of contexts.
6238 * @static
6239 * @param string $tablealias context table alias in the query
6240 * @return array (table.column=>alias, ...)
6242 public static function get_preload_record_columns($tablealias) {
6243 return [
6244 "$tablealias.id" => "ctxid",
6245 "$tablealias.path" => "ctxpath",
6246 "$tablealias.depth" => "ctxdepth",
6247 "$tablealias.contextlevel" => "ctxlevel",
6248 "$tablealias.instanceid" => "ctxinstance",
6249 "$tablealias.locked" => "ctxlocked",
6254 * Returns all fields necessary for context preloading from user $rec.
6256 * This helps with performance when dealing with hundreds of contexts.
6258 * @static
6259 * @param string $tablealias context table alias in the query
6260 * @return string
6262 public static function get_preload_record_columns_sql($tablealias) {
6263 return "$tablealias.id AS ctxid, " .
6264 "$tablealias.path AS ctxpath, " .
6265 "$tablealias.depth AS ctxdepth, " .
6266 "$tablealias.contextlevel AS ctxlevel, " .
6267 "$tablealias.instanceid AS ctxinstance, " .
6268 "$tablealias.locked AS ctxlocked";
6272 * Preloads context cache with information from db record and strips the cached info.
6274 * The db request has to contain all columns from context_helper::get_preload_record_columns().
6276 * @static
6277 * @param stdClass $rec
6278 * @return void This is intentional. See MDL-37115. You will need to get the context
6279 * in the normal way, but it is now cached, so that will be fast.
6281 public static function preload_from_record(stdClass $rec) {
6282 context::preload_from_record($rec);
6286 * Preload a set of contexts using their contextid.
6288 * @param array $contextids
6290 public static function preload_contexts_by_id(array $contextids) {
6291 global $DB;
6293 // Determine which contexts are not already cached.
6294 $tofetch = [];
6295 foreach ($contextids as $contextid) {
6296 if (!self::cache_get_by_id($contextid)) {
6297 $tofetch[] = $contextid;
6301 if (count($tofetch) > 1) {
6302 // There are at least two to fetch.
6303 // There is no point only fetching a single context as this would be no more efficient than calling the existing code.
6304 list($insql, $inparams) = $DB->get_in_or_equal($tofetch, SQL_PARAMS_NAMED);
6305 $ctxs = $DB->get_records_select('context', "id {$insql}", $inparams, '',
6306 \context_helper::get_preload_record_columns_sql('{context}'));
6307 foreach ($ctxs as $ctx) {
6308 self::preload_from_record($ctx);
6314 * Preload all contexts instances from course.
6316 * To be used if you expect multiple queries for course activities...
6318 * @static
6319 * @param int $courseid
6321 public static function preload_course($courseid) {
6322 // Users can call this multiple times without doing any harm
6323 if (isset(context::$cache_preloaded[$courseid])) {
6324 return;
6326 $coursecontext = context_course::instance($courseid);
6327 $coursecontext->get_child_contexts();
6329 context::$cache_preloaded[$courseid] = true;
6333 * Delete context instance
6335 * @static
6336 * @param int $contextlevel
6337 * @param int $instanceid
6338 * @return void
6340 public static function delete_instance($contextlevel, $instanceid) {
6341 global $DB;
6343 // double check the context still exists
6344 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
6345 $context = context::create_instance_from_record($record);
6346 $context->delete();
6347 } else {
6348 // we should try to purge the cache anyway
6353 * Returns the name of specified context level
6355 * @static
6356 * @param int $contextlevel
6357 * @return string name of the context level
6359 public static function get_level_name($contextlevel) {
6360 $classname = context_helper::get_class_for_level($contextlevel);
6361 return $classname::get_level_name();
6365 * Gets the current context to be used for navigation tree filtering.
6367 * @param context|null $context The current context to be checked against.
6368 * @return context|null the context that navigation tree filtering should use.
6370 public static function get_navigation_filter_context(?context $context): ?context {
6371 global $CFG;
6372 if (!empty($CFG->filternavigationwithsystemcontext)) {
6373 return context_system::instance();
6374 } else {
6375 return $context;
6380 * not used
6382 public function get_url() {
6386 * not used
6388 * @param string $sort
6390 public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
6396 * System context class
6398 * @package core_access
6399 * @category access
6400 * @copyright Petr Skoda {@link http://skodak.org}
6401 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6402 * @since Moodle 2.2
6404 class context_system extends context {
6406 * Please use context_system::instance() if you need the instance of context.
6408 * @param stdClass $record
6410 protected function __construct(stdClass $record) {
6411 parent::__construct($record);
6412 if ($record->contextlevel != CONTEXT_SYSTEM) {
6413 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
6418 * Returns human readable context level name.
6420 * @static
6421 * @return string the human readable context level name.
6423 public static function get_level_name() {
6424 return get_string('coresystem');
6428 * Returns human readable context identifier.
6430 * @param boolean $withprefix does not apply to system context
6431 * @param boolean $short does not apply to system context
6432 * @param boolean $escape does not apply to system context
6433 * @return string the human readable context name.
6435 public function get_context_name($withprefix = true, $short = false, $escape = true) {
6436 return self::get_level_name();
6440 * Returns the most relevant URL for this context.
6442 * @return moodle_url
6444 public function get_url() {
6445 return new moodle_url('/');
6449 * Returns array of relevant context capability records.
6451 * @param string $sort
6452 * @return array
6454 public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
6455 global $DB;
6457 return $DB->get_records('capabilities', [], $sort);
6461 * Create missing context instances at system context
6462 * @static
6464 protected static function create_level_instances() {
6465 // nothing to do here, the system context is created automatically in installer
6466 self::instance(0);
6470 * Returns system context instance.
6472 * @static
6473 * @param int $instanceid should be 0
6474 * @param int $strictness
6475 * @param bool $cache
6476 * @return context_system context instance
6478 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
6479 global $DB;
6481 if ($instanceid != 0) {
6482 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
6485 // SYSCONTEXTID is cached in local cache to eliminate 1 query per page.
6486 if (defined('SYSCONTEXTID') and $cache) {
6487 if (!isset(context::$systemcontext)) {
6488 $record = new stdClass();
6489 $record->id = SYSCONTEXTID;
6490 $record->contextlevel = CONTEXT_SYSTEM;
6491 $record->instanceid = 0;
6492 $record->path = '/'.SYSCONTEXTID;
6493 $record->depth = 1;
6494 $record->locked = 0;
6495 context::$systemcontext = new context_system($record);
6497 return context::$systemcontext;
6500 try {
6501 // We ignore the strictness completely because system context must exist except during install.
6502 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6503 } catch (dml_exception $e) {
6504 //table or record does not exist
6505 if (!during_initial_install()) {
6506 // do not mess with system context after install, it simply must exist
6507 throw $e;
6509 $record = null;
6512 if (!$record) {
6513 $record = new stdClass();
6514 $record->contextlevel = CONTEXT_SYSTEM;
6515 $record->instanceid = 0;
6516 $record->depth = 1;
6517 $record->path = null; // Not known before insert.
6518 $record->locked = 0;
6520 try {
6521 if ($DB->count_records('context')) {
6522 // contexts already exist, this is very weird, system must be first!!!
6523 return null;
6525 if (defined('SYSCONTEXTID')) {
6526 // this would happen only in unittest on sites that went through weird 1.7 upgrade
6527 $record->id = SYSCONTEXTID;
6528 $DB->import_record('context', $record);
6529 $DB->get_manager()->reset_sequence('context');
6530 } else {
6531 $record->id = $DB->insert_record('context', $record);
6533 } catch (dml_exception $e) {
6534 // can not create context - table does not exist yet, sorry
6535 return null;
6539 if ($record->instanceid != 0) {
6540 // this is very weird, somebody must be messing with context table
6541 debugging('Invalid system context detected');
6544 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6545 // fix path if necessary, initial install or path reset
6546 $record->depth = 1;
6547 $record->path = '/'.$record->id;
6548 $DB->update_record('context', $record);
6551 if (empty($record->locked)) {
6552 $record->locked = 0;
6555 if (!defined('SYSCONTEXTID')) {
6556 define('SYSCONTEXTID', $record->id);
6559 context::$systemcontext = new context_system($record);
6560 return context::$systemcontext;
6564 * Returns all site contexts except the system context, DO NOT call on production servers!!
6566 * Contexts are not cached.
6568 * @return array
6570 public function get_child_contexts() {
6571 global $DB;
6573 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6575 // Just get all the contexts except for CONTEXT_SYSTEM level
6576 // and hope we don't OOM in the process - don't cache
6577 $sql = "SELECT c.*
6578 FROM {context} c
6579 WHERE contextlevel > ".CONTEXT_SYSTEM;
6580 $records = $DB->get_records_sql($sql);
6582 $result = array();
6583 foreach ($records as $record) {
6584 $result[$record->id] = context::create_instance_from_record($record);
6587 return $result;
6591 * Returns sql necessary for purging of stale context instances.
6593 * @static
6594 * @return string cleanup SQL
6596 protected static function get_cleanup_sql() {
6597 $sql = "
6598 SELECT c.*
6599 FROM {context} c
6600 WHERE 1=2
6603 return $sql;
6607 * Rebuild context paths and depths at system context level.
6609 * @static
6610 * @param bool $force
6612 protected static function build_paths($force) {
6613 global $DB;
6615 /* note: ignore $force here, we always do full test of system context */
6617 // exactly one record must exist
6618 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6620 if ($record->instanceid != 0) {
6621 debugging('Invalid system context detected');
6624 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6625 debugging('Invalid SYSCONTEXTID detected');
6628 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6629 // fix path if necessary, initial install or path reset
6630 $record->depth = 1;
6631 $record->path = '/'.$record->id;
6632 $DB->update_record('context', $record);
6637 * Set whether this context has been locked or not.
6639 * @param bool $locked
6640 * @return $this
6642 public function set_locked(bool $locked) {
6643 throw new \coding_exception('It is not possible to lock the system context');
6645 return $this;
6651 * User context class
6653 * @package core_access
6654 * @category access
6655 * @copyright Petr Skoda {@link http://skodak.org}
6656 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6657 * @since Moodle 2.2
6659 class context_user extends context {
6661 * Please use context_user::instance($userid) if you need the instance of context.
6662 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6664 * @param stdClass $record
6666 protected function __construct(stdClass $record) {
6667 parent::__construct($record);
6668 if ($record->contextlevel != CONTEXT_USER) {
6669 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6674 * Returns human readable context level name.
6676 * @static
6677 * @return string the human readable context level name.
6679 public static function get_level_name() {
6680 return get_string('user');
6684 * Returns human readable context identifier.
6686 * @param boolean $withprefix whether to prefix the name of the context with User
6687 * @param boolean $short does not apply to user context
6688 * @param boolean $escape does not apply to user context
6689 * @return string the human readable context name.
6691 public function get_context_name($withprefix = true, $short = false, $escape = true) {
6692 global $DB;
6694 $name = '';
6695 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6696 if ($withprefix){
6697 $name = get_string('user').': ';
6699 $name .= fullname($user);
6701 return $name;
6705 * Returns the most relevant URL for this context.
6707 * @return moodle_url
6709 public function get_url() {
6710 global $COURSE;
6712 if ($COURSE->id == SITEID) {
6713 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6714 } else {
6715 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6717 return $url;
6721 * Returns array of relevant context capability records.
6723 * @param string $sort
6724 * @return array
6726 public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
6727 global $DB;
6729 $extracaps = array('moodle/grade:viewall');
6730 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6732 return $DB->get_records_select('capabilities', "contextlevel = :level OR name {$extra}",
6733 $params + ['level' => CONTEXT_USER], $sort);
6737 * Returns user context instance.
6739 * @static
6740 * @param int $userid id from {user} table
6741 * @param int $strictness
6742 * @return context_user context instance
6744 public static function instance($userid, $strictness = MUST_EXIST) {
6745 global $DB;
6747 if ($context = context::cache_get(CONTEXT_USER, $userid)) {
6748 return $context;
6751 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER, 'instanceid' => $userid))) {
6752 if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6753 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6757 if ($record) {
6758 $context = new context_user($record);
6759 context::cache_add($context);
6760 return $context;
6763 return false;
6767 * Create missing context instances at user context level
6768 * @static
6770 protected static function create_level_instances() {
6771 global $DB;
6773 $sql = "SELECT ".CONTEXT_USER.", u.id
6774 FROM {user} u
6775 WHERE u.deleted = 0
6776 AND NOT EXISTS (SELECT 'x'
6777 FROM {context} cx
6778 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6779 $contextdata = $DB->get_recordset_sql($sql);
6780 foreach ($contextdata as $context) {
6781 context::insert_context_record(CONTEXT_USER, $context->id, null);
6783 $contextdata->close();
6787 * Returns sql necessary for purging of stale context instances.
6789 * @static
6790 * @return string cleanup SQL
6792 protected static function get_cleanup_sql() {
6793 $sql = "
6794 SELECT c.*
6795 FROM {context} c
6796 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6797 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6800 return $sql;
6804 * Rebuild context paths and depths at user context level.
6806 * @static
6807 * @param bool $force
6809 protected static function build_paths($force) {
6810 global $DB;
6812 // First update normal users.
6813 $path = $DB->sql_concat('?', 'id');
6814 $pathstart = '/' . SYSCONTEXTID . '/';
6815 $params = array($pathstart);
6817 if ($force) {
6818 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6819 $params[] = $pathstart;
6820 } else {
6821 $where = "depth = 0 OR path IS NULL";
6824 $sql = "UPDATE {context}
6825 SET depth = 2,
6826 path = {$path}
6827 WHERE contextlevel = " . CONTEXT_USER . "
6828 AND ($where)";
6829 $DB->execute($sql, $params);
6835 * Course category context class
6837 * @package core_access
6838 * @category access
6839 * @copyright Petr Skoda {@link http://skodak.org}
6840 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6841 * @since Moodle 2.2
6843 class context_coursecat extends context {
6845 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6846 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6848 * @param stdClass $record
6850 protected function __construct(stdClass $record) {
6851 parent::__construct($record);
6852 if ($record->contextlevel != CONTEXT_COURSECAT) {
6853 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6858 * Returns human readable context level name.
6860 * @static
6861 * @return string the human readable context level name.
6863 public static function get_level_name() {
6864 return get_string('category');
6868 * Returns human readable context identifier.
6870 * @param boolean $withprefix whether to prefix the name of the context with Category
6871 * @param boolean $short does not apply to course categories
6872 * @param boolean $escape Whether the returned name of the context is to be HTML escaped or not.
6873 * @return string the human readable context name.
6875 public function get_context_name($withprefix = true, $short = false, $escape = true) {
6876 global $DB;
6878 $name = '';
6879 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6880 if ($withprefix){
6881 $name = get_string('category').': ';
6883 if (!$escape) {
6884 $name .= format_string($category->name, true, array('context' => $this, 'escape' => false));
6885 } else {
6886 $name .= format_string($category->name, true, array('context' => $this));
6889 return $name;
6893 * Returns the most relevant URL for this context.
6895 * @return moodle_url
6897 public function get_url() {
6898 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6902 * Returns array of relevant context capability records.
6904 * @param string $sort
6905 * @return array
6907 public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
6908 global $DB;
6910 return $DB->get_records_list('capabilities', 'contextlevel', [
6911 CONTEXT_COURSECAT,
6912 CONTEXT_COURSE,
6913 CONTEXT_MODULE,
6914 CONTEXT_BLOCK,
6915 ], $sort);
6919 * Returns course category context instance.
6921 * @static
6922 * @param int $categoryid id from {course_categories} table
6923 * @param int $strictness
6924 * @return context_coursecat context instance
6926 public static function instance($categoryid, $strictness = MUST_EXIST) {
6927 global $DB;
6929 if ($context = context::cache_get(CONTEXT_COURSECAT, $categoryid)) {
6930 return $context;
6933 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT, 'instanceid' => $categoryid))) {
6934 if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6935 if ($category->parent) {
6936 $parentcontext = context_coursecat::instance($category->parent);
6937 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6938 } else {
6939 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6944 if ($record) {
6945 $context = new context_coursecat($record);
6946 context::cache_add($context);
6947 return $context;
6950 return false;
6954 * Returns immediate child contexts of category and all subcategories,
6955 * children of subcategories and courses are not returned.
6957 * @return array
6959 public function get_child_contexts() {
6960 global $DB;
6962 if (empty($this->_path) or empty($this->_depth)) {
6963 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6964 return array();
6967 $sql = "SELECT ctx.*
6968 FROM {context} ctx
6969 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6970 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6971 $records = $DB->get_records_sql($sql, $params);
6973 $result = array();
6974 foreach ($records as $record) {
6975 $result[$record->id] = context::create_instance_from_record($record);
6978 return $result;
6982 * Create missing context instances at course category context level
6983 * @static
6985 protected static function create_level_instances() {
6986 global $DB;
6988 $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6989 FROM {course_categories} cc
6990 WHERE NOT EXISTS (SELECT 'x'
6991 FROM {context} cx
6992 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6993 $contextdata = $DB->get_recordset_sql($sql);
6994 foreach ($contextdata as $context) {
6995 context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6997 $contextdata->close();
7001 * Returns sql necessary for purging of stale context instances.
7003 * @static
7004 * @return string cleanup SQL
7006 protected static function get_cleanup_sql() {
7007 $sql = "
7008 SELECT c.*
7009 FROM {context} c
7010 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
7011 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
7014 return $sql;
7018 * Rebuild context paths and depths at course category context level.
7020 * @static
7021 * @param bool $force
7023 protected static function build_paths($force) {
7024 global $DB;
7026 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
7027 if ($force) {
7028 $ctxemptyclause = $emptyclause = '';
7029 } else {
7030 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7031 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
7034 $base = '/'.SYSCONTEXTID;
7036 // Normal top level categories
7037 $sql = "UPDATE {context}
7038 SET depth=2,
7039 path=".$DB->sql_concat("'$base/'", 'id')."
7040 WHERE contextlevel=".CONTEXT_COURSECAT."
7041 AND EXISTS (SELECT 'x'
7042 FROM {course_categories} cc
7043 WHERE cc.id = {context}.instanceid AND cc.depth=1)
7044 $emptyclause";
7045 $DB->execute($sql);
7047 // Deeper categories - one query per depthlevel
7048 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
7049 for ($n=2; $n<=$maxdepth; $n++) {
7050 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7051 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7052 FROM {context} ctx
7053 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
7054 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
7055 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7056 $ctxemptyclause";
7057 $trans = $DB->start_delegated_transaction();
7058 $DB->delete_records('context_temp');
7059 $DB->execute($sql);
7060 context::merge_context_temp_table();
7061 $DB->delete_records('context_temp');
7062 $trans->allow_commit();
7071 * Course context class
7073 * @package core_access
7074 * @category access
7075 * @copyright Petr Skoda {@link http://skodak.org}
7076 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7077 * @since Moodle 2.2
7079 class context_course extends context {
7081 * Please use context_course::instance($courseid) if you need the instance of context.
7082 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7084 * @param stdClass $record
7086 protected function __construct(stdClass $record) {
7087 parent::__construct($record);
7088 if ($record->contextlevel != CONTEXT_COURSE) {
7089 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
7094 * Returns human readable context level name.
7096 * @static
7097 * @return string the human readable context level name.
7099 public static function get_level_name() {
7100 return get_string('course');
7104 * Returns human readable context identifier.
7106 * @param boolean $withprefix whether to prefix the name of the context with Course
7107 * @param boolean $short whether to use the short name of the thing.
7108 * @param bool $escape Whether the returned category name is to be HTML escaped or not.
7109 * @return string the human readable context name.
7111 public function get_context_name($withprefix = true, $short = false, $escape = true) {
7112 global $DB;
7114 $name = '';
7115 if ($this->_instanceid == SITEID) {
7116 $name = get_string('frontpage', 'admin');
7117 } else {
7118 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
7119 if ($withprefix){
7120 $name = get_string('course').': ';
7122 if ($short){
7123 if (!$escape) {
7124 $name .= format_string($course->shortname, true, array('context' => $this, 'escape' => false));
7125 } else {
7126 $name .= format_string($course->shortname, true, array('context' => $this));
7128 } else {
7129 if (!$escape) {
7130 $name .= format_string(get_course_display_name_for_list($course), true, array('context' => $this,
7131 'escape' => false));
7132 } else {
7133 $name .= format_string(get_course_display_name_for_list($course), true, array('context' => $this));
7138 return $name;
7142 * Returns the most relevant URL for this context.
7144 * @return moodle_url
7146 public function get_url() {
7147 if ($this->_instanceid != SITEID) {
7148 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
7151 return new moodle_url('/');
7155 * Returns array of relevant context capability records.
7157 * @param string $sort
7158 * @return array
7160 public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
7161 global $DB;
7163 return $DB->get_records_list('capabilities', 'contextlevel', [
7164 CONTEXT_COURSE,
7165 CONTEXT_MODULE,
7166 CONTEXT_BLOCK,
7167 ], $sort);
7171 * Is this context part of any course? If yes return course context.
7173 * @param bool $strict true means throw exception if not found, false means return false if not found
7174 * @return context_course context of the enclosing course, null if not found or exception
7176 public function get_course_context($strict = true) {
7177 return $this;
7181 * Returns course context instance.
7183 * @static
7184 * @param int $courseid id from {course} table
7185 * @param int $strictness
7186 * @return context_course context instance
7188 public static function instance($courseid, $strictness = MUST_EXIST) {
7189 global $DB;
7191 if ($context = context::cache_get(CONTEXT_COURSE, $courseid)) {
7192 return $context;
7195 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $courseid))) {
7196 if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
7197 if ($course->category) {
7198 $parentcontext = context_coursecat::instance($course->category);
7199 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
7200 } else {
7201 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
7206 if ($record) {
7207 $context = new context_course($record);
7208 context::cache_add($context);
7209 return $context;
7212 return false;
7216 * Create missing context instances at course context level
7217 * @static
7219 protected static function create_level_instances() {
7220 global $DB;
7222 $sql = "SELECT ".CONTEXT_COURSE.", c.id
7223 FROM {course} c
7224 WHERE NOT EXISTS (SELECT 'x'
7225 FROM {context} cx
7226 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
7227 $contextdata = $DB->get_recordset_sql($sql);
7228 foreach ($contextdata as $context) {
7229 context::insert_context_record(CONTEXT_COURSE, $context->id, null);
7231 $contextdata->close();
7235 * Returns sql necessary for purging of stale context instances.
7237 * @static
7238 * @return string cleanup SQL
7240 protected static function get_cleanup_sql() {
7241 $sql = "
7242 SELECT c.*
7243 FROM {context} c
7244 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
7245 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
7248 return $sql;
7252 * Rebuild context paths and depths at course context level.
7254 * @static
7255 * @param bool $force
7257 protected static function build_paths($force) {
7258 global $DB;
7260 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
7261 if ($force) {
7262 $ctxemptyclause = $emptyclause = '';
7263 } else {
7264 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7265 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
7268 $base = '/'.SYSCONTEXTID;
7270 // Standard frontpage
7271 $sql = "UPDATE {context}
7272 SET depth = 2,
7273 path = ".$DB->sql_concat("'$base/'", 'id')."
7274 WHERE contextlevel = ".CONTEXT_COURSE."
7275 AND EXISTS (SELECT 'x'
7276 FROM {course} c
7277 WHERE c.id = {context}.instanceid AND c.category = 0)
7278 $emptyclause";
7279 $DB->execute($sql);
7281 // standard courses
7282 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7283 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7284 FROM {context} ctx
7285 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
7286 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
7287 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7288 $ctxemptyclause";
7289 $trans = $DB->start_delegated_transaction();
7290 $DB->delete_records('context_temp');
7291 $DB->execute($sql);
7292 context::merge_context_temp_table();
7293 $DB->delete_records('context_temp');
7294 $trans->allow_commit();
7301 * Course module context class
7303 * @package core_access
7304 * @category access
7305 * @copyright Petr Skoda {@link http://skodak.org}
7306 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7307 * @since Moodle 2.2
7309 class context_module extends context {
7311 * Please use context_module::instance($cmid) if you need the instance of context.
7312 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7314 * @param stdClass $record
7316 protected function __construct(stdClass $record) {
7317 parent::__construct($record);
7318 if ($record->contextlevel != CONTEXT_MODULE) {
7319 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
7324 * Returns human readable context level name.
7326 * @static
7327 * @return string the human readable context level name.
7329 public static function get_level_name() {
7330 return get_string('activitymodule');
7334 * Returns human readable context identifier.
7336 * @param boolean $withprefix whether to prefix the name of the context with the
7337 * module name, e.g. Forum, Glossary, etc.
7338 * @param boolean $short does not apply to module context
7339 * @param boolean $escape Whether the returned name of the context is to be HTML escaped or not.
7340 * @return string the human readable context name.
7342 public function get_context_name($withprefix = true, $short = false, $escape = true) {
7343 global $DB;
7345 $name = '';
7346 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
7347 FROM {course_modules} cm
7348 JOIN {modules} md ON md.id = cm.module
7349 WHERE cm.id = ?", array($this->_instanceid))) {
7350 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
7351 if ($withprefix){
7352 $name = get_string('modulename', $cm->modname).': ';
7354 if (!$escape) {
7355 $name .= format_string($mod->name, true, array('context' => $this, 'escape' => false));
7356 } else {
7357 $name .= format_string($mod->name, true, array('context' => $this));
7361 return $name;
7365 * Returns the most relevant URL for this context.
7367 * @return moodle_url
7369 public function get_url() {
7370 global $DB;
7372 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
7373 FROM {course_modules} cm
7374 JOIN {modules} md ON md.id = cm.module
7375 WHERE cm.id = ?", array($this->_instanceid))) {
7376 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
7379 return new moodle_url('/');
7383 * Returns array of relevant context capability records.
7385 * @param string $sort
7386 * @return array
7388 public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
7389 global $DB, $CFG;
7391 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
7392 $module = $DB->get_record('modules', array('id'=>$cm->module));
7394 $subcaps = array();
7396 $modulepath = "{$CFG->dirroot}/mod/{$module->name}";
7397 if (file_exists("{$modulepath}/db/subplugins.json")) {
7398 $subplugins = (array) json_decode(file_get_contents("{$modulepath}/db/subplugins.json"))->plugintypes;
7399 } else if (file_exists("{$modulepath}/db/subplugins.php")) {
7400 debugging('Use of subplugins.php has been deprecated. ' .
7401 'Please update your plugin to provide a subplugins.json file instead.',
7402 DEBUG_DEVELOPER);
7403 $subplugins = array(); // should be redefined in the file
7404 include("{$modulepath}/db/subplugins.php");
7407 if (!empty($subplugins)) {
7408 foreach (array_keys($subplugins) as $subplugintype) {
7409 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
7410 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
7415 $modfile = "{$modulepath}/lib.php";
7416 $extracaps = array();
7417 if (file_exists($modfile)) {
7418 include_once($modfile);
7419 $modfunction = $module->name.'_get_extra_capabilities';
7420 if (function_exists($modfunction)) {
7421 $extracaps = $modfunction();
7425 $extracaps = array_merge($subcaps, $extracaps);
7426 $extra = '';
7427 list($extra, $params) = $DB->get_in_or_equal(
7428 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
7429 if (!empty($extra)) {
7430 $extra = "OR name $extra";
7433 // Fetch the list of modules, and remove this one.
7434 $components = \core_component::get_component_list();
7435 $componentnames = $components['mod'];
7436 unset($componentnames["mod_{$module->name}"]);
7437 $componentnames = array_keys($componentnames);
7439 // Exclude all other modules.
7440 list($notcompsql, $notcompparams) = $DB->get_in_or_equal($componentnames, SQL_PARAMS_NAMED, 'notcomp', false);
7441 $params = array_merge($params, $notcompparams);
7444 // Exclude other component submodules.
7445 $i = 0;
7446 $ignorecomponents = [];
7447 foreach ($componentnames as $mod) {
7448 if ($subplugins = \core_component::get_subplugins($mod)) {
7449 foreach (array_keys($subplugins) as $subplugintype) {
7450 $paramname = "notlike{$i}";
7451 $ignorecomponents[] = $DB->sql_like('component', ":{$paramname}", true, true, true);
7452 $params[$paramname] = "{$subplugintype}_%";
7453 $i++;
7457 $notlikesql = "(" . implode(' AND ', $ignorecomponents) . ")";
7459 $sql = "SELECT *
7460 FROM {capabilities}
7461 WHERE (contextlevel = ".CONTEXT_MODULE."
7462 AND component {$notcompsql}
7463 AND {$notlikesql})
7464 $extra
7465 ORDER BY $sort";
7467 return $DB->get_records_sql($sql, $params);
7471 * Is this context part of any course? If yes return course context.
7473 * @param bool $strict true means throw exception if not found, false means return false if not found
7474 * @return context_course context of the enclosing course, null if not found or exception
7476 public function get_course_context($strict = true) {
7477 return $this->get_parent_context();
7481 * Returns module context instance.
7483 * @static
7484 * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
7485 * @param int $strictness
7486 * @return context_module context instance
7488 public static function instance($cmid, $strictness = MUST_EXIST) {
7489 global $DB;
7491 if ($context = context::cache_get(CONTEXT_MODULE, $cmid)) {
7492 return $context;
7495 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE, 'instanceid' => $cmid))) {
7496 if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
7497 $parentcontext = context_course::instance($cm->course);
7498 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
7502 if ($record) {
7503 $context = new context_module($record);
7504 context::cache_add($context);
7505 return $context;
7508 return false;
7512 * Create missing context instances at module context level
7513 * @static
7515 protected static function create_level_instances() {
7516 global $DB;
7518 $sql = "SELECT ".CONTEXT_MODULE.", cm.id
7519 FROM {course_modules} cm
7520 WHERE NOT EXISTS (SELECT 'x'
7521 FROM {context} cx
7522 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
7523 $contextdata = $DB->get_recordset_sql($sql);
7524 foreach ($contextdata as $context) {
7525 context::insert_context_record(CONTEXT_MODULE, $context->id, null);
7527 $contextdata->close();
7531 * Returns sql necessary for purging of stale context instances.
7533 * @static
7534 * @return string cleanup SQL
7536 protected static function get_cleanup_sql() {
7537 $sql = "
7538 SELECT c.*
7539 FROM {context} c
7540 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
7541 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
7544 return $sql;
7548 * Rebuild context paths and depths at module context level.
7550 * @static
7551 * @param bool $force
7553 protected static function build_paths($force) {
7554 global $DB;
7556 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
7557 if ($force) {
7558 $ctxemptyclause = '';
7559 } else {
7560 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7563 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7564 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7565 FROM {context} ctx
7566 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
7567 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
7568 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7569 $ctxemptyclause";
7570 $trans = $DB->start_delegated_transaction();
7571 $DB->delete_records('context_temp');
7572 $DB->execute($sql);
7573 context::merge_context_temp_table();
7574 $DB->delete_records('context_temp');
7575 $trans->allow_commit();
7582 * Block context class
7584 * @package core_access
7585 * @category access
7586 * @copyright Petr Skoda {@link http://skodak.org}
7587 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7588 * @since Moodle 2.2
7590 class context_block extends context {
7592 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
7593 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7595 * @param stdClass $record
7597 protected function __construct(stdClass $record) {
7598 parent::__construct($record);
7599 if ($record->contextlevel != CONTEXT_BLOCK) {
7600 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
7605 * Returns human readable context level name.
7607 * @static
7608 * @return string the human readable context level name.
7610 public static function get_level_name() {
7611 return get_string('block');
7615 * Returns human readable context identifier.
7617 * @param boolean $withprefix whether to prefix the name of the context with Block
7618 * @param boolean $short does not apply to block context
7619 * @param boolean $escape does not apply to block context
7620 * @return string the human readable context name.
7622 public function get_context_name($withprefix = true, $short = false, $escape = true) {
7623 global $DB, $CFG;
7625 $name = '';
7626 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
7627 global $CFG;
7628 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7629 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7630 $blockname = "block_$blockinstance->blockname";
7631 if ($blockobject = new $blockname()) {
7632 if ($withprefix){
7633 $name = get_string('block').': ';
7635 $name .= $blockobject->title;
7639 return $name;
7643 * Returns the most relevant URL for this context.
7645 * @return moodle_url
7647 public function get_url() {
7648 $parentcontexts = $this->get_parent_context();
7649 return $parentcontexts->get_url();
7653 * Returns array of relevant context capability records.
7655 * @param string $sort
7656 * @return array
7658 public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
7659 global $DB;
7661 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
7663 $select = '(contextlevel = :level AND component = :component)';
7664 $params = [
7665 'level' => CONTEXT_BLOCK,
7666 'component' => 'block_' . $bi->blockname,
7669 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7670 if ($extracaps) {
7671 list($extra, $extraparams) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7672 $select .= " OR name $extra";
7673 $params = array_merge($params, $extraparams);
7676 return $DB->get_records_select('capabilities', $select, $params, $sort);
7680 * Is this context part of any course? If yes return course context.
7682 * @param bool $strict true means throw exception if not found, false means return false if not found
7683 * @return context_course context of the enclosing course, null if not found or exception
7685 public function get_course_context($strict = true) {
7686 $parentcontext = $this->get_parent_context();
7687 return $parentcontext->get_course_context($strict);
7691 * Returns block context instance.
7693 * @static
7694 * @param int $blockinstanceid id from {block_instances} table.
7695 * @param int $strictness
7696 * @return context_block context instance
7698 public static function instance($blockinstanceid, $strictness = MUST_EXIST) {
7699 global $DB;
7701 if ($context = context::cache_get(CONTEXT_BLOCK, $blockinstanceid)) {
7702 return $context;
7705 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $blockinstanceid))) {
7706 if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
7707 $parentcontext = context::instance_by_id($bi->parentcontextid);
7708 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7712 if ($record) {
7713 $context = new context_block($record);
7714 context::cache_add($context);
7715 return $context;
7718 return false;
7722 * Block do not have child contexts...
7723 * @return array
7725 public function get_child_contexts() {
7726 return array();
7730 * Create missing context instances at block context level
7731 * @static
7733 protected static function create_level_instances() {
7734 global $DB;
7736 $sql = <<<EOF
7737 INSERT INTO {context} (
7738 contextlevel,
7739 instanceid
7740 ) SELECT
7741 :contextlevel,
7742 bi.id as instanceid
7743 FROM {block_instances} bi
7744 WHERE NOT EXISTS (
7745 SELECT 'x' FROM {context} cx WHERE bi.id = cx.instanceid AND cx.contextlevel = :existingcontextlevel
7747 EOF;
7749 $DB->execute($sql, [
7750 'contextlevel' => CONTEXT_BLOCK,
7751 'existingcontextlevel' => CONTEXT_BLOCK,
7756 * Returns sql necessary for purging of stale context instances.
7758 * @static
7759 * @return string cleanup SQL
7761 protected static function get_cleanup_sql() {
7762 $sql = "
7763 SELECT c.*
7764 FROM {context} c
7765 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7766 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7769 return $sql;
7773 * Rebuild context paths and depths at block context level.
7775 * @static
7776 * @param bool $force
7778 protected static function build_paths($force) {
7779 global $DB;
7781 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7782 if ($force) {
7783 $ctxemptyclause = '';
7784 } else {
7785 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7788 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7789 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7790 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7791 FROM {context} ctx
7792 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7793 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7794 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7795 $ctxemptyclause";
7796 $trans = $DB->start_delegated_transaction();
7797 $DB->delete_records('context_temp');
7798 $DB->execute($sql);
7799 context::merge_context_temp_table();
7800 $DB->delete_records('context_temp');
7801 $trans->allow_commit();
7807 // ============== DEPRECATED FUNCTIONS ==========================================
7808 // Old context related functions were deprecated in 2.0, it is recommended
7809 // to use context classes in new code. Old function can be used when
7810 // creating patches that are supposed to be backported to older stable branches.
7811 // These deprecated functions will not be removed in near future,
7812 // before removing devs will be warned with a debugging message first,
7813 // then we will add error message and only after that we can remove the functions
7814 // completely.
7817 * Runs get_records select on context table and returns the result
7818 * Does get_records_select on the context table, and returns the results ordered
7819 * by contextlevel, and then the natural sort order within each level.
7820 * for the purpose of $select, you need to know that the context table has been
7821 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7823 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7824 * @param array $params any parameters required by $select.
7825 * @return array the requested context records.
7827 function get_sorted_contexts($select, $params = array()) {
7829 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7831 global $DB;
7832 if ($select) {
7833 $select = 'WHERE ' . $select;
7835 return $DB->get_records_sql("
7836 SELECT ctx.*
7837 FROM {context} ctx
7838 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7839 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7840 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7841 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7842 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7843 $select
7844 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7845 ", $params);
7849 * Given context and array of users, returns array of users whose enrolment status is suspended,
7850 * or enrolment has expired or has not started. Also removes those users from the given array
7852 * @param context $context context in which suspended users should be extracted.
7853 * @param array $users list of users.
7854 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7855 * @return array list of suspended users.
7857 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7858 global $DB;
7860 // Get active enrolled users.
7861 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7862 $activeusers = $DB->get_records_sql($sql, $params);
7864 // Move suspended users to a separate array & remove from the initial one.
7865 $susers = array();
7866 if (sizeof($activeusers)) {
7867 foreach ($users as $userid => $user) {
7868 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7869 $susers[$userid] = $user;
7870 unset($users[$userid]);
7874 return $susers;
7878 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7879 * or enrolment has expired or not started.
7881 * @param context $context context in which user enrolment is checked.
7882 * @param bool $usecache Enable or disable (default) the request cache
7883 * @return array list of suspended user id's.
7885 function get_suspended_userids(context $context, $usecache = false) {
7886 global $DB;
7888 if ($usecache) {
7889 $cache = cache::make('core', 'suspended_userids');
7890 $susers = $cache->get($context->id);
7891 if ($susers !== false) {
7892 return $susers;
7896 $coursecontext = $context->get_course_context();
7897 $susers = array();
7899 // Front page users are always enrolled, so suspended list is empty.
7900 if ($coursecontext->instanceid != SITEID) {
7901 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7902 $susers = $DB->get_fieldset_sql($sql, $params);
7903 $susers = array_combine($susers, $susers);
7906 // Cache results for the remainder of this request.
7907 if ($usecache) {
7908 $cache->set($context->id, $susers);
7911 return $susers;
7915 * Gets sql for finding users with capability in the given context
7917 * @param context $context
7918 * @param string|array $capability Capability name or array of names.
7919 * If an array is provided then this is the equivalent of a logical 'OR',
7920 * i.e. the user needs to have one of these capabilities.
7921 * @return array($sql, $params)
7923 function get_with_capability_sql(context $context, $capability) {
7924 static $i = 0;
7925 $i++;
7926 $prefix = 'cu' . $i . '_';
7928 $capjoin = get_with_capability_join($context, $capability, $prefix . 'u.id');
7930 $sql = "SELECT DISTINCT {$prefix}u.id
7931 FROM {user} {$prefix}u
7932 $capjoin->joins
7933 WHERE {$prefix}u.deleted = 0 AND $capjoin->wheres";
7935 return array($sql, $capjoin->params);