MDL-74789 course: category full width
[moodle.git] / lib / accesslib.php
blobbf7e1f7d6ab00898edd2a3803322ee622dfc1709
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);
170 * Although this looks like a global variable, it isn't really.
172 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
173 * It is used to cache various bits of data between function calls for performance reasons.
174 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
175 * as methods of a class, instead of functions.
177 * @access private
178 * @global stdClass $ACCESSLIB_PRIVATE
179 * @name $ACCESSLIB_PRIVATE
181 global $ACCESSLIB_PRIVATE;
182 $ACCESSLIB_PRIVATE = new stdClass();
183 $ACCESSLIB_PRIVATE->cacheroledefs = array(); // Holds site-wide role definitions.
184 $ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache, loaded from DB once per page
185 $ACCESSLIB_PRIVATE->dirtyusers = null; // Dirty users cache, loaded from DB once per $USER->id
186 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
189 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
191 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
192 * accesslib's private caches. You need to do this before setting up test data,
193 * and also at the end of the tests.
195 * @access private
196 * @return void
198 function accesslib_clear_all_caches_for_unit_testing() {
199 global $USER;
200 if (!PHPUNIT_TEST) {
201 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
204 accesslib_clear_all_caches(true);
205 accesslib_reset_role_cache();
207 unset($USER->access);
211 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
213 * This reset does not touch global $USER.
215 * @access private
216 * @param bool $resetcontexts
217 * @return void
219 function accesslib_clear_all_caches($resetcontexts) {
220 global $ACCESSLIB_PRIVATE;
222 $ACCESSLIB_PRIVATE->dirtycontexts = null;
223 $ACCESSLIB_PRIVATE->dirtyusers = null;
224 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
226 if ($resetcontexts) {
227 context_helper::reset_caches();
232 * Full reset of accesslib's private role cache. ONLY TO BE USED FROM THIS LIBRARY FILE!
234 * This reset does not touch global $USER.
236 * Note: Only use this when the roles that need a refresh are unknown.
238 * @see accesslib_clear_role_cache()
240 * @access private
241 * @return void
243 function accesslib_reset_role_cache() {
244 global $ACCESSLIB_PRIVATE;
246 $ACCESSLIB_PRIVATE->cacheroledefs = array();
247 $cache = cache::make('core', 'roledefs');
248 $cache->purge();
252 * Clears accesslib's private cache of a specific role or roles. ONLY BE USED FROM THIS LIBRARY FILE!
254 * This reset does not touch global $USER.
256 * @access private
257 * @param int|array $roles
258 * @return void
260 function accesslib_clear_role_cache($roles) {
261 global $ACCESSLIB_PRIVATE;
263 if (!is_array($roles)) {
264 $roles = [$roles];
267 foreach ($roles as $role) {
268 if (isset($ACCESSLIB_PRIVATE->cacheroledefs[$role])) {
269 unset($ACCESSLIB_PRIVATE->cacheroledefs[$role]);
273 $cache = cache::make('core', 'roledefs');
274 $cache->delete_many($roles);
278 * Role is assigned at system context.
280 * @access private
281 * @param int $roleid
282 * @return array
284 function get_role_access($roleid) {
285 $accessdata = get_empty_accessdata();
286 $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
287 return $accessdata;
291 * Fetch raw "site wide" role definitions.
292 * Even MUC static acceleration cache appears a bit slow for this.
293 * Important as can be hit hundreds of times per page.
295 * @param array $roleids List of role ids to fetch definitions for.
296 * @return array Complete definition for each requested role.
298 function get_role_definitions(array $roleids) {
299 global $ACCESSLIB_PRIVATE;
301 if (empty($roleids)) {
302 return array();
305 // Grab all keys we have not yet got in our static cache.
306 if ($uncached = array_diff($roleids, array_keys($ACCESSLIB_PRIVATE->cacheroledefs))) {
307 $cache = cache::make('core', 'roledefs');
308 foreach ($cache->get_many($uncached) as $roleid => $cachedroledef) {
309 if (is_array($cachedroledef)) {
310 $ACCESSLIB_PRIVATE->cacheroledefs[$roleid] = $cachedroledef;
314 // Check we have the remaining keys from the MUC.
315 if ($uncached = array_diff($roleids, array_keys($ACCESSLIB_PRIVATE->cacheroledefs))) {
316 $uncached = get_role_definitions_uncached($uncached);
317 $ACCESSLIB_PRIVATE->cacheroledefs += $uncached;
318 $cache->set_many($uncached);
322 // Return just the roles we need.
323 return array_intersect_key($ACCESSLIB_PRIVATE->cacheroledefs, array_flip($roleids));
327 * Query raw "site wide" role definitions.
329 * @param array $roleids List of role ids to fetch definitions for.
330 * @return array Complete definition for each requested role.
332 function get_role_definitions_uncached(array $roleids) {
333 global $DB;
335 if (empty($roleids)) {
336 return array();
339 // Create a blank results array: even if a role has no capabilities,
340 // we need to ensure it is included in the results to show we have
341 // loaded all the capabilities that there are.
342 $rdefs = array();
343 foreach ($roleids as $roleid) {
344 $rdefs[$roleid] = array();
347 // Load all the capabilities for these roles in all contexts.
348 list($sql, $params) = $DB->get_in_or_equal($roleids);
349 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
350 FROM {role_capabilities} rc
351 JOIN {context} ctx ON rc.contextid = ctx.id
352 JOIN {capabilities} cap ON rc.capability = cap.name
353 WHERE rc.roleid $sql";
354 $rs = $DB->get_recordset_sql($sql, $params);
356 // Store the capabilities into the expected data structure.
357 foreach ($rs as $rd) {
358 if (!isset($rdefs[$rd->roleid][$rd->path])) {
359 $rdefs[$rd->roleid][$rd->path] = array();
361 $rdefs[$rd->roleid][$rd->path][$rd->capability] = (int) $rd->permission;
364 $rs->close();
366 // Sometimes (e.g. get_user_capability_course_helper::get_capability_info_at_each_context)
367 // we process role definitinons in a way that requires we see parent contexts
368 // before child contexts. This sort ensures that works (and is faster than
369 // sorting in the SQL query).
370 foreach ($rdefs as $roleid => $rdef) {
371 ksort($rdefs[$roleid]);
374 return $rdefs;
378 * Get the default guest role, this is used for guest account,
379 * search engine spiders, etc.
381 * @return stdClass role record
383 function get_guest_role() {
384 global $CFG, $DB;
386 if (empty($CFG->guestroleid)) {
387 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
388 $guestrole = array_shift($roles); // Pick the first one
389 set_config('guestroleid', $guestrole->id);
390 return $guestrole;
391 } else {
392 debugging('Can not find any guest role!');
393 return false;
395 } else {
396 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
397 return $guestrole;
398 } else {
399 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
400 set_config('guestroleid', '');
401 return get_guest_role();
407 * Check whether a user has a particular capability in a given context.
409 * For example:
410 * $context = context_module::instance($cm->id);
411 * has_capability('mod/forum:replypost', $context)
413 * By default checks the capabilities of the current user, but you can pass a
414 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
416 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
417 * or capabilities with XSS, config or data loss risks.
419 * @category access
421 * @param string $capability the name of the capability to check. For example mod/forum:view
422 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
423 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
424 * @param boolean $doanything If false, ignores effect of admin role assignment
425 * @return boolean true if the user has this capability. Otherwise false.
427 function has_capability($capability, context $context, $user = null, $doanything = true) {
428 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
430 if (during_initial_install()) {
431 if ($SCRIPT === "/$CFG->admin/index.php"
432 or $SCRIPT === "/$CFG->admin/cli/install.php"
433 or $SCRIPT === "/$CFG->admin/cli/install_database.php"
434 or (defined('BEHAT_UTIL') and BEHAT_UTIL)
435 or (defined('PHPUNIT_UTIL') and PHPUNIT_UTIL)) {
436 // we are in an installer - roles can not work yet
437 return true;
438 } else {
439 return false;
443 if (strpos($capability, 'moodle/legacy:') === 0) {
444 throw new coding_exception('Legacy capabilities can not be used any more!');
447 if (!is_bool($doanything)) {
448 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
451 // capability must exist
452 if (!$capinfo = get_capability_info($capability)) {
453 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
454 return false;
457 if (!isset($USER->id)) {
458 // should never happen
459 $USER->id = 0;
460 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER);
463 // make sure there is a real user specified
464 if ($user === null) {
465 $userid = $USER->id;
466 } else {
467 $userid = is_object($user) ? $user->id : $user;
470 // make sure forcelogin cuts off not-logged-in users if enabled
471 if (!empty($CFG->forcelogin) and $userid == 0) {
472 return false;
475 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
476 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
477 if (isguestuser($userid) or $userid == 0) {
478 return false;
482 // Check whether context locking is enabled.
483 if (!empty($CFG->contextlocking)) {
484 if ($capinfo->captype === 'write' && $context->locked) {
485 // Context locking applies to any write capability in a locked context.
486 // It does not apply to moodle/site:managecontextlocks - this is to allow context locking to be unlocked.
487 if ($capinfo->name !== 'moodle/site:managecontextlocks') {
488 // It applies to all users who are not site admins.
489 // It also applies to site admins when contextlockappliestoadmin is set.
490 if (!is_siteadmin($userid) || !empty($CFG->contextlockappliestoadmin)) {
491 return false;
497 // somehow make sure the user is not deleted and actually exists
498 if ($userid != 0) {
499 if ($userid == $USER->id and isset($USER->deleted)) {
500 // this prevents one query per page, it is a bit of cheating,
501 // but hopefully session is terminated properly once user is deleted
502 if ($USER->deleted) {
503 return false;
505 } else {
506 if (!context_user::instance($userid, IGNORE_MISSING)) {
507 // no user context == invalid userid
508 return false;
513 // context path/depth must be valid
514 if (empty($context->path) or $context->depth == 0) {
515 // this should not happen often, each upgrade tries to rebuild the context paths
516 debugging('Context id '.$context->id.' does not have valid path, please use context_helper::build_all_paths()');
517 if (is_siteadmin($userid)) {
518 return true;
519 } else {
520 return false;
524 if (!empty($USER->loginascontext)) {
525 // The current user is logged in as another user and can assume their identity at or below the `loginascontext`
526 // defined in the USER session.
527 // The user may not assume their identity at any other location.
528 if (!$USER->loginascontext->is_parent_of($context, true)) {
529 // The context being checked is not the specified context, or one of its children.
530 return false;
534 // Find out if user is admin - it is not possible to override the doanything in any way
535 // and it is not possible to switch to admin role either.
536 if ($doanything) {
537 if (is_siteadmin($userid)) {
538 if ($userid != $USER->id) {
539 return true;
541 // make sure switchrole is not used in this context
542 if (empty($USER->access['rsw'])) {
543 return true;
545 $parts = explode('/', trim($context->path, '/'));
546 $path = '';
547 $switched = false;
548 foreach ($parts as $part) {
549 $path .= '/' . $part;
550 if (!empty($USER->access['rsw'][$path])) {
551 $switched = true;
552 break;
555 if (!$switched) {
556 return true;
558 //ok, admin switched role in this context, let's use normal access control rules
562 // Careful check for staleness...
563 $context->reload_if_dirty();
565 if ($USER->id == $userid) {
566 if (!isset($USER->access)) {
567 load_all_capabilities();
569 $access =& $USER->access;
571 } else {
572 // make sure user accessdata is really loaded
573 get_user_accessdata($userid, true);
574 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
577 return has_capability_in_accessdata($capability, $context, $access);
581 * Check if the user has any one of several capabilities from a list.
583 * This is just a utility method that calls has_capability in a loop. Try to put
584 * the capabilities that most users are likely to have first in the list for best
585 * performance.
587 * @category access
588 * @see has_capability()
590 * @param array $capabilities an array of capability names.
591 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
592 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
593 * @param boolean $doanything If false, ignore effect of admin role assignment
594 * @return boolean true if the user has any of these capabilities. Otherwise false.
596 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
597 foreach ($capabilities as $capability) {
598 if (has_capability($capability, $context, $user, $doanything)) {
599 return true;
602 return false;
606 * Check if the user has all the capabilities in a list.
608 * This is just a utility method that calls has_capability in a loop. Try to put
609 * the capabilities that fewest users are likely to have first in the list for best
610 * performance.
612 * @category access
613 * @see has_capability()
615 * @param array $capabilities an array of capability names.
616 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
617 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
618 * @param boolean $doanything If false, ignore effect of admin role assignment
619 * @return boolean true if the user has all of these capabilities. Otherwise false.
621 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
622 foreach ($capabilities as $capability) {
623 if (!has_capability($capability, $context, $user, $doanything)) {
624 return false;
627 return true;
631 * Is course creator going to have capability in a new course?
633 * This is intended to be used in enrolment plugins before or during course creation,
634 * do not use after the course is fully created.
636 * @category access
638 * @param string $capability the name of the capability to check.
639 * @param context $context course or category context where is course going to be created
640 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
641 * @return boolean true if the user will have this capability.
643 * @throws coding_exception if different type of context submitted
645 function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) {
646 global $CFG;
648 if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) {
649 throw new coding_exception('Only course or course category context expected');
652 if (has_capability($capability, $context, $user)) {
653 // User already has the capability, it could be only removed if CAP_PROHIBIT
654 // was involved here, but we ignore that.
655 return true;
658 if (!has_capability('moodle/course:create', $context, $user)) {
659 return false;
662 if (!enrol_is_enabled('manual')) {
663 return false;
666 if (empty($CFG->creatornewroleid)) {
667 return false;
670 if ($context->contextlevel == CONTEXT_COURSE) {
671 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
672 return false;
674 } else {
675 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
676 return false;
680 // Most likely they will be enrolled after the course creation is finished,
681 // does the new role have the required capability?
682 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
683 return isset($neededroles[$CFG->creatornewroleid]);
687 * Check if the user is an admin at the site level.
689 * Please note that use of proper capabilities is always encouraged,
690 * this function is supposed to be used from core or for temporary hacks.
692 * @category access
694 * @param int|stdClass $user_or_id user id or user object
695 * @return bool true if user is one of the administrators, false otherwise
697 function is_siteadmin($user_or_id = null) {
698 global $CFG, $USER;
700 if ($user_or_id === null) {
701 $user_or_id = $USER;
704 if (empty($user_or_id)) {
705 return false;
707 if (!empty($user_or_id->id)) {
708 $userid = $user_or_id->id;
709 } else {
710 $userid = $user_or_id;
713 // Because this script is called many times (150+ for course page) with
714 // the same parameters, it is worth doing minor optimisations. This static
715 // cache stores the value for a single userid, saving about 2ms from course
716 // page load time without using significant memory. As the static cache
717 // also includes the value it depends on, this cannot break unit tests.
718 static $knownid, $knownresult, $knownsiteadmins;
719 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
720 return $knownresult;
722 $knownid = $userid;
723 $knownsiteadmins = $CFG->siteadmins;
725 $siteadmins = explode(',', $CFG->siteadmins);
726 $knownresult = in_array($userid, $siteadmins);
727 return $knownresult;
731 * Returns true if user has at least one role assign
732 * of 'coursecontact' role (is potentially listed in some course descriptions).
734 * @param int $userid
735 * @return bool
737 function has_coursecontact_role($userid) {
738 global $DB, $CFG;
740 if (empty($CFG->coursecontact)) {
741 return false;
743 $sql = "SELECT 1
744 FROM {role_assignments}
745 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
746 return $DB->record_exists_sql($sql, array('userid'=>$userid));
750 * Does the user have a capability to do something?
752 * Walk the accessdata array and return true/false.
753 * Deals with prohibits, role switching, aggregating
754 * capabilities, etc.
756 * The main feature of here is being FAST and with no
757 * side effects.
759 * Notes:
761 * Switch Role merges with default role
762 * ------------------------------------
763 * If you are a teacher in course X, you have at least
764 * teacher-in-X + defaultloggedinuser-sitewide. So in the
765 * course you'll have techer+defaultloggedinuser.
766 * We try to mimic that in switchrole.
768 * Permission evaluation
769 * ---------------------
770 * Originally there was an extremely complicated way
771 * to determine the user access that dealt with
772 * "locality" or role assignments and role overrides.
773 * Now we simply evaluate access for each role separately
774 * and then verify if user has at least one role with allow
775 * and at the same time no role with prohibit.
777 * @access private
778 * @param string $capability
779 * @param context $context
780 * @param array $accessdata
781 * @return bool
783 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
784 global $CFG;
786 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
787 $path = $context->path;
788 $paths = array($path);
789 while ($path = rtrim($path, '0123456789')) {
790 $path = rtrim($path, '/');
791 if ($path === '') {
792 break;
794 $paths[] = $path;
797 $roles = array();
798 $switchedrole = false;
800 // Find out if role switched
801 if (!empty($accessdata['rsw'])) {
802 // From the bottom up...
803 foreach ($paths as $path) {
804 if (isset($accessdata['rsw'][$path])) {
805 // Found a switchrole assignment - check for that role _plus_ the default user role
806 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
807 $switchedrole = true;
808 break;
813 if (!$switchedrole) {
814 // get all users roles in this context and above
815 foreach ($paths as $path) {
816 if (isset($accessdata['ra'][$path])) {
817 foreach ($accessdata['ra'][$path] as $roleid) {
818 $roles[$roleid] = null;
824 // Now find out what access is given to each role, going bottom-->up direction
825 $rdefs = get_role_definitions(array_keys($roles));
826 $allowed = false;
828 foreach ($roles as $roleid => $ignored) {
829 foreach ($paths as $path) {
830 if (isset($rdefs[$roleid][$path][$capability])) {
831 $perm = (int)$rdefs[$roleid][$path][$capability];
832 if ($perm === CAP_PROHIBIT) {
833 // any CAP_PROHIBIT found means no permission for the user
834 return false;
836 if (is_null($roles[$roleid])) {
837 $roles[$roleid] = $perm;
841 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
842 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
845 return $allowed;
849 * A convenience function that tests has_capability, and displays an error if
850 * the user does not have that capability.
852 * NOTE before Moodle 2.0, this function attempted to make an appropriate
853 * require_login call before checking the capability. This is no longer the case.
854 * You must call require_login (or one of its variants) if you want to check the
855 * user is logged in, before you call this function.
857 * @see has_capability()
859 * @param string $capability the name of the capability to check. For example mod/forum:view
860 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
861 * @param int $userid A user id. By default (null) checks the permissions of the current user.
862 * @param bool $doanything If false, ignore effect of admin role assignment
863 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
864 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
865 * @return void terminates with an error if the user does not have the given capability.
867 function require_capability($capability, context $context, $userid = null, $doanything = true,
868 $errormessage = 'nopermissions', $stringfile = '') {
869 if (!has_capability($capability, $context, $userid, $doanything)) {
870 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
875 * A convenience function that tests has_capability for a list of capabilities, and displays an error if
876 * the user does not have that capability.
878 * This is just a utility method that calls has_capability in a loop. Try to put
879 * the capabilities that fewest users are likely to have first in the list for best
880 * performance.
882 * @category access
883 * @see has_capability()
885 * @param array $capabilities an array of capability names.
886 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
887 * @param int $userid A user id. By default (null) checks the permissions of the current user.
888 * @param bool $doanything If false, ignore effect of admin role assignment
889 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
890 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
891 * @return void terminates with an error if the user does not have the given capability.
893 function require_all_capabilities(array $capabilities, context $context, $userid = null, $doanything = true,
894 $errormessage = 'nopermissions', $stringfile = ''): void {
895 foreach ($capabilities as $capability) {
896 if (!has_capability($capability, $context, $userid, $doanything)) {
897 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
903 * Return a nested array showing all role assignments for the user.
904 * [ra] => [contextpath][roleid] = roleid
906 * @access private
907 * @param int $userid - the id of the user
908 * @return array access info array
910 function get_user_roles_sitewide_accessdata($userid) {
911 global $CFG, $DB;
913 $accessdata = get_empty_accessdata();
915 // start with the default role
916 if (!empty($CFG->defaultuserroleid)) {
917 $syscontext = context_system::instance();
918 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
921 // load the "default frontpage role"
922 if (!empty($CFG->defaultfrontpageroleid)) {
923 $frontpagecontext = context_course::instance(get_site()->id);
924 if ($frontpagecontext->path) {
925 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
929 // Preload every assigned role.
930 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
931 FROM {role_assignments} ra
932 JOIN {context} ctx ON ctx.id = ra.contextid
933 WHERE ra.userid = :userid";
935 $rs = $DB->get_recordset_sql($sql, array('userid' => $userid));
937 foreach ($rs as $ra) {
938 // RAs leafs are arrays to support multi-role assignments...
939 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
942 $rs->close();
944 return $accessdata;
948 * Returns empty accessdata structure.
950 * @access private
951 * @return array empt accessdata
953 function get_empty_accessdata() {
954 $accessdata = array(); // named list
955 $accessdata['ra'] = array();
956 $accessdata['time'] = time();
957 $accessdata['rsw'] = array();
959 return $accessdata;
963 * Get accessdata for a given user.
965 * @access private
966 * @param int $userid
967 * @param bool $preloadonly true means do not return access array
968 * @return array accessdata
970 function get_user_accessdata($userid, $preloadonly=false) {
971 global $CFG, $ACCESSLIB_PRIVATE, $USER;
973 if (isset($USER->access)) {
974 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->access;
977 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
978 if (empty($userid)) {
979 if (!empty($CFG->notloggedinroleid)) {
980 $accessdata = get_role_access($CFG->notloggedinroleid);
981 } else {
982 // weird
983 return get_empty_accessdata();
986 } else if (isguestuser($userid)) {
987 if ($guestrole = get_guest_role()) {
988 $accessdata = get_role_access($guestrole->id);
989 } else {
990 //weird
991 return get_empty_accessdata();
994 } else {
995 // Includes default role and frontpage role.
996 $accessdata = get_user_roles_sitewide_accessdata($userid);
999 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1002 if ($preloadonly) {
1003 return;
1004 } else {
1005 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1010 * A convenience function to completely load all the capabilities
1011 * for the current user. It is called from has_capability() and functions change permissions.
1013 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1014 * @see check_enrolment_plugins()
1016 * @access private
1017 * @return void
1019 function load_all_capabilities() {
1020 global $USER;
1022 // roles not installed yet - we are in the middle of installation
1023 if (during_initial_install()) {
1024 return;
1027 if (!isset($USER->id)) {
1028 // this should not happen
1029 $USER->id = 0;
1032 unset($USER->access);
1033 $USER->access = get_user_accessdata($USER->id);
1035 // Clear to force a refresh
1036 unset($USER->mycourses);
1038 // init/reset internal enrol caches - active course enrolments and temp access
1039 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1043 * A convenience function to completely reload all the capabilities
1044 * for the current user when roles have been updated in a relevant
1045 * context -- but PRESERVING switchroles and loginas.
1046 * This function resets all accesslib and context caches.
1048 * That is - completely transparent to the user.
1050 * Note: reloads $USER->access completely.
1052 * @access private
1053 * @return void
1055 function reload_all_capabilities() {
1056 global $USER, $DB, $ACCESSLIB_PRIVATE;
1058 // copy switchroles
1059 $sw = array();
1060 if (!empty($USER->access['rsw'])) {
1061 $sw = $USER->access['rsw'];
1064 accesslib_clear_all_caches(true);
1065 unset($USER->access);
1067 // Prevent dirty flags refetching on this page.
1068 $ACCESSLIB_PRIVATE->dirtycontexts = array();
1069 $ACCESSLIB_PRIVATE->dirtyusers = array($USER->id => false);
1071 load_all_capabilities();
1073 foreach ($sw as $path => $roleid) {
1074 if ($record = $DB->get_record('context', array('path'=>$path))) {
1075 $context = context::instance_by_id($record->id);
1076 if (has_capability('moodle/role:switchroles', $context)) {
1077 role_switch($roleid, $context);
1084 * Adds a temp role to current USER->access array.
1086 * Useful for the "temporary guest" access we grant to logged-in users.
1087 * This is useful for enrol plugins only.
1089 * @since Moodle 2.2
1090 * @param context_course $coursecontext
1091 * @param int $roleid
1092 * @return void
1094 function load_temp_course_role(context_course $coursecontext, $roleid) {
1095 global $USER, $SITE;
1097 if (empty($roleid)) {
1098 debugging('invalid role specified in load_temp_course_role()');
1099 return;
1102 if ($coursecontext->instanceid == $SITE->id) {
1103 debugging('Can not use temp roles on the frontpage');
1104 return;
1107 if (!isset($USER->access)) {
1108 load_all_capabilities();
1111 $coursecontext->reload_if_dirty();
1113 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1114 return;
1117 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1121 * Removes any extra guest roles from current USER->access array.
1122 * This is useful for enrol plugins only.
1124 * @since Moodle 2.2
1125 * @param context_course $coursecontext
1126 * @return void
1128 function remove_temp_course_roles(context_course $coursecontext) {
1129 global $DB, $USER, $SITE;
1131 if ($coursecontext->instanceid == $SITE->id) {
1132 debugging('Can not use temp roles on the frontpage');
1133 return;
1136 if (empty($USER->access['ra'][$coursecontext->path])) {
1137 //no roles here, weird
1138 return;
1141 $sql = "SELECT DISTINCT ra.roleid AS id
1142 FROM {role_assignments} ra
1143 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1144 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1146 $USER->access['ra'][$coursecontext->path] = array();
1147 foreach ($ras as $r) {
1148 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1153 * Returns array of all role archetypes.
1155 * @return array
1157 function get_role_archetypes() {
1158 return array(
1159 'manager' => 'manager',
1160 'coursecreator' => 'coursecreator',
1161 'editingteacher' => 'editingteacher',
1162 'teacher' => 'teacher',
1163 'student' => 'student',
1164 'guest' => 'guest',
1165 'user' => 'user',
1166 'frontpage' => 'frontpage'
1171 * Assign the defaults found in this capability definition to roles that have
1172 * the corresponding legacy capabilities assigned to them.
1174 * @param string $capability
1175 * @param array $legacyperms an array in the format (example):
1176 * 'guest' => CAP_PREVENT,
1177 * 'student' => CAP_ALLOW,
1178 * 'teacher' => CAP_ALLOW,
1179 * 'editingteacher' => CAP_ALLOW,
1180 * 'coursecreator' => CAP_ALLOW,
1181 * 'manager' => CAP_ALLOW
1182 * @return boolean success or failure.
1184 function assign_legacy_capabilities($capability, $legacyperms) {
1186 $archetypes = get_role_archetypes();
1188 foreach ($legacyperms as $type => $perm) {
1190 $systemcontext = context_system::instance();
1191 if ($type === 'admin') {
1192 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1193 $type = 'manager';
1196 if (!array_key_exists($type, $archetypes)) {
1197 throw new \moodle_exception('invalidlegacy', '', '', $type);
1200 if ($roles = get_archetype_roles($type)) {
1201 foreach ($roles as $role) {
1202 // Assign a site level capability.
1203 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1204 return false;
1209 return true;
1213 * Verify capability risks.
1215 * @param stdClass $capability a capability - a row from the capabilities table.
1216 * @return boolean whether this capability is safe - that is, whether people with the
1217 * safeoverrides capability should be allowed to change it.
1219 function is_safe_capability($capability) {
1220 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1224 * Get the local override (if any) for a given capability in a role in a context
1226 * @param int $roleid
1227 * @param int $contextid
1228 * @param string $capability
1229 * @return stdClass local capability override
1231 function get_local_override($roleid, $contextid, $capability) {
1232 global $DB;
1234 return $DB->get_record_sql("
1235 SELECT rc.*
1236 FROM {role_capabilities} rc
1237 JOIN {capability} cap ON rc.capability = cap.name
1238 WHERE rc.roleid = :roleid AND rc.capability = :capability AND rc.contextid = :contextid", [
1239 'roleid' => $roleid,
1240 'contextid' => $contextid,
1241 'capability' => $capability,
1247 * Returns context instance plus related course and cm instances
1249 * @param int $contextid
1250 * @return array of ($context, $course, $cm)
1252 function get_context_info_array($contextid) {
1253 global $DB;
1255 $context = context::instance_by_id($contextid, MUST_EXIST);
1256 $course = null;
1257 $cm = null;
1259 if ($context->contextlevel == CONTEXT_COURSE) {
1260 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1262 } else if ($context->contextlevel == CONTEXT_MODULE) {
1263 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1264 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1266 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1267 $parent = $context->get_parent_context();
1269 if ($parent->contextlevel == CONTEXT_COURSE) {
1270 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1271 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1272 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1273 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1277 return array($context, $course, $cm);
1281 * Function that creates a role
1283 * @param string $name role name
1284 * @param string $shortname role short name
1285 * @param string $description role description
1286 * @param string $archetype
1287 * @return int id or dml_exception
1289 function create_role($name, $shortname, $description, $archetype = '') {
1290 global $DB;
1292 if (strpos($archetype, 'moodle/legacy:') !== false) {
1293 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1296 // verify role archetype actually exists
1297 $archetypes = get_role_archetypes();
1298 if (empty($archetypes[$archetype])) {
1299 $archetype = '';
1302 // Insert the role record.
1303 $role = new stdClass();
1304 $role->name = $name;
1305 $role->shortname = $shortname;
1306 $role->description = $description;
1307 $role->archetype = $archetype;
1309 //find free sortorder number
1310 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1311 if (empty($role->sortorder)) {
1312 $role->sortorder = 1;
1314 $id = $DB->insert_record('role', $role);
1316 return $id;
1320 * Function that deletes a role and cleanups up after it
1322 * @param int $roleid id of role to delete
1323 * @return bool always true
1325 function delete_role($roleid) {
1326 global $DB;
1328 // first unssign all users
1329 role_unassign_all(array('roleid'=>$roleid));
1331 // cleanup all references to this role, ignore errors
1332 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1333 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1334 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1335 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1336 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1337 $DB->delete_records('role_names', array('roleid'=>$roleid));
1338 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1340 // Get role record before it's deleted.
1341 $role = $DB->get_record('role', array('id'=>$roleid));
1343 // Finally delete the role itself.
1344 $DB->delete_records('role', array('id'=>$roleid));
1346 // Trigger event.
1347 $event = \core\event\role_deleted::create(
1348 array(
1349 'context' => context_system::instance(),
1350 'objectid' => $roleid,
1351 'other' =>
1352 array(
1353 'shortname' => $role->shortname,
1354 'description' => $role->description,
1355 'archetype' => $role->archetype
1359 $event->add_record_snapshot('role', $role);
1360 $event->trigger();
1362 // Reset any cache of this role, including MUC.
1363 accesslib_clear_role_cache($roleid);
1365 return true;
1369 * Function to write context specific overrides, or default capabilities.
1371 * @param string $capability string name
1372 * @param int $permission CAP_ constants
1373 * @param int $roleid role id
1374 * @param int|context $contextid context id
1375 * @param bool $overwrite
1376 * @return bool always true or exception
1378 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1379 global $USER, $DB;
1381 if ($contextid instanceof context) {
1382 $context = $contextid;
1383 } else {
1384 $context = context::instance_by_id($contextid);
1387 // Capability must exist.
1388 if (!$capinfo = get_capability_info($capability)) {
1389 throw new coding_exception("Capability '{$capability}' was not found! This has to be fixed in code.");
1392 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1393 unassign_capability($capability, $roleid, $context->id);
1394 return true;
1397 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1399 if ($existing and !$overwrite) { // We want to keep whatever is there already
1400 return true;
1403 $cap = new stdClass();
1404 $cap->contextid = $context->id;
1405 $cap->roleid = $roleid;
1406 $cap->capability = $capability;
1407 $cap->permission = $permission;
1408 $cap->timemodified = time();
1409 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1411 if ($existing) {
1412 $cap->id = $existing->id;
1413 $DB->update_record('role_capabilities', $cap);
1414 } else {
1415 if ($DB->record_exists('context', array('id'=>$context->id))) {
1416 $DB->insert_record('role_capabilities', $cap);
1420 // Trigger capability_assigned event.
1421 \core\event\capability_assigned::create([
1422 'userid' => $cap->modifierid,
1423 'context' => $context,
1424 'objectid' => $roleid,
1425 'other' => [
1426 'capability' => $capability,
1427 'oldpermission' => $existing->permission ?? CAP_INHERIT,
1428 'permission' => $permission
1430 ])->trigger();
1432 // Reset any cache of this role, including MUC.
1433 accesslib_clear_role_cache($roleid);
1435 return true;
1439 * Unassign a capability from a role.
1441 * @param string $capability the name of the capability
1442 * @param int $roleid the role id
1443 * @param int|context $contextid null means all contexts
1444 * @return boolean true or exception
1446 function unassign_capability($capability, $roleid, $contextid = null) {
1447 global $DB, $USER;
1449 // Capability must exist.
1450 if (!$capinfo = get_capability_info($capability)) {
1451 throw new coding_exception("Capability '{$capability}' was not found! This has to be fixed in code.");
1454 if (!empty($contextid)) {
1455 if ($contextid instanceof context) {
1456 $context = $contextid;
1457 } else {
1458 $context = context::instance_by_id($contextid);
1460 // delete from context rel, if this is the last override in this context
1461 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1462 } else {
1463 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1466 // Trigger capability_assigned event.
1467 \core\event\capability_unassigned::create([
1468 'userid' => $USER->id,
1469 'context' => $context ?? context_system::instance(),
1470 'objectid' => $roleid,
1471 'other' => [
1472 'capability' => $capability,
1474 ])->trigger();
1476 // Reset any cache of this role, including MUC.
1477 accesslib_clear_role_cache($roleid);
1479 return true;
1483 * Get the roles that have a given capability assigned to it
1485 * This function does not resolve the actual permission of the capability.
1486 * It just checks for permissions and overrides.
1487 * Use get_roles_with_cap_in_context() if resolution is required.
1489 * @param string $capability capability name (string)
1490 * @param string $permission optional, the permission defined for this capability
1491 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1492 * @param stdClass $context null means any
1493 * @return array of role records
1495 function get_roles_with_capability($capability, $permission = null, $context = null) {
1496 global $DB;
1498 if ($context) {
1499 $contexts = $context->get_parent_context_ids(true);
1500 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1501 $contextsql = "AND rc.contextid $insql";
1502 } else {
1503 $params = array();
1504 $contextsql = '';
1507 if ($permission) {
1508 $permissionsql = " AND rc.permission = :permission";
1509 $params['permission'] = $permission;
1510 } else {
1511 $permissionsql = '';
1514 $sql = "SELECT r.*
1515 FROM {role} r
1516 WHERE r.id IN (SELECT rc.roleid
1517 FROM {role_capabilities} rc
1518 JOIN {capabilities} cap ON rc.capability = cap.name
1519 WHERE rc.capability = :capname
1520 $contextsql
1521 $permissionsql)";
1522 $params['capname'] = $capability;
1525 return $DB->get_records_sql($sql, $params);
1529 * This function makes a role-assignment (a role for a user in a particular context)
1531 * @param int $roleid the role of the id
1532 * @param int $userid userid
1533 * @param int|context $contextid id of the context
1534 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1535 * @param int $itemid id of enrolment/auth plugin
1536 * @param string $timemodified defaults to current time
1537 * @return int new/existing id of the assignment
1539 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1540 global $USER, $DB;
1542 // first of all detect if somebody is using old style parameters
1543 if ($contextid === 0 or is_numeric($component)) {
1544 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1547 // now validate all parameters
1548 if (empty($roleid)) {
1549 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1552 if (empty($userid)) {
1553 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1556 if ($itemid) {
1557 if (strpos($component, '_') === false) {
1558 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1560 } else {
1561 $itemid = 0;
1562 if ($component !== '' and strpos($component, '_') === false) {
1563 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1567 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1568 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1571 if ($contextid instanceof context) {
1572 $context = $contextid;
1573 } else {
1574 $context = context::instance_by_id($contextid, MUST_EXIST);
1577 if (!$timemodified) {
1578 $timemodified = time();
1581 // Check for existing entry
1582 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1584 if ($ras) {
1585 // role already assigned - this should not happen
1586 if (count($ras) > 1) {
1587 // very weird - remove all duplicates!
1588 $ra = array_shift($ras);
1589 foreach ($ras as $r) {
1590 $DB->delete_records('role_assignments', array('id'=>$r->id));
1592 } else {
1593 $ra = reset($ras);
1596 // actually there is no need to update, reset anything or trigger any event, so just return
1597 return $ra->id;
1600 // Create a new entry
1601 $ra = new stdClass();
1602 $ra->roleid = $roleid;
1603 $ra->contextid = $context->id;
1604 $ra->userid = $userid;
1605 $ra->component = $component;
1606 $ra->itemid = $itemid;
1607 $ra->timemodified = $timemodified;
1608 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1609 $ra->sortorder = 0;
1611 $ra->id = $DB->insert_record('role_assignments', $ra);
1613 // Role assignments have changed, so mark user as dirty.
1614 mark_user_dirty($userid);
1616 core_course_category::role_assignment_changed($roleid, $context);
1618 $event = \core\event\role_assigned::create(array(
1619 'context' => $context,
1620 'objectid' => $ra->roleid,
1621 'relateduserid' => $ra->userid,
1622 'other' => array(
1623 'id' => $ra->id,
1624 'component' => $ra->component,
1625 'itemid' => $ra->itemid
1628 $event->add_record_snapshot('role_assignments', $ra);
1629 $event->trigger();
1631 return $ra->id;
1635 * Removes one role assignment
1637 * @param int $roleid
1638 * @param int $userid
1639 * @param int $contextid
1640 * @param string $component
1641 * @param int $itemid
1642 * @return void
1644 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1645 // first make sure the params make sense
1646 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1647 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1650 if ($itemid) {
1651 if (strpos($component, '_') === false) {
1652 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1654 } else {
1655 $itemid = 0;
1656 if ($component !== '' and strpos($component, '_') === false) {
1657 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1661 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1665 * Removes multiple role assignments, parameters may contain:
1666 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1668 * @param array $params role assignment parameters
1669 * @param bool $subcontexts unassign in subcontexts too
1670 * @param bool $includemanual include manual role assignments too
1671 * @return void
1673 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1674 global $USER, $CFG, $DB;
1676 if (!$params) {
1677 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1680 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1681 foreach ($params as $key=>$value) {
1682 if (!in_array($key, $allowed)) {
1683 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1687 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1688 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1691 if ($includemanual) {
1692 if (!isset($params['component']) or $params['component'] === '') {
1693 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1697 if ($subcontexts) {
1698 if (empty($params['contextid'])) {
1699 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1703 $ras = $DB->get_records('role_assignments', $params);
1704 foreach ($ras as $ra) {
1705 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1706 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1707 // Role assignments have changed, so mark user as dirty.
1708 mark_user_dirty($ra->userid);
1710 $event = \core\event\role_unassigned::create(array(
1711 'context' => $context,
1712 'objectid' => $ra->roleid,
1713 'relateduserid' => $ra->userid,
1714 'other' => array(
1715 'id' => $ra->id,
1716 'component' => $ra->component,
1717 'itemid' => $ra->itemid
1720 $event->add_record_snapshot('role_assignments', $ra);
1721 $event->trigger();
1722 core_course_category::role_assignment_changed($ra->roleid, $context);
1725 unset($ras);
1727 // process subcontexts
1728 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1729 if ($params['contextid'] instanceof context) {
1730 $context = $params['contextid'];
1731 } else {
1732 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1735 if ($context) {
1736 $contexts = $context->get_child_contexts();
1737 $mparams = $params;
1738 foreach ($contexts as $context) {
1739 $mparams['contextid'] = $context->id;
1740 $ras = $DB->get_records('role_assignments', $mparams);
1741 foreach ($ras as $ra) {
1742 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1743 // Role assignments have changed, so mark user as dirty.
1744 mark_user_dirty($ra->userid);
1746 $event = \core\event\role_unassigned::create(
1747 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1748 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1749 $event->add_record_snapshot('role_assignments', $ra);
1750 $event->trigger();
1751 core_course_category::role_assignment_changed($ra->roleid, $context);
1757 // do this once more for all manual role assignments
1758 if ($includemanual) {
1759 $params['component'] = '';
1760 role_unassign_all($params, $subcontexts, false);
1765 * Mark a user as dirty (with timestamp) so as to force reloading of the user session.
1767 * @param int $userid
1768 * @return void
1770 function mark_user_dirty($userid) {
1771 global $CFG, $ACCESSLIB_PRIVATE;
1773 if (during_initial_install()) {
1774 return;
1777 // Throw exception if invalid userid is provided.
1778 if (empty($userid)) {
1779 throw new coding_exception('Invalid user parameter supplied for mark_user_dirty() function!');
1782 // Set dirty flag in database, set dirty field locally, and clear local accessdata cache.
1783 set_cache_flag('accesslib/dirtyusers', $userid, 1, time() + $CFG->sessiontimeout);
1784 $ACCESSLIB_PRIVATE->dirtyusers[$userid] = 1;
1785 unset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
1789 * Determines if a user is currently logged in
1791 * @category access
1793 * @return bool
1795 function isloggedin() {
1796 global $USER;
1798 return (!empty($USER->id));
1802 * Determines if a user is logged in as real guest user with username 'guest'.
1804 * @category access
1806 * @param int|object $user mixed user object or id, $USER if not specified
1807 * @return bool true if user is the real guest user, false if not logged in or other user
1809 function isguestuser($user = null) {
1810 global $USER, $DB, $CFG;
1812 // make sure we have the user id cached in config table, because we are going to use it a lot
1813 if (empty($CFG->siteguest)) {
1814 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1815 // guest does not exist yet, weird
1816 return false;
1818 set_config('siteguest', $guestid);
1820 if ($user === null) {
1821 $user = $USER;
1824 if ($user === null) {
1825 // happens when setting the $USER
1826 return false;
1828 } else if (is_numeric($user)) {
1829 return ($CFG->siteguest == $user);
1831 } else if (is_object($user)) {
1832 if (empty($user->id)) {
1833 return false; // not logged in means is not be guest
1834 } else {
1835 return ($CFG->siteguest == $user->id);
1838 } else {
1839 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1844 * Does user have a (temporary or real) guest access to course?
1846 * @category access
1848 * @param context $context
1849 * @param stdClass|int $user
1850 * @return bool
1852 function is_guest(context $context, $user = null) {
1853 global $USER;
1855 // first find the course context
1856 $coursecontext = $context->get_course_context();
1858 // make sure there is a real user specified
1859 if ($user === null) {
1860 $userid = isset($USER->id) ? $USER->id : 0;
1861 } else {
1862 $userid = is_object($user) ? $user->id : $user;
1865 if (isguestuser($userid)) {
1866 // can not inspect or be enrolled
1867 return true;
1870 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1871 // viewing users appear out of nowhere, they are neither guests nor participants
1872 return false;
1875 // consider only real active enrolments here
1876 if (is_enrolled($coursecontext, $user, '', true)) {
1877 return false;
1880 return true;
1884 * Returns true if the user has moodle/course:view capability in the course,
1885 * this is intended for admins, managers (aka small admins), inspectors, etc.
1887 * @category access
1889 * @param context $context
1890 * @param int|stdClass $user if null $USER is used
1891 * @param string $withcapability extra capability name
1892 * @return bool
1894 function is_viewing(context $context, $user = null, $withcapability = '') {
1895 // first find the course context
1896 $coursecontext = $context->get_course_context();
1898 if (isguestuser($user)) {
1899 // can not inspect
1900 return false;
1903 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1904 // admins are allowed to inspect courses
1905 return false;
1908 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1909 // site admins always have the capability, but the enrolment above blocks
1910 return false;
1913 return true;
1917 * Returns true if the user is able to access the course.
1919 * This function is in no way, shape, or form a substitute for require_login.
1920 * It should only be used in circumstances where it is not possible to call require_login
1921 * such as the navigation.
1923 * This function checks many of the methods of access to a course such as the view
1924 * capability, enrollments, and guest access. It also makes use of the cache
1925 * generated by require_login for guest access.
1927 * The flags within the $USER object that are used here should NEVER be used outside
1928 * of this function can_access_course and require_login. Doing so WILL break future
1929 * versions.
1931 * @param stdClass $course record
1932 * @param stdClass|int|null $user user record or id, current user if null
1933 * @param string $withcapability Check for this capability as well.
1934 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1935 * @return boolean Returns true if the user is able to access the course
1937 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
1938 global $DB, $USER;
1940 // this function originally accepted $coursecontext parameter
1941 if ($course instanceof context) {
1942 if ($course instanceof context_course) {
1943 debugging('deprecated context parameter, please use $course record');
1944 $coursecontext = $course;
1945 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
1946 } else {
1947 debugging('Invalid context parameter, please use $course record');
1948 return false;
1950 } else {
1951 $coursecontext = context_course::instance($course->id);
1954 if (!isset($USER->id)) {
1955 // should never happen
1956 $USER->id = 0;
1957 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
1960 // make sure there is a user specified
1961 if ($user === null) {
1962 $userid = $USER->id;
1963 } else {
1964 $userid = is_object($user) ? $user->id : $user;
1966 unset($user);
1968 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
1969 return false;
1972 if ($userid == $USER->id) {
1973 if (!empty($USER->access['rsw'][$coursecontext->path])) {
1974 // the fact that somebody switched role means they can access the course no matter to what role they switched
1975 return true;
1979 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
1980 return false;
1983 if (is_viewing($coursecontext, $userid)) {
1984 return true;
1987 if ($userid != $USER->id) {
1988 // for performance reasons we do not verify temporary guest access for other users, sorry...
1989 return is_enrolled($coursecontext, $userid, '', $onlyactive);
1992 // === from here we deal only with $USER ===
1994 $coursecontext->reload_if_dirty();
1996 if (isset($USER->enrol['enrolled'][$course->id])) {
1997 if ($USER->enrol['enrolled'][$course->id] > time()) {
1998 return true;
2001 if (isset($USER->enrol['tempguest'][$course->id])) {
2002 if ($USER->enrol['tempguest'][$course->id] > time()) {
2003 return true;
2007 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2008 return true;
2011 if (!core_course_category::can_view_course_info($course)) {
2012 // No guest access if user does not have capability to browse courses.
2013 return false;
2016 // if not enrolled try to gain temporary guest access
2017 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2018 $enrols = enrol_get_plugins(true);
2019 foreach ($instances as $instance) {
2020 if (!isset($enrols[$instance->enrol])) {
2021 continue;
2023 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2024 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2025 if ($until !== false and $until > time()) {
2026 $USER->enrol['tempguest'][$course->id] = $until;
2027 return true;
2030 if (isset($USER->enrol['tempguest'][$course->id])) {
2031 unset($USER->enrol['tempguest'][$course->id]);
2032 remove_temp_course_roles($coursecontext);
2035 return false;
2039 * Loads the capability definitions for the component (from file).
2041 * Loads the capability definitions for the component (from file). If no
2042 * capabilities are defined for the component, we simply return an empty array.
2044 * @access private
2045 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2046 * @return array array of capabilities
2048 function load_capability_def($component) {
2049 $defpath = core_component::get_component_directory($component).'/db/access.php';
2051 $capabilities = array();
2052 if (file_exists($defpath)) {
2053 require($defpath);
2054 if (!empty(${$component.'_capabilities'})) {
2055 // BC capability array name
2056 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2057 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2058 $capabilities = ${$component.'_capabilities'};
2062 return $capabilities;
2066 * Gets the capabilities that have been cached in the database for this component.
2068 * @access private
2069 * @param string $component - examples: 'moodle', 'mod_forum'
2070 * @return array array of capabilities
2072 function get_cached_capabilities($component = 'moodle') {
2073 global $DB;
2074 $caps = get_all_capabilities();
2075 $componentcaps = array();
2076 foreach ($caps as $cap) {
2077 if ($cap['component'] == $component) {
2078 $componentcaps[] = (object) $cap;
2081 return $componentcaps;
2085 * Returns default capabilities for given role archetype.
2087 * @param string $archetype role archetype
2088 * @return array
2090 function get_default_capabilities($archetype) {
2091 global $DB;
2093 if (!$archetype) {
2094 return array();
2097 $alldefs = array();
2098 $defaults = array();
2099 $components = array();
2100 $allcaps = get_all_capabilities();
2102 foreach ($allcaps as $cap) {
2103 if (!in_array($cap['component'], $components)) {
2104 $components[] = $cap['component'];
2105 $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
2108 foreach ($alldefs as $name=>$def) {
2109 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2110 if (isset($def['archetypes'])) {
2111 if (isset($def['archetypes'][$archetype])) {
2112 $defaults[$name] = $def['archetypes'][$archetype];
2114 // 'legacy' is for backward compatibility with 1.9 access.php
2115 } else {
2116 if (isset($def['legacy'][$archetype])) {
2117 $defaults[$name] = $def['legacy'][$archetype];
2122 return $defaults;
2126 * Return default roles that can be assigned, overridden or switched
2127 * by give role archetype.
2129 * @param string $type assign|override|switch|view
2130 * @param string $archetype
2131 * @return array of role ids
2133 function get_default_role_archetype_allows($type, $archetype) {
2134 global $DB;
2136 if (empty($archetype)) {
2137 return array();
2140 $roles = $DB->get_records('role');
2141 $archetypemap = array();
2142 foreach ($roles as $role) {
2143 if ($role->archetype) {
2144 $archetypemap[$role->archetype][$role->id] = $role->id;
2148 $defaults = array(
2149 'assign' => array(
2150 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2151 'coursecreator' => array(),
2152 'editingteacher' => array('teacher', 'student'),
2153 'teacher' => array(),
2154 'student' => array(),
2155 'guest' => array(),
2156 'user' => array(),
2157 'frontpage' => array(),
2159 'override' => array(
2160 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2161 'coursecreator' => array(),
2162 'editingteacher' => array('teacher', 'student', 'guest'),
2163 'teacher' => array(),
2164 'student' => array(),
2165 'guest' => array(),
2166 'user' => array(),
2167 'frontpage' => array(),
2169 'switch' => array(
2170 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2171 'coursecreator' => array(),
2172 'editingteacher' => array('teacher', 'student', 'guest'),
2173 'teacher' => array('student', 'guest'),
2174 'student' => array(),
2175 'guest' => array(),
2176 'user' => array(),
2177 'frontpage' => array(),
2179 'view' => array(
2180 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2181 'coursecreator' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2182 'editingteacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2183 'teacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2184 'student' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2185 'guest' => array(),
2186 'user' => array(),
2187 'frontpage' => array(),
2191 if (!isset($defaults[$type][$archetype])) {
2192 debugging("Unknown type '$type'' or archetype '$archetype''");
2193 return array();
2196 $return = array();
2197 foreach ($defaults[$type][$archetype] as $at) {
2198 if (isset($archetypemap[$at])) {
2199 foreach ($archetypemap[$at] as $roleid) {
2200 $return[$roleid] = $roleid;
2205 return $return;
2209 * Reset role capabilities to default according to selected role archetype.
2210 * If no archetype selected, removes all capabilities.
2212 * This applies to capabilities that are assigned to the role (that you could
2213 * edit in the 'define roles' interface), and not to any capability overrides
2214 * in different locations.
2216 * @param int $roleid ID of role to reset capabilities for
2218 function reset_role_capabilities($roleid) {
2219 global $DB;
2221 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2222 $defaultcaps = get_default_capabilities($role->archetype);
2224 $systemcontext = context_system::instance();
2226 $DB->delete_records('role_capabilities',
2227 array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2229 foreach ($defaultcaps as $cap=>$permission) {
2230 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2233 // Reset any cache of this role, including MUC.
2234 accesslib_clear_role_cache($roleid);
2238 * Updates the capabilities table with the component capability definitions.
2239 * If no parameters are given, the function updates the core moodle
2240 * capabilities.
2242 * Note that the absence of the db/access.php capabilities definition file
2243 * will cause any stored capabilities for the component to be removed from
2244 * the database.
2246 * @access private
2247 * @param string $component examples: 'moodle', 'mod_forum', 'block_activity_results'
2248 * @return boolean true if success, exception in case of any problems
2250 function update_capabilities($component = 'moodle') {
2251 global $DB, $OUTPUT;
2253 $storedcaps = array();
2255 $filecaps = load_capability_def($component);
2256 foreach ($filecaps as $capname=>$unused) {
2257 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2258 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2262 // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2263 // So ensure our updating is based on fresh data.
2264 cache::make('core', 'capabilities')->delete('core_capabilities');
2266 $cachedcaps = get_cached_capabilities($component);
2267 if ($cachedcaps) {
2268 foreach ($cachedcaps as $cachedcap) {
2269 array_push($storedcaps, $cachedcap->name);
2270 // update risk bitmasks and context levels in existing capabilities if needed
2271 if (array_key_exists($cachedcap->name, $filecaps)) {
2272 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2273 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2275 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2276 $updatecap = new stdClass();
2277 $updatecap->id = $cachedcap->id;
2278 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2279 $DB->update_record('capabilities', $updatecap);
2281 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2282 $updatecap = new stdClass();
2283 $updatecap->id = $cachedcap->id;
2284 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2285 $DB->update_record('capabilities', $updatecap);
2288 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2289 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2291 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2292 $updatecap = new stdClass();
2293 $updatecap->id = $cachedcap->id;
2294 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2295 $DB->update_record('capabilities', $updatecap);
2301 // Flush the cached again, as we have changed DB.
2302 cache::make('core', 'capabilities')->delete('core_capabilities');
2304 // Are there new capabilities in the file definition?
2305 $newcaps = array();
2307 foreach ($filecaps as $filecap => $def) {
2308 if (!$storedcaps ||
2309 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2310 if (!array_key_exists('riskbitmask', $def)) {
2311 $def['riskbitmask'] = 0; // no risk if not specified
2313 $newcaps[$filecap] = $def;
2316 // Add new capabilities to the stored definition.
2317 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2318 foreach ($newcaps as $capname => $capdef) {
2319 $capability = new stdClass();
2320 $capability->name = $capname;
2321 $capability->captype = $capdef['captype'];
2322 $capability->contextlevel = $capdef['contextlevel'];
2323 $capability->component = $component;
2324 $capability->riskbitmask = $capdef['riskbitmask'];
2326 $DB->insert_record('capabilities', $capability, false);
2328 // Flush the cached, as we have changed DB.
2329 cache::make('core', 'capabilities')->delete('core_capabilities');
2331 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2332 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2333 foreach ($rolecapabilities as $rolecapability){
2334 //assign_capability will update rather than insert if capability exists
2335 if (!assign_capability($capname, $rolecapability->permission,
2336 $rolecapability->roleid, $rolecapability->contextid, true)){
2337 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2341 // we ignore archetype key if we have cloned permissions
2342 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2343 assign_legacy_capabilities($capname, $capdef['archetypes']);
2344 // 'legacy' is for backward compatibility with 1.9 access.php
2345 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2346 assign_legacy_capabilities($capname, $capdef['legacy']);
2349 // Are there any capabilities that have been removed from the file
2350 // definition that we need to delete from the stored capabilities and
2351 // role assignments?
2352 capabilities_cleanup($component, $filecaps);
2354 // reset static caches
2355 accesslib_reset_role_cache();
2357 // Flush the cached again, as we have changed DB.
2358 cache::make('core', 'capabilities')->delete('core_capabilities');
2360 return true;
2364 * Deletes cached capabilities that are no longer needed by the component.
2365 * Also unassigns these capabilities from any roles that have them.
2366 * NOTE: this function is called from lib/db/upgrade.php
2368 * @access private
2369 * @param string $component examples: 'moodle', 'mod_forum', 'block_activity_results'
2370 * @param array $newcapdef array of the new capability definitions that will be
2371 * compared with the cached capabilities
2372 * @return int number of deprecated capabilities that have been removed
2374 function capabilities_cleanup($component, $newcapdef = null) {
2375 global $DB;
2377 $removedcount = 0;
2379 if ($cachedcaps = get_cached_capabilities($component)) {
2380 foreach ($cachedcaps as $cachedcap) {
2381 if (empty($newcapdef) ||
2382 array_key_exists($cachedcap->name, $newcapdef) === false) {
2384 // Delete from roles.
2385 if ($roles = get_roles_with_capability($cachedcap->name)) {
2386 foreach ($roles as $role) {
2387 if (!unassign_capability($cachedcap->name, $role->id)) {
2388 throw new \moodle_exception('cannotunassigncap', 'error', '',
2389 (object)array('cap' => $cachedcap->name, 'role' => $role->name));
2394 // Remove from role_capabilities for any old ones.
2395 $DB->delete_records('role_capabilities', array('capability' => $cachedcap->name));
2397 // Remove from capabilities cache.
2398 $DB->delete_records('capabilities', array('name' => $cachedcap->name));
2399 $removedcount++;
2400 } // End if.
2403 if ($removedcount) {
2404 cache::make('core', 'capabilities')->delete('core_capabilities');
2406 return $removedcount;
2410 * Returns an array of all the known types of risk
2411 * The array keys can be used, for example as CSS class names, or in calls to
2412 * print_risk_icon. The values are the corresponding RISK_ constants.
2414 * @return array all the known types of risk.
2416 function get_all_risks() {
2417 return array(
2418 'riskmanagetrust' => RISK_MANAGETRUST,
2419 'riskconfig' => RISK_CONFIG,
2420 'riskxss' => RISK_XSS,
2421 'riskpersonal' => RISK_PERSONAL,
2422 'riskspam' => RISK_SPAM,
2423 'riskdataloss' => RISK_DATALOSS,
2428 * Return a link to moodle docs for a given capability name
2430 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2431 * @return string the human-readable capability name as a link to Moodle Docs.
2433 function get_capability_docs_link($capability) {
2434 $url = get_docs_url('Capabilities/' . $capability->name);
2435 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2439 * This function pulls out all the resolved capabilities (overrides and
2440 * defaults) of a role used in capability overrides in contexts at a given
2441 * context.
2443 * @param int $roleid
2444 * @param context $context
2445 * @param string $cap capability, optional, defaults to ''
2446 * @return array Array of capabilities
2448 function role_context_capabilities($roleid, context $context, $cap = '') {
2449 global $DB;
2451 $contexts = $context->get_parent_context_ids(true);
2452 $contexts = '('.implode(',', $contexts).')';
2454 $params = array($roleid);
2456 if ($cap) {
2457 $search = " AND rc.capability = ? ";
2458 $params[] = $cap;
2459 } else {
2460 $search = '';
2463 $sql = "SELECT rc.*
2464 FROM {role_capabilities} rc
2465 JOIN {context} c ON rc.contextid = c.id
2466 JOIN {capabilities} cap ON rc.capability = cap.name
2467 WHERE rc.contextid in $contexts
2468 AND rc.roleid = ?
2469 $search
2470 ORDER BY c.contextlevel DESC, rc.capability DESC";
2472 $capabilities = array();
2474 if ($records = $DB->get_records_sql($sql, $params)) {
2475 // We are traversing via reverse order.
2476 foreach ($records as $record) {
2477 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2478 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2479 $capabilities[$record->capability] = $record->permission;
2483 return $capabilities;
2487 * Constructs array with contextids as first parameter and context paths,
2488 * in both cases bottom top including self.
2490 * @access private
2491 * @param context $context
2492 * @return array
2494 function get_context_info_list(context $context) {
2495 $contextids = explode('/', ltrim($context->path, '/'));
2496 $contextpaths = array();
2497 $contextids2 = $contextids;
2498 while ($contextids2) {
2499 $contextpaths[] = '/' . implode('/', $contextids2);
2500 array_pop($contextids2);
2502 return array($contextids, $contextpaths);
2506 * Check if context is the front page context or a context inside it
2508 * Returns true if this context is the front page context, or a context inside it,
2509 * otherwise false.
2511 * @param context $context a context object.
2512 * @return bool
2514 function is_inside_frontpage(context $context) {
2515 $frontpagecontext = context_course::instance(SITEID);
2516 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2520 * Returns capability information (cached)
2522 * @param string $capabilityname
2523 * @return stdClass or null if capability not found
2525 function get_capability_info($capabilityname) {
2526 $caps = get_all_capabilities();
2528 if (!isset($caps[$capabilityname])) {
2529 return null;
2532 return (object) $caps[$capabilityname];
2536 * Returns all capabilitiy records, preferably from MUC and not database.
2538 * @return array All capability records indexed by capability name
2540 function get_all_capabilities() {
2541 global $DB;
2542 $cache = cache::make('core', 'capabilities');
2543 if (!$allcaps = $cache->get('core_capabilities')) {
2544 $rs = $DB->get_recordset('capabilities');
2545 $allcaps = array();
2546 foreach ($rs as $capability) {
2547 $capability->riskbitmask = (int) $capability->riskbitmask;
2548 $allcaps[$capability->name] = (array) $capability;
2550 $rs->close();
2551 $cache->set('core_capabilities', $allcaps);
2553 return $allcaps;
2557 * Returns the human-readable, translated version of the capability.
2558 * Basically a big switch statement.
2560 * @param string $capabilityname e.g. mod/choice:readresponses
2561 * @return string
2563 function get_capability_string($capabilityname) {
2565 // Typical capability name is 'plugintype/pluginname:capabilityname'
2566 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2568 if ($type === 'moodle') {
2569 $component = 'core_role';
2570 } else if ($type === 'quizreport') {
2571 //ugly hack!!
2572 $component = 'quiz_'.$name;
2573 } else {
2574 $component = $type.'_'.$name;
2577 $stringname = $name.':'.$capname;
2579 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2580 return get_string($stringname, $component);
2583 $dir = core_component::get_component_directory($component);
2584 if (!file_exists($dir)) {
2585 // plugin broken or does not exist, do not bother with printing of debug message
2586 return $capabilityname.' ???';
2589 // something is wrong in plugin, better print debug
2590 return get_string($stringname, $component);
2594 * This gets the mod/block/course/core etc strings.
2596 * @param string $component
2597 * @param int $contextlevel
2598 * @return string|bool String is success, false if failed
2600 function get_component_string($component, $contextlevel) {
2602 if ($component === 'moodle' || $component === 'core') {
2603 return context_helper::get_level_name($contextlevel);
2606 list($type, $name) = core_component::normalize_component($component);
2607 $dir = core_component::get_plugin_directory($type, $name);
2608 if (!file_exists($dir)) {
2609 // plugin not installed, bad luck, there is no way to find the name
2610 return $component . ' ???';
2613 // Some plugin types need an extra prefix to make the name easy to understand.
2614 switch ($type) {
2615 case 'quiz':
2616 $prefix = get_string('quizreport', 'quiz') . ': ';
2617 break;
2618 case 'repository':
2619 $prefix = get_string('repository', 'repository') . ': ';
2620 break;
2621 case 'gradeimport':
2622 $prefix = get_string('gradeimport', 'grades') . ': ';
2623 break;
2624 case 'gradeexport':
2625 $prefix = get_string('gradeexport', 'grades') . ': ';
2626 break;
2627 case 'gradereport':
2628 $prefix = get_string('gradereport', 'grades') . ': ';
2629 break;
2630 case 'webservice':
2631 $prefix = get_string('webservice', 'webservice') . ': ';
2632 break;
2633 case 'block':
2634 $prefix = get_string('block') . ': ';
2635 break;
2636 case 'mod':
2637 $prefix = get_string('activity') . ': ';
2638 break;
2640 // Default case, just use the plugin name.
2641 default:
2642 $prefix = '';
2644 return $prefix . get_string('pluginname', $component);
2648 * Gets the list of roles assigned to this context and up (parents)
2649 * from the aggregation of:
2650 * a) the list of roles that are visible on user profile page and participants page (profileroles setting) and;
2651 * b) if applicable, those roles that are assigned in the context.
2653 * @param context $context
2654 * @return array
2656 function get_profile_roles(context $context) {
2657 global $CFG, $DB;
2658 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2659 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2660 if (has_capability('moodle/role:assign', $context)) {
2661 $rolesinscope = array_keys(get_all_roles($context));
2662 } else {
2663 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2666 if (empty($rolesinscope)) {
2667 return [];
2670 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2671 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2672 $params = array_merge($params, $cparams);
2674 if ($coursecontext = $context->get_course_context(false)) {
2675 $params['coursecontext'] = $coursecontext->id;
2676 } else {
2677 $params['coursecontext'] = 0;
2680 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2681 FROM {role_assignments} ra, {role} r
2682 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2683 WHERE r.id = ra.roleid
2684 AND ra.contextid $contextlist
2685 AND r.id $rallowed
2686 ORDER BY r.sortorder ASC";
2688 return $DB->get_records_sql($sql, $params);
2692 * Gets the list of roles assigned to this context and up (parents)
2694 * @param context $context
2695 * @param boolean $includeparents, false means without parents.
2696 * @return array
2698 function get_roles_used_in_context(context $context, $includeparents = true) {
2699 global $DB;
2701 if ($includeparents === true) {
2702 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2703 } else {
2704 list($contextlist, $params) = $DB->get_in_or_equal($context->id, SQL_PARAMS_NAMED, 'cl');
2707 if ($coursecontext = $context->get_course_context(false)) {
2708 $params['coursecontext'] = $coursecontext->id;
2709 } else {
2710 $params['coursecontext'] = 0;
2713 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2714 FROM {role_assignments} ra, {role} r
2715 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2716 WHERE r.id = ra.roleid
2717 AND ra.contextid $contextlist
2718 ORDER BY r.sortorder ASC";
2720 return $DB->get_records_sql($sql, $params);
2724 * This function is used to print roles column in user profile page.
2725 * It is using the CFG->profileroles to limit the list to only interesting roles.
2726 * (The permission tab has full details of user role assignments.)
2728 * @param int $userid
2729 * @param int $courseid
2730 * @return string
2732 function get_user_roles_in_course($userid, $courseid) {
2733 global $CFG, $DB;
2734 if ($courseid == SITEID) {
2735 $context = context_system::instance();
2736 } else {
2737 $context = context_course::instance($courseid);
2739 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2740 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2741 if (has_capability('moodle/role:assign', $context)) {
2742 $rolesinscope = array_keys(get_all_roles($context));
2743 } else {
2744 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2746 if (empty($rolesinscope)) {
2747 return '';
2750 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2751 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2752 $params = array_merge($params, $cparams);
2754 if ($coursecontext = $context->get_course_context(false)) {
2755 $params['coursecontext'] = $coursecontext->id;
2756 } else {
2757 $params['coursecontext'] = 0;
2760 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2761 FROM {role_assignments} ra, {role} r
2762 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2763 WHERE r.id = ra.roleid
2764 AND ra.contextid $contextlist
2765 AND r.id $rallowed
2766 AND ra.userid = :userid
2767 ORDER BY r.sortorder ASC";
2768 $params['userid'] = $userid;
2770 $rolestring = '';
2772 if ($roles = $DB->get_records_sql($sql, $params)) {
2773 $viewableroles = get_viewable_roles($context, $userid);
2775 $rolenames = array();
2776 foreach ($roles as $roleid => $unused) {
2777 if (isset($viewableroles[$roleid])) {
2778 $url = new moodle_url('/user/index.php', ['contextid' => $context->id, 'roleid' => $roleid]);
2779 $rolenames[] = '<a href="' . $url . '">' . $viewableroles[$roleid] . '</a>';
2782 $rolestring = implode(', ', $rolenames);
2785 return $rolestring;
2789 * Checks if a user can assign users to a particular role in this context
2791 * @param context $context
2792 * @param int $targetroleid - the id of the role you want to assign users to
2793 * @return boolean
2795 function user_can_assign(context $context, $targetroleid) {
2796 global $DB;
2798 // First check to see if the user is a site administrator.
2799 if (is_siteadmin()) {
2800 return true;
2803 // Check if user has override capability.
2804 // If not return false.
2805 if (!has_capability('moodle/role:assign', $context)) {
2806 return false;
2808 // pull out all active roles of this user from this context(or above)
2809 if ($userroles = get_user_roles($context)) {
2810 foreach ($userroles as $userrole) {
2811 // if any in the role_allow_override table, then it's ok
2812 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2813 return true;
2818 return false;
2822 * Returns all site roles in correct sort order.
2824 * Note: this method does not localise role names or descriptions,
2825 * use role_get_names() if you need role names.
2827 * @param context $context optional context for course role name aliases
2828 * @return array of role records with optional coursealias property
2830 function get_all_roles(context $context = null) {
2831 global $DB;
2833 if (!$context or !$coursecontext = $context->get_course_context(false)) {
2834 $coursecontext = null;
2837 if ($coursecontext) {
2838 $sql = "SELECT r.*, rn.name AS coursealias
2839 FROM {role} r
2840 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2841 ORDER BY r.sortorder ASC";
2842 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
2844 } else {
2845 return $DB->get_records('role', array(), 'sortorder ASC');
2850 * Returns roles of a specified archetype
2852 * @param string $archetype
2853 * @return array of full role records
2855 function get_archetype_roles($archetype) {
2856 global $DB;
2857 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2861 * Gets all the user roles assigned in this context, or higher contexts for a list of users.
2863 * If you try using the combination $userids = [], $checkparentcontexts = true then this is likely
2864 * to cause an out-of-memory error on large Moodle sites, so this combination is deprecated and
2865 * outputs a warning, even though it is the default.
2867 * @param context $context
2868 * @param array $userids. An empty list means fetch all role assignments for the context.
2869 * @param bool $checkparentcontexts defaults to true
2870 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2871 * @return array
2873 function get_users_roles(context $context, $userids = [], $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2874 global $DB;
2876 if (!$userids && $checkparentcontexts) {
2877 debugging('Please do not call get_users_roles() with $checkparentcontexts = true ' .
2878 'and $userids array not set. This combination causes large Moodle sites ' .
2879 'with lots of site-wide role assignemnts to run out of memory.', DEBUG_DEVELOPER);
2882 if ($checkparentcontexts) {
2883 $contextids = $context->get_parent_context_ids();
2884 } else {
2885 $contextids = array();
2887 $contextids[] = $context->id;
2889 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
2891 // If userids was passed as an empty array, we fetch all role assignments for the course.
2892 if (empty($userids)) {
2893 $useridlist = ' IS NOT NULL ';
2894 $uparams = [];
2895 } else {
2896 list($useridlist, $uparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'uids');
2899 $sql = "SELECT ra.*, r.name, r.shortname, ra.userid
2900 FROM {role_assignments} ra, {role} r, {context} c
2901 WHERE ra.userid $useridlist
2902 AND ra.roleid = r.id
2903 AND ra.contextid = c.id
2904 AND ra.contextid $contextids
2905 ORDER BY $order";
2907 $all = $DB->get_records_sql($sql , array_merge($params, $uparams));
2909 // Return results grouped by userid.
2910 $result = [];
2911 foreach ($all as $id => $record) {
2912 if (!isset($result[$record->userid])) {
2913 $result[$record->userid] = [];
2915 $result[$record->userid][$record->id] = $record;
2918 // Make sure all requested users are included in the result, even if they had no role assignments.
2919 foreach ($userids as $id) {
2920 if (!isset($result[$id])) {
2921 $result[$id] = [];
2925 return $result;
2930 * Gets all the user roles assigned in this context, or higher contexts
2931 * this is mainly used when checking if a user can assign a role, or overriding a role
2932 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2933 * allow_override tables
2935 * @param context $context
2936 * @param int $userid
2937 * @param bool $checkparentcontexts defaults to true
2938 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2939 * @return array
2941 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2942 global $USER, $DB;
2944 if (empty($userid)) {
2945 if (empty($USER->id)) {
2946 return array();
2948 $userid = $USER->id;
2951 if ($checkparentcontexts) {
2952 $contextids = $context->get_parent_context_ids();
2953 } else {
2954 $contextids = array();
2956 $contextids[] = $context->id;
2958 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2960 array_unshift($params, $userid);
2962 $sql = "SELECT ra.*, r.name, r.shortname
2963 FROM {role_assignments} ra, {role} r, {context} c
2964 WHERE ra.userid = ?
2965 AND ra.roleid = r.id
2966 AND ra.contextid = c.id
2967 AND ra.contextid $contextids
2968 ORDER BY $order";
2970 return $DB->get_records_sql($sql ,$params);
2974 * Like get_user_roles, but adds in the authenticated user role, and the front
2975 * page roles, if applicable.
2977 * @param context $context the context.
2978 * @param int $userid optional. Defaults to $USER->id
2979 * @return array of objects with fields ->userid, ->contextid and ->roleid.
2981 function get_user_roles_with_special(context $context, $userid = 0) {
2982 global $CFG, $USER;
2984 if (empty($userid)) {
2985 if (empty($USER->id)) {
2986 return array();
2988 $userid = $USER->id;
2991 $ras = get_user_roles($context, $userid);
2993 // Add front-page role if relevant.
2994 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2995 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
2996 is_inside_frontpage($context);
2997 if ($defaultfrontpageroleid && $isfrontpage) {
2998 $frontpagecontext = context_course::instance(SITEID);
2999 $ra = new stdClass();
3000 $ra->userid = $userid;
3001 $ra->contextid = $frontpagecontext->id;
3002 $ra->roleid = $defaultfrontpageroleid;
3003 $ras[] = $ra;
3006 // Add authenticated user role if relevant.
3007 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3008 if ($defaultuserroleid && !isguestuser($userid)) {
3009 $systemcontext = context_system::instance();
3010 $ra = new stdClass();
3011 $ra->userid = $userid;
3012 $ra->contextid = $systemcontext->id;
3013 $ra->roleid = $defaultuserroleid;
3014 $ras[] = $ra;
3017 return $ras;
3021 * Creates a record in the role_allow_override table
3023 * @param int $fromroleid source roleid
3024 * @param int $targetroleid target roleid
3025 * @return void
3027 function core_role_set_override_allowed($fromroleid, $targetroleid) {
3028 global $DB;
3030 $record = new stdClass();
3031 $record->roleid = $fromroleid;
3032 $record->allowoverride = $targetroleid;
3033 $DB->insert_record('role_allow_override', $record);
3037 * Creates a record in the role_allow_assign table
3039 * @param int $fromroleid source roleid
3040 * @param int $targetroleid target roleid
3041 * @return void
3043 function core_role_set_assign_allowed($fromroleid, $targetroleid) {
3044 global $DB;
3046 $record = new stdClass();
3047 $record->roleid = $fromroleid;
3048 $record->allowassign = $targetroleid;
3049 $DB->insert_record('role_allow_assign', $record);
3053 * Creates a record in the role_allow_switch table
3055 * @param int $fromroleid source roleid
3056 * @param int $targetroleid target roleid
3057 * @return void
3059 function core_role_set_switch_allowed($fromroleid, $targetroleid) {
3060 global $DB;
3062 $record = new stdClass();
3063 $record->roleid = $fromroleid;
3064 $record->allowswitch = $targetroleid;
3065 $DB->insert_record('role_allow_switch', $record);
3069 * Creates a record in the role_allow_view table
3071 * @param int $fromroleid source roleid
3072 * @param int $targetroleid target roleid
3073 * @return void
3075 function core_role_set_view_allowed($fromroleid, $targetroleid) {
3076 global $DB;
3078 $record = new stdClass();
3079 $record->roleid = $fromroleid;
3080 $record->allowview = $targetroleid;
3081 $DB->insert_record('role_allow_view', $record);
3085 * Gets a list of roles that this user can assign in this context
3087 * @param context $context the context.
3088 * @param int $rolenamedisplay the type of role name to display. One of the
3089 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3090 * @param bool $withusercounts if true, count the number of users with each role.
3091 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3092 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3093 * if $withusercounts is true, returns a list of three arrays,
3094 * $rolenames, $rolecounts, and $nameswithcounts.
3096 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3097 global $USER, $DB;
3099 // make sure there is a real user specified
3100 if ($user === null) {
3101 $userid = isset($USER->id) ? $USER->id : 0;
3102 } else {
3103 $userid = is_object($user) ? $user->id : $user;
3106 if (!has_capability('moodle/role:assign', $context, $userid)) {
3107 if ($withusercounts) {
3108 return array(array(), array(), array());
3109 } else {
3110 return array();
3114 $params = array();
3115 $extrafields = '';
3117 if ($withusercounts) {
3118 $extrafields = ', (SELECT COUNT(DISTINCT u.id)
3119 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3120 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3121 ) AS usercount';
3122 $params['conid'] = $context->id;
3125 if (is_siteadmin($userid)) {
3126 // show all roles allowed in this context to admins
3127 $assignrestriction = "";
3128 } else {
3129 $parents = $context->get_parent_context_ids(true);
3130 $contexts = implode(',' , $parents);
3131 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3132 FROM {role_allow_assign} raa
3133 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3134 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3135 ) ar ON ar.id = r.id";
3136 $params['userid'] = $userid;
3138 $params['contextlevel'] = $context->contextlevel;
3140 if ($coursecontext = $context->get_course_context(false)) {
3141 $params['coursecontext'] = $coursecontext->id;
3142 } else {
3143 $params['coursecontext'] = 0; // no course aliases
3144 $coursecontext = null;
3146 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3147 FROM {role} r
3148 $assignrestriction
3149 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3150 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3151 ORDER BY r.sortorder ASC";
3152 $roles = $DB->get_records_sql($sql, $params);
3154 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3156 if (!$withusercounts) {
3157 return $rolenames;
3160 $rolecounts = array();
3161 $nameswithcounts = array();
3162 foreach ($roles as $role) {
3163 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3164 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3166 return array($rolenames, $rolecounts, $nameswithcounts);
3170 * Gets a list of roles that this user can switch to in a context
3172 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3173 * This function just process the contents of the role_allow_switch table. You also need to
3174 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3176 * @param context $context a context.
3177 * @param int $rolenamedisplay the type of role name to display. One of the
3178 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3179 * @return array an array $roleid => $rolename.
3181 function get_switchable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS) {
3182 global $USER, $DB;
3184 // You can't switch roles without this capability.
3185 if (!has_capability('moodle/role:switchroles', $context)) {
3186 return [];
3189 $params = array();
3190 $extrajoins = '';
3191 $extrawhere = '';
3192 if (!is_siteadmin()) {
3193 // Admins are allowed to switch to any role with.
3194 // Others are subject to the additional constraint that the switch-to role must be allowed by
3195 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3196 $parents = $context->get_parent_context_ids(true);
3197 $contexts = implode(',' , $parents);
3199 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3200 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3201 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3202 $params['userid'] = $USER->id;
3205 if ($coursecontext = $context->get_course_context(false)) {
3206 $params['coursecontext'] = $coursecontext->id;
3207 } else {
3208 $params['coursecontext'] = 0; // no course aliases
3209 $coursecontext = null;
3212 $query = "
3213 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3214 FROM (SELECT DISTINCT rc.roleid
3215 FROM {role_capabilities} rc
3217 $extrajoins
3218 $extrawhere) idlist
3219 JOIN {role} r ON r.id = idlist.roleid
3220 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3221 ORDER BY r.sortorder";
3222 $roles = $DB->get_records_sql($query, $params);
3224 return role_fix_names($roles, $context, $rolenamedisplay, true);
3228 * Gets a list of roles that this user can view in a context
3230 * @param context $context a context.
3231 * @param int $userid id of user.
3232 * @param int $rolenamedisplay the type of role name to display. One of the
3233 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3234 * @return array an array $roleid => $rolename.
3236 function get_viewable_roles(context $context, $userid = null, $rolenamedisplay = ROLENAME_ALIAS) {
3237 global $USER, $DB;
3239 if ($userid == null) {
3240 $userid = $USER->id;
3243 $params = array();
3244 $extrajoins = '';
3245 $extrawhere = '';
3246 if (!is_siteadmin()) {
3247 // Admins are allowed to view any role.
3248 // Others are subject to the additional constraint that the view role must be allowed by
3249 // 'role_allow_view' for some role they have assigned in this context or any parent.
3250 $contexts = $context->get_parent_context_ids(true);
3251 list($insql, $inparams) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED);
3253 $extrajoins = "JOIN {role_allow_view} ras ON ras.allowview = r.id
3254 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3255 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid $insql";
3257 $params += $inparams;
3258 $params['userid'] = $userid;
3261 if ($coursecontext = $context->get_course_context(false)) {
3262 $params['coursecontext'] = $coursecontext->id;
3263 } else {
3264 $params['coursecontext'] = 0; // No course aliases.
3265 $coursecontext = null;
3268 $query = "
3269 SELECT r.id, r.name, r.shortname, rn.name AS coursealias, r.sortorder
3270 FROM {role} r
3271 $extrajoins
3272 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3273 $extrawhere
3274 GROUP BY r.id, r.name, r.shortname, rn.name, r.sortorder
3275 ORDER BY r.sortorder";
3276 $roles = $DB->get_records_sql($query, $params);
3278 return role_fix_names($roles, $context, $rolenamedisplay, true);
3282 * Gets a list of roles that this user can override in this context.
3284 * @param context $context the context.
3285 * @param int $rolenamedisplay the type of role name to display. One of the
3286 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3287 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3288 * @return array if $withcounts is false, then an array $roleid => $rolename.
3289 * if $withusercounts is true, returns a list of three arrays,
3290 * $rolenames, $rolecounts, and $nameswithcounts.
3292 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3293 global $USER, $DB;
3295 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3296 if ($withcounts) {
3297 return array(array(), array(), array());
3298 } else {
3299 return array();
3303 $parents = $context->get_parent_context_ids(true);
3304 $contexts = implode(',' , $parents);
3306 $params = array();
3307 $extrafields = '';
3309 $params['userid'] = $USER->id;
3310 if ($withcounts) {
3311 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3312 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3313 $params['conid'] = $context->id;
3316 if ($coursecontext = $context->get_course_context(false)) {
3317 $params['coursecontext'] = $coursecontext->id;
3318 } else {
3319 $params['coursecontext'] = 0; // no course aliases
3320 $coursecontext = null;
3323 if (is_siteadmin()) {
3324 // show all roles to admins
3325 $roles = $DB->get_records_sql("
3326 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3327 FROM {role} ro
3328 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3329 ORDER BY ro.sortorder ASC", $params);
3331 } else {
3332 $roles = $DB->get_records_sql("
3333 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3334 FROM {role} ro
3335 JOIN (SELECT DISTINCT r.id
3336 FROM {role} r
3337 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3338 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3339 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3340 ) inline_view ON ro.id = inline_view.id
3341 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3342 ORDER BY ro.sortorder ASC", $params);
3345 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3347 if (!$withcounts) {
3348 return $rolenames;
3351 $rolecounts = array();
3352 $nameswithcounts = array();
3353 foreach ($roles as $role) {
3354 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3355 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3357 return array($rolenames, $rolecounts, $nameswithcounts);
3361 * Create a role menu suitable for default role selection in enrol plugins.
3363 * @package core_enrol
3365 * @param context $context
3366 * @param int $addroleid current or default role - always added to list
3367 * @return array roleid=>localised role name
3369 function get_default_enrol_roles(context $context, $addroleid = null) {
3370 global $DB;
3372 $params = array('contextlevel'=>CONTEXT_COURSE);
3374 if ($coursecontext = $context->get_course_context(false)) {
3375 $params['coursecontext'] = $coursecontext->id;
3376 } else {
3377 $params['coursecontext'] = 0; // no course names
3378 $coursecontext = null;
3381 if ($addroleid) {
3382 $addrole = "OR r.id = :addroleid";
3383 $params['addroleid'] = $addroleid;
3384 } else {
3385 $addrole = "";
3388 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3389 FROM {role} r
3390 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3391 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3392 WHERE rcl.id IS NOT NULL $addrole
3393 ORDER BY sortorder DESC";
3395 $roles = $DB->get_records_sql($sql, $params);
3397 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3401 * Return context levels where this role is assignable.
3403 * @param integer $roleid the id of a role.
3404 * @return array list of the context levels at which this role may be assigned.
3406 function get_role_contextlevels($roleid) {
3407 global $DB;
3408 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3409 'contextlevel', 'id,contextlevel');
3413 * Return roles suitable for assignment at the specified context level.
3415 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3417 * @param integer $contextlevel a contextlevel.
3418 * @return array list of role ids that are assignable at this context level.
3420 function get_roles_for_contextlevels($contextlevel) {
3421 global $DB;
3422 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3423 '', 'id,roleid');
3427 * Returns default context levels where roles can be assigned.
3429 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3430 * from the array returned by get_role_archetypes();
3431 * @return array list of the context levels at which this type of role may be assigned by default.
3433 function get_default_contextlevels($rolearchetype) {
3434 static $defaults = array(
3435 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3436 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3437 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3438 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3439 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3440 'guest' => array(),
3441 'user' => array(),
3442 'frontpage' => array());
3444 if (isset($defaults[$rolearchetype])) {
3445 return $defaults[$rolearchetype];
3446 } else {
3447 return array();
3452 * Set the context levels at which a particular role can be assigned.
3453 * Throws exceptions in case of error.
3455 * @param integer $roleid the id of a role.
3456 * @param array $contextlevels the context levels at which this role should be assignable,
3457 * duplicate levels are removed.
3458 * @return void
3460 function set_role_contextlevels($roleid, array $contextlevels) {
3461 global $DB;
3462 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3463 $rcl = new stdClass();
3464 $rcl->roleid = $roleid;
3465 $contextlevels = array_unique($contextlevels);
3466 foreach ($contextlevels as $level) {
3467 $rcl->contextlevel = $level;
3468 $DB->insert_record('role_context_levels', $rcl, false, true);
3473 * Gets sql joins for finding users with capability in the given context.
3475 * @param context $context Context for the join.
3476 * @param string|array $capability Capability name or array of names.
3477 * If an array is provided then this is the equivalent of a logical 'OR',
3478 * i.e. the user needs to have one of these capabilities.
3479 * @param string $useridcolumn e.g. 'u.id'.
3480 * @return \core\dml\sql_join Contains joins, wheres, params.
3481 * This function will set ->cannotmatchanyrows if applicable.
3482 * This may let you skip doing a DB query.
3484 function get_with_capability_join(context $context, $capability, $useridcolumn) {
3485 global $CFG, $DB;
3487 // Add a unique prefix to param names to ensure they are unique.
3488 static $i = 0;
3489 $i++;
3490 $paramprefix = 'eu' . $i . '_';
3492 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3493 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3495 $ctxids = trim($context->path, '/');
3496 $ctxids = str_replace('/', ',', $ctxids);
3498 // Context is the frontpage
3499 $isfrontpage = $context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID;
3500 $isfrontpage = $isfrontpage || is_inside_frontpage($context);
3502 $caps = (array) $capability;
3504 // Construct list of context paths bottom --> top.
3505 list($contextids, $paths) = get_context_info_list($context);
3507 // We need to find out all roles that have these capabilities either in definition or in overrides.
3508 $defs = [];
3509 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, $paramprefix . 'con');
3510 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, $paramprefix . 'cap');
3512 // Check whether context locking is enabled.
3513 // Filter out any write capability if this is the case.
3514 $excludelockedcaps = '';
3515 $excludelockedcapsparams = [];
3516 if (!empty($CFG->contextlocking) && $context->locked) {
3517 $excludelockedcaps = 'AND (cap.captype = :capread OR cap.name = :managelockscap)';
3518 $excludelockedcapsparams['capread'] = 'read';
3519 $excludelockedcapsparams['managelockscap'] = 'moodle/site:managecontextlocks';
3522 $params = array_merge($params, $params2, $excludelockedcapsparams);
3523 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3524 FROM {role_capabilities} rc
3525 JOIN {capabilities} cap ON rc.capability = cap.name
3526 JOIN {context} ctx on rc.contextid = ctx.id
3527 WHERE rc.contextid $incontexts AND rc.capability $incaps $excludelockedcaps";
3529 $rcs = $DB->get_records_sql($sql, $params);
3530 foreach ($rcs as $rc) {
3531 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3534 // Go through the permissions bottom-->top direction to evaluate the current permission,
3535 // first one wins (prohibit is an exception that always wins).
3536 $access = [];
3537 foreach ($caps as $cap) {
3538 foreach ($paths as $path) {
3539 if (empty($defs[$cap][$path])) {
3540 continue;
3542 foreach ($defs[$cap][$path] as $roleid => $perm) {
3543 if ($perm == CAP_PROHIBIT) {
3544 $access[$cap][$roleid] = CAP_PROHIBIT;
3545 continue;
3547 if (!isset($access[$cap][$roleid])) {
3548 $access[$cap][$roleid] = (int)$perm;
3554 // Make lists of roles that are needed and prohibited in this context.
3555 $needed = []; // One of these is enough.
3556 $prohibited = []; // Must not have any of these.
3557 foreach ($caps as $cap) {
3558 if (empty($access[$cap])) {
3559 continue;
3561 foreach ($access[$cap] as $roleid => $perm) {
3562 if ($perm == CAP_PROHIBIT) {
3563 unset($needed[$cap][$roleid]);
3564 $prohibited[$cap][$roleid] = true;
3565 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3566 $needed[$cap][$roleid] = true;
3569 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3570 // Easy, nobody has the permission.
3571 unset($needed[$cap]);
3572 unset($prohibited[$cap]);
3573 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3574 // Everybody is disqualified on the frontpage.
3575 unset($needed[$cap]);
3576 unset($prohibited[$cap]);
3578 if (empty($prohibited[$cap])) {
3579 unset($prohibited[$cap]);
3583 if (empty($needed)) {
3584 // There can not be anybody if no roles match this request.
3585 return new \core\dml\sql_join('', '1 = 2', [], true);
3588 if (empty($prohibited)) {
3589 // We can compact the needed roles.
3590 $n = [];
3591 foreach ($needed as $cap) {
3592 foreach ($cap as $roleid => $unused) {
3593 $n[$roleid] = true;
3596 $needed = ['any' => $n];
3597 unset($n);
3600 // Prepare query clauses.
3601 $wherecond = [];
3602 $params = [];
3603 $joins = [];
3604 $cannotmatchanyrows = false;
3606 // We never return deleted users or guest account.
3607 // Use a hack to get the deleted user column without an API change.
3608 $deletedusercolumn = substr($useridcolumn, 0, -2) . 'deleted';
3609 $wherecond[] = "$deletedusercolumn = 0 AND $useridcolumn <> :{$paramprefix}guestid";
3610 $params[$paramprefix . 'guestid'] = $CFG->siteguest;
3612 // Now add the needed and prohibited roles conditions as joins.
3613 if (!empty($needed['any'])) {
3614 // Simple case - there are no prohibits involved.
3615 if (!empty($needed['any'][$defaultuserroleid]) ||
3616 ($isfrontpage && !empty($needed['any'][$defaultfrontpageroleid]))) {
3617 // Everybody.
3618 } else {
3619 $joins[] = "JOIN (SELECT DISTINCT userid
3620 FROM {role_assignments}
3621 WHERE contextid IN ($ctxids)
3622 AND roleid IN (" . implode(',', array_keys($needed['any'])) . ")
3623 ) ra ON ra.userid = $useridcolumn";
3625 } else {
3626 $unions = [];
3627 $everybody = false;
3628 foreach ($needed as $cap => $unused) {
3629 if (empty($prohibited[$cap])) {
3630 if (!empty($needed[$cap][$defaultuserroleid]) ||
3631 ($isfrontpage && !empty($needed[$cap][$defaultfrontpageroleid]))) {
3632 $everybody = true;
3633 break;
3634 } else {
3635 $unions[] = "SELECT userid
3636 FROM {role_assignments}
3637 WHERE contextid IN ($ctxids)
3638 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3640 } else {
3641 if (!empty($prohibited[$cap][$defaultuserroleid]) ||
3642 ($isfrontpage && !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3643 // Nobody can have this cap because it is prohibited in default roles.
3644 continue;
3646 } else if (!empty($needed[$cap][$defaultuserroleid]) ||
3647 ($isfrontpage && !empty($needed[$cap][$defaultfrontpageroleid]))) {
3648 // Everybody except the prohibited - hiding does not matter.
3649 $unions[] = "SELECT id AS userid
3650 FROM {user}
3651 WHERE id NOT IN (SELECT userid
3652 FROM {role_assignments}
3653 WHERE contextid IN ($ctxids)
3654 AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . "))";
3656 } else {
3657 $unions[] = "SELECT userid
3658 FROM {role_assignments}
3659 WHERE contextid IN ($ctxids) AND roleid IN (" . implode(',', array_keys($needed[$cap])) . ")
3660 AND userid NOT IN (
3661 SELECT userid
3662 FROM {role_assignments}
3663 WHERE contextid IN ($ctxids)
3664 AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . "))";
3669 if (!$everybody) {
3670 if ($unions) {
3671 $joins[] = "JOIN (
3672 SELECT DISTINCT userid
3673 FROM (
3674 " . implode("\n UNION \n", $unions) . "
3675 ) us
3676 ) ra ON ra.userid = $useridcolumn";
3677 } else {
3678 // Only prohibits found - nobody can be matched.
3679 $wherecond[] = "1 = 2";
3680 $cannotmatchanyrows = true;
3685 return new \core\dml\sql_join(implode("\n", $joins), implode(" AND ", $wherecond), $params, $cannotmatchanyrows);
3689 * Who has this capability in this context?
3691 * This can be a very expensive call - use sparingly and keep
3692 * the results if you are going to need them again soon.
3694 * Note if $fields is empty this function attempts to get u.*
3695 * which can get rather large - and has a serious perf impact
3696 * on some DBs.
3698 * @param context $context
3699 * @param string|array $capability - capability name(s)
3700 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3701 * @param string $sort - the sort order. Default is lastaccess time.
3702 * @param mixed $limitfrom - number of records to skip (offset)
3703 * @param mixed $limitnum - number of records to fetch
3704 * @param string|array $groups - single group or array of groups - only return
3705 * users who are in one of these group(s).
3706 * @param string|array $exceptions - list of users to exclude, comma separated or array
3707 * @param bool $notuseddoanything not used any more, admin accounts are never returned
3708 * @param bool $notusedview - use get_enrolled_sql() instead
3709 * @param bool $useviewallgroups if $groups is set the return users who
3710 * have capability both $capability and moodle/site:accessallgroups
3711 * in this context, as well as users who have $capability and who are
3712 * in $groups.
3713 * @return array of user records
3715 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3716 $groups = '', $exceptions = '', $notuseddoanything = null, $notusedview = null, $useviewallgroups = false) {
3717 global $CFG, $DB;
3719 // Context is a course page other than the frontpage.
3720 $iscoursepage = $context->contextlevel == CONTEXT_COURSE && $context->instanceid != SITEID;
3722 // Set up default fields list if necessary.
3723 if (empty($fields)) {
3724 if ($iscoursepage) {
3725 $fields = 'u.*, ul.timeaccess AS lastaccess';
3726 } else {
3727 $fields = 'u.*';
3729 } else {
3730 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3731 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3735 // Set up default sort if necessary.
3736 if (empty($sort)) { // default to course lastaccess or just lastaccess
3737 if ($iscoursepage) {
3738 $sort = 'ul.timeaccess';
3739 } else {
3740 $sort = 'u.lastaccess';
3744 // Get the bits of SQL relating to capabilities.
3745 $sqljoin = get_with_capability_join($context, $capability, 'u.id');
3746 if ($sqljoin->cannotmatchanyrows) {
3747 return [];
3750 // Prepare query clauses.
3751 $wherecond = [$sqljoin->wheres];
3752 $params = $sqljoin->params;
3753 $joins = [$sqljoin->joins];
3755 // Add user lastaccess JOIN, if required.
3756 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3757 // Here user_lastaccess is not required MDL-13810.
3758 } else {
3759 if ($iscoursepage) {
3760 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3761 } else {
3762 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3766 // Groups.
3767 if ($groups) {
3768 $groups = (array)$groups;
3769 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3770 $joins[] = "LEFT OUTER JOIN (SELECT DISTINCT userid
3771 FROM {groups_members}
3772 WHERE groupid $grouptest
3773 ) gm ON gm.userid = u.id";
3775 $params = array_merge($params, $grpparams);
3777 $grouptest = 'gm.userid IS NOT NULL';
3778 if ($useviewallgroups) {
3779 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3780 if (!empty($viewallgroupsusers)) {
3781 $grouptest .= ' OR u.id IN (' . implode(',', array_keys($viewallgroupsusers)) . ')';
3784 $wherecond[] = "($grouptest)";
3787 // User exceptions.
3788 if (!empty($exceptions)) {
3789 $exceptions = (array)$exceptions;
3790 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3791 $params = array_merge($params, $exparams);
3792 $wherecond[] = "u.id $exsql";
3795 // Collect WHERE conditions and needed joins.
3796 $where = implode(' AND ', $wherecond);
3797 if ($where !== '') {
3798 $where = 'WHERE ' . $where;
3800 $joins = implode("\n", $joins);
3802 // Finally! we have all the bits, run the query.
3803 $sql = "SELECT $fields
3804 FROM {user} u
3805 $joins
3806 $where
3807 ORDER BY $sort";
3809 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3813 * Re-sort a users array based on a sorting policy
3815 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3816 * based on a sorting policy. This is to support the odd practice of
3817 * sorting teachers by 'authority', where authority was "lowest id of the role
3818 * assignment".
3820 * Will execute 1 database query. Only suitable for small numbers of users, as it
3821 * uses an u.id IN() clause.
3823 * Notes about the sorting criteria.
3825 * As a default, we cannot rely on role.sortorder because then
3826 * admins/coursecreators will always win. That is why the sane
3827 * rule "is locality matters most", with sortorder as 2nd
3828 * consideration.
3830 * If you want role.sortorder, use the 'sortorder' policy, and
3831 * name explicitly what roles you want to cover. It's probably
3832 * a good idea to see what roles have the capabilities you want
3833 * (array_diff() them against roiles that have 'can-do-anything'
3834 * to weed out admin-ish roles. Or fetch a list of roles from
3835 * variables like $CFG->coursecontact .
3837 * @param array $users Users array, keyed on userid
3838 * @param context $context
3839 * @param array $roles ids of the roles to include, optional
3840 * @param string $sortpolicy defaults to locality, more about
3841 * @return array sorted copy of the array
3843 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3844 global $DB;
3846 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3847 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3848 if (empty($roles)) {
3849 $roleswhere = '';
3850 } else {
3851 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3854 $sql = "SELECT ra.userid
3855 FROM {role_assignments} ra
3856 JOIN {role} r
3857 ON ra.roleid=r.id
3858 JOIN {context} ctx
3859 ON ra.contextid=ctx.id
3860 WHERE $userswhere
3861 $contextwhere
3862 $roleswhere";
3864 // Default 'locality' policy -- read PHPDoc notes
3865 // about sort policies...
3866 $orderby = 'ORDER BY '
3867 .'ctx.depth DESC, ' /* locality wins */
3868 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3869 .'ra.id'; /* role assignment order tie-breaker */
3870 if ($sortpolicy === 'sortorder') {
3871 $orderby = 'ORDER BY '
3872 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3873 .'ra.id'; /* role assignment order tie-breaker */
3876 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3877 $sortedusers = array();
3878 $seen = array();
3880 foreach ($sortedids as $id) {
3881 // Avoid duplicates
3882 if (isset($seen[$id])) {
3883 continue;
3885 $seen[$id] = true;
3887 // assign
3888 $sortedusers[$id] = $users[$id];
3890 return $sortedusers;
3894 * Gets all the users assigned this role in this context or higher
3896 * Note that moodle is based on capabilities and it is usually better
3897 * to check permissions than to check role ids as the capabilities
3898 * system is more flexible. If you really need, you can to use this
3899 * function but consider has_capability() as a possible substitute.
3901 * All $sort fields are added into $fields if not present there yet.
3903 * If $roleid is an array or is empty (all roles) you need to set $fields
3904 * (and $sort by extension) params according to it, as the first field
3905 * returned by the database should be unique (ra.id is the best candidate).
3907 * @param int $roleid (can also be an array of ints!)
3908 * @param context $context
3909 * @param bool $parent if true, get list of users assigned in higher context too
3910 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3911 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3912 * null => use default sort from users_order_by_sql.
3913 * @param bool $all true means all, false means limit to enrolled users
3914 * @param string $group defaults to ''
3915 * @param mixed $limitfrom defaults to ''
3916 * @param mixed $limitnum defaults to ''
3917 * @param string $extrawheretest defaults to ''
3918 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3919 * @return array
3921 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3922 $sort = null, $all = true, $group = '',
3923 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3924 global $DB;
3926 if (empty($fields)) {
3927 $userfieldsapi = \core_user\fields::for_name();
3928 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
3929 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
3930 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3931 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3932 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3933 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3936 // Prevent wrong function uses.
3937 if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
3938 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
3939 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
3941 if (!empty($roleid)) {
3942 // Solving partially the issue when specifying multiple roles.
3943 $users = array();
3944 foreach ($roleid as $id) {
3945 // Ignoring duplicated keys keeping the first user appearance.
3946 $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
3947 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
3949 return $users;
3953 $parentcontexts = '';
3954 if ($parent) {
3955 $parentcontexts = substr($context->path, 1); // kill leading slash
3956 $parentcontexts = str_replace('/', ',', $parentcontexts);
3957 if ($parentcontexts !== '') {
3958 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3962 if ($roleid) {
3963 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
3964 $roleselect = "AND ra.roleid $rids";
3965 } else {
3966 $params = array();
3967 $roleselect = '';
3970 if ($coursecontext = $context->get_course_context(false)) {
3971 $params['coursecontext'] = $coursecontext->id;
3972 } else {
3973 $params['coursecontext'] = 0;
3976 if ($group) {
3977 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3978 $groupselect = " AND gm.groupid = :groupid ";
3979 $params['groupid'] = $group;
3980 } else {
3981 $groupjoin = '';
3982 $groupselect = '';
3985 $params['contextid'] = $context->id;
3987 if ($extrawheretest) {
3988 $extrawheretest = ' AND ' . $extrawheretest;
3991 if ($whereorsortparams) {
3992 $params = array_merge($params, $whereorsortparams);
3995 if (!$sort) {
3996 list($sort, $sortparams) = users_order_by_sql('u');
3997 $params = array_merge($params, $sortparams);
4000 // Adding the fields from $sort that are not present in $fields.
4001 $sortarray = preg_split('/,\s*/', $sort);
4002 $fieldsarray = preg_split('/,\s*/', $fields);
4004 // Discarding aliases from the fields.
4005 $fieldnames = array();
4006 foreach ($fieldsarray as $key => $field) {
4007 list($fieldnames[$key]) = explode(' ', $field);
4010 $addedfields = array();
4011 foreach ($sortarray as $sortfield) {
4012 // Throw away any additional arguments to the sort (e.g. ASC/DESC).
4013 list($sortfield) = explode(' ', $sortfield);
4014 list($tableprefix) = explode('.', $sortfield);
4015 $fieldpresent = false;
4016 foreach ($fieldnames as $fieldname) {
4017 if ($fieldname === $sortfield || $fieldname === $tableprefix.'.*') {
4018 $fieldpresent = true;
4019 break;
4023 if (!$fieldpresent) {
4024 $fieldsarray[] = $sortfield;
4025 $addedfields[] = $sortfield;
4029 $fields = implode(', ', $fieldsarray);
4030 if (!empty($addedfields)) {
4031 $addedfields = implode(', ', $addedfields);
4032 debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
4035 if ($all === null) {
4036 // Previously null was used to indicate that parameter was not used.
4037 $all = true;
4039 if (!$all and $coursecontext) {
4040 // Do not use get_enrolled_sql() here for performance reasons.
4041 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
4042 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
4043 $params['ecourseid'] = $coursecontext->instanceid;
4044 } else {
4045 $ejoin = "";
4048 $sql = "SELECT DISTINCT $fields, ra.roleid
4049 FROM {role_assignments} ra
4050 JOIN {user} u ON u.id = ra.userid
4051 JOIN {role} r ON ra.roleid = r.id
4052 $ejoin
4053 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
4054 $groupjoin
4055 WHERE (ra.contextid = :contextid $parentcontexts)
4056 $roleselect
4057 $groupselect
4058 $extrawheretest
4059 ORDER BY $sort"; // join now so that we can just use fullname() later
4061 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
4065 * Counts all the users assigned this role in this context or higher
4067 * @param int|array $roleid either int or an array of ints
4068 * @param context $context
4069 * @param bool $parent if true, get list of users assigned in higher context too
4070 * @return int Returns the result count
4072 function count_role_users($roleid, context $context, $parent = false) {
4073 global $DB;
4075 if ($parent) {
4076 if ($contexts = $context->get_parent_context_ids()) {
4077 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4078 } else {
4079 $parentcontexts = '';
4081 } else {
4082 $parentcontexts = '';
4085 if ($roleid) {
4086 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
4087 $roleselect = "AND r.roleid $rids";
4088 } else {
4089 $params = array();
4090 $roleselect = '';
4093 array_unshift($params, $context->id);
4095 $sql = "SELECT COUNT(DISTINCT u.id)
4096 FROM {role_assignments} r
4097 JOIN {user} u ON u.id = r.userid
4098 WHERE (r.contextid = ? $parentcontexts)
4099 $roleselect
4100 AND u.deleted = 0";
4102 return $DB->count_records_sql($sql, $params);
4106 * This function gets the list of course and course category contexts that this user has a particular capability in.
4108 * It is now reasonably efficient, but bear in mind that if there are users who have the capability
4109 * everywhere, it may return an array of all contexts.
4111 * @param string $capability Capability in question
4112 * @param int $userid User ID or null for current user
4113 * @param bool $getcategories Wether to return also course_categories
4114 * @param bool $doanything True if 'doanything' is permitted (default)
4115 * @param string $coursefieldsexceptid Leave blank if you only need 'id' in the course records;
4116 * otherwise use a comma-separated list of the fields you require, not including id.
4117 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
4118 * @param string $categoryfieldsexceptid Leave blank if you only need 'id' in the course records;
4119 * otherwise use a comma-separated list of the fields you require, not including id.
4120 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
4121 * @param string $courseorderby If set, use a comma-separated list of fields from course
4122 * table with sql modifiers (DESC) if needed
4123 * @param string $categoryorderby If set, use a comma-separated list of fields from course_category
4124 * table with sql modifiers (DESC) if needed
4125 * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
4126 * @return array Array of categories and courses.
4128 function get_user_capability_contexts(string $capability, bool $getcategories, $userid = null, $doanything = true,
4129 $coursefieldsexceptid = '', $categoryfieldsexceptid = '', $courseorderby = '',
4130 $categoryorderby = '', $limit = 0): array {
4131 global $DB, $USER;
4133 // Default to current user.
4134 if (!$userid) {
4135 $userid = $USER->id;
4138 if ($doanything && is_siteadmin($userid)) {
4139 // If the user is a site admin and $doanything is enabled then there is no need to restrict
4140 // the list of courses.
4141 $contextlimitsql = '';
4142 $contextlimitparams = [];
4143 } else {
4144 // Gets SQL to limit contexts ('x' table) to those where the user has this capability.
4145 list ($contextlimitsql, $contextlimitparams) = \core\access\get_user_capability_course_helper::get_sql(
4146 $userid, $capability);
4147 if (!$contextlimitsql) {
4148 // If the does not have this capability in any context, return false without querying.
4149 return [false, false];
4152 $contextlimitsql = 'WHERE' . $contextlimitsql;
4155 $categories = [];
4156 if ($getcategories) {
4157 $fieldlist = \core\access\get_user_capability_course_helper::map_fieldnames($categoryfieldsexceptid);
4158 if ($categoryorderby) {
4159 $fields = explode(',', $categoryorderby);
4160 $orderby = '';
4161 foreach ($fields as $field) {
4162 if ($orderby) {
4163 $orderby .= ',';
4165 $orderby .= 'c.'.$field;
4167 $orderby = 'ORDER BY '.$orderby;
4169 $rs = $DB->get_recordset_sql("
4170 SELECT c.id $fieldlist
4171 FROM {course_categories} c
4172 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
4173 $contextlimitsql
4174 $orderby", array_merge([CONTEXT_COURSECAT], $contextlimitparams));
4175 $basedlimit = $limit;
4176 foreach ($rs as $category) {
4177 $categories[] = $category;
4178 $basedlimit--;
4179 if ($basedlimit == 0) {
4180 break;
4185 $courses = [];
4186 $fieldlist = \core\access\get_user_capability_course_helper::map_fieldnames($coursefieldsexceptid);
4187 if ($courseorderby) {
4188 $fields = explode(',', $courseorderby);
4189 $courseorderby = '';
4190 foreach ($fields as $field) {
4191 if ($courseorderby) {
4192 $courseorderby .= ',';
4194 $courseorderby .= 'c.'.$field;
4196 $courseorderby = 'ORDER BY '.$courseorderby;
4198 $rs = $DB->get_recordset_sql("
4199 SELECT c.id $fieldlist
4200 FROM {course} c
4201 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
4202 $contextlimitsql
4203 $courseorderby", array_merge([CONTEXT_COURSE], $contextlimitparams));
4204 foreach ($rs as $course) {
4205 $courses[] = $course;
4206 $limit--;
4207 if ($limit == 0) {
4208 break;
4211 $rs->close();
4212 return [$categories, $courses];
4216 * This function gets the list of courses that this user has a particular capability in.
4218 * It is now reasonably efficient, but bear in mind that if there are users who have the capability
4219 * everywhere, it may return an array of all courses.
4221 * @param string $capability Capability in question
4222 * @param int $userid User ID or null for current user
4223 * @param bool $doanything True if 'doanything' is permitted (default)
4224 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4225 * otherwise use a comma-separated list of the fields you require, not including id.
4226 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
4227 * @param string $orderby If set, use a comma-separated list of fields from course
4228 * table with sql modifiers (DESC) if needed
4229 * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
4230 * @return array|bool Array of courses, if none found false is returned.
4232 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '',
4233 $orderby = '', $limit = 0) {
4234 list($categories, $courses) = get_user_capability_contexts(
4235 $capability,
4236 false,
4237 $userid,
4238 $doanything,
4239 $fieldsexceptid,
4241 $orderby,
4243 $limit
4245 return $courses;
4249 * Switches the current user to another role for the current session and only
4250 * in the given context.
4252 * The caller *must* check
4253 * - that this op is allowed
4254 * - that the requested role can be switched to in this context (use get_switchable_roles)
4255 * - that the requested role is NOT $CFG->defaultuserroleid
4257 * To "unswitch" pass 0 as the roleid.
4259 * This function *will* modify $USER->access - beware
4261 * @param integer $roleid the role to switch to.
4262 * @param context $context the context in which to perform the switch.
4263 * @return bool success or failure.
4265 function role_switch($roleid, context $context) {
4266 global $USER;
4268 // Add the ghost RA to $USER->access as $USER->access['rsw'][$path] = $roleid.
4269 // To un-switch just unset($USER->access['rsw'][$path]).
4271 // Note: it is not possible to switch to roles that do not have course:view
4273 if (!isset($USER->access)) {
4274 load_all_capabilities();
4277 // Add the switch RA
4278 if ($roleid == 0) {
4279 unset($USER->access['rsw'][$context->path]);
4280 return true;
4283 $USER->access['rsw'][$context->path] = $roleid;
4285 return true;
4289 * Checks if the user has switched roles within the given course.
4291 * Note: You can only switch roles within the course, hence it takes a course id
4292 * rather than a context. On that note Petr volunteered to implement this across
4293 * all other contexts, all requests for this should be forwarded to him ;)
4295 * @param int $courseid The id of the course to check
4296 * @return bool True if the user has switched roles within the course.
4298 function is_role_switched($courseid) {
4299 global $USER;
4300 $context = context_course::instance($courseid, MUST_EXIST);
4301 return (!empty($USER->access['rsw'][$context->path]));
4305 * Get any role that has an override on exact context
4307 * @param context $context The context to check
4308 * @return array An array of roles
4310 function get_roles_with_override_on_context(context $context) {
4311 global $DB;
4313 return $DB->get_records_sql("SELECT r.*
4314 FROM {role_capabilities} rc, {role} r
4315 WHERE rc.roleid = r.id AND rc.contextid = ?",
4316 array($context->id));
4320 * Get all capabilities for this role on this context (overrides)
4322 * @param stdClass $role
4323 * @param context $context
4324 * @return array
4326 function get_capabilities_from_role_on_context($role, context $context) {
4327 global $DB;
4329 return $DB->get_records_sql("SELECT *
4330 FROM {role_capabilities}
4331 WHERE contextid = ? AND roleid = ?",
4332 array($context->id, $role->id));
4336 * Find all user assignment of users for this role, on this context
4338 * @param stdClass $role
4339 * @param context $context
4340 * @return array
4342 function get_users_from_role_on_context($role, context $context) {
4343 global $DB;
4345 return $DB->get_records_sql("SELECT *
4346 FROM {role_assignments}
4347 WHERE contextid = ? AND roleid = ?",
4348 array($context->id, $role->id));
4352 * Simple function returning a boolean true if user has roles
4353 * in context or parent contexts, otherwise false.
4355 * @param int $userid
4356 * @param int $roleid
4357 * @param int $contextid empty means any context
4358 * @return bool
4360 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4361 global $DB;
4363 if ($contextid) {
4364 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4365 return false;
4367 $parents = $context->get_parent_context_ids(true);
4368 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4369 $params['userid'] = $userid;
4370 $params['roleid'] = $roleid;
4372 $sql = "SELECT COUNT(ra.id)
4373 FROM {role_assignments} ra
4374 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4376 $count = $DB->get_field_sql($sql, $params);
4377 return ($count > 0);
4379 } else {
4380 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4385 * Get localised role name or alias if exists and format the text.
4387 * @param stdClass $role role object
4388 * - optional 'coursealias' property should be included for performance reasons if course context used
4389 * - description property is not required here
4390 * @param context|bool $context empty means system context
4391 * @param int $rolenamedisplay type of role name
4392 * @return string localised role name or course role name alias
4394 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4395 global $DB;
4397 if ($rolenamedisplay == ROLENAME_SHORT) {
4398 return $role->shortname;
4401 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4402 $coursecontext = null;
4405 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4406 $role = clone($role); // Do not modify parameters.
4407 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4408 $role->coursealias = $r->name;
4409 } else {
4410 $role->coursealias = null;
4414 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4415 if ($coursecontext) {
4416 return $role->coursealias;
4417 } else {
4418 return null;
4422 if (trim($role->name) !== '') {
4423 // For filtering always use context where was the thing defined - system for roles here.
4424 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4426 } else {
4427 // Empty role->name means we want to see localised role name based on shortname,
4428 // only default roles are supposed to be localised.
4429 switch ($role->shortname) {
4430 case 'manager': $original = get_string('manager', 'role'); break;
4431 case 'coursecreator': $original = get_string('coursecreators'); break;
4432 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4433 case 'teacher': $original = get_string('noneditingteacher'); break;
4434 case 'student': $original = get_string('defaultcoursestudent'); break;
4435 case 'guest': $original = get_string('guest'); break;
4436 case 'user': $original = get_string('authenticateduser'); break;
4437 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4438 // We should not get here, the role UI should require the name for custom roles!
4439 default: $original = $role->shortname; break;
4443 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4444 return $original;
4447 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4448 return "$original ($role->shortname)";
4451 if ($rolenamedisplay == ROLENAME_ALIAS) {
4452 if ($coursecontext and trim($role->coursealias) !== '') {
4453 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4454 } else {
4455 return $original;
4459 if ($rolenamedisplay == ROLENAME_BOTH) {
4460 if ($coursecontext and trim($role->coursealias) !== '') {
4461 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4462 } else {
4463 return $original;
4467 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4471 * Returns localised role description if available.
4472 * If the name is empty it tries to find the default role name using
4473 * hardcoded list of default role names or other methods in the future.
4475 * @param stdClass $role
4476 * @return string localised role name
4478 function role_get_description(stdClass $role) {
4479 if (!html_is_blank($role->description)) {
4480 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4483 switch ($role->shortname) {
4484 case 'manager': return get_string('managerdescription', 'role');
4485 case 'coursecreator': return get_string('coursecreatorsdescription');
4486 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4487 case 'teacher': return get_string('noneditingteacherdescription');
4488 case 'student': return get_string('defaultcoursestudentdescription');
4489 case 'guest': return get_string('guestdescription');
4490 case 'user': return get_string('authenticateduserdescription');
4491 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4492 default: return '';
4497 * Get all the localised role names for a context.
4499 * In new installs default roles have empty names, this function
4500 * add localised role names using current language pack.
4502 * @param context $context the context, null means system context
4503 * @param array of role objects with a ->localname field containing the context-specific role name.
4504 * @param int $rolenamedisplay
4505 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4506 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4508 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4509 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4513 * Prepare list of roles for display, apply aliases and localise default role names.
4515 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4516 * @param context $context the context, null means system context
4517 * @param int $rolenamedisplay
4518 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4519 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4521 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4522 global $DB;
4524 if (empty($roleoptions)) {
4525 return array();
4528 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4529 $coursecontext = null;
4532 // We usually need all role columns...
4533 $first = reset($roleoptions);
4534 if ($returnmenu === null) {
4535 $returnmenu = !is_object($first);
4538 if (!is_object($first) or !property_exists($first, 'shortname')) {
4539 $allroles = get_all_roles($context);
4540 foreach ($roleoptions as $rid => $unused) {
4541 $roleoptions[$rid] = $allroles[$rid];
4545 // Inject coursealias if necessary.
4546 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4547 $first = reset($roleoptions);
4548 if (!property_exists($first, 'coursealias')) {
4549 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4550 foreach ($aliasnames as $alias) {
4551 if (isset($roleoptions[$alias->roleid])) {
4552 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4558 // Add localname property.
4559 foreach ($roleoptions as $rid => $role) {
4560 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4563 if (!$returnmenu) {
4564 return $roleoptions;
4567 $menu = array();
4568 foreach ($roleoptions as $rid => $role) {
4569 $menu[$rid] = $role->localname;
4572 return $menu;
4576 * Aids in detecting if a new line is required when reading a new capability
4578 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4579 * when we read in a new capability.
4580 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4581 * but when we are in grade, all reports/import/export capabilities should be together
4583 * @param string $cap component string a
4584 * @param string $comp component string b
4585 * @param int $contextlevel
4586 * @return bool whether 2 component are in different "sections"
4588 function component_level_changed($cap, $comp, $contextlevel) {
4590 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4591 $compsa = explode('/', $cap->component);
4592 $compsb = explode('/', $comp);
4594 // list of system reports
4595 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4596 return false;
4599 // we are in gradebook, still
4600 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4601 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4602 return false;
4605 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4606 return false;
4610 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4614 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4615 * and return an array of roleids in order.
4617 * @param array $allroles array of roles, as returned by get_all_roles();
4618 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4620 function fix_role_sortorder($allroles) {
4621 global $DB;
4623 $rolesort = array();
4624 $i = 0;
4625 foreach ($allroles as $role) {
4626 $rolesort[$i] = $role->id;
4627 if ($role->sortorder != $i) {
4628 $r = new stdClass();
4629 $r->id = $role->id;
4630 $r->sortorder = $i;
4631 $DB->update_record('role', $r);
4632 $allroles[$role->id]->sortorder = $i;
4634 $i++;
4636 return $rolesort;
4640 * Switch the sort order of two roles (used in admin/roles/manage.php).
4642 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4643 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4644 * @return boolean success or failure
4646 function switch_roles($first, $second) {
4647 global $DB;
4648 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4649 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4650 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4651 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4652 return $result;
4656 * Duplicates all the base definitions of a role
4658 * @param stdClass $sourcerole role to copy from
4659 * @param int $targetrole id of role to copy to
4661 function role_cap_duplicate($sourcerole, $targetrole) {
4662 global $DB;
4664 $systemcontext = context_system::instance();
4665 $caps = $DB->get_records_sql("SELECT *
4666 FROM {role_capabilities}
4667 WHERE roleid = ? AND contextid = ?",
4668 array($sourcerole->id, $systemcontext->id));
4669 // adding capabilities
4670 foreach ($caps as $cap) {
4671 unset($cap->id);
4672 $cap->roleid = $targetrole;
4673 $DB->insert_record('role_capabilities', $cap);
4676 // Reset any cache of this role, including MUC.
4677 accesslib_clear_role_cache($targetrole);
4681 * Returns two lists, this can be used to find out if user has capability.
4682 * Having any needed role and no forbidden role in this context means
4683 * user has this capability in this context.
4684 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4686 * @param stdClass $context
4687 * @param string $capability
4688 * @return array($neededroles, $forbiddenroles)
4690 function get_roles_with_cap_in_context($context, $capability) {
4691 global $DB;
4693 $ctxids = trim($context->path, '/'); // kill leading slash
4694 $ctxids = str_replace('/', ',', $ctxids);
4696 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4697 FROM {role_capabilities} rc
4698 JOIN {context} ctx ON ctx.id = rc.contextid
4699 JOIN {capabilities} cap ON rc.capability = cap.name
4700 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4701 ORDER BY rc.roleid ASC, ctx.depth DESC";
4702 $params = array('cap'=>$capability);
4704 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4705 // no cap definitions --> no capability
4706 return array(array(), array());
4709 $forbidden = array();
4710 $needed = array();
4711 foreach ($capdefs as $def) {
4712 if (isset($forbidden[$def->roleid])) {
4713 continue;
4715 if ($def->permission == CAP_PROHIBIT) {
4716 $forbidden[$def->roleid] = $def->roleid;
4717 unset($needed[$def->roleid]);
4718 continue;
4720 if (!isset($needed[$def->roleid])) {
4721 if ($def->permission == CAP_ALLOW) {
4722 $needed[$def->roleid] = true;
4723 } else if ($def->permission == CAP_PREVENT) {
4724 $needed[$def->roleid] = false;
4728 unset($capdefs);
4730 // remove all those roles not allowing
4731 foreach ($needed as $key=>$value) {
4732 if (!$value) {
4733 unset($needed[$key]);
4734 } else {
4735 $needed[$key] = $key;
4739 return array($needed, $forbidden);
4743 * Returns an array of role IDs that have ALL of the the supplied capabilities
4744 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4746 * @param stdClass $context
4747 * @param array $capabilities An array of capabilities
4748 * @return array of roles with all of the required capabilities
4750 function get_roles_with_caps_in_context($context, $capabilities) {
4751 $neededarr = array();
4752 $forbiddenarr = array();
4753 foreach ($capabilities as $caprequired) {
4754 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4757 $rolesthatcanrate = array();
4758 if (!empty($neededarr)) {
4759 foreach ($neededarr as $needed) {
4760 if (empty($rolesthatcanrate)) {
4761 $rolesthatcanrate = $needed;
4762 } else {
4763 //only want roles that have all caps
4764 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4768 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4769 foreach ($forbiddenarr as $forbidden) {
4770 //remove any roles that are forbidden any of the caps
4771 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4774 return $rolesthatcanrate;
4778 * Returns an array of role names that have ALL of the the supplied capabilities
4779 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4781 * @param stdClass $context
4782 * @param array $capabilities An array of capabilities
4783 * @return array of roles with all of the required capabilities
4785 function get_role_names_with_caps_in_context($context, $capabilities) {
4786 global $DB;
4788 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4789 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4791 $roles = array();
4792 foreach ($rolesthatcanrate as $r) {
4793 $roles[$r] = $allroles[$r];
4796 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4800 * This function verifies the prohibit comes from this context
4801 * and there are no more prohibits in parent contexts.
4803 * @param int $roleid
4804 * @param context $context
4805 * @param string $capability name
4806 * @return bool
4808 function prohibit_is_removable($roleid, context $context, $capability) {
4809 global $DB;
4811 $ctxids = trim($context->path, '/'); // kill leading slash
4812 $ctxids = str_replace('/', ',', $ctxids);
4814 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4816 $sql = "SELECT ctx.id
4817 FROM {role_capabilities} rc
4818 JOIN {context} ctx ON ctx.id = rc.contextid
4819 JOIN {capabilities} cap ON rc.capability = cap.name
4820 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4821 ORDER BY ctx.depth DESC";
4823 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4824 // no prohibits == nothing to remove
4825 return true;
4828 if (count($prohibits) > 1) {
4829 // more prohibits can not be removed
4830 return false;
4833 return !empty($prohibits[$context->id]);
4837 * More user friendly role permission changing,
4838 * it should produce as few overrides as possible.
4840 * @param int $roleid
4841 * @param stdClass $context
4842 * @param string $capname capability name
4843 * @param int $permission
4844 * @return void
4846 function role_change_permission($roleid, $context, $capname, $permission) {
4847 global $DB;
4849 if ($permission == CAP_INHERIT) {
4850 unassign_capability($capname, $roleid, $context->id);
4851 return;
4854 $ctxids = trim($context->path, '/'); // kill leading slash
4855 $ctxids = str_replace('/', ',', $ctxids);
4857 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4859 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4860 FROM {role_capabilities} rc
4861 JOIN {context} ctx ON ctx.id = rc.contextid
4862 JOIN {capabilities} cap ON rc.capability = cap.name
4863 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4864 ORDER BY ctx.depth DESC";
4866 if ($existing = $DB->get_records_sql($sql, $params)) {
4867 foreach ($existing as $e) {
4868 if ($e->permission == CAP_PROHIBIT) {
4869 // prohibit can not be overridden, no point in changing anything
4870 return;
4873 $lowest = array_shift($existing);
4874 if ($lowest->permission == $permission) {
4875 // permission already set in this context or parent - nothing to do
4876 return;
4878 if ($existing) {
4879 $parent = array_shift($existing);
4880 if ($parent->permission == $permission) {
4881 // permission already set in parent context or parent - just unset in this context
4882 // we do this because we want as few overrides as possible for performance reasons
4883 unassign_capability($capname, $roleid, $context->id);
4884 return;
4888 } else {
4889 if ($permission == CAP_PREVENT) {
4890 // nothing means role does not have permission
4891 return;
4895 // assign the needed capability
4896 assign_capability($capname, $permission, $roleid, $context->id, true);
4901 * Basic moodle context abstraction class.
4903 * Google confirms that no other important framework is using "context" class,
4904 * we could use something else like mcontext or moodle_context, but we need to type
4905 * this very often which would be annoying and it would take too much space...
4907 * This class is derived from stdClass for backwards compatibility with
4908 * odl $context record that was returned from DML $DB->get_record()
4910 * @package core_access
4911 * @category access
4912 * @copyright Petr Skoda {@link http://skodak.org}
4913 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4914 * @since Moodle 2.2
4916 * @property-read int $id context id
4917 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4918 * @property-read int $instanceid id of related instance in each context
4919 * @property-read string $path path to context, starts with system context
4920 * @property-read int $depth
4922 abstract class context extends stdClass implements IteratorAggregate {
4924 /** @var string Default sorting of capabilities in {@see get_capabilities} */
4925 protected const DEFAULT_CAPABILITY_SORT = 'contextlevel, component, name';
4928 * The context id
4929 * Can be accessed publicly through $context->id
4930 * @var int
4932 protected $_id;
4935 * The context level
4936 * Can be accessed publicly through $context->contextlevel
4937 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4939 protected $_contextlevel;
4942 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4943 * Can be accessed publicly through $context->instanceid
4944 * @var int
4946 protected $_instanceid;
4949 * The path to the context always starting from the system context
4950 * Can be accessed publicly through $context->path
4951 * @var string
4953 protected $_path;
4956 * The depth of the context in relation to parent contexts
4957 * Can be accessed publicly through $context->depth
4958 * @var int
4960 protected $_depth;
4963 * Whether this context is locked or not.
4965 * Can be accessed publicly through $context->locked.
4967 * @var int
4969 protected $_locked;
4972 * @var array Context caching info
4974 private static $cache_contextsbyid = array();
4977 * @var array Context caching info
4979 private static $cache_contexts = array();
4982 * Context count
4983 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4984 * @var int
4986 protected static $cache_count = 0;
4989 * @var array Context caching info
4991 protected static $cache_preloaded = array();
4994 * @var context_system The system context once initialised
4996 protected static $systemcontext = null;
4999 * Resets the cache to remove all data.
5000 * @static
5002 protected static function reset_caches() {
5003 self::$cache_contextsbyid = array();
5004 self::$cache_contexts = array();
5005 self::$cache_count = 0;
5006 self::$cache_preloaded = array();
5008 self::$systemcontext = null;
5012 * Adds a context to the cache. If the cache is full, discards a batch of
5013 * older entries.
5015 * @static
5016 * @param context $context New context to add
5017 * @return void
5019 protected static function cache_add(context $context) {
5020 if (isset(self::$cache_contextsbyid[$context->id])) {
5021 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5022 return;
5025 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
5026 $i = 0;
5027 foreach (self::$cache_contextsbyid as $ctx) {
5028 $i++;
5029 if ($i <= 100) {
5030 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
5031 continue;
5033 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
5034 // we remove oldest third of the contexts to make room for more contexts
5035 break;
5037 unset(self::$cache_contextsbyid[$ctx->id]);
5038 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
5039 self::$cache_count--;
5043 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
5044 self::$cache_contextsbyid[$context->id] = $context;
5045 self::$cache_count++;
5049 * Removes a context from the cache.
5051 * @static
5052 * @param context $context Context object to remove
5053 * @return void
5055 protected static function cache_remove(context $context) {
5056 if (!isset(self::$cache_contextsbyid[$context->id])) {
5057 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5058 return;
5060 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
5061 unset(self::$cache_contextsbyid[$context->id]);
5063 self::$cache_count--;
5065 if (self::$cache_count < 0) {
5066 self::$cache_count = 0;
5071 * Gets a context from the cache.
5073 * @static
5074 * @param int $contextlevel Context level
5075 * @param int $instance Instance ID
5076 * @return context|bool Context or false if not in cache
5078 protected static function cache_get($contextlevel, $instance) {
5079 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
5080 return self::$cache_contexts[$contextlevel][$instance];
5082 return false;
5086 * Gets a context from the cache based on its id.
5088 * @static
5089 * @param int $id Context ID
5090 * @return context|bool Context or false if not in cache
5092 protected static function cache_get_by_id($id) {
5093 if (isset(self::$cache_contextsbyid[$id])) {
5094 return self::$cache_contextsbyid[$id];
5096 return false;
5100 * Preloads context information from db record and strips the cached info.
5102 * @static
5103 * @param stdClass $rec
5104 * @return void (modifies $rec)
5106 protected static function preload_from_record(stdClass $rec) {
5107 $notenoughdata = false;
5108 $notenoughdata = $notenoughdata || empty($rec->ctxid);
5109 $notenoughdata = $notenoughdata || empty($rec->ctxlevel);
5110 $notenoughdata = $notenoughdata || !isset($rec->ctxinstance);
5111 $notenoughdata = $notenoughdata || empty($rec->ctxpath);
5112 $notenoughdata = $notenoughdata || empty($rec->ctxdepth);
5113 $notenoughdata = $notenoughdata || !isset($rec->ctxlocked);
5114 if ($notenoughdata) {
5115 // The record does not have enough data, passed here repeatedly or context does not exist yet.
5116 if (isset($rec->ctxid) && !isset($rec->ctxlocked)) {
5117 debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER);
5119 return;
5122 $record = (object) [
5123 'id' => $rec->ctxid,
5124 'contextlevel' => $rec->ctxlevel,
5125 'instanceid' => $rec->ctxinstance,
5126 'path' => $rec->ctxpath,
5127 'depth' => $rec->ctxdepth,
5128 'locked' => $rec->ctxlocked,
5131 unset($rec->ctxid);
5132 unset($rec->ctxlevel);
5133 unset($rec->ctxinstance);
5134 unset($rec->ctxpath);
5135 unset($rec->ctxdepth);
5136 unset($rec->ctxlocked);
5138 return context::create_instance_from_record($record);
5142 // ====== magic methods =======
5145 * Magic setter method, we do not want anybody to modify properties from the outside
5146 * @param string $name
5147 * @param mixed $value
5149 public function __set($name, $value) {
5150 debugging('Can not change context instance properties!');
5154 * Magic method getter, redirects to read only values.
5155 * @param string $name
5156 * @return mixed
5158 public function __get($name) {
5159 switch ($name) {
5160 case 'id':
5161 return $this->_id;
5162 case 'contextlevel':
5163 return $this->_contextlevel;
5164 case 'instanceid':
5165 return $this->_instanceid;
5166 case 'path':
5167 return $this->_path;
5168 case 'depth':
5169 return $this->_depth;
5170 case 'locked':
5171 return $this->is_locked();
5173 default:
5174 debugging('Invalid context property accessed! '.$name);
5175 return null;
5180 * Full support for isset on our magic read only properties.
5181 * @param string $name
5182 * @return bool
5184 public function __isset($name) {
5185 switch ($name) {
5186 case 'id':
5187 return isset($this->_id);
5188 case 'contextlevel':
5189 return isset($this->_contextlevel);
5190 case 'instanceid':
5191 return isset($this->_instanceid);
5192 case 'path':
5193 return isset($this->_path);
5194 case 'depth':
5195 return isset($this->_depth);
5196 case 'locked':
5197 // Locked is always set.
5198 return true;
5199 default:
5200 return false;
5205 * All properties are read only, sorry.
5206 * @param string $name
5208 public function __unset($name) {
5209 debugging('Can not unset context instance properties!');
5212 // ====== implementing method from interface IteratorAggregate ======
5215 * Create an iterator because magic vars can't be seen by 'foreach'.
5217 * Now we can convert context object to array using convert_to_array(),
5218 * and feed it properly to json_encode().
5220 public function getIterator() {
5221 $ret = array(
5222 'id' => $this->id,
5223 'contextlevel' => $this->contextlevel,
5224 'instanceid' => $this->instanceid,
5225 'path' => $this->path,
5226 'depth' => $this->depth,
5227 'locked' => $this->locked,
5229 return new ArrayIterator($ret);
5232 // ====== general context methods ======
5235 * Constructor is protected so that devs are forced to
5236 * use context_xxx::instance() or context::instance_by_id().
5238 * @param stdClass $record
5240 protected function __construct(stdClass $record) {
5241 $this->_id = (int)$record->id;
5242 $this->_contextlevel = (int)$record->contextlevel;
5243 $this->_instanceid = $record->instanceid;
5244 $this->_path = $record->path;
5245 $this->_depth = $record->depth;
5247 if (isset($record->locked)) {
5248 $this->_locked = $record->locked;
5249 } else if (!during_initial_install() && !moodle_needs_upgrading()) {
5250 debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER);
5255 * This function is also used to work around 'protected' keyword problems in context_helper.
5256 * @static
5257 * @param stdClass $record
5258 * @return context instance
5260 protected static function create_instance_from_record(stdClass $record) {
5261 $classname = context_helper::get_class_for_level($record->contextlevel);
5263 if ($context = context::cache_get_by_id($record->id)) {
5264 return $context;
5267 $context = new $classname($record);
5268 context::cache_add($context);
5270 return $context;
5274 * Copy prepared new contexts from temp table to context table,
5275 * we do this in db specific way for perf reasons only.
5276 * @static
5278 protected static function merge_context_temp_table() {
5279 global $DB;
5281 /* MDL-11347:
5282 * - mysql does not allow to use FROM in UPDATE statements
5283 * - using two tables after UPDATE works in mysql, but might give unexpected
5284 * results in pg 8 (depends on configuration)
5285 * - using table alias in UPDATE does not work in pg < 8.2
5287 * Different code for each database - mostly for performance reasons
5290 $dbfamily = $DB->get_dbfamily();
5291 if ($dbfamily == 'mysql') {
5292 $updatesql = "UPDATE {context} ct, {context_temp} temp
5293 SET ct.path = temp.path,
5294 ct.depth = temp.depth,
5295 ct.locked = temp.locked
5296 WHERE ct.id = temp.id";
5297 } else if ($dbfamily == 'oracle') {
5298 $updatesql = "UPDATE {context} ct
5299 SET (ct.path, ct.depth, ct.locked) =
5300 (SELECT temp.path, temp.depth, temp.locked
5301 FROM {context_temp} temp
5302 WHERE temp.id=ct.id)
5303 WHERE EXISTS (SELECT 'x'
5304 FROM {context_temp} temp
5305 WHERE temp.id = ct.id)";
5306 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5307 $updatesql = "UPDATE {context}
5308 SET path = temp.path,
5309 depth = temp.depth,
5310 locked = temp.locked
5311 FROM {context_temp} temp
5312 WHERE temp.id={context}.id";
5313 } else {
5314 // sqlite and others
5315 $updatesql = "UPDATE {context}
5316 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5317 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id),
5318 locked = (SELECT locked FROM {context_temp} WHERE id = {context}.id)
5319 WHERE id IN (SELECT id FROM {context_temp})";
5322 $DB->execute($updatesql);
5326 * Get a context instance as an object, from a given context id.
5328 * @static
5329 * @param int $id context id
5330 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5331 * MUST_EXIST means throw exception if no record found
5332 * @return context|bool the context object or false if not found
5334 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5335 global $DB;
5337 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5338 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5339 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5342 if ($id == SYSCONTEXTID) {
5343 return context_system::instance(0, $strictness);
5346 if (is_array($id) or is_object($id) or empty($id)) {
5347 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5350 if ($context = context::cache_get_by_id($id)) {
5351 return $context;
5354 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5355 return context::create_instance_from_record($record);
5358 return false;
5362 * Update context info after moving context in the tree structure.
5364 * @param context $newparent
5365 * @return void
5367 public function update_moved(context $newparent) {
5368 global $DB;
5370 $frompath = $this->_path;
5371 $newpath = $newparent->path . '/' . $this->_id;
5373 $trans = $DB->start_delegated_transaction();
5375 $setdepth = '';
5376 if (($newparent->depth +1) != $this->_depth) {
5377 $diff = $newparent->depth - $this->_depth + 1;
5378 $setdepth = ", depth = depth + $diff";
5380 $sql = "UPDATE {context}
5381 SET path = ?
5382 $setdepth
5383 WHERE id = ?";
5384 $params = array($newpath, $this->_id);
5385 $DB->execute($sql, $params);
5387 $this->_path = $newpath;
5388 $this->_depth = $newparent->depth + 1;
5390 $sql = "UPDATE {context}
5391 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5392 $setdepth
5393 WHERE path LIKE ?";
5394 $params = array($newpath, "{$frompath}/%");
5395 $DB->execute($sql, $params);
5397 $this->mark_dirty();
5399 context::reset_caches();
5401 $trans->allow_commit();
5405 * Set whether this context has been locked or not.
5407 * @param bool $locked
5408 * @return $this
5410 public function set_locked(bool $locked) {
5411 global $DB;
5413 if ($this->_locked == $locked) {
5414 return $this;
5417 $this->_locked = $locked;
5418 $DB->set_field('context', 'locked', (int) $locked, ['id' => $this->id]);
5419 $this->mark_dirty();
5421 if ($locked) {
5422 $eventname = '\\core\\event\\context_locked';
5423 } else {
5424 $eventname = '\\core\\event\\context_unlocked';
5426 $event = $eventname::create(['context' => $this, 'objectid' => $this->id]);
5427 $event->trigger();
5429 self::reset_caches();
5431 return $this;
5435 * Remove all context path info and optionally rebuild it.
5437 * @param bool $rebuild
5438 * @return void
5440 public function reset_paths($rebuild = true) {
5441 global $DB;
5443 if ($this->_path) {
5444 $this->mark_dirty();
5446 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5447 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5448 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5449 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5450 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5451 $this->_depth = 0;
5452 $this->_path = null;
5455 if ($rebuild) {
5456 context_helper::build_all_paths(false);
5459 context::reset_caches();
5463 * Delete all data linked to content, do not delete the context record itself
5465 public function delete_content() {
5466 global $CFG, $DB;
5468 blocks_delete_all_for_context($this->_id);
5469 filter_delete_all_for_context($this->_id);
5471 require_once($CFG->dirroot . '/comment/lib.php');
5472 comment::delete_comments(array('contextid'=>$this->_id));
5474 require_once($CFG->dirroot.'/rating/lib.php');
5475 $delopt = new stdclass();
5476 $delopt->contextid = $this->_id;
5477 $rm = new rating_manager();
5478 $rm->delete_ratings($delopt);
5480 // delete all files attached to this context
5481 $fs = get_file_storage();
5482 $fs->delete_area_files($this->_id);
5484 // Delete all repository instances attached to this context.
5485 require_once($CFG->dirroot . '/repository/lib.php');
5486 repository::delete_all_for_context($this->_id);
5488 // delete all advanced grading data attached to this context
5489 require_once($CFG->dirroot.'/grade/grading/lib.php');
5490 grading_manager::delete_all_for_context($this->_id);
5492 // now delete stuff from role related tables, role_unassign_all
5493 // and unenrol should be called earlier to do proper cleanup
5494 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5495 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5496 $this->delete_capabilities();
5500 * Unassign all capabilities from a context.
5502 public function delete_capabilities() {
5503 global $DB;
5505 $ids = $DB->get_fieldset_select('role_capabilities', 'DISTINCT roleid', 'contextid = ?', array($this->_id));
5506 if ($ids) {
5507 $DB->delete_records('role_capabilities', array('contextid' => $this->_id));
5509 // Reset any cache of these roles, including MUC.
5510 accesslib_clear_role_cache($ids);
5515 * Delete the context content and the context record itself
5517 public function delete() {
5518 global $DB;
5520 if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5521 throw new coding_exception('Cannot delete system context');
5524 // double check the context still exists
5525 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5526 context::cache_remove($this);
5527 return;
5530 $this->delete_content();
5531 $DB->delete_records('context', array('id'=>$this->_id));
5532 // purge static context cache if entry present
5533 context::cache_remove($this);
5535 // Inform search engine to delete data related to this context.
5536 \core_search\manager::context_deleted($this);
5539 // ====== context level related methods ======
5542 * Utility method for context creation
5544 * @static
5545 * @param int $contextlevel
5546 * @param int $instanceid
5547 * @param string $parentpath
5548 * @return stdClass context record
5550 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5551 global $DB;
5553 $record = new stdClass();
5554 $record->contextlevel = $contextlevel;
5555 $record->instanceid = $instanceid;
5556 $record->depth = 0;
5557 $record->path = null; //not known before insert
5558 $record->locked = 0;
5560 $record->id = $DB->insert_record('context', $record);
5562 // now add path if known - it can be added later
5563 if (!is_null($parentpath)) {
5564 $record->path = $parentpath.'/'.$record->id;
5565 $record->depth = substr_count($record->path, '/');
5566 $DB->update_record('context', $record);
5569 return $record;
5573 * Returns human readable context identifier.
5575 * @param boolean $withprefix whether to prefix the name of the context with the
5576 * type of context, e.g. User, Course, Forum, etc.
5577 * @param boolean $short whether to use the short name of the thing. Only applies
5578 * to course contexts
5579 * @param boolean $escape Whether the returned name of the thing is to be
5580 * HTML escaped or not.
5581 * @return string the human readable context name.
5583 public function get_context_name($withprefix = true, $short = false, $escape = true) {
5584 // must be implemented in all context levels
5585 throw new coding_exception('can not get name of abstract context');
5589 * Whether the current context is locked.
5591 * @return bool
5593 public function is_locked() {
5594 if ($this->_locked) {
5595 return true;
5598 if ($parent = $this->get_parent_context()) {
5599 return $parent->is_locked();
5602 return false;
5606 * Returns the most relevant URL for this context.
5608 * @return moodle_url
5610 public abstract function get_url();
5613 * Returns array of relevant context capability records.
5615 * @param string $sort SQL order by snippet for sorting returned capabilities sensibly for display
5616 * @return array
5618 public abstract function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT);
5621 * Recursive function which, given a context, find all its children context ids.
5623 * For course category contexts it will return immediate children and all subcategory contexts.
5624 * It will NOT recurse into courses or subcategories categories.
5625 * If you want to do that, call it on the returned courses/categories.
5627 * When called for a course context, it will return the modules and blocks
5628 * displayed in the course page and blocks displayed on the module pages.
5630 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5631 * contexts ;-)
5633 * @return array Array of child records
5635 public function get_child_contexts() {
5636 global $DB;
5638 if (empty($this->_path) or empty($this->_depth)) {
5639 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5640 return array();
5643 $sql = "SELECT ctx.*
5644 FROM {context} ctx
5645 WHERE ctx.path LIKE ?";
5646 $params = array($this->_path.'/%');
5647 $records = $DB->get_records_sql($sql, $params);
5649 $result = array();
5650 foreach ($records as $record) {
5651 $result[$record->id] = context::create_instance_from_record($record);
5654 return $result;
5658 * Determine if the current context is a parent of the possible child.
5660 * @param context $possiblechild
5661 * @param bool $includeself Whether to check the current context
5662 * @return bool
5664 public function is_parent_of(context $possiblechild, bool $includeself): bool {
5665 // A simple substring check is used on the context path.
5666 // The possible child's path is used as a haystack, with the current context as the needle.
5667 // The path is prefixed with '+' to ensure that the parent always starts at the top.
5668 // It is suffixed with '+' to ensure that parents are not included.
5669 // The needle always suffixes with a '/' to ensure that the contextid uses a complete match (i.e. 142/ instead of 14).
5670 // The haystack is suffixed with '/+' if $includeself is true to allow the current context to match.
5671 // The haystack is suffixed with '+' if $includeself is false to prevent the current context from matching.
5672 $haystacksuffix = $includeself ? '/+' : '+';
5674 $strpos = strpos(
5675 "+{$possiblechild->path}{$haystacksuffix}",
5676 "+{$this->path}/"
5678 return $strpos === 0;
5682 * Returns parent contexts of this context in reversed order, i.e. parent first,
5683 * then grand parent, etc.
5685 * @param bool $includeself true means include self too
5686 * @return array of context instances
5688 public function get_parent_contexts($includeself = false) {
5689 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5690 return array();
5693 // Preload the contexts to reduce DB calls.
5694 context_helper::preload_contexts_by_id($contextids);
5696 $result = array();
5697 foreach ($contextids as $contextid) {
5698 $parent = context::instance_by_id($contextid, MUST_EXIST);
5699 $result[$parent->id] = $parent;
5702 return $result;
5706 * Determine if the current context is a child of the possible parent.
5708 * @param context $possibleparent
5709 * @param bool $includeself Whether to check the current context
5710 * @return bool
5712 public function is_child_of(context $possibleparent, bool $includeself): bool {
5713 // A simple substring check is used on the context path.
5714 // The current context is used as a haystack, with the possible parent as the needle.
5715 // The path is prefixed with '+' to ensure that the parent always starts at the top.
5716 // It is suffixed with '+' to ensure that children are not included.
5717 // The needle always suffixes with a '/' to ensure that the contextid uses a complete match (i.e. 142/ instead of 14).
5718 // The haystack is suffixed with '/+' if $includeself is true to allow the current context to match.
5719 // The haystack is suffixed with '+' if $includeself is false to prevent the current context from matching.
5720 $haystacksuffix = $includeself ? '/+' : '+';
5722 $strpos = strpos(
5723 "+{$this->path}{$haystacksuffix}",
5724 "+{$possibleparent->path}/"
5726 return $strpos === 0;
5730 * Returns parent context ids of this context in reversed order, i.e. parent first,
5731 * then grand parent, etc.
5733 * @param bool $includeself true means include self too
5734 * @return array of context ids
5736 public function get_parent_context_ids($includeself = false) {
5737 if (empty($this->_path)) {
5738 return array();
5741 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5742 $parentcontexts = explode('/', $parentcontexts);
5743 if (!$includeself) {
5744 array_pop($parentcontexts); // and remove its own id
5747 return array_reverse($parentcontexts);
5751 * Returns parent context paths of this context.
5753 * @param bool $includeself true means include self too
5754 * @return array of context paths
5756 public function get_parent_context_paths($includeself = false) {
5757 if (empty($this->_path)) {
5758 return array();
5761 $contextids = explode('/', $this->_path);
5763 $path = '';
5764 $paths = array();
5765 foreach ($contextids as $contextid) {
5766 if ($contextid) {
5767 $path .= '/' . $contextid;
5768 $paths[$contextid] = $path;
5772 if (!$includeself) {
5773 unset($paths[$this->_id]);
5776 return $paths;
5780 * Returns parent context
5782 * @return context
5784 public function get_parent_context() {
5785 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5786 return false;
5789 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5790 $parentcontexts = explode('/', $parentcontexts);
5791 array_pop($parentcontexts); // self
5792 $contextid = array_pop($parentcontexts); // immediate parent
5794 return context::instance_by_id($contextid, MUST_EXIST);
5798 * Is this context part of any course? If yes return course context.
5800 * @param bool $strict true means throw exception if not found, false means return false if not found
5801 * @return context_course context of the enclosing course, null if not found or exception
5803 public function get_course_context($strict = true) {
5804 if ($strict) {
5805 throw new coding_exception('Context does not belong to any course.');
5806 } else {
5807 return false;
5812 * Returns sql necessary for purging of stale context instances.
5814 * @static
5815 * @return string cleanup SQL
5817 protected static function get_cleanup_sql() {
5818 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5822 * Rebuild context paths and depths at context level.
5824 * @static
5825 * @param bool $force
5826 * @return void
5828 protected static function build_paths($force) {
5829 throw new coding_exception('build_paths() method must be implemented in all context levels');
5833 * Create missing context instances at given level
5835 * @static
5836 * @return void
5838 protected static function create_level_instances() {
5839 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5843 * Reset all cached permissions and definitions if the necessary.
5844 * @return void
5846 public function reload_if_dirty() {
5847 global $ACCESSLIB_PRIVATE, $USER;
5849 // Load dirty contexts list if needed
5850 if (CLI_SCRIPT) {
5851 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5852 // we do not load dirty flags in CLI and cron
5853 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5855 } else {
5856 if (!isset($USER->access['time'])) {
5857 // Nothing has been loaded yet, so we do not need to check dirty flags now.
5858 return;
5861 // From skodak: No idea why -2 is there, server cluster time difference maybe...
5862 $changedsince = $USER->access['time'] - 2;
5864 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5865 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $changedsince);
5868 if (!isset($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
5869 $ACCESSLIB_PRIVATE->dirtyusers[$USER->id] = get_cache_flag('accesslib/dirtyusers', $USER->id, $changedsince);
5873 $dirty = false;
5875 if (!empty($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
5876 $dirty = true;
5877 } else if (!empty($ACCESSLIB_PRIVATE->dirtycontexts)) {
5878 $paths = $this->get_parent_context_paths(true);
5880 foreach ($paths as $path) {
5881 if (isset($ACCESSLIB_PRIVATE->dirtycontexts[$path])) {
5882 $dirty = true;
5883 break;
5888 if ($dirty) {
5889 // Reload all capabilities of USER and others - preserving loginas, roleswitches, etc.
5890 // Then cleanup any marks of dirtyness... at least from our short term memory!
5891 reload_all_capabilities();
5896 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5898 public function mark_dirty() {
5899 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5901 if (during_initial_install()) {
5902 return;
5905 // only if it is a non-empty string
5906 if (is_string($this->_path) && $this->_path !== '') {
5907 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5908 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5909 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5910 } else {
5911 if (CLI_SCRIPT) {
5912 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5913 } else {
5914 if (isset($USER->access['time'])) {
5915 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5916 } else {
5917 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5919 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5928 * Context maintenance and helper methods.
5930 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5931 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5932 * level implementation from the rest of code, the code completion returns what developers need.
5934 * Thank you Tim Hunt for helping me with this nasty trick.
5936 * @package core_access
5937 * @category access
5938 * @copyright Petr Skoda {@link http://skodak.org}
5939 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5940 * @since Moodle 2.2
5942 class context_helper extends context {
5945 * @var array An array mapping context levels to classes
5947 private static $alllevels;
5950 * Instance does not make sense here, only static use
5952 protected function __construct() {
5956 * Reset internal context levels array.
5958 public static function reset_levels() {
5959 self::$alllevels = null;
5963 * Initialise context levels, call before using self::$alllevels.
5965 private static function init_levels() {
5966 global $CFG;
5968 if (isset(self::$alllevels)) {
5969 return;
5971 self::$alllevels = array(
5972 CONTEXT_SYSTEM => 'context_system',
5973 CONTEXT_USER => 'context_user',
5974 CONTEXT_COURSECAT => 'context_coursecat',
5975 CONTEXT_COURSE => 'context_course',
5976 CONTEXT_MODULE => 'context_module',
5977 CONTEXT_BLOCK => 'context_block',
5980 if (empty($CFG->custom_context_classes)) {
5981 return;
5984 $levels = $CFG->custom_context_classes;
5985 if (!is_array($levels)) {
5986 $levels = @unserialize($levels);
5988 if (!is_array($levels)) {
5989 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
5990 return;
5993 // Unsupported custom levels, use with care!!!
5994 foreach ($levels as $level => $classname) {
5995 self::$alllevels[$level] = $classname;
5997 ksort(self::$alllevels);
6001 * Returns a class name of the context level class
6003 * @static
6004 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
6005 * @return string class name of the context class
6007 public static function get_class_for_level($contextlevel) {
6008 self::init_levels();
6009 if (isset(self::$alllevels[$contextlevel])) {
6010 return self::$alllevels[$contextlevel];
6011 } else {
6012 throw new coding_exception('Invalid context level specified');
6017 * Returns a list of all context levels
6019 * @static
6020 * @return array int=>string (level=>level class name)
6022 public static function get_all_levels() {
6023 self::init_levels();
6024 return self::$alllevels;
6028 * Remove stale contexts that belonged to deleted instances.
6029 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
6031 * @static
6032 * @return void
6034 public static function cleanup_instances() {
6035 global $DB;
6036 self::init_levels();
6038 $sqls = array();
6039 foreach (self::$alllevels as $level=>$classname) {
6040 $sqls[] = $classname::get_cleanup_sql();
6043 $sql = implode(" UNION ", $sqls);
6045 // it is probably better to use transactions, it might be faster too
6046 $transaction = $DB->start_delegated_transaction();
6048 $rs = $DB->get_recordset_sql($sql);
6049 foreach ($rs as $record) {
6050 $context = context::create_instance_from_record($record);
6051 $context->delete();
6053 $rs->close();
6055 $transaction->allow_commit();
6059 * Create all context instances at the given level and above.
6061 * @static
6062 * @param int $contextlevel null means all levels
6063 * @param bool $buildpaths
6064 * @return void
6066 public static function create_instances($contextlevel = null, $buildpaths = true) {
6067 self::init_levels();
6068 foreach (self::$alllevels as $level=>$classname) {
6069 if ($contextlevel and $level > $contextlevel) {
6070 // skip potential sub-contexts
6071 continue;
6073 $classname::create_level_instances();
6074 if ($buildpaths) {
6075 $classname::build_paths(false);
6081 * Rebuild paths and depths in all context levels.
6083 * @static
6084 * @param bool $force false means add missing only
6085 * @return void
6087 public static function build_all_paths($force = false) {
6088 self::init_levels();
6089 foreach (self::$alllevels as $classname) {
6090 $classname::build_paths($force);
6093 // reset static course cache - it might have incorrect cached data
6094 accesslib_clear_all_caches(true);
6098 * Resets the cache to remove all data.
6099 * @static
6101 public static function reset_caches() {
6102 context::reset_caches();
6106 * Returns all fields necessary for context preloading from user $rec.
6108 * This helps with performance when dealing with hundreds of contexts.
6110 * @static
6111 * @param string $tablealias context table alias in the query
6112 * @return array (table.column=>alias, ...)
6114 public static function get_preload_record_columns($tablealias) {
6115 return [
6116 "$tablealias.id" => "ctxid",
6117 "$tablealias.path" => "ctxpath",
6118 "$tablealias.depth" => "ctxdepth",
6119 "$tablealias.contextlevel" => "ctxlevel",
6120 "$tablealias.instanceid" => "ctxinstance",
6121 "$tablealias.locked" => "ctxlocked",
6126 * Returns all fields necessary for context preloading from user $rec.
6128 * This helps with performance when dealing with hundreds of contexts.
6130 * @static
6131 * @param string $tablealias context table alias in the query
6132 * @return string
6134 public static function get_preload_record_columns_sql($tablealias) {
6135 return "$tablealias.id AS ctxid, " .
6136 "$tablealias.path AS ctxpath, " .
6137 "$tablealias.depth AS ctxdepth, " .
6138 "$tablealias.contextlevel AS ctxlevel, " .
6139 "$tablealias.instanceid AS ctxinstance, " .
6140 "$tablealias.locked AS ctxlocked";
6144 * Preloads context information from db record and strips the cached info.
6146 * The db request has to contain all columns from context_helper::get_preload_record_columns().
6148 * @static
6149 * @param stdClass $rec
6150 * @return void (modifies $rec)
6152 public static function preload_from_record(stdClass $rec) {
6153 context::preload_from_record($rec);
6157 * Preload a set of contexts using their contextid.
6159 * @param array $contextids
6161 public static function preload_contexts_by_id(array $contextids) {
6162 global $DB;
6164 // Determine which contexts are not already cached.
6165 $tofetch = [];
6166 foreach ($contextids as $contextid) {
6167 if (!self::cache_get_by_id($contextid)) {
6168 $tofetch[] = $contextid;
6172 if (count($tofetch) > 1) {
6173 // There are at least two to fetch.
6174 // There is no point only fetching a single context as this would be no more efficient than calling the existing code.
6175 list($insql, $inparams) = $DB->get_in_or_equal($tofetch, SQL_PARAMS_NAMED);
6176 $ctxs = $DB->get_records_select('context', "id {$insql}", $inparams, '',
6177 \context_helper::get_preload_record_columns_sql('{context}'));
6178 foreach ($ctxs as $ctx) {
6179 self::preload_from_record($ctx);
6185 * Preload all contexts instances from course.
6187 * To be used if you expect multiple queries for course activities...
6189 * @static
6190 * @param int $courseid
6192 public static function preload_course($courseid) {
6193 // Users can call this multiple times without doing any harm
6194 if (isset(context::$cache_preloaded[$courseid])) {
6195 return;
6197 $coursecontext = context_course::instance($courseid);
6198 $coursecontext->get_child_contexts();
6200 context::$cache_preloaded[$courseid] = true;
6204 * Delete context instance
6206 * @static
6207 * @param int $contextlevel
6208 * @param int $instanceid
6209 * @return void
6211 public static function delete_instance($contextlevel, $instanceid) {
6212 global $DB;
6214 // double check the context still exists
6215 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
6216 $context = context::create_instance_from_record($record);
6217 $context->delete();
6218 } else {
6219 // we should try to purge the cache anyway
6224 * Returns the name of specified context level
6226 * @static
6227 * @param int $contextlevel
6228 * @return string name of the context level
6230 public static function get_level_name($contextlevel) {
6231 $classname = context_helper::get_class_for_level($contextlevel);
6232 return $classname::get_level_name();
6236 * Gets the current context to be used for navigation tree filtering.
6238 * @param context|null $context The current context to be checked against.
6239 * @return context|null the context that navigation tree filtering should use.
6241 public static function get_navigation_filter_context(?context $context): ?context {
6242 global $CFG;
6243 if (!empty($CFG->filternavigationwithsystemcontext)) {
6244 return context_system::instance();
6245 } else {
6246 return $context;
6251 * not used
6253 public function get_url() {
6257 * not used
6259 * @param string $sort
6261 public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
6267 * System context class
6269 * @package core_access
6270 * @category access
6271 * @copyright Petr Skoda {@link http://skodak.org}
6272 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6273 * @since Moodle 2.2
6275 class context_system extends context {
6277 * Please use context_system::instance() if you need the instance of context.
6279 * @param stdClass $record
6281 protected function __construct(stdClass $record) {
6282 parent::__construct($record);
6283 if ($record->contextlevel != CONTEXT_SYSTEM) {
6284 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
6289 * Returns human readable context level name.
6291 * @static
6292 * @return string the human readable context level name.
6294 public static function get_level_name() {
6295 return get_string('coresystem');
6299 * Returns human readable context identifier.
6301 * @param boolean $withprefix does not apply to system context
6302 * @param boolean $short does not apply to system context
6303 * @param boolean $escape does not apply to system context
6304 * @return string the human readable context name.
6306 public function get_context_name($withprefix = true, $short = false, $escape = true) {
6307 return self::get_level_name();
6311 * Returns the most relevant URL for this context.
6313 * @return moodle_url
6315 public function get_url() {
6316 return new moodle_url('/');
6320 * Returns array of relevant context capability records.
6322 * @param string $sort
6323 * @return array
6325 public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
6326 global $DB;
6328 return $DB->get_records('capabilities', [], $sort);
6332 * Create missing context instances at system context
6333 * @static
6335 protected static function create_level_instances() {
6336 // nothing to do here, the system context is created automatically in installer
6337 self::instance(0);
6341 * Returns system context instance.
6343 * @static
6344 * @param int $instanceid should be 0
6345 * @param int $strictness
6346 * @param bool $cache
6347 * @return context_system context instance
6349 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
6350 global $DB;
6352 if ($instanceid != 0) {
6353 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
6356 // SYSCONTEXTID is cached in local cache to eliminate 1 query per page.
6357 if (defined('SYSCONTEXTID') and $cache) {
6358 if (!isset(context::$systemcontext)) {
6359 $record = new stdClass();
6360 $record->id = SYSCONTEXTID;
6361 $record->contextlevel = CONTEXT_SYSTEM;
6362 $record->instanceid = 0;
6363 $record->path = '/'.SYSCONTEXTID;
6364 $record->depth = 1;
6365 $record->locked = 0;
6366 context::$systemcontext = new context_system($record);
6368 return context::$systemcontext;
6371 try {
6372 // We ignore the strictness completely because system context must exist except during install.
6373 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6374 } catch (dml_exception $e) {
6375 //table or record does not exist
6376 if (!during_initial_install()) {
6377 // do not mess with system context after install, it simply must exist
6378 throw $e;
6380 $record = null;
6383 if (!$record) {
6384 $record = new stdClass();
6385 $record->contextlevel = CONTEXT_SYSTEM;
6386 $record->instanceid = 0;
6387 $record->depth = 1;
6388 $record->path = null; // Not known before insert.
6389 $record->locked = 0;
6391 try {
6392 if ($DB->count_records('context')) {
6393 // contexts already exist, this is very weird, system must be first!!!
6394 return null;
6396 if (defined('SYSCONTEXTID')) {
6397 // this would happen only in unittest on sites that went through weird 1.7 upgrade
6398 $record->id = SYSCONTEXTID;
6399 $DB->import_record('context', $record);
6400 $DB->get_manager()->reset_sequence('context');
6401 } else {
6402 $record->id = $DB->insert_record('context', $record);
6404 } catch (dml_exception $e) {
6405 // can not create context - table does not exist yet, sorry
6406 return null;
6410 if ($record->instanceid != 0) {
6411 // this is very weird, somebody must be messing with context table
6412 debugging('Invalid system context detected');
6415 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6416 // fix path if necessary, initial install or path reset
6417 $record->depth = 1;
6418 $record->path = '/'.$record->id;
6419 $DB->update_record('context', $record);
6422 if (empty($record->locked)) {
6423 $record->locked = 0;
6426 if (!defined('SYSCONTEXTID')) {
6427 define('SYSCONTEXTID', $record->id);
6430 context::$systemcontext = new context_system($record);
6431 return context::$systemcontext;
6435 * Returns all site contexts except the system context, DO NOT call on production servers!!
6437 * Contexts are not cached.
6439 * @return array
6441 public function get_child_contexts() {
6442 global $DB;
6444 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6446 // Just get all the contexts except for CONTEXT_SYSTEM level
6447 // and hope we don't OOM in the process - don't cache
6448 $sql = "SELECT c.*
6449 FROM {context} c
6450 WHERE contextlevel > ".CONTEXT_SYSTEM;
6451 $records = $DB->get_records_sql($sql);
6453 $result = array();
6454 foreach ($records as $record) {
6455 $result[$record->id] = context::create_instance_from_record($record);
6458 return $result;
6462 * Returns sql necessary for purging of stale context instances.
6464 * @static
6465 * @return string cleanup SQL
6467 protected static function get_cleanup_sql() {
6468 $sql = "
6469 SELECT c.*
6470 FROM {context} c
6471 WHERE 1=2
6474 return $sql;
6478 * Rebuild context paths and depths at system context level.
6480 * @static
6481 * @param bool $force
6483 protected static function build_paths($force) {
6484 global $DB;
6486 /* note: ignore $force here, we always do full test of system context */
6488 // exactly one record must exist
6489 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6491 if ($record->instanceid != 0) {
6492 debugging('Invalid system context detected');
6495 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6496 debugging('Invalid SYSCONTEXTID detected');
6499 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6500 // fix path if necessary, initial install or path reset
6501 $record->depth = 1;
6502 $record->path = '/'.$record->id;
6503 $DB->update_record('context', $record);
6508 * Set whether this context has been locked or not.
6510 * @param bool $locked
6511 * @return $this
6513 public function set_locked(bool $locked) {
6514 throw new \coding_exception('It is not possible to lock the system context');
6516 return $this;
6522 * User context class
6524 * @package core_access
6525 * @category access
6526 * @copyright Petr Skoda {@link http://skodak.org}
6527 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6528 * @since Moodle 2.2
6530 class context_user extends context {
6532 * Please use context_user::instance($userid) if you need the instance of context.
6533 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6535 * @param stdClass $record
6537 protected function __construct(stdClass $record) {
6538 parent::__construct($record);
6539 if ($record->contextlevel != CONTEXT_USER) {
6540 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6545 * Returns human readable context level name.
6547 * @static
6548 * @return string the human readable context level name.
6550 public static function get_level_name() {
6551 return get_string('user');
6555 * Returns human readable context identifier.
6557 * @param boolean $withprefix whether to prefix the name of the context with User
6558 * @param boolean $short does not apply to user context
6559 * @param boolean $escape does not apply to user context
6560 * @return string the human readable context name.
6562 public function get_context_name($withprefix = true, $short = false, $escape = true) {
6563 global $DB;
6565 $name = '';
6566 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6567 if ($withprefix){
6568 $name = get_string('user').': ';
6570 $name .= fullname($user);
6572 return $name;
6576 * Returns the most relevant URL for this context.
6578 * @return moodle_url
6580 public function get_url() {
6581 global $COURSE;
6583 if ($COURSE->id == SITEID) {
6584 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6585 } else {
6586 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6588 return $url;
6592 * Returns array of relevant context capability records.
6594 * @param string $sort
6595 * @return array
6597 public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
6598 global $DB;
6600 $extracaps = array('moodle/grade:viewall');
6601 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6603 return $DB->get_records_select('capabilities', "contextlevel = :level OR name {$extra}",
6604 $params + ['level' => CONTEXT_USER], $sort);
6608 * Returns user context instance.
6610 * @static
6611 * @param int $userid id from {user} table
6612 * @param int $strictness
6613 * @return context_user context instance
6615 public static function instance($userid, $strictness = MUST_EXIST) {
6616 global $DB;
6618 if ($context = context::cache_get(CONTEXT_USER, $userid)) {
6619 return $context;
6622 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER, 'instanceid' => $userid))) {
6623 if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6624 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6628 if ($record) {
6629 $context = new context_user($record);
6630 context::cache_add($context);
6631 return $context;
6634 return false;
6638 * Create missing context instances at user context level
6639 * @static
6641 protected static function create_level_instances() {
6642 global $DB;
6644 $sql = "SELECT ".CONTEXT_USER.", u.id
6645 FROM {user} u
6646 WHERE u.deleted = 0
6647 AND NOT EXISTS (SELECT 'x'
6648 FROM {context} cx
6649 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6650 $contextdata = $DB->get_recordset_sql($sql);
6651 foreach ($contextdata as $context) {
6652 context::insert_context_record(CONTEXT_USER, $context->id, null);
6654 $contextdata->close();
6658 * Returns sql necessary for purging of stale context instances.
6660 * @static
6661 * @return string cleanup SQL
6663 protected static function get_cleanup_sql() {
6664 $sql = "
6665 SELECT c.*
6666 FROM {context} c
6667 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6668 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6671 return $sql;
6675 * Rebuild context paths and depths at user context level.
6677 * @static
6678 * @param bool $force
6680 protected static function build_paths($force) {
6681 global $DB;
6683 // First update normal users.
6684 $path = $DB->sql_concat('?', 'id');
6685 $pathstart = '/' . SYSCONTEXTID . '/';
6686 $params = array($pathstart);
6688 if ($force) {
6689 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6690 $params[] = $pathstart;
6691 } else {
6692 $where = "depth = 0 OR path IS NULL";
6695 $sql = "UPDATE {context}
6696 SET depth = 2,
6697 path = {$path}
6698 WHERE contextlevel = " . CONTEXT_USER . "
6699 AND ($where)";
6700 $DB->execute($sql, $params);
6706 * Course category context class
6708 * @package core_access
6709 * @category access
6710 * @copyright Petr Skoda {@link http://skodak.org}
6711 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6712 * @since Moodle 2.2
6714 class context_coursecat extends context {
6716 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6717 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6719 * @param stdClass $record
6721 protected function __construct(stdClass $record) {
6722 parent::__construct($record);
6723 if ($record->contextlevel != CONTEXT_COURSECAT) {
6724 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6729 * Returns human readable context level name.
6731 * @static
6732 * @return string the human readable context level name.
6734 public static function get_level_name() {
6735 return get_string('category');
6739 * Returns human readable context identifier.
6741 * @param boolean $withprefix whether to prefix the name of the context with Category
6742 * @param boolean $short does not apply to course categories
6743 * @param boolean $escape Whether the returned name of the context is to be HTML escaped or not.
6744 * @return string the human readable context name.
6746 public function get_context_name($withprefix = true, $short = false, $escape = true) {
6747 global $DB;
6749 $name = '';
6750 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6751 if ($withprefix){
6752 $name = get_string('category').': ';
6754 if (!$escape) {
6755 $name .= format_string($category->name, true, array('context' => $this, 'escape' => false));
6756 } else {
6757 $name .= format_string($category->name, true, array('context' => $this));
6760 return $name;
6764 * Returns the most relevant URL for this context.
6766 * @return moodle_url
6768 public function get_url() {
6769 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6773 * Returns array of relevant context capability records.
6775 * @param string $sort
6776 * @return array
6778 public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
6779 global $DB;
6781 return $DB->get_records_list('capabilities', 'contextlevel', [
6782 CONTEXT_COURSECAT,
6783 CONTEXT_COURSE,
6784 CONTEXT_MODULE,
6785 CONTEXT_BLOCK,
6786 ], $sort);
6790 * Returns course category context instance.
6792 * @static
6793 * @param int $categoryid id from {course_categories} table
6794 * @param int $strictness
6795 * @return context_coursecat context instance
6797 public static function instance($categoryid, $strictness = MUST_EXIST) {
6798 global $DB;
6800 if ($context = context::cache_get(CONTEXT_COURSECAT, $categoryid)) {
6801 return $context;
6804 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT, 'instanceid' => $categoryid))) {
6805 if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6806 if ($category->parent) {
6807 $parentcontext = context_coursecat::instance($category->parent);
6808 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6809 } else {
6810 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6815 if ($record) {
6816 $context = new context_coursecat($record);
6817 context::cache_add($context);
6818 return $context;
6821 return false;
6825 * Returns immediate child contexts of category and all subcategories,
6826 * children of subcategories and courses are not returned.
6828 * @return array
6830 public function get_child_contexts() {
6831 global $DB;
6833 if (empty($this->_path) or empty($this->_depth)) {
6834 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6835 return array();
6838 $sql = "SELECT ctx.*
6839 FROM {context} ctx
6840 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6841 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6842 $records = $DB->get_records_sql($sql, $params);
6844 $result = array();
6845 foreach ($records as $record) {
6846 $result[$record->id] = context::create_instance_from_record($record);
6849 return $result;
6853 * Create missing context instances at course category context level
6854 * @static
6856 protected static function create_level_instances() {
6857 global $DB;
6859 $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6860 FROM {course_categories} cc
6861 WHERE NOT EXISTS (SELECT 'x'
6862 FROM {context} cx
6863 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6864 $contextdata = $DB->get_recordset_sql($sql);
6865 foreach ($contextdata as $context) {
6866 context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6868 $contextdata->close();
6872 * Returns sql necessary for purging of stale context instances.
6874 * @static
6875 * @return string cleanup SQL
6877 protected static function get_cleanup_sql() {
6878 $sql = "
6879 SELECT c.*
6880 FROM {context} c
6881 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6882 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6885 return $sql;
6889 * Rebuild context paths and depths at course category context level.
6891 * @static
6892 * @param bool $force
6894 protected static function build_paths($force) {
6895 global $DB;
6897 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6898 if ($force) {
6899 $ctxemptyclause = $emptyclause = '';
6900 } else {
6901 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6902 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6905 $base = '/'.SYSCONTEXTID;
6907 // Normal top level categories
6908 $sql = "UPDATE {context}
6909 SET depth=2,
6910 path=".$DB->sql_concat("'$base/'", 'id')."
6911 WHERE contextlevel=".CONTEXT_COURSECAT."
6912 AND EXISTS (SELECT 'x'
6913 FROM {course_categories} cc
6914 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6915 $emptyclause";
6916 $DB->execute($sql);
6918 // Deeper categories - one query per depthlevel
6919 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6920 for ($n=2; $n<=$maxdepth; $n++) {
6921 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
6922 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
6923 FROM {context} ctx
6924 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6925 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6926 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6927 $ctxemptyclause";
6928 $trans = $DB->start_delegated_transaction();
6929 $DB->delete_records('context_temp');
6930 $DB->execute($sql);
6931 context::merge_context_temp_table();
6932 $DB->delete_records('context_temp');
6933 $trans->allow_commit();
6942 * Course context class
6944 * @package core_access
6945 * @category access
6946 * @copyright Petr Skoda {@link http://skodak.org}
6947 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6948 * @since Moodle 2.2
6950 class context_course extends context {
6952 * Please use context_course::instance($courseid) if you need the instance of context.
6953 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6955 * @param stdClass $record
6957 protected function __construct(stdClass $record) {
6958 parent::__construct($record);
6959 if ($record->contextlevel != CONTEXT_COURSE) {
6960 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6965 * Returns human readable context level name.
6967 * @static
6968 * @return string the human readable context level name.
6970 public static function get_level_name() {
6971 return get_string('course');
6975 * Returns human readable context identifier.
6977 * @param boolean $withprefix whether to prefix the name of the context with Course
6978 * @param boolean $short whether to use the short name of the thing.
6979 * @param bool $escape Whether the returned category name is to be HTML escaped or not.
6980 * @return string the human readable context name.
6982 public function get_context_name($withprefix = true, $short = false, $escape = true) {
6983 global $DB;
6985 $name = '';
6986 if ($this->_instanceid == SITEID) {
6987 $name = get_string('frontpage', 'admin');
6988 } else {
6989 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6990 if ($withprefix){
6991 $name = get_string('course').': ';
6993 if ($short){
6994 if (!$escape) {
6995 $name .= format_string($course->shortname, true, array('context' => $this, 'escape' => false));
6996 } else {
6997 $name .= format_string($course->shortname, true, array('context' => $this));
6999 } else {
7000 if (!$escape) {
7001 $name .= format_string(get_course_display_name_for_list($course), true, array('context' => $this,
7002 'escape' => false));
7003 } else {
7004 $name .= format_string(get_course_display_name_for_list($course), true, array('context' => $this));
7009 return $name;
7013 * Returns the most relevant URL for this context.
7015 * @return moodle_url
7017 public function get_url() {
7018 if ($this->_instanceid != SITEID) {
7019 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
7022 return new moodle_url('/');
7026 * Returns array of relevant context capability records.
7028 * @param string $sort
7029 * @return array
7031 public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
7032 global $DB;
7034 return $DB->get_records_list('capabilities', 'contextlevel', [
7035 CONTEXT_COURSE,
7036 CONTEXT_MODULE,
7037 CONTEXT_BLOCK,
7038 ], $sort);
7042 * Is this context part of any course? If yes return course context.
7044 * @param bool $strict true means throw exception if not found, false means return false if not found
7045 * @return context_course context of the enclosing course, null if not found or exception
7047 public function get_course_context($strict = true) {
7048 return $this;
7052 * Returns course context instance.
7054 * @static
7055 * @param int $courseid id from {course} table
7056 * @param int $strictness
7057 * @return context_course context instance
7059 public static function instance($courseid, $strictness = MUST_EXIST) {
7060 global $DB;
7062 if ($context = context::cache_get(CONTEXT_COURSE, $courseid)) {
7063 return $context;
7066 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $courseid))) {
7067 if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
7068 if ($course->category) {
7069 $parentcontext = context_coursecat::instance($course->category);
7070 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
7071 } else {
7072 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
7077 if ($record) {
7078 $context = new context_course($record);
7079 context::cache_add($context);
7080 return $context;
7083 return false;
7087 * Create missing context instances at course context level
7088 * @static
7090 protected static function create_level_instances() {
7091 global $DB;
7093 $sql = "SELECT ".CONTEXT_COURSE.", c.id
7094 FROM {course} c
7095 WHERE NOT EXISTS (SELECT 'x'
7096 FROM {context} cx
7097 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
7098 $contextdata = $DB->get_recordset_sql($sql);
7099 foreach ($contextdata as $context) {
7100 context::insert_context_record(CONTEXT_COURSE, $context->id, null);
7102 $contextdata->close();
7106 * Returns sql necessary for purging of stale context instances.
7108 * @static
7109 * @return string cleanup SQL
7111 protected static function get_cleanup_sql() {
7112 $sql = "
7113 SELECT c.*
7114 FROM {context} c
7115 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
7116 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
7119 return $sql;
7123 * Rebuild context paths and depths at course context level.
7125 * @static
7126 * @param bool $force
7128 protected static function build_paths($force) {
7129 global $DB;
7131 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
7132 if ($force) {
7133 $ctxemptyclause = $emptyclause = '';
7134 } else {
7135 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7136 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
7139 $base = '/'.SYSCONTEXTID;
7141 // Standard frontpage
7142 $sql = "UPDATE {context}
7143 SET depth = 2,
7144 path = ".$DB->sql_concat("'$base/'", 'id')."
7145 WHERE contextlevel = ".CONTEXT_COURSE."
7146 AND EXISTS (SELECT 'x'
7147 FROM {course} c
7148 WHERE c.id = {context}.instanceid AND c.category = 0)
7149 $emptyclause";
7150 $DB->execute($sql);
7152 // standard courses
7153 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7154 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7155 FROM {context} ctx
7156 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
7157 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
7158 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7159 $ctxemptyclause";
7160 $trans = $DB->start_delegated_transaction();
7161 $DB->delete_records('context_temp');
7162 $DB->execute($sql);
7163 context::merge_context_temp_table();
7164 $DB->delete_records('context_temp');
7165 $trans->allow_commit();
7172 * Course module context class
7174 * @package core_access
7175 * @category access
7176 * @copyright Petr Skoda {@link http://skodak.org}
7177 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7178 * @since Moodle 2.2
7180 class context_module extends context {
7182 * Please use context_module::instance($cmid) if you need the instance of context.
7183 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7185 * @param stdClass $record
7187 protected function __construct(stdClass $record) {
7188 parent::__construct($record);
7189 if ($record->contextlevel != CONTEXT_MODULE) {
7190 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
7195 * Returns human readable context level name.
7197 * @static
7198 * @return string the human readable context level name.
7200 public static function get_level_name() {
7201 return get_string('activitymodule');
7205 * Returns human readable context identifier.
7207 * @param boolean $withprefix whether to prefix the name of the context with the
7208 * module name, e.g. Forum, Glossary, etc.
7209 * @param boolean $short does not apply to module context
7210 * @param boolean $escape Whether the returned name of the context is to be HTML escaped or not.
7211 * @return string the human readable context name.
7213 public function get_context_name($withprefix = true, $short = false, $escape = true) {
7214 global $DB;
7216 $name = '';
7217 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
7218 FROM {course_modules} cm
7219 JOIN {modules} md ON md.id = cm.module
7220 WHERE cm.id = ?", array($this->_instanceid))) {
7221 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
7222 if ($withprefix){
7223 $name = get_string('modulename', $cm->modname).': ';
7225 if (!$escape) {
7226 $name .= format_string($mod->name, true, array('context' => $this, 'escape' => false));
7227 } else {
7228 $name .= format_string($mod->name, true, array('context' => $this));
7232 return $name;
7236 * Returns the most relevant URL for this context.
7238 * @return moodle_url
7240 public function get_url() {
7241 global $DB;
7243 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
7244 FROM {course_modules} cm
7245 JOIN {modules} md ON md.id = cm.module
7246 WHERE cm.id = ?", array($this->_instanceid))) {
7247 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
7250 return new moodle_url('/');
7254 * Returns array of relevant context capability records.
7256 * @param string $sort
7257 * @return array
7259 public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
7260 global $DB, $CFG;
7262 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
7263 $module = $DB->get_record('modules', array('id'=>$cm->module));
7265 $subcaps = array();
7267 $modulepath = "{$CFG->dirroot}/mod/{$module->name}";
7268 if (file_exists("{$modulepath}/db/subplugins.json")) {
7269 $subplugins = (array) json_decode(file_get_contents("{$modulepath}/db/subplugins.json"))->plugintypes;
7270 } else if (file_exists("{$modulepath}/db/subplugins.php")) {
7271 debugging('Use of subplugins.php has been deprecated. ' .
7272 'Please update your plugin to provide a subplugins.json file instead.',
7273 DEBUG_DEVELOPER);
7274 $subplugins = array(); // should be redefined in the file
7275 include("{$modulepath}/db/subplugins.php");
7278 if (!empty($subplugins)) {
7279 foreach (array_keys($subplugins) as $subplugintype) {
7280 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
7281 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
7286 $modfile = "{$modulepath}/lib.php";
7287 $extracaps = array();
7288 if (file_exists($modfile)) {
7289 include_once($modfile);
7290 $modfunction = $module->name.'_get_extra_capabilities';
7291 if (function_exists($modfunction)) {
7292 $extracaps = $modfunction();
7296 $extracaps = array_merge($subcaps, $extracaps);
7297 $extra = '';
7298 list($extra, $params) = $DB->get_in_or_equal(
7299 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
7300 if (!empty($extra)) {
7301 $extra = "OR name $extra";
7304 // Fetch the list of modules, and remove this one.
7305 $components = \core_component::get_component_list();
7306 $componentnames = $components['mod'];
7307 unset($componentnames["mod_{$module->name}"]);
7308 $componentnames = array_keys($componentnames);
7310 // Exclude all other modules.
7311 list($notcompsql, $notcompparams) = $DB->get_in_or_equal($componentnames, SQL_PARAMS_NAMED, 'notcomp', false);
7312 $params = array_merge($params, $notcompparams);
7315 // Exclude other component submodules.
7316 $i = 0;
7317 $ignorecomponents = [];
7318 foreach ($componentnames as $mod) {
7319 if ($subplugins = \core_component::get_subplugins($mod)) {
7320 foreach (array_keys($subplugins) as $subplugintype) {
7321 $paramname = "notlike{$i}";
7322 $ignorecomponents[] = $DB->sql_like('component', ":{$paramname}", true, true, true);
7323 $params[$paramname] = "{$subplugintype}_%";
7324 $i++;
7328 $notlikesql = "(" . implode(' AND ', $ignorecomponents) . ")";
7330 $sql = "SELECT *
7331 FROM {capabilities}
7332 WHERE (contextlevel = ".CONTEXT_MODULE."
7333 AND component {$notcompsql}
7334 AND {$notlikesql})
7335 $extra
7336 ORDER BY $sort";
7338 return $DB->get_records_sql($sql, $params);
7342 * Is this context part of any course? If yes return course context.
7344 * @param bool $strict true means throw exception if not found, false means return false if not found
7345 * @return context_course context of the enclosing course, null if not found or exception
7347 public function get_course_context($strict = true) {
7348 return $this->get_parent_context();
7352 * Returns module context instance.
7354 * @static
7355 * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
7356 * @param int $strictness
7357 * @return context_module context instance
7359 public static function instance($cmid, $strictness = MUST_EXIST) {
7360 global $DB;
7362 if ($context = context::cache_get(CONTEXT_MODULE, $cmid)) {
7363 return $context;
7366 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE, 'instanceid' => $cmid))) {
7367 if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
7368 $parentcontext = context_course::instance($cm->course);
7369 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
7373 if ($record) {
7374 $context = new context_module($record);
7375 context::cache_add($context);
7376 return $context;
7379 return false;
7383 * Create missing context instances at module context level
7384 * @static
7386 protected static function create_level_instances() {
7387 global $DB;
7389 $sql = "SELECT ".CONTEXT_MODULE.", cm.id
7390 FROM {course_modules} cm
7391 WHERE NOT EXISTS (SELECT 'x'
7392 FROM {context} cx
7393 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
7394 $contextdata = $DB->get_recordset_sql($sql);
7395 foreach ($contextdata as $context) {
7396 context::insert_context_record(CONTEXT_MODULE, $context->id, null);
7398 $contextdata->close();
7402 * Returns sql necessary for purging of stale context instances.
7404 * @static
7405 * @return string cleanup SQL
7407 protected static function get_cleanup_sql() {
7408 $sql = "
7409 SELECT c.*
7410 FROM {context} c
7411 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
7412 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
7415 return $sql;
7419 * Rebuild context paths and depths at module context level.
7421 * @static
7422 * @param bool $force
7424 protected static function build_paths($force) {
7425 global $DB;
7427 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
7428 if ($force) {
7429 $ctxemptyclause = '';
7430 } else {
7431 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7434 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7435 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7436 FROM {context} ctx
7437 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
7438 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
7439 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7440 $ctxemptyclause";
7441 $trans = $DB->start_delegated_transaction();
7442 $DB->delete_records('context_temp');
7443 $DB->execute($sql);
7444 context::merge_context_temp_table();
7445 $DB->delete_records('context_temp');
7446 $trans->allow_commit();
7453 * Block context class
7455 * @package core_access
7456 * @category access
7457 * @copyright Petr Skoda {@link http://skodak.org}
7458 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7459 * @since Moodle 2.2
7461 class context_block extends context {
7463 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
7464 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7466 * @param stdClass $record
7468 protected function __construct(stdClass $record) {
7469 parent::__construct($record);
7470 if ($record->contextlevel != CONTEXT_BLOCK) {
7471 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
7476 * Returns human readable context level name.
7478 * @static
7479 * @return string the human readable context level name.
7481 public static function get_level_name() {
7482 return get_string('block');
7486 * Returns human readable context identifier.
7488 * @param boolean $withprefix whether to prefix the name of the context with Block
7489 * @param boolean $short does not apply to block context
7490 * @param boolean $escape does not apply to block context
7491 * @return string the human readable context name.
7493 public function get_context_name($withprefix = true, $short = false, $escape = true) {
7494 global $DB, $CFG;
7496 $name = '';
7497 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
7498 global $CFG;
7499 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7500 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7501 $blockname = "block_$blockinstance->blockname";
7502 if ($blockobject = new $blockname()) {
7503 if ($withprefix){
7504 $name = get_string('block').': ';
7506 $name .= $blockobject->title;
7510 return $name;
7514 * Returns the most relevant URL for this context.
7516 * @return moodle_url
7518 public function get_url() {
7519 $parentcontexts = $this->get_parent_context();
7520 return $parentcontexts->get_url();
7524 * Returns array of relevant context capability records.
7526 * @param string $sort
7527 * @return array
7529 public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
7530 global $DB;
7532 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
7534 $select = '(contextlevel = :level AND component = :component)';
7535 $params = [
7536 'level' => CONTEXT_BLOCK,
7537 'component' => 'block_' . $bi->blockname,
7540 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7541 if ($extracaps) {
7542 list($extra, $extraparams) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7543 $select .= " OR name $extra";
7544 $params = array_merge($params, $extraparams);
7547 return $DB->get_records_select('capabilities', $select, $params, $sort);
7551 * Is this context part of any course? If yes return course context.
7553 * @param bool $strict true means throw exception if not found, false means return false if not found
7554 * @return context_course context of the enclosing course, null if not found or exception
7556 public function get_course_context($strict = true) {
7557 $parentcontext = $this->get_parent_context();
7558 return $parentcontext->get_course_context($strict);
7562 * Returns block context instance.
7564 * @static
7565 * @param int $blockinstanceid id from {block_instances} table.
7566 * @param int $strictness
7567 * @return context_block context instance
7569 public static function instance($blockinstanceid, $strictness = MUST_EXIST) {
7570 global $DB;
7572 if ($context = context::cache_get(CONTEXT_BLOCK, $blockinstanceid)) {
7573 return $context;
7576 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $blockinstanceid))) {
7577 if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
7578 $parentcontext = context::instance_by_id($bi->parentcontextid);
7579 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7583 if ($record) {
7584 $context = new context_block($record);
7585 context::cache_add($context);
7586 return $context;
7589 return false;
7593 * Block do not have child contexts...
7594 * @return array
7596 public function get_child_contexts() {
7597 return array();
7601 * Create missing context instances at block context level
7602 * @static
7604 protected static function create_level_instances() {
7605 global $DB;
7607 $sql = <<<EOF
7608 INSERT INTO {context} (
7609 contextlevel,
7610 instanceid
7611 ) SELECT
7612 :contextlevel,
7613 bi.id as instanceid
7614 FROM {block_instances} bi
7615 WHERE NOT EXISTS (
7616 SELECT 'x' FROM {context} cx WHERE bi.id = cx.instanceid AND cx.contextlevel = :existingcontextlevel
7618 EOF;
7620 $DB->execute($sql, [
7621 'contextlevel' => CONTEXT_BLOCK,
7622 'existingcontextlevel' => CONTEXT_BLOCK,
7627 * Returns sql necessary for purging of stale context instances.
7629 * @static
7630 * @return string cleanup SQL
7632 protected static function get_cleanup_sql() {
7633 $sql = "
7634 SELECT c.*
7635 FROM {context} c
7636 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7637 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7640 return $sql;
7644 * Rebuild context paths and depths at block context level.
7646 * @static
7647 * @param bool $force
7649 protected static function build_paths($force) {
7650 global $DB;
7652 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7653 if ($force) {
7654 $ctxemptyclause = '';
7655 } else {
7656 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7659 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7660 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7661 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7662 FROM {context} ctx
7663 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7664 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7665 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7666 $ctxemptyclause";
7667 $trans = $DB->start_delegated_transaction();
7668 $DB->delete_records('context_temp');
7669 $DB->execute($sql);
7670 context::merge_context_temp_table();
7671 $DB->delete_records('context_temp');
7672 $trans->allow_commit();
7678 // ============== DEPRECATED FUNCTIONS ==========================================
7679 // Old context related functions were deprecated in 2.0, it is recommended
7680 // to use context classes in new code. Old function can be used when
7681 // creating patches that are supposed to be backported to older stable branches.
7682 // These deprecated functions will not be removed in near future,
7683 // before removing devs will be warned with a debugging message first,
7684 // then we will add error message and only after that we can remove the functions
7685 // completely.
7688 * Runs get_records select on context table and returns the result
7689 * Does get_records_select on the context table, and returns the results ordered
7690 * by contextlevel, and then the natural sort order within each level.
7691 * for the purpose of $select, you need to know that the context table has been
7692 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7694 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7695 * @param array $params any parameters required by $select.
7696 * @return array the requested context records.
7698 function get_sorted_contexts($select, $params = array()) {
7700 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7702 global $DB;
7703 if ($select) {
7704 $select = 'WHERE ' . $select;
7706 return $DB->get_records_sql("
7707 SELECT ctx.*
7708 FROM {context} ctx
7709 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7710 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7711 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7712 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7713 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7714 $select
7715 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7716 ", $params);
7720 * Given context and array of users, returns array of users whose enrolment status is suspended,
7721 * or enrolment has expired or has not started. Also removes those users from the given array
7723 * @param context $context context in which suspended users should be extracted.
7724 * @param array $users list of users.
7725 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7726 * @return array list of suspended users.
7728 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7729 global $DB;
7731 // Get active enrolled users.
7732 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7733 $activeusers = $DB->get_records_sql($sql, $params);
7735 // Move suspended users to a separate array & remove from the initial one.
7736 $susers = array();
7737 if (sizeof($activeusers)) {
7738 foreach ($users as $userid => $user) {
7739 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7740 $susers[$userid] = $user;
7741 unset($users[$userid]);
7745 return $susers;
7749 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7750 * or enrolment has expired or not started.
7752 * @param context $context context in which user enrolment is checked.
7753 * @param bool $usecache Enable or disable (default) the request cache
7754 * @return array list of suspended user id's.
7756 function get_suspended_userids(context $context, $usecache = false) {
7757 global $DB;
7759 if ($usecache) {
7760 $cache = cache::make('core', 'suspended_userids');
7761 $susers = $cache->get($context->id);
7762 if ($susers !== false) {
7763 return $susers;
7767 $coursecontext = $context->get_course_context();
7768 $susers = array();
7770 // Front page users are always enrolled, so suspended list is empty.
7771 if ($coursecontext->instanceid != SITEID) {
7772 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7773 $susers = $DB->get_fieldset_sql($sql, $params);
7774 $susers = array_combine($susers, $susers);
7777 // Cache results for the remainder of this request.
7778 if ($usecache) {
7779 $cache->set($context->id, $susers);
7782 return $susers;
7786 * Gets sql for finding users with capability in the given context
7788 * @param context $context
7789 * @param string|array $capability Capability name or array of names.
7790 * If an array is provided then this is the equivalent of a logical 'OR',
7791 * i.e. the user needs to have one of these capabilities.
7792 * @return array($sql, $params)
7794 function get_with_capability_sql(context $context, $capability) {
7795 static $i = 0;
7796 $i++;
7797 $prefix = 'cu' . $i . '_';
7799 $capjoin = get_with_capability_join($context, $capability, $prefix . 'u.id');
7801 $sql = "SELECT DISTINCT {$prefix}u.id
7802 FROM {user} {$prefix}u
7803 $capjoin->joins
7804 WHERE {$prefix}u.deleted = 0 AND $capjoin->wheres";
7806 return array($sql, $capjoin->params);