MDL-67734 core_xapi: Fix MSSQL PHPUnit failure with duplicated id
[moodle.git] / lib / accesslib.php
blob6c419f2cb3af58af7f186912ccbb71e7fe8b183b
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 // Find out if user is admin - it is not possible to override the doanything in any way
525 // and it is not possible to switch to admin role either.
526 if ($doanything) {
527 if (is_siteadmin($userid)) {
528 if ($userid != $USER->id) {
529 return true;
531 // make sure switchrole is not used in this context
532 if (empty($USER->access['rsw'])) {
533 return true;
535 $parts = explode('/', trim($context->path, '/'));
536 $path = '';
537 $switched = false;
538 foreach ($parts as $part) {
539 $path .= '/' . $part;
540 if (!empty($USER->access['rsw'][$path])) {
541 $switched = true;
542 break;
545 if (!$switched) {
546 return true;
548 //ok, admin switched role in this context, let's use normal access control rules
552 // Careful check for staleness...
553 $context->reload_if_dirty();
555 if ($USER->id == $userid) {
556 if (!isset($USER->access)) {
557 load_all_capabilities();
559 $access =& $USER->access;
561 } else {
562 // make sure user accessdata is really loaded
563 get_user_accessdata($userid, true);
564 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
567 return has_capability_in_accessdata($capability, $context, $access);
571 * Check if the user has any one of several capabilities from a list.
573 * This is just a utility method that calls has_capability in a loop. Try to put
574 * the capabilities that most users are likely to have first in the list for best
575 * performance.
577 * @category access
578 * @see has_capability()
580 * @param array $capabilities an array of capability names.
581 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
582 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
583 * @param boolean $doanything If false, ignore effect of admin role assignment
584 * @return boolean true if the user has any of these capabilities. Otherwise false.
586 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
587 foreach ($capabilities as $capability) {
588 if (has_capability($capability, $context, $user, $doanything)) {
589 return true;
592 return false;
596 * Check if the user has all the capabilities in a list.
598 * This is just a utility method that calls has_capability in a loop. Try to put
599 * the capabilities that fewest users are likely to have first in the list for best
600 * performance.
602 * @category access
603 * @see has_capability()
605 * @param array $capabilities an array of capability names.
606 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
607 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
608 * @param boolean $doanything If false, ignore effect of admin role assignment
609 * @return boolean true if the user has all of these capabilities. Otherwise false.
611 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
612 foreach ($capabilities as $capability) {
613 if (!has_capability($capability, $context, $user, $doanything)) {
614 return false;
617 return true;
621 * Is course creator going to have capability in a new course?
623 * This is intended to be used in enrolment plugins before or during course creation,
624 * do not use after the course is fully created.
626 * @category access
628 * @param string $capability the name of the capability to check.
629 * @param context $context course or category context where is course going to be created
630 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
631 * @return boolean true if the user will have this capability.
633 * @throws coding_exception if different type of context submitted
635 function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) {
636 global $CFG;
638 if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) {
639 throw new coding_exception('Only course or course category context expected');
642 if (has_capability($capability, $context, $user)) {
643 // User already has the capability, it could be only removed if CAP_PROHIBIT
644 // was involved here, but we ignore that.
645 return true;
648 if (!has_capability('moodle/course:create', $context, $user)) {
649 return false;
652 if (!enrol_is_enabled('manual')) {
653 return false;
656 if (empty($CFG->creatornewroleid)) {
657 return false;
660 if ($context->contextlevel == CONTEXT_COURSE) {
661 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
662 return false;
664 } else {
665 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
666 return false;
670 // Most likely they will be enrolled after the course creation is finished,
671 // does the new role have the required capability?
672 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
673 return isset($neededroles[$CFG->creatornewroleid]);
677 * Check if the user is an admin at the site level.
679 * Please note that use of proper capabilities is always encouraged,
680 * this function is supposed to be used from core or for temporary hacks.
682 * @category access
684 * @param int|stdClass $user_or_id user id or user object
685 * @return bool true if user is one of the administrators, false otherwise
687 function is_siteadmin($user_or_id = null) {
688 global $CFG, $USER;
690 if ($user_or_id === null) {
691 $user_or_id = $USER;
694 if (empty($user_or_id)) {
695 return false;
697 if (!empty($user_or_id->id)) {
698 $userid = $user_or_id->id;
699 } else {
700 $userid = $user_or_id;
703 // Because this script is called many times (150+ for course page) with
704 // the same parameters, it is worth doing minor optimisations. This static
705 // cache stores the value for a single userid, saving about 2ms from course
706 // page load time without using significant memory. As the static cache
707 // also includes the value it depends on, this cannot break unit tests.
708 static $knownid, $knownresult, $knownsiteadmins;
709 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
710 return $knownresult;
712 $knownid = $userid;
713 $knownsiteadmins = $CFG->siteadmins;
715 $siteadmins = explode(',', $CFG->siteadmins);
716 $knownresult = in_array($userid, $siteadmins);
717 return $knownresult;
721 * Returns true if user has at least one role assign
722 * of 'coursecontact' role (is potentially listed in some course descriptions).
724 * @param int $userid
725 * @return bool
727 function has_coursecontact_role($userid) {
728 global $DB, $CFG;
730 if (empty($CFG->coursecontact)) {
731 return false;
733 $sql = "SELECT 1
734 FROM {role_assignments}
735 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
736 return $DB->record_exists_sql($sql, array('userid'=>$userid));
740 * Does the user have a capability to do something?
742 * Walk the accessdata array and return true/false.
743 * Deals with prohibits, role switching, aggregating
744 * capabilities, etc.
746 * The main feature of here is being FAST and with no
747 * side effects.
749 * Notes:
751 * Switch Role merges with default role
752 * ------------------------------------
753 * If you are a teacher in course X, you have at least
754 * teacher-in-X + defaultloggedinuser-sitewide. So in the
755 * course you'll have techer+defaultloggedinuser.
756 * We try to mimic that in switchrole.
758 * Permission evaluation
759 * ---------------------
760 * Originally there was an extremely complicated way
761 * to determine the user access that dealt with
762 * "locality" or role assignments and role overrides.
763 * Now we simply evaluate access for each role separately
764 * and then verify if user has at least one role with allow
765 * and at the same time no role with prohibit.
767 * @access private
768 * @param string $capability
769 * @param context $context
770 * @param array $accessdata
771 * @return bool
773 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
774 global $CFG;
776 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
777 $path = $context->path;
778 $paths = array($path);
779 while($path = rtrim($path, '0123456789')) {
780 $path = rtrim($path, '/');
781 if ($path === '') {
782 break;
784 $paths[] = $path;
787 $roles = array();
788 $switchedrole = false;
790 // Find out if role switched
791 if (!empty($accessdata['rsw'])) {
792 // From the bottom up...
793 foreach ($paths as $path) {
794 if (isset($accessdata['rsw'][$path])) {
795 // Found a switchrole assignment - check for that role _plus_ the default user role
796 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
797 $switchedrole = true;
798 break;
803 if (!$switchedrole) {
804 // get all users roles in this context and above
805 foreach ($paths as $path) {
806 if (isset($accessdata['ra'][$path])) {
807 foreach ($accessdata['ra'][$path] as $roleid) {
808 $roles[$roleid] = null;
814 // Now find out what access is given to each role, going bottom-->up direction
815 $rdefs = get_role_definitions(array_keys($roles));
816 $allowed = false;
818 foreach ($roles as $roleid => $ignored) {
819 foreach ($paths as $path) {
820 if (isset($rdefs[$roleid][$path][$capability])) {
821 $perm = (int)$rdefs[$roleid][$path][$capability];
822 if ($perm === CAP_PROHIBIT) {
823 // any CAP_PROHIBIT found means no permission for the user
824 return false;
826 if (is_null($roles[$roleid])) {
827 $roles[$roleid] = $perm;
831 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
832 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
835 return $allowed;
839 * A convenience function that tests has_capability, and displays an error if
840 * the user does not have that capability.
842 * NOTE before Moodle 2.0, this function attempted to make an appropriate
843 * require_login call before checking the capability. This is no longer the case.
844 * You must call require_login (or one of its variants) if you want to check the
845 * user is logged in, before you call this function.
847 * @see has_capability()
849 * @param string $capability the name of the capability to check. For example mod/forum:view
850 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
851 * @param int $userid A user id. By default (null) checks the permissions of the current user.
852 * @param bool $doanything If false, ignore effect of admin role assignment
853 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
854 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
855 * @return void terminates with an error if the user does not have the given capability.
857 function require_capability($capability, context $context, $userid = null, $doanything = true,
858 $errormessage = 'nopermissions', $stringfile = '') {
859 if (!has_capability($capability, $context, $userid, $doanything)) {
860 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
865 * Return a nested array showing all role assignments for the user.
866 * [ra] => [contextpath][roleid] = roleid
868 * @access private
869 * @param int $userid - the id of the user
870 * @return array access info array
872 function get_user_roles_sitewide_accessdata($userid) {
873 global $CFG, $DB;
875 $accessdata = get_empty_accessdata();
877 // start with the default role
878 if (!empty($CFG->defaultuserroleid)) {
879 $syscontext = context_system::instance();
880 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
883 // load the "default frontpage role"
884 if (!empty($CFG->defaultfrontpageroleid)) {
885 $frontpagecontext = context_course::instance(get_site()->id);
886 if ($frontpagecontext->path) {
887 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
891 // Preload every assigned role.
892 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
893 FROM {role_assignments} ra
894 JOIN {context} ctx ON ctx.id = ra.contextid
895 WHERE ra.userid = :userid";
897 $rs = $DB->get_recordset_sql($sql, array('userid' => $userid));
899 foreach ($rs as $ra) {
900 // RAs leafs are arrays to support multi-role assignments...
901 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
904 $rs->close();
906 return $accessdata;
910 * Returns empty accessdata structure.
912 * @access private
913 * @return array empt accessdata
915 function get_empty_accessdata() {
916 $accessdata = array(); // named list
917 $accessdata['ra'] = array();
918 $accessdata['time'] = time();
919 $accessdata['rsw'] = array();
921 return $accessdata;
925 * Get accessdata for a given user.
927 * @access private
928 * @param int $userid
929 * @param bool $preloadonly true means do not return access array
930 * @return array accessdata
932 function get_user_accessdata($userid, $preloadonly=false) {
933 global $CFG, $ACCESSLIB_PRIVATE, $USER;
935 if (isset($USER->access)) {
936 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->access;
939 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
940 if (empty($userid)) {
941 if (!empty($CFG->notloggedinroleid)) {
942 $accessdata = get_role_access($CFG->notloggedinroleid);
943 } else {
944 // weird
945 return get_empty_accessdata();
948 } else if (isguestuser($userid)) {
949 if ($guestrole = get_guest_role()) {
950 $accessdata = get_role_access($guestrole->id);
951 } else {
952 //weird
953 return get_empty_accessdata();
956 } else {
957 // Includes default role and frontpage role.
958 $accessdata = get_user_roles_sitewide_accessdata($userid);
961 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
964 if ($preloadonly) {
965 return;
966 } else {
967 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
972 * A convenience function to completely load all the capabilities
973 * for the current user. It is called from has_capability() and functions change permissions.
975 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
976 * @see check_enrolment_plugins()
978 * @access private
979 * @return void
981 function load_all_capabilities() {
982 global $USER;
984 // roles not installed yet - we are in the middle of installation
985 if (during_initial_install()) {
986 return;
989 if (!isset($USER->id)) {
990 // this should not happen
991 $USER->id = 0;
994 unset($USER->access);
995 $USER->access = get_user_accessdata($USER->id);
997 // Clear to force a refresh
998 unset($USER->mycourses);
1000 // init/reset internal enrol caches - active course enrolments and temp access
1001 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1005 * A convenience function to completely reload all the capabilities
1006 * for the current user when roles have been updated in a relevant
1007 * context -- but PRESERVING switchroles and loginas.
1008 * This function resets all accesslib and context caches.
1010 * That is - completely transparent to the user.
1012 * Note: reloads $USER->access completely.
1014 * @access private
1015 * @return void
1017 function reload_all_capabilities() {
1018 global $USER, $DB, $ACCESSLIB_PRIVATE;
1020 // copy switchroles
1021 $sw = array();
1022 if (!empty($USER->access['rsw'])) {
1023 $sw = $USER->access['rsw'];
1026 accesslib_clear_all_caches(true);
1027 unset($USER->access);
1029 // Prevent dirty flags refetching on this page.
1030 $ACCESSLIB_PRIVATE->dirtycontexts = array();
1031 $ACCESSLIB_PRIVATE->dirtyusers = array($USER->id => false);
1033 load_all_capabilities();
1035 foreach ($sw as $path => $roleid) {
1036 if ($record = $DB->get_record('context', array('path'=>$path))) {
1037 $context = context::instance_by_id($record->id);
1038 if (has_capability('moodle/role:switchroles', $context)) {
1039 role_switch($roleid, $context);
1046 * Adds a temp role to current USER->access array.
1048 * Useful for the "temporary guest" access we grant to logged-in users.
1049 * This is useful for enrol plugins only.
1051 * @since Moodle 2.2
1052 * @param context_course $coursecontext
1053 * @param int $roleid
1054 * @return void
1056 function load_temp_course_role(context_course $coursecontext, $roleid) {
1057 global $USER, $SITE;
1059 if (empty($roleid)) {
1060 debugging('invalid role specified in load_temp_course_role()');
1061 return;
1064 if ($coursecontext->instanceid == $SITE->id) {
1065 debugging('Can not use temp roles on the frontpage');
1066 return;
1069 if (!isset($USER->access)) {
1070 load_all_capabilities();
1073 $coursecontext->reload_if_dirty();
1075 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1076 return;
1079 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1083 * Removes any extra guest roles from current USER->access array.
1084 * This is useful for enrol plugins only.
1086 * @since Moodle 2.2
1087 * @param context_course $coursecontext
1088 * @return void
1090 function remove_temp_course_roles(context_course $coursecontext) {
1091 global $DB, $USER, $SITE;
1093 if ($coursecontext->instanceid == $SITE->id) {
1094 debugging('Can not use temp roles on the frontpage');
1095 return;
1098 if (empty($USER->access['ra'][$coursecontext->path])) {
1099 //no roles here, weird
1100 return;
1103 $sql = "SELECT DISTINCT ra.roleid AS id
1104 FROM {role_assignments} ra
1105 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1106 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1108 $USER->access['ra'][$coursecontext->path] = array();
1109 foreach($ras as $r) {
1110 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1115 * Returns array of all role archetypes.
1117 * @return array
1119 function get_role_archetypes() {
1120 return array(
1121 'manager' => 'manager',
1122 'coursecreator' => 'coursecreator',
1123 'editingteacher' => 'editingteacher',
1124 'teacher' => 'teacher',
1125 'student' => 'student',
1126 'guest' => 'guest',
1127 'user' => 'user',
1128 'frontpage' => 'frontpage'
1133 * Assign the defaults found in this capability definition to roles that have
1134 * the corresponding legacy capabilities assigned to them.
1136 * @param string $capability
1137 * @param array $legacyperms an array in the format (example):
1138 * 'guest' => CAP_PREVENT,
1139 * 'student' => CAP_ALLOW,
1140 * 'teacher' => CAP_ALLOW,
1141 * 'editingteacher' => CAP_ALLOW,
1142 * 'coursecreator' => CAP_ALLOW,
1143 * 'manager' => CAP_ALLOW
1144 * @return boolean success or failure.
1146 function assign_legacy_capabilities($capability, $legacyperms) {
1148 $archetypes = get_role_archetypes();
1150 foreach ($legacyperms as $type => $perm) {
1152 $systemcontext = context_system::instance();
1153 if ($type === 'admin') {
1154 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1155 $type = 'manager';
1158 if (!array_key_exists($type, $archetypes)) {
1159 print_error('invalidlegacy', '', '', $type);
1162 if ($roles = get_archetype_roles($type)) {
1163 foreach ($roles as $role) {
1164 // Assign a site level capability.
1165 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1166 return false;
1171 return true;
1175 * Verify capability risks.
1177 * @param stdClass $capability a capability - a row from the capabilities table.
1178 * @return boolean whether this capability is safe - that is, whether people with the
1179 * safeoverrides capability should be allowed to change it.
1181 function is_safe_capability($capability) {
1182 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1186 * Get the local override (if any) for a given capability in a role in a context
1188 * @param int $roleid
1189 * @param int $contextid
1190 * @param string $capability
1191 * @return stdClass local capability override
1193 function get_local_override($roleid, $contextid, $capability) {
1194 global $DB;
1196 return $DB->get_record_sql("
1197 SELECT rc.*
1198 FROM {role_capabilities} rc
1199 JOIN {capability} cap ON rc.capability = cap.name
1200 WHERE rc.roleid = :roleid AND rc.capability = :capability AND rc.contextid = :contextid", [
1201 'roleid' => $roleid,
1202 'contextid' => $contextid,
1203 'capability' => $capability,
1209 * Returns context instance plus related course and cm instances
1211 * @param int $contextid
1212 * @return array of ($context, $course, $cm)
1214 function get_context_info_array($contextid) {
1215 global $DB;
1217 $context = context::instance_by_id($contextid, MUST_EXIST);
1218 $course = null;
1219 $cm = null;
1221 if ($context->contextlevel == CONTEXT_COURSE) {
1222 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1224 } else if ($context->contextlevel == CONTEXT_MODULE) {
1225 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1226 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1228 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1229 $parent = $context->get_parent_context();
1231 if ($parent->contextlevel == CONTEXT_COURSE) {
1232 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1233 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1234 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1235 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1239 return array($context, $course, $cm);
1243 * Function that creates a role
1245 * @param string $name role name
1246 * @param string $shortname role short name
1247 * @param string $description role description
1248 * @param string $archetype
1249 * @return int id or dml_exception
1251 function create_role($name, $shortname, $description, $archetype = '') {
1252 global $DB;
1254 if (strpos($archetype, 'moodle/legacy:') !== false) {
1255 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1258 // verify role archetype actually exists
1259 $archetypes = get_role_archetypes();
1260 if (empty($archetypes[$archetype])) {
1261 $archetype = '';
1264 // Insert the role record.
1265 $role = new stdClass();
1266 $role->name = $name;
1267 $role->shortname = $shortname;
1268 $role->description = $description;
1269 $role->archetype = $archetype;
1271 //find free sortorder number
1272 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1273 if (empty($role->sortorder)) {
1274 $role->sortorder = 1;
1276 $id = $DB->insert_record('role', $role);
1278 return $id;
1282 * Function that deletes a role and cleanups up after it
1284 * @param int $roleid id of role to delete
1285 * @return bool always true
1287 function delete_role($roleid) {
1288 global $DB;
1290 // first unssign all users
1291 role_unassign_all(array('roleid'=>$roleid));
1293 // cleanup all references to this role, ignore errors
1294 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1295 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1296 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1297 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1298 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1299 $DB->delete_records('role_names', array('roleid'=>$roleid));
1300 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1302 // Get role record before it's deleted.
1303 $role = $DB->get_record('role', array('id'=>$roleid));
1305 // Finally delete the role itself.
1306 $DB->delete_records('role', array('id'=>$roleid));
1308 // Trigger event.
1309 $event = \core\event\role_deleted::create(
1310 array(
1311 'context' => context_system::instance(),
1312 'objectid' => $roleid,
1313 'other' =>
1314 array(
1315 'shortname' => $role->shortname,
1316 'description' => $role->description,
1317 'archetype' => $role->archetype
1321 $event->add_record_snapshot('role', $role);
1322 $event->trigger();
1324 // Reset any cache of this role, including MUC.
1325 accesslib_clear_role_cache($roleid);
1327 return true;
1331 * Function to write context specific overrides, or default capabilities.
1333 * @param string $capability string name
1334 * @param int $permission CAP_ constants
1335 * @param int $roleid role id
1336 * @param int|context $contextid context id
1337 * @param bool $overwrite
1338 * @return bool always true or exception
1340 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1341 global $USER, $DB;
1343 if ($contextid instanceof context) {
1344 $context = $contextid;
1345 } else {
1346 $context = context::instance_by_id($contextid);
1349 // Capability must exist.
1350 if (!$capinfo = get_capability_info($capability)) {
1351 throw new coding_exception("Capability '{$capability}' was not found! This has to be fixed in code.");
1354 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1355 unassign_capability($capability, $roleid, $context->id);
1356 return true;
1359 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1361 if ($existing and !$overwrite) { // We want to keep whatever is there already
1362 return true;
1365 $cap = new stdClass();
1366 $cap->contextid = $context->id;
1367 $cap->roleid = $roleid;
1368 $cap->capability = $capability;
1369 $cap->permission = $permission;
1370 $cap->timemodified = time();
1371 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1373 if ($existing) {
1374 $cap->id = $existing->id;
1375 $DB->update_record('role_capabilities', $cap);
1376 } else {
1377 if ($DB->record_exists('context', array('id'=>$context->id))) {
1378 $DB->insert_record('role_capabilities', $cap);
1382 // Trigger capability_assigned event.
1383 \core\event\capability_assigned::create([
1384 'userid' => $cap->modifierid,
1385 'context' => $context,
1386 'objectid' => $roleid,
1387 'other' => [
1388 'capability' => $capability,
1389 'oldpermission' => $existing->permission ?? CAP_INHERIT,
1390 'permission' => $permission
1392 ])->trigger();
1394 // Reset any cache of this role, including MUC.
1395 accesslib_clear_role_cache($roleid);
1397 return true;
1401 * Unassign a capability from a role.
1403 * @param string $capability the name of the capability
1404 * @param int $roleid the role id
1405 * @param int|context $contextid null means all contexts
1406 * @return boolean true or exception
1408 function unassign_capability($capability, $roleid, $contextid = null) {
1409 global $DB, $USER;
1411 // Capability must exist.
1412 if (!$capinfo = get_capability_info($capability)) {
1413 throw new coding_exception("Capability '{$capability}' was not found! This has to be fixed in code.");
1416 if (!empty($contextid)) {
1417 if ($contextid instanceof context) {
1418 $context = $contextid;
1419 } else {
1420 $context = context::instance_by_id($contextid);
1422 // delete from context rel, if this is the last override in this context
1423 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1424 } else {
1425 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1428 // Trigger capability_assigned event.
1429 \core\event\capability_unassigned::create([
1430 'userid' => $USER->id,
1431 'context' => $context ?? context_system::instance(),
1432 'objectid' => $roleid,
1433 'other' => [
1434 'capability' => $capability,
1436 ])->trigger();
1438 // Reset any cache of this role, including MUC.
1439 accesslib_clear_role_cache($roleid);
1441 return true;
1445 * Get the roles that have a given capability assigned to it
1447 * This function does not resolve the actual permission of the capability.
1448 * It just checks for permissions and overrides.
1449 * Use get_roles_with_cap_in_context() if resolution is required.
1451 * @param string $capability capability name (string)
1452 * @param string $permission optional, the permission defined for this capability
1453 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1454 * @param stdClass $context null means any
1455 * @return array of role records
1457 function get_roles_with_capability($capability, $permission = null, $context = null) {
1458 global $DB;
1460 if ($context) {
1461 $contexts = $context->get_parent_context_ids(true);
1462 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1463 $contextsql = "AND rc.contextid $insql";
1464 } else {
1465 $params = array();
1466 $contextsql = '';
1469 if ($permission) {
1470 $permissionsql = " AND rc.permission = :permission";
1471 $params['permission'] = $permission;
1472 } else {
1473 $permissionsql = '';
1476 $sql = "SELECT r.*
1477 FROM {role} r
1478 WHERE r.id IN (SELECT rc.roleid
1479 FROM {role_capabilities} rc
1480 JOIN {capabilities} cap ON rc.capability = cap.name
1481 WHERE rc.capability = :capname
1482 $contextsql
1483 $permissionsql)";
1484 $params['capname'] = $capability;
1487 return $DB->get_records_sql($sql, $params);
1491 * This function makes a role-assignment (a role for a user in a particular context)
1493 * @param int $roleid the role of the id
1494 * @param int $userid userid
1495 * @param int|context $contextid id of the context
1496 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1497 * @param int $itemid id of enrolment/auth plugin
1498 * @param string $timemodified defaults to current time
1499 * @return int new/existing id of the assignment
1501 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1502 global $USER, $DB;
1504 // first of all detect if somebody is using old style parameters
1505 if ($contextid === 0 or is_numeric($component)) {
1506 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1509 // now validate all parameters
1510 if (empty($roleid)) {
1511 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1514 if (empty($userid)) {
1515 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1518 if ($itemid) {
1519 if (strpos($component, '_') === false) {
1520 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1522 } else {
1523 $itemid = 0;
1524 if ($component !== '' and strpos($component, '_') === false) {
1525 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1529 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1530 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1533 if ($contextid instanceof context) {
1534 $context = $contextid;
1535 } else {
1536 $context = context::instance_by_id($contextid, MUST_EXIST);
1539 if (!$timemodified) {
1540 $timemodified = time();
1543 // Check for existing entry
1544 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1546 if ($ras) {
1547 // role already assigned - this should not happen
1548 if (count($ras) > 1) {
1549 // very weird - remove all duplicates!
1550 $ra = array_shift($ras);
1551 foreach ($ras as $r) {
1552 $DB->delete_records('role_assignments', array('id'=>$r->id));
1554 } else {
1555 $ra = reset($ras);
1558 // actually there is no need to update, reset anything or trigger any event, so just return
1559 return $ra->id;
1562 // Create a new entry
1563 $ra = new stdClass();
1564 $ra->roleid = $roleid;
1565 $ra->contextid = $context->id;
1566 $ra->userid = $userid;
1567 $ra->component = $component;
1568 $ra->itemid = $itemid;
1569 $ra->timemodified = $timemodified;
1570 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1571 $ra->sortorder = 0;
1573 $ra->id = $DB->insert_record('role_assignments', $ra);
1575 // Role assignments have changed, so mark user as dirty.
1576 mark_user_dirty($userid);
1578 core_course_category::role_assignment_changed($roleid, $context);
1580 $event = \core\event\role_assigned::create(array(
1581 'context' => $context,
1582 'objectid' => $ra->roleid,
1583 'relateduserid' => $ra->userid,
1584 'other' => array(
1585 'id' => $ra->id,
1586 'component' => $ra->component,
1587 'itemid' => $ra->itemid
1590 $event->add_record_snapshot('role_assignments', $ra);
1591 $event->trigger();
1593 return $ra->id;
1597 * Removes one role assignment
1599 * @param int $roleid
1600 * @param int $userid
1601 * @param int $contextid
1602 * @param string $component
1603 * @param int $itemid
1604 * @return void
1606 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1607 // first make sure the params make sense
1608 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1609 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1612 if ($itemid) {
1613 if (strpos($component, '_') === false) {
1614 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1616 } else {
1617 $itemid = 0;
1618 if ($component !== '' and strpos($component, '_') === false) {
1619 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1623 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1627 * Removes multiple role assignments, parameters may contain:
1628 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1630 * @param array $params role assignment parameters
1631 * @param bool $subcontexts unassign in subcontexts too
1632 * @param bool $includemanual include manual role assignments too
1633 * @return void
1635 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1636 global $USER, $CFG, $DB;
1638 if (!$params) {
1639 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1642 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1643 foreach ($params as $key=>$value) {
1644 if (!in_array($key, $allowed)) {
1645 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1649 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1650 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1653 if ($includemanual) {
1654 if (!isset($params['component']) or $params['component'] === '') {
1655 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1659 if ($subcontexts) {
1660 if (empty($params['contextid'])) {
1661 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1665 $ras = $DB->get_records('role_assignments', $params);
1666 foreach($ras as $ra) {
1667 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1668 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1669 // Role assignments have changed, so mark user as dirty.
1670 mark_user_dirty($ra->userid);
1672 $event = \core\event\role_unassigned::create(array(
1673 'context' => $context,
1674 'objectid' => $ra->roleid,
1675 'relateduserid' => $ra->userid,
1676 'other' => array(
1677 'id' => $ra->id,
1678 'component' => $ra->component,
1679 'itemid' => $ra->itemid
1682 $event->add_record_snapshot('role_assignments', $ra);
1683 $event->trigger();
1684 core_course_category::role_assignment_changed($ra->roleid, $context);
1687 unset($ras);
1689 // process subcontexts
1690 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1691 if ($params['contextid'] instanceof context) {
1692 $context = $params['contextid'];
1693 } else {
1694 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1697 if ($context) {
1698 $contexts = $context->get_child_contexts();
1699 $mparams = $params;
1700 foreach($contexts as $context) {
1701 $mparams['contextid'] = $context->id;
1702 $ras = $DB->get_records('role_assignments', $mparams);
1703 foreach($ras as $ra) {
1704 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1705 // Role assignments have changed, so mark user as dirty.
1706 mark_user_dirty($ra->userid);
1708 $event = \core\event\role_unassigned::create(
1709 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1710 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1711 $event->add_record_snapshot('role_assignments', $ra);
1712 $event->trigger();
1713 core_course_category::role_assignment_changed($ra->roleid, $context);
1719 // do this once more for all manual role assignments
1720 if ($includemanual) {
1721 $params['component'] = '';
1722 role_unassign_all($params, $subcontexts, false);
1727 * Mark a user as dirty (with timestamp) so as to force reloading of the user session.
1729 * @param int $userid
1730 * @return void
1732 function mark_user_dirty($userid) {
1733 global $CFG, $ACCESSLIB_PRIVATE;
1735 if (during_initial_install()) {
1736 return;
1739 // Throw exception if invalid userid is provided.
1740 if (empty($userid)) {
1741 throw new coding_exception('Invalid user parameter supplied for mark_user_dirty() function!');
1744 // Set dirty flag in database, set dirty field locally, and clear local accessdata cache.
1745 set_cache_flag('accesslib/dirtyusers', $userid, 1, time() + $CFG->sessiontimeout);
1746 $ACCESSLIB_PRIVATE->dirtyusers[$userid] = 1;
1747 unset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
1751 * Determines if a user is currently logged in
1753 * @category access
1755 * @return bool
1757 function isloggedin() {
1758 global $USER;
1760 return (!empty($USER->id));
1764 * Determines if a user is logged in as real guest user with username 'guest'.
1766 * @category access
1768 * @param int|object $user mixed user object or id, $USER if not specified
1769 * @return bool true if user is the real guest user, false if not logged in or other user
1771 function isguestuser($user = null) {
1772 global $USER, $DB, $CFG;
1774 // make sure we have the user id cached in config table, because we are going to use it a lot
1775 if (empty($CFG->siteguest)) {
1776 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1777 // guest does not exist yet, weird
1778 return false;
1780 set_config('siteguest', $guestid);
1782 if ($user === null) {
1783 $user = $USER;
1786 if ($user === null) {
1787 // happens when setting the $USER
1788 return false;
1790 } else if (is_numeric($user)) {
1791 return ($CFG->siteguest == $user);
1793 } else if (is_object($user)) {
1794 if (empty($user->id)) {
1795 return false; // not logged in means is not be guest
1796 } else {
1797 return ($CFG->siteguest == $user->id);
1800 } else {
1801 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1806 * Does user have a (temporary or real) guest access to course?
1808 * @category access
1810 * @param context $context
1811 * @param stdClass|int $user
1812 * @return bool
1814 function is_guest(context $context, $user = null) {
1815 global $USER;
1817 // first find the course context
1818 $coursecontext = $context->get_course_context();
1820 // make sure there is a real user specified
1821 if ($user === null) {
1822 $userid = isset($USER->id) ? $USER->id : 0;
1823 } else {
1824 $userid = is_object($user) ? $user->id : $user;
1827 if (isguestuser($userid)) {
1828 // can not inspect or be enrolled
1829 return true;
1832 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1833 // viewing users appear out of nowhere, they are neither guests nor participants
1834 return false;
1837 // consider only real active enrolments here
1838 if (is_enrolled($coursecontext, $user, '', true)) {
1839 return false;
1842 return true;
1846 * Returns true if the user has moodle/course:view capability in the course,
1847 * this is intended for admins, managers (aka small admins), inspectors, etc.
1849 * @category access
1851 * @param context $context
1852 * @param int|stdClass $user if null $USER is used
1853 * @param string $withcapability extra capability name
1854 * @return bool
1856 function is_viewing(context $context, $user = null, $withcapability = '') {
1857 // first find the course context
1858 $coursecontext = $context->get_course_context();
1860 if (isguestuser($user)) {
1861 // can not inspect
1862 return false;
1865 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1866 // admins are allowed to inspect courses
1867 return false;
1870 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1871 // site admins always have the capability, but the enrolment above blocks
1872 return false;
1875 return true;
1879 * Returns true if the user is able to access the course.
1881 * This function is in no way, shape, or form a substitute for require_login.
1882 * It should only be used in circumstances where it is not possible to call require_login
1883 * such as the navigation.
1885 * This function checks many of the methods of access to a course such as the view
1886 * capability, enrollments, and guest access. It also makes use of the cache
1887 * generated by require_login for guest access.
1889 * The flags within the $USER object that are used here should NEVER be used outside
1890 * of this function can_access_course and require_login. Doing so WILL break future
1891 * versions.
1893 * @param stdClass $course record
1894 * @param stdClass|int|null $user user record or id, current user if null
1895 * @param string $withcapability Check for this capability as well.
1896 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1897 * @return boolean Returns true if the user is able to access the course
1899 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
1900 global $DB, $USER;
1902 // this function originally accepted $coursecontext parameter
1903 if ($course instanceof context) {
1904 if ($course instanceof context_course) {
1905 debugging('deprecated context parameter, please use $course record');
1906 $coursecontext = $course;
1907 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
1908 } else {
1909 debugging('Invalid context parameter, please use $course record');
1910 return false;
1912 } else {
1913 $coursecontext = context_course::instance($course->id);
1916 if (!isset($USER->id)) {
1917 // should never happen
1918 $USER->id = 0;
1919 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
1922 // make sure there is a user specified
1923 if ($user === null) {
1924 $userid = $USER->id;
1925 } else {
1926 $userid = is_object($user) ? $user->id : $user;
1928 unset($user);
1930 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
1931 return false;
1934 if ($userid == $USER->id) {
1935 if (!empty($USER->access['rsw'][$coursecontext->path])) {
1936 // the fact that somebody switched role means they can access the course no matter to what role they switched
1937 return true;
1941 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
1942 return false;
1945 if (is_viewing($coursecontext, $userid)) {
1946 return true;
1949 if ($userid != $USER->id) {
1950 // for performance reasons we do not verify temporary guest access for other users, sorry...
1951 return is_enrolled($coursecontext, $userid, '', $onlyactive);
1954 // === from here we deal only with $USER ===
1956 $coursecontext->reload_if_dirty();
1958 if (isset($USER->enrol['enrolled'][$course->id])) {
1959 if ($USER->enrol['enrolled'][$course->id] > time()) {
1960 return true;
1963 if (isset($USER->enrol['tempguest'][$course->id])) {
1964 if ($USER->enrol['tempguest'][$course->id] > time()) {
1965 return true;
1969 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
1970 return true;
1973 if (!core_course_category::can_view_course_info($course)) {
1974 // No guest access if user does not have capability to browse courses.
1975 return false;
1978 // if not enrolled try to gain temporary guest access
1979 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
1980 $enrols = enrol_get_plugins(true);
1981 foreach($instances as $instance) {
1982 if (!isset($enrols[$instance->enrol])) {
1983 continue;
1985 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
1986 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
1987 if ($until !== false and $until > time()) {
1988 $USER->enrol['tempguest'][$course->id] = $until;
1989 return true;
1992 if (isset($USER->enrol['tempguest'][$course->id])) {
1993 unset($USER->enrol['tempguest'][$course->id]);
1994 remove_temp_course_roles($coursecontext);
1997 return false;
2001 * Loads the capability definitions for the component (from file).
2003 * Loads the capability definitions for the component (from file). If no
2004 * capabilities are defined for the component, we simply return an empty array.
2006 * @access private
2007 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2008 * @return array array of capabilities
2010 function load_capability_def($component) {
2011 $defpath = core_component::get_component_directory($component).'/db/access.php';
2013 $capabilities = array();
2014 if (file_exists($defpath)) {
2015 require($defpath);
2016 if (!empty(${$component.'_capabilities'})) {
2017 // BC capability array name
2018 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2019 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2020 $capabilities = ${$component.'_capabilities'};
2024 return $capabilities;
2028 * Gets the capabilities that have been cached in the database for this component.
2030 * @access private
2031 * @param string $component - examples: 'moodle', 'mod_forum'
2032 * @return array array of capabilities
2034 function get_cached_capabilities($component = 'moodle') {
2035 global $DB;
2036 $caps = get_all_capabilities();
2037 $componentcaps = array();
2038 foreach ($caps as $cap) {
2039 if ($cap['component'] == $component) {
2040 $componentcaps[] = (object) $cap;
2043 return $componentcaps;
2047 * Returns default capabilities for given role archetype.
2049 * @param string $archetype role archetype
2050 * @return array
2052 function get_default_capabilities($archetype) {
2053 global $DB;
2055 if (!$archetype) {
2056 return array();
2059 $alldefs = array();
2060 $defaults = array();
2061 $components = array();
2062 $allcaps = get_all_capabilities();
2064 foreach ($allcaps as $cap) {
2065 if (!in_array($cap['component'], $components)) {
2066 $components[] = $cap['component'];
2067 $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
2070 foreach($alldefs as $name=>$def) {
2071 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2072 if (isset($def['archetypes'])) {
2073 if (isset($def['archetypes'][$archetype])) {
2074 $defaults[$name] = $def['archetypes'][$archetype];
2076 // 'legacy' is for backward compatibility with 1.9 access.php
2077 } else {
2078 if (isset($def['legacy'][$archetype])) {
2079 $defaults[$name] = $def['legacy'][$archetype];
2084 return $defaults;
2088 * Return default roles that can be assigned, overridden or switched
2089 * by give role archetype.
2091 * @param string $type assign|override|switch|view
2092 * @param string $archetype
2093 * @return array of role ids
2095 function get_default_role_archetype_allows($type, $archetype) {
2096 global $DB;
2098 if (empty($archetype)) {
2099 return array();
2102 $roles = $DB->get_records('role');
2103 $archetypemap = array();
2104 foreach ($roles as $role) {
2105 if ($role->archetype) {
2106 $archetypemap[$role->archetype][$role->id] = $role->id;
2110 $defaults = array(
2111 'assign' => array(
2112 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2113 'coursecreator' => array(),
2114 'editingteacher' => array('teacher', 'student'),
2115 'teacher' => array(),
2116 'student' => array(),
2117 'guest' => array(),
2118 'user' => array(),
2119 'frontpage' => array(),
2121 'override' => array(
2122 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2123 'coursecreator' => array(),
2124 'editingteacher' => array('teacher', 'student', 'guest'),
2125 'teacher' => array(),
2126 'student' => array(),
2127 'guest' => array(),
2128 'user' => array(),
2129 'frontpage' => array(),
2131 'switch' => array(
2132 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2133 'coursecreator' => array(),
2134 'editingteacher' => array('teacher', 'student', 'guest'),
2135 'teacher' => array('student', 'guest'),
2136 'student' => array(),
2137 'guest' => array(),
2138 'user' => array(),
2139 'frontpage' => array(),
2141 'view' => array(
2142 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2143 'coursecreator' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2144 'editingteacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2145 'teacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2146 'student' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2147 'guest' => array(),
2148 'user' => array(),
2149 'frontpage' => array(),
2153 if (!isset($defaults[$type][$archetype])) {
2154 debugging("Unknown type '$type'' or archetype '$archetype''");
2155 return array();
2158 $return = array();
2159 foreach ($defaults[$type][$archetype] as $at) {
2160 if (isset($archetypemap[$at])) {
2161 foreach ($archetypemap[$at] as $roleid) {
2162 $return[$roleid] = $roleid;
2167 return $return;
2171 * Reset role capabilities to default according to selected role archetype.
2172 * If no archetype selected, removes all capabilities.
2174 * This applies to capabilities that are assigned to the role (that you could
2175 * edit in the 'define roles' interface), and not to any capability overrides
2176 * in different locations.
2178 * @param int $roleid ID of role to reset capabilities for
2180 function reset_role_capabilities($roleid) {
2181 global $DB;
2183 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2184 $defaultcaps = get_default_capabilities($role->archetype);
2186 $systemcontext = context_system::instance();
2188 $DB->delete_records('role_capabilities',
2189 array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2191 foreach($defaultcaps as $cap=>$permission) {
2192 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2195 // Reset any cache of this role, including MUC.
2196 accesslib_clear_role_cache($roleid);
2200 * Updates the capabilities table with the component capability definitions.
2201 * If no parameters are given, the function updates the core moodle
2202 * capabilities.
2204 * Note that the absence of the db/access.php capabilities definition file
2205 * will cause any stored capabilities for the component to be removed from
2206 * the database.
2208 * @access private
2209 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2210 * @return boolean true if success, exception in case of any problems
2212 function update_capabilities($component = 'moodle') {
2213 global $DB, $OUTPUT;
2215 $storedcaps = array();
2217 $filecaps = load_capability_def($component);
2218 foreach($filecaps as $capname=>$unused) {
2219 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2220 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2224 // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2225 // So ensure our updating is based on fresh data.
2226 cache::make('core', 'capabilities')->delete('core_capabilities');
2228 $cachedcaps = get_cached_capabilities($component);
2229 if ($cachedcaps) {
2230 foreach ($cachedcaps as $cachedcap) {
2231 array_push($storedcaps, $cachedcap->name);
2232 // update risk bitmasks and context levels in existing capabilities if needed
2233 if (array_key_exists($cachedcap->name, $filecaps)) {
2234 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2235 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2237 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2238 $updatecap = new stdClass();
2239 $updatecap->id = $cachedcap->id;
2240 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2241 $DB->update_record('capabilities', $updatecap);
2243 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2244 $updatecap = new stdClass();
2245 $updatecap->id = $cachedcap->id;
2246 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2247 $DB->update_record('capabilities', $updatecap);
2250 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2251 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2253 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2254 $updatecap = new stdClass();
2255 $updatecap->id = $cachedcap->id;
2256 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2257 $DB->update_record('capabilities', $updatecap);
2263 // Flush the cached again, as we have changed DB.
2264 cache::make('core', 'capabilities')->delete('core_capabilities');
2266 // Are there new capabilities in the file definition?
2267 $newcaps = array();
2269 foreach ($filecaps as $filecap => $def) {
2270 if (!$storedcaps ||
2271 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2272 if (!array_key_exists('riskbitmask', $def)) {
2273 $def['riskbitmask'] = 0; // no risk if not specified
2275 $newcaps[$filecap] = $def;
2278 // Add new capabilities to the stored definition.
2279 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2280 foreach ($newcaps as $capname => $capdef) {
2281 $capability = new stdClass();
2282 $capability->name = $capname;
2283 $capability->captype = $capdef['captype'];
2284 $capability->contextlevel = $capdef['contextlevel'];
2285 $capability->component = $component;
2286 $capability->riskbitmask = $capdef['riskbitmask'];
2288 $DB->insert_record('capabilities', $capability, false);
2290 // Flush the cached, as we have changed DB.
2291 cache::make('core', 'capabilities')->delete('core_capabilities');
2293 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2294 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2295 foreach ($rolecapabilities as $rolecapability){
2296 //assign_capability will update rather than insert if capability exists
2297 if (!assign_capability($capname, $rolecapability->permission,
2298 $rolecapability->roleid, $rolecapability->contextid, true)){
2299 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2303 // we ignore archetype key if we have cloned permissions
2304 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2305 assign_legacy_capabilities($capname, $capdef['archetypes']);
2306 // 'legacy' is for backward compatibility with 1.9 access.php
2307 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2308 assign_legacy_capabilities($capname, $capdef['legacy']);
2311 // Are there any capabilities that have been removed from the file
2312 // definition that we need to delete from the stored capabilities and
2313 // role assignments?
2314 capabilities_cleanup($component, $filecaps);
2316 // reset static caches
2317 accesslib_reset_role_cache();
2319 // Flush the cached again, as we have changed DB.
2320 cache::make('core', 'capabilities')->delete('core_capabilities');
2322 return true;
2326 * Deletes cached capabilities that are no longer needed by the component.
2327 * Also unassigns these capabilities from any roles that have them.
2328 * NOTE: this function is called from lib/db/upgrade.php
2330 * @access private
2331 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2332 * @param array $newcapdef array of the new capability definitions that will be
2333 * compared with the cached capabilities
2334 * @return int number of deprecated capabilities that have been removed
2336 function capabilities_cleanup($component, $newcapdef = null) {
2337 global $DB;
2339 $removedcount = 0;
2341 if ($cachedcaps = get_cached_capabilities($component)) {
2342 foreach ($cachedcaps as $cachedcap) {
2343 if (empty($newcapdef) ||
2344 array_key_exists($cachedcap->name, $newcapdef) === false) {
2346 // Delete from roles.
2347 if ($roles = get_roles_with_capability($cachedcap->name)) {
2348 foreach($roles as $role) {
2349 if (!unassign_capability($cachedcap->name, $role->id)) {
2350 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2355 // Remove from role_capabilities for any old ones.
2356 $DB->delete_records('role_capabilities', array('capability' => $cachedcap->name));
2358 // Remove from capabilities cache.
2359 $DB->delete_records('capabilities', array('name' => $cachedcap->name));
2360 $removedcount++;
2361 } // End if.
2364 if ($removedcount) {
2365 cache::make('core', 'capabilities')->delete('core_capabilities');
2367 return $removedcount;
2371 * Returns an array of all the known types of risk
2372 * The array keys can be used, for example as CSS class names, or in calls to
2373 * print_risk_icon. The values are the corresponding RISK_ constants.
2375 * @return array all the known types of risk.
2377 function get_all_risks() {
2378 return array(
2379 'riskmanagetrust' => RISK_MANAGETRUST,
2380 'riskconfig' => RISK_CONFIG,
2381 'riskxss' => RISK_XSS,
2382 'riskpersonal' => RISK_PERSONAL,
2383 'riskspam' => RISK_SPAM,
2384 'riskdataloss' => RISK_DATALOSS,
2389 * Return a link to moodle docs for a given capability name
2391 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2392 * @return string the human-readable capability name as a link to Moodle Docs.
2394 function get_capability_docs_link($capability) {
2395 $url = get_docs_url('Capabilities/' . $capability->name);
2396 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2400 * This function pulls out all the resolved capabilities (overrides and
2401 * defaults) of a role used in capability overrides in contexts at a given
2402 * context.
2404 * @param int $roleid
2405 * @param context $context
2406 * @param string $cap capability, optional, defaults to ''
2407 * @return array Array of capabilities
2409 function role_context_capabilities($roleid, context $context, $cap = '') {
2410 global $DB;
2412 $contexts = $context->get_parent_context_ids(true);
2413 $contexts = '('.implode(',', $contexts).')';
2415 $params = array($roleid);
2417 if ($cap) {
2418 $search = " AND rc.capability = ? ";
2419 $params[] = $cap;
2420 } else {
2421 $search = '';
2424 $sql = "SELECT rc.*
2425 FROM {role_capabilities} rc
2426 JOIN {context} c ON rc.contextid = c.id
2427 JOIN {capabilities} cap ON rc.capability = cap.name
2428 WHERE rc.contextid in $contexts
2429 AND rc.roleid = ?
2430 $search
2431 ORDER BY c.contextlevel DESC, rc.capability DESC";
2433 $capabilities = array();
2435 if ($records = $DB->get_records_sql($sql, $params)) {
2436 // We are traversing via reverse order.
2437 foreach ($records as $record) {
2438 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2439 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2440 $capabilities[$record->capability] = $record->permission;
2444 return $capabilities;
2448 * Constructs array with contextids as first parameter and context paths,
2449 * in both cases bottom top including self.
2451 * @access private
2452 * @param context $context
2453 * @return array
2455 function get_context_info_list(context $context) {
2456 $contextids = explode('/', ltrim($context->path, '/'));
2457 $contextpaths = array();
2458 $contextids2 = $contextids;
2459 while ($contextids2) {
2460 $contextpaths[] = '/' . implode('/', $contextids2);
2461 array_pop($contextids2);
2463 return array($contextids, $contextpaths);
2467 * Check if context is the front page context or a context inside it
2469 * Returns true if this context is the front page context, or a context inside it,
2470 * otherwise false.
2472 * @param context $context a context object.
2473 * @return bool
2475 function is_inside_frontpage(context $context) {
2476 $frontpagecontext = context_course::instance(SITEID);
2477 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2481 * Returns capability information (cached)
2483 * @param string $capabilityname
2484 * @return stdClass or null if capability not found
2486 function get_capability_info($capabilityname) {
2487 $caps = get_all_capabilities();
2489 if (!isset($caps[$capabilityname])) {
2490 return null;
2493 return (object) $caps[$capabilityname];
2497 * Returns all capabilitiy records, preferably from MUC and not database.
2499 * @return array All capability records indexed by capability name
2501 function get_all_capabilities() {
2502 global $DB;
2503 $cache = cache::make('core', 'capabilities');
2504 if (!$allcaps = $cache->get('core_capabilities')) {
2505 $rs = $DB->get_recordset('capabilities');
2506 $allcaps = array();
2507 foreach ($rs as $capability) {
2508 $capability->riskbitmask = (int) $capability->riskbitmask;
2509 $allcaps[$capability->name] = (array) $capability;
2511 $rs->close();
2512 $cache->set('core_capabilities', $allcaps);
2514 return $allcaps;
2518 * Returns the human-readable, translated version of the capability.
2519 * Basically a big switch statement.
2521 * @param string $capabilityname e.g. mod/choice:readresponses
2522 * @return string
2524 function get_capability_string($capabilityname) {
2526 // Typical capability name is 'plugintype/pluginname:capabilityname'
2527 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2529 if ($type === 'moodle') {
2530 $component = 'core_role';
2531 } else if ($type === 'quizreport') {
2532 //ugly hack!!
2533 $component = 'quiz_'.$name;
2534 } else {
2535 $component = $type.'_'.$name;
2538 $stringname = $name.':'.$capname;
2540 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2541 return get_string($stringname, $component);
2544 $dir = core_component::get_component_directory($component);
2545 if (!file_exists($dir)) {
2546 // plugin broken or does not exist, do not bother with printing of debug message
2547 return $capabilityname.' ???';
2550 // something is wrong in plugin, better print debug
2551 return get_string($stringname, $component);
2555 * This gets the mod/block/course/core etc strings.
2557 * @param string $component
2558 * @param int $contextlevel
2559 * @return string|bool String is success, false if failed
2561 function get_component_string($component, $contextlevel) {
2563 if ($component === 'moodle' || $component === 'core') {
2564 return context_helper::get_level_name($contextlevel);
2567 list($type, $name) = core_component::normalize_component($component);
2568 $dir = core_component::get_plugin_directory($type, $name);
2569 if (!file_exists($dir)) {
2570 // plugin not installed, bad luck, there is no way to find the name
2571 return $component . ' ???';
2574 // Some plugin types need an extra prefix to make the name easy to understand.
2575 switch ($type) {
2576 case 'quiz':
2577 $prefix = get_string('quizreport', 'quiz') . ': ';
2578 break;
2579 case 'repository':
2580 $prefix = get_string('repository', 'repository') . ': ';
2581 break;
2582 case 'gradeimport':
2583 $prefix = get_string('gradeimport', 'grades') . ': ';
2584 break;
2585 case 'gradeexport':
2586 $prefix = get_string('gradeexport', 'grades') . ': ';
2587 break;
2588 case 'gradereport':
2589 $prefix = get_string('gradereport', 'grades') . ': ';
2590 break;
2591 case 'webservice':
2592 $prefix = get_string('webservice', 'webservice') . ': ';
2593 break;
2594 case 'block':
2595 $prefix = get_string('block') . ': ';
2596 break;
2597 case 'mod':
2598 $prefix = get_string('activity') . ': ';
2599 break;
2601 // Default case, just use the plugin name.
2602 default:
2603 $prefix = '';
2605 return $prefix . get_string('pluginname', $component);
2609 * Gets the list of roles assigned to this context and up (parents)
2610 * from the aggregation of:
2611 * a) the list of roles that are visible on user profile page and participants page (profileroles setting) and;
2612 * b) if applicable, those roles that are assigned in the context.
2614 * @param context $context
2615 * @return array
2617 function get_profile_roles(context $context) {
2618 global $CFG, $DB;
2619 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2620 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2621 if (has_capability('moodle/role:assign', $context)) {
2622 $rolesinscope = array_keys(get_all_roles($context));
2623 } else {
2624 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2627 if (empty($rolesinscope)) {
2628 return [];
2631 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2632 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2633 $params = array_merge($params, $cparams);
2635 if ($coursecontext = $context->get_course_context(false)) {
2636 $params['coursecontext'] = $coursecontext->id;
2637 } else {
2638 $params['coursecontext'] = 0;
2641 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2642 FROM {role_assignments} ra, {role} r
2643 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2644 WHERE r.id = ra.roleid
2645 AND ra.contextid $contextlist
2646 AND r.id $rallowed
2647 ORDER BY r.sortorder ASC";
2649 return $DB->get_records_sql($sql, $params);
2653 * Gets the list of roles assigned to this context and up (parents)
2655 * @param context $context
2656 * @param boolean $includeparents, false means without parents.
2657 * @return array
2659 function get_roles_used_in_context(context $context, $includeparents = true) {
2660 global $DB;
2662 if ($includeparents === true) {
2663 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2664 } else {
2665 list($contextlist, $params) = $DB->get_in_or_equal($context->id, SQL_PARAMS_NAMED, 'cl');
2668 if ($coursecontext = $context->get_course_context(false)) {
2669 $params['coursecontext'] = $coursecontext->id;
2670 } else {
2671 $params['coursecontext'] = 0;
2674 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2675 FROM {role_assignments} ra, {role} r
2676 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2677 WHERE r.id = ra.roleid
2678 AND ra.contextid $contextlist
2679 ORDER BY r.sortorder ASC";
2681 return $DB->get_records_sql($sql, $params);
2685 * This function is used to print roles column in user profile page.
2686 * It is using the CFG->profileroles to limit the list to only interesting roles.
2687 * (The permission tab has full details of user role assignments.)
2689 * @param int $userid
2690 * @param int $courseid
2691 * @return string
2693 function get_user_roles_in_course($userid, $courseid) {
2694 global $CFG, $DB;
2695 if ($courseid == SITEID) {
2696 $context = context_system::instance();
2697 } else {
2698 $context = context_course::instance($courseid);
2700 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2701 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2702 if (has_capability('moodle/role:assign', $context)) {
2703 $rolesinscope = array_keys(get_all_roles($context));
2704 } else {
2705 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2707 if (empty($rolesinscope)) {
2708 return '';
2711 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2712 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2713 $params = array_merge($params, $cparams);
2715 if ($coursecontext = $context->get_course_context(false)) {
2716 $params['coursecontext'] = $coursecontext->id;
2717 } else {
2718 $params['coursecontext'] = 0;
2721 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2722 FROM {role_assignments} ra, {role} r
2723 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2724 WHERE r.id = ra.roleid
2725 AND ra.contextid $contextlist
2726 AND r.id $rallowed
2727 AND ra.userid = :userid
2728 ORDER BY r.sortorder ASC";
2729 $params['userid'] = $userid;
2731 $rolestring = '';
2733 if ($roles = $DB->get_records_sql($sql, $params)) {
2734 $viewableroles = get_viewable_roles($context, $userid);
2736 $rolenames = array();
2737 foreach ($roles as $roleid => $unused) {
2738 if (isset($viewableroles[$roleid])) {
2739 $url = new moodle_url('/user/index.php', ['contextid' => $context->id, 'roleid' => $roleid]);
2740 $rolenames[] = '<a href="' . $url . '">' . $viewableroles[$roleid] . '</a>';
2743 $rolestring = implode(',', $rolenames);
2746 return $rolestring;
2750 * Checks if a user can assign users to a particular role in this context
2752 * @param context $context
2753 * @param int $targetroleid - the id of the role you want to assign users to
2754 * @return boolean
2756 function user_can_assign(context $context, $targetroleid) {
2757 global $DB;
2759 // First check to see if the user is a site administrator.
2760 if (is_siteadmin()) {
2761 return true;
2764 // Check if user has override capability.
2765 // If not return false.
2766 if (!has_capability('moodle/role:assign', $context)) {
2767 return false;
2769 // pull out all active roles of this user from this context(or above)
2770 if ($userroles = get_user_roles($context)) {
2771 foreach ($userroles as $userrole) {
2772 // if any in the role_allow_override table, then it's ok
2773 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2774 return true;
2779 return false;
2783 * Returns all site roles in correct sort order.
2785 * Note: this method does not localise role names or descriptions,
2786 * use role_get_names() if you need role names.
2788 * @param context $context optional context for course role name aliases
2789 * @return array of role records with optional coursealias property
2791 function get_all_roles(context $context = null) {
2792 global $DB;
2794 if (!$context or !$coursecontext = $context->get_course_context(false)) {
2795 $coursecontext = null;
2798 if ($coursecontext) {
2799 $sql = "SELECT r.*, rn.name AS coursealias
2800 FROM {role} r
2801 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2802 ORDER BY r.sortorder ASC";
2803 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
2805 } else {
2806 return $DB->get_records('role', array(), 'sortorder ASC');
2811 * Returns roles of a specified archetype
2813 * @param string $archetype
2814 * @return array of full role records
2816 function get_archetype_roles($archetype) {
2817 global $DB;
2818 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2822 * Gets all the user roles assigned in this context, or higher contexts for a list of users.
2824 * If you try using the combination $userids = [], $checkparentcontexts = true then this is likely
2825 * to cause an out-of-memory error on large Moodle sites, so this combination is deprecated and
2826 * outputs a warning, even though it is the default.
2828 * @param context $context
2829 * @param array $userids. An empty list means fetch all role assignments for the context.
2830 * @param bool $checkparentcontexts defaults to true
2831 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2832 * @return array
2834 function get_users_roles(context $context, $userids = [], $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2835 global $DB;
2837 if (!$userids && $checkparentcontexts) {
2838 debugging('Please do not call get_users_roles() with $checkparentcontexts = true ' .
2839 'and $userids array not set. This combination causes large Moodle sites ' .
2840 'with lots of site-wide role assignemnts to run out of memory.', DEBUG_DEVELOPER);
2843 if ($checkparentcontexts) {
2844 $contextids = $context->get_parent_context_ids();
2845 } else {
2846 $contextids = array();
2848 $contextids[] = $context->id;
2850 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
2852 // If userids was passed as an empty array, we fetch all role assignments for the course.
2853 if (empty($userids)) {
2854 $useridlist = ' IS NOT NULL ';
2855 $uparams = [];
2856 } else {
2857 list($useridlist, $uparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'uids');
2860 $sql = "SELECT ra.*, r.name, r.shortname, ra.userid
2861 FROM {role_assignments} ra, {role} r, {context} c
2862 WHERE ra.userid $useridlist
2863 AND ra.roleid = r.id
2864 AND ra.contextid = c.id
2865 AND ra.contextid $contextids
2866 ORDER BY $order";
2868 $all = $DB->get_records_sql($sql , array_merge($params, $uparams));
2870 // Return results grouped by userid.
2871 $result = [];
2872 foreach ($all as $id => $record) {
2873 if (!isset($result[$record->userid])) {
2874 $result[$record->userid] = [];
2876 $result[$record->userid][$record->id] = $record;
2879 // Make sure all requested users are included in the result, even if they had no role assignments.
2880 foreach ($userids as $id) {
2881 if (!isset($result[$id])) {
2882 $result[$id] = [];
2886 return $result;
2891 * Gets all the user roles assigned in this context, or higher contexts
2892 * this is mainly used when checking if a user can assign a role, or overriding a role
2893 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2894 * allow_override tables
2896 * @param context $context
2897 * @param int $userid
2898 * @param bool $checkparentcontexts defaults to true
2899 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2900 * @return array
2902 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2903 global $USER, $DB;
2905 if (empty($userid)) {
2906 if (empty($USER->id)) {
2907 return array();
2909 $userid = $USER->id;
2912 if ($checkparentcontexts) {
2913 $contextids = $context->get_parent_context_ids();
2914 } else {
2915 $contextids = array();
2917 $contextids[] = $context->id;
2919 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2921 array_unshift($params, $userid);
2923 $sql = "SELECT ra.*, r.name, r.shortname
2924 FROM {role_assignments} ra, {role} r, {context} c
2925 WHERE ra.userid = ?
2926 AND ra.roleid = r.id
2927 AND ra.contextid = c.id
2928 AND ra.contextid $contextids
2929 ORDER BY $order";
2931 return $DB->get_records_sql($sql ,$params);
2935 * Like get_user_roles, but adds in the authenticated user role, and the front
2936 * page roles, if applicable.
2938 * @param context $context the context.
2939 * @param int $userid optional. Defaults to $USER->id
2940 * @return array of objects with fields ->userid, ->contextid and ->roleid.
2942 function get_user_roles_with_special(context $context, $userid = 0) {
2943 global $CFG, $USER;
2945 if (empty($userid)) {
2946 if (empty($USER->id)) {
2947 return array();
2949 $userid = $USER->id;
2952 $ras = get_user_roles($context, $userid);
2954 // Add front-page role if relevant.
2955 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2956 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
2957 is_inside_frontpage($context);
2958 if ($defaultfrontpageroleid && $isfrontpage) {
2959 $frontpagecontext = context_course::instance(SITEID);
2960 $ra = new stdClass();
2961 $ra->userid = $userid;
2962 $ra->contextid = $frontpagecontext->id;
2963 $ra->roleid = $defaultfrontpageroleid;
2964 $ras[] = $ra;
2967 // Add authenticated user role if relevant.
2968 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2969 if ($defaultuserroleid && !isguestuser($userid)) {
2970 $systemcontext = context_system::instance();
2971 $ra = new stdClass();
2972 $ra->userid = $userid;
2973 $ra->contextid = $systemcontext->id;
2974 $ra->roleid = $defaultuserroleid;
2975 $ras[] = $ra;
2978 return $ras;
2982 * Creates a record in the role_allow_override table
2984 * @param int $fromroleid source roleid
2985 * @param int $targetroleid target roleid
2986 * @return void
2988 function core_role_set_override_allowed($fromroleid, $targetroleid) {
2989 global $DB;
2991 $record = new stdClass();
2992 $record->roleid = $fromroleid;
2993 $record->allowoverride = $targetroleid;
2994 $DB->insert_record('role_allow_override', $record);
2998 * Creates a record in the role_allow_assign table
3000 * @param int $fromroleid source roleid
3001 * @param int $targetroleid target roleid
3002 * @return void
3004 function core_role_set_assign_allowed($fromroleid, $targetroleid) {
3005 global $DB;
3007 $record = new stdClass();
3008 $record->roleid = $fromroleid;
3009 $record->allowassign = $targetroleid;
3010 $DB->insert_record('role_allow_assign', $record);
3014 * Creates a record in the role_allow_switch table
3016 * @param int $fromroleid source roleid
3017 * @param int $targetroleid target roleid
3018 * @return void
3020 function core_role_set_switch_allowed($fromroleid, $targetroleid) {
3021 global $DB;
3023 $record = new stdClass();
3024 $record->roleid = $fromroleid;
3025 $record->allowswitch = $targetroleid;
3026 $DB->insert_record('role_allow_switch', $record);
3030 * Creates a record in the role_allow_view table
3032 * @param int $fromroleid source roleid
3033 * @param int $targetroleid target roleid
3034 * @return void
3036 function core_role_set_view_allowed($fromroleid, $targetroleid) {
3037 global $DB;
3039 $record = new stdClass();
3040 $record->roleid = $fromroleid;
3041 $record->allowview = $targetroleid;
3042 $DB->insert_record('role_allow_view', $record);
3046 * Gets a list of roles that this user can assign in this context
3048 * @param context $context the context.
3049 * @param int $rolenamedisplay the type of role name to display. One of the
3050 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3051 * @param bool $withusercounts if true, count the number of users with each role.
3052 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3053 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3054 * if $withusercounts is true, returns a list of three arrays,
3055 * $rolenames, $rolecounts, and $nameswithcounts.
3057 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3058 global $USER, $DB;
3060 // make sure there is a real user specified
3061 if ($user === null) {
3062 $userid = isset($USER->id) ? $USER->id : 0;
3063 } else {
3064 $userid = is_object($user) ? $user->id : $user;
3067 if (!has_capability('moodle/role:assign', $context, $userid)) {
3068 if ($withusercounts) {
3069 return array(array(), array(), array());
3070 } else {
3071 return array();
3075 $params = array();
3076 $extrafields = '';
3078 if ($withusercounts) {
3079 $extrafields = ', (SELECT COUNT(DISTINCT u.id)
3080 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3081 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3082 ) AS usercount';
3083 $params['conid'] = $context->id;
3086 if (is_siteadmin($userid)) {
3087 // show all roles allowed in this context to admins
3088 $assignrestriction = "";
3089 } else {
3090 $parents = $context->get_parent_context_ids(true);
3091 $contexts = implode(',' , $parents);
3092 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3093 FROM {role_allow_assign} raa
3094 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3095 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3096 ) ar ON ar.id = r.id";
3097 $params['userid'] = $userid;
3099 $params['contextlevel'] = $context->contextlevel;
3101 if ($coursecontext = $context->get_course_context(false)) {
3102 $params['coursecontext'] = $coursecontext->id;
3103 } else {
3104 $params['coursecontext'] = 0; // no course aliases
3105 $coursecontext = null;
3107 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3108 FROM {role} r
3109 $assignrestriction
3110 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3111 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3112 ORDER BY r.sortorder ASC";
3113 $roles = $DB->get_records_sql($sql, $params);
3115 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3117 if (!$withusercounts) {
3118 return $rolenames;
3121 $rolecounts = array();
3122 $nameswithcounts = array();
3123 foreach ($roles as $role) {
3124 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3125 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3127 return array($rolenames, $rolecounts, $nameswithcounts);
3131 * Gets a list of roles that this user can switch to in a context
3133 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3134 * This function just process the contents of the role_allow_switch table. You also need to
3135 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3137 * @param context $context a context.
3138 * @return array an array $roleid => $rolename.
3140 function get_switchable_roles(context $context) {
3141 global $USER, $DB;
3143 // You can't switch roles without this capability.
3144 if (!has_capability('moodle/role:switchroles', $context)) {
3145 return [];
3148 $params = array();
3149 $extrajoins = '';
3150 $extrawhere = '';
3151 if (!is_siteadmin()) {
3152 // Admins are allowed to switch to any role with.
3153 // Others are subject to the additional constraint that the switch-to role must be allowed by
3154 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3155 $parents = $context->get_parent_context_ids(true);
3156 $contexts = implode(',' , $parents);
3158 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3159 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3160 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3161 $params['userid'] = $USER->id;
3164 if ($coursecontext = $context->get_course_context(false)) {
3165 $params['coursecontext'] = $coursecontext->id;
3166 } else {
3167 $params['coursecontext'] = 0; // no course aliases
3168 $coursecontext = null;
3171 $query = "
3172 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3173 FROM (SELECT DISTINCT rc.roleid
3174 FROM {role_capabilities} rc
3176 $extrajoins
3177 $extrawhere) idlist
3178 JOIN {role} r ON r.id = idlist.roleid
3179 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3180 ORDER BY r.sortorder";
3181 $roles = $DB->get_records_sql($query, $params);
3183 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3187 * Gets a list of roles that this user can view in a context
3189 * @param context $context a context.
3190 * @param int $userid id of user.
3191 * @return array an array $roleid => $rolename.
3193 function get_viewable_roles(context $context, $userid = null) {
3194 global $USER, $DB;
3196 if ($userid == null) {
3197 $userid = $USER->id;
3200 $params = array();
3201 $extrajoins = '';
3202 $extrawhere = '';
3203 if (!is_siteadmin()) {
3204 // Admins are allowed to view any role.
3205 // Others are subject to the additional constraint that the view role must be allowed by
3206 // 'role_allow_view' for some role they have assigned in this context or any parent.
3207 $contexts = $context->get_parent_context_ids(true);
3208 list($insql, $inparams) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED);
3210 $extrajoins = "JOIN {role_allow_view} ras ON ras.allowview = r.id
3211 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3212 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid $insql";
3214 $params += $inparams;
3215 $params['userid'] = $userid;
3218 if ($coursecontext = $context->get_course_context(false)) {
3219 $params['coursecontext'] = $coursecontext->id;
3220 } else {
3221 $params['coursecontext'] = 0; // No course aliases.
3222 $coursecontext = null;
3225 $query = "
3226 SELECT r.id, r.name, r.shortname, rn.name AS coursealias, r.sortorder
3227 FROM {role} r
3228 $extrajoins
3229 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3230 $extrawhere
3231 GROUP BY r.id, r.name, r.shortname, rn.name, r.sortorder
3232 ORDER BY r.sortorder";
3233 $roles = $DB->get_records_sql($query, $params);
3235 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3239 * Gets a list of roles that this user can override in this context.
3241 * @param context $context the context.
3242 * @param int $rolenamedisplay the type of role name to display. One of the
3243 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3244 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3245 * @return array if $withcounts is false, then an array $roleid => $rolename.
3246 * if $withusercounts is true, returns a list of three arrays,
3247 * $rolenames, $rolecounts, and $nameswithcounts.
3249 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3250 global $USER, $DB;
3252 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3253 if ($withcounts) {
3254 return array(array(), array(), array());
3255 } else {
3256 return array();
3260 $parents = $context->get_parent_context_ids(true);
3261 $contexts = implode(',' , $parents);
3263 $params = array();
3264 $extrafields = '';
3266 $params['userid'] = $USER->id;
3267 if ($withcounts) {
3268 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3269 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3270 $params['conid'] = $context->id;
3273 if ($coursecontext = $context->get_course_context(false)) {
3274 $params['coursecontext'] = $coursecontext->id;
3275 } else {
3276 $params['coursecontext'] = 0; // no course aliases
3277 $coursecontext = null;
3280 if (is_siteadmin()) {
3281 // show all roles to admins
3282 $roles = $DB->get_records_sql("
3283 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3284 FROM {role} ro
3285 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3286 ORDER BY ro.sortorder ASC", $params);
3288 } else {
3289 $roles = $DB->get_records_sql("
3290 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3291 FROM {role} ro
3292 JOIN (SELECT DISTINCT r.id
3293 FROM {role} r
3294 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3295 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3296 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3297 ) inline_view ON ro.id = inline_view.id
3298 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3299 ORDER BY ro.sortorder ASC", $params);
3302 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3304 if (!$withcounts) {
3305 return $rolenames;
3308 $rolecounts = array();
3309 $nameswithcounts = array();
3310 foreach ($roles as $role) {
3311 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3312 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3314 return array($rolenames, $rolecounts, $nameswithcounts);
3318 * Create a role menu suitable for default role selection in enrol plugins.
3320 * @package core_enrol
3322 * @param context $context
3323 * @param int $addroleid current or default role - always added to list
3324 * @return array roleid=>localised role name
3326 function get_default_enrol_roles(context $context, $addroleid = null) {
3327 global $DB;
3329 $params = array('contextlevel'=>CONTEXT_COURSE);
3331 if ($coursecontext = $context->get_course_context(false)) {
3332 $params['coursecontext'] = $coursecontext->id;
3333 } else {
3334 $params['coursecontext'] = 0; // no course names
3335 $coursecontext = null;
3338 if ($addroleid) {
3339 $addrole = "OR r.id = :addroleid";
3340 $params['addroleid'] = $addroleid;
3341 } else {
3342 $addrole = "";
3345 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3346 FROM {role} r
3347 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3348 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3349 WHERE rcl.id IS NOT NULL $addrole
3350 ORDER BY sortorder DESC";
3352 $roles = $DB->get_records_sql($sql, $params);
3354 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3358 * Return context levels where this role is assignable.
3360 * @param integer $roleid the id of a role.
3361 * @return array list of the context levels at which this role may be assigned.
3363 function get_role_contextlevels($roleid) {
3364 global $DB;
3365 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3366 'contextlevel', 'id,contextlevel');
3370 * Return roles suitable for assignment at the specified context level.
3372 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3374 * @param integer $contextlevel a contextlevel.
3375 * @return array list of role ids that are assignable at this context level.
3377 function get_roles_for_contextlevels($contextlevel) {
3378 global $DB;
3379 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3380 '', 'id,roleid');
3384 * Returns default context levels where roles can be assigned.
3386 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3387 * from the array returned by get_role_archetypes();
3388 * @return array list of the context levels at which this type of role may be assigned by default.
3390 function get_default_contextlevels($rolearchetype) {
3391 static $defaults = array(
3392 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3393 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3394 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3395 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3396 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3397 'guest' => array(),
3398 'user' => array(),
3399 'frontpage' => array());
3401 if (isset($defaults[$rolearchetype])) {
3402 return $defaults[$rolearchetype];
3403 } else {
3404 return array();
3409 * Set the context levels at which a particular role can be assigned.
3410 * Throws exceptions in case of error.
3412 * @param integer $roleid the id of a role.
3413 * @param array $contextlevels the context levels at which this role should be assignable,
3414 * duplicate levels are removed.
3415 * @return void
3417 function set_role_contextlevels($roleid, array $contextlevels) {
3418 global $DB;
3419 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3420 $rcl = new stdClass();
3421 $rcl->roleid = $roleid;
3422 $contextlevels = array_unique($contextlevels);
3423 foreach ($contextlevels as $level) {
3424 $rcl->contextlevel = $level;
3425 $DB->insert_record('role_context_levels', $rcl, false, true);
3430 * Who has this capability in this context?
3432 * This can be a very expensive call - use sparingly and keep
3433 * the results if you are going to need them again soon.
3435 * Note if $fields is empty this function attempts to get u.*
3436 * which can get rather large - and has a serious perf impact
3437 * on some DBs.
3439 * @param context $context
3440 * @param string|array $capability - capability name(s)
3441 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3442 * @param string $sort - the sort order. Default is lastaccess time.
3443 * @param mixed $limitfrom - number of records to skip (offset)
3444 * @param mixed $limitnum - number of records to fetch
3445 * @param string|array $groups - single group or array of groups - only return
3446 * users who are in one of these group(s).
3447 * @param string|array $exceptions - list of users to exclude, comma separated or array
3448 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3449 * @param bool $view_ignored - use get_enrolled_sql() instead
3450 * @param bool $useviewallgroups if $groups is set the return users who
3451 * have capability both $capability and moodle/site:accessallgroups
3452 * in this context, as well as users who have $capability and who are
3453 * in $groups.
3454 * @return array of user records
3456 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3457 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3458 global $CFG, $DB;
3460 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3461 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3463 $ctxids = trim($context->path, '/');
3464 $ctxids = str_replace('/', ',', $ctxids);
3466 // Context is the frontpage
3467 $iscoursepage = false; // coursepage other than fp
3468 $isfrontpage = false;
3469 if ($context->contextlevel == CONTEXT_COURSE) {
3470 if ($context->instanceid == SITEID) {
3471 $isfrontpage = true;
3472 } else {
3473 $iscoursepage = true;
3476 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3478 $caps = (array)$capability;
3480 // construct list of context paths bottom-->top
3481 list($contextids, $paths) = get_context_info_list($context);
3483 // we need to find out all roles that have these capabilities either in definition or in overrides
3484 $defs = array();
3485 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3486 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3488 // Check whether context locking is enabled.
3489 // Filter out any write capability if this is the case.
3490 $excludelockedcaps = '';
3491 $excludelockedcapsparams = [];
3492 if (!empty($CFG->contextlocking) && $context->locked) {
3493 $excludelockedcaps = 'AND (cap.captype = :capread OR cap.name = :managelockscap)';
3494 $excludelockedcapsparams['capread'] = 'read';
3495 $excludelockedcapsparams['managelockscap'] = 'moodle/site:managecontextlocks';
3498 $params = array_merge($params, $params2, $excludelockedcapsparams);
3499 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3500 FROM {role_capabilities} rc
3501 JOIN {capabilities} cap ON rc.capability = cap.name
3502 JOIN {context} ctx on rc.contextid = ctx.id
3503 WHERE rc.contextid $incontexts AND rc.capability $incaps $excludelockedcaps";
3505 $rcs = $DB->get_records_sql($sql, $params);
3506 foreach ($rcs as $rc) {
3507 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3510 // go through the permissions bottom-->top direction to evaluate the current permission,
3511 // first one wins (prohibit is an exception that always wins)
3512 $access = array();
3513 foreach ($caps as $cap) {
3514 foreach ($paths as $path) {
3515 if (empty($defs[$cap][$path])) {
3516 continue;
3518 foreach($defs[$cap][$path] as $roleid => $perm) {
3519 if ($perm == CAP_PROHIBIT) {
3520 $access[$cap][$roleid] = CAP_PROHIBIT;
3521 continue;
3523 if (!isset($access[$cap][$roleid])) {
3524 $access[$cap][$roleid] = (int)$perm;
3530 // make lists of roles that are needed and prohibited in this context
3531 $needed = array(); // one of these is enough
3532 $prohibited = array(); // must not have any of these
3533 foreach ($caps as $cap) {
3534 if (empty($access[$cap])) {
3535 continue;
3537 foreach ($access[$cap] as $roleid => $perm) {
3538 if ($perm == CAP_PROHIBIT) {
3539 unset($needed[$cap][$roleid]);
3540 $prohibited[$cap][$roleid] = true;
3541 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3542 $needed[$cap][$roleid] = true;
3545 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3546 // easy, nobody has the permission
3547 unset($needed[$cap]);
3548 unset($prohibited[$cap]);
3549 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3550 // everybody is disqualified on the frontpage
3551 unset($needed[$cap]);
3552 unset($prohibited[$cap]);
3554 if (empty($prohibited[$cap])) {
3555 unset($prohibited[$cap]);
3559 if (empty($needed)) {
3560 // there can not be anybody if no roles match this request
3561 return array();
3564 if (empty($prohibited)) {
3565 // we can compact the needed roles
3566 $n = array();
3567 foreach ($needed as $cap) {
3568 foreach ($cap as $roleid=>$unused) {
3569 $n[$roleid] = true;
3572 $needed = array('any'=>$n);
3573 unset($n);
3576 // ***** Set up default fields ******
3577 if (empty($fields)) {
3578 if ($iscoursepage) {
3579 $fields = 'u.*, ul.timeaccess AS lastaccess';
3580 } else {
3581 $fields = 'u.*';
3583 } else {
3584 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3585 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3589 // Set up default sort
3590 if (empty($sort)) { // default to course lastaccess or just lastaccess
3591 if ($iscoursepage) {
3592 $sort = 'ul.timeaccess';
3593 } else {
3594 $sort = 'u.lastaccess';
3598 // Prepare query clauses
3599 $wherecond = array();
3600 $params = array();
3601 $joins = array();
3603 // User lastaccess JOIN
3604 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3605 // user_lastaccess is not required MDL-13810
3606 } else {
3607 if ($iscoursepage) {
3608 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3609 } else {
3610 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3614 // We never return deleted users or guest account.
3615 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3616 $params['guestid'] = $CFG->siteguest;
3618 // Groups
3619 if ($groups) {
3620 $groups = (array)$groups;
3621 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3622 $joins[] = "LEFT OUTER JOIN (SELECT DISTINCT userid
3623 FROM {groups_members}
3624 WHERE groupid $grouptest
3625 ) gm ON gm.userid = u.id";
3627 $params = array_merge($params, $grpparams);
3629 $grouptest = 'gm.userid IS NOT NULL';
3630 if ($useviewallgroups) {
3631 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3632 if (!empty($viewallgroupsusers)) {
3633 $grouptest .= ' OR u.id IN (' . implode(',', array_keys($viewallgroupsusers)) . ')';
3636 $wherecond[] = "($grouptest)";
3639 // User exceptions
3640 if (!empty($exceptions)) {
3641 $exceptions = (array)$exceptions;
3642 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3643 $params = array_merge($params, $exparams);
3644 $wherecond[] = "u.id $exsql";
3647 // now add the needed and prohibited roles conditions as joins
3648 if (!empty($needed['any'])) {
3649 // simple case - there are no prohibits involved
3650 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3651 // everybody
3652 } else {
3653 $joins[] = "JOIN (SELECT DISTINCT userid
3654 FROM {role_assignments}
3655 WHERE contextid IN ($ctxids)
3656 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3657 ) ra ON ra.userid = u.id";
3659 } else {
3660 $unions = array();
3661 $everybody = false;
3662 foreach ($needed as $cap=>$unused) {
3663 if (empty($prohibited[$cap])) {
3664 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3665 $everybody = true;
3666 break;
3667 } else {
3668 $unions[] = "SELECT userid
3669 FROM {role_assignments}
3670 WHERE contextid IN ($ctxids)
3671 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3673 } else {
3674 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3675 // nobody can have this cap because it is prevented in default roles
3676 continue;
3678 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3679 // everybody except the prohibitted - hiding does not matter
3680 $unions[] = "SELECT id AS userid
3681 FROM {user}
3682 WHERE id NOT IN (SELECT userid
3683 FROM {role_assignments}
3684 WHERE contextid IN ($ctxids)
3685 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3687 } else {
3688 $unions[] = "SELECT userid
3689 FROM {role_assignments}
3690 WHERE contextid IN ($ctxids) AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3691 AND userid NOT IN (
3692 SELECT userid
3693 FROM {role_assignments}
3694 WHERE contextid IN ($ctxids)
3695 AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . ")
3700 if (!$everybody) {
3701 if ($unions) {
3702 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3703 } else {
3704 // only prohibits found - nobody can be matched
3705 $wherecond[] = "1 = 2";
3710 // Collect WHERE conditions and needed joins
3711 $where = implode(' AND ', $wherecond);
3712 if ($where !== '') {
3713 $where = 'WHERE ' . $where;
3715 $joins = implode("\n", $joins);
3717 // Ok, let's get the users!
3718 $sql = "SELECT $fields
3719 FROM {user} u
3720 $joins
3721 $where
3722 ORDER BY $sort";
3724 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3728 * Re-sort a users array based on a sorting policy
3730 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3731 * based on a sorting policy. This is to support the odd practice of
3732 * sorting teachers by 'authority', where authority was "lowest id of the role
3733 * assignment".
3735 * Will execute 1 database query. Only suitable for small numbers of users, as it
3736 * uses an u.id IN() clause.
3738 * Notes about the sorting criteria.
3740 * As a default, we cannot rely on role.sortorder because then
3741 * admins/coursecreators will always win. That is why the sane
3742 * rule "is locality matters most", with sortorder as 2nd
3743 * consideration.
3745 * If you want role.sortorder, use the 'sortorder' policy, and
3746 * name explicitly what roles you want to cover. It's probably
3747 * a good idea to see what roles have the capabilities you want
3748 * (array_diff() them against roiles that have 'can-do-anything'
3749 * to weed out admin-ish roles. Or fetch a list of roles from
3750 * variables like $CFG->coursecontact .
3752 * @param array $users Users array, keyed on userid
3753 * @param context $context
3754 * @param array $roles ids of the roles to include, optional
3755 * @param string $sortpolicy defaults to locality, more about
3756 * @return array sorted copy of the array
3758 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3759 global $DB;
3761 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3762 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3763 if (empty($roles)) {
3764 $roleswhere = '';
3765 } else {
3766 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3769 $sql = "SELECT ra.userid
3770 FROM {role_assignments} ra
3771 JOIN {role} r
3772 ON ra.roleid=r.id
3773 JOIN {context} ctx
3774 ON ra.contextid=ctx.id
3775 WHERE $userswhere
3776 $contextwhere
3777 $roleswhere";
3779 // Default 'locality' policy -- read PHPDoc notes
3780 // about sort policies...
3781 $orderby = 'ORDER BY '
3782 .'ctx.depth DESC, ' /* locality wins */
3783 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3784 .'ra.id'; /* role assignment order tie-breaker */
3785 if ($sortpolicy === 'sortorder') {
3786 $orderby = 'ORDER BY '
3787 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3788 .'ra.id'; /* role assignment order tie-breaker */
3791 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3792 $sortedusers = array();
3793 $seen = array();
3795 foreach ($sortedids as $id) {
3796 // Avoid duplicates
3797 if (isset($seen[$id])) {
3798 continue;
3800 $seen[$id] = true;
3802 // assign
3803 $sortedusers[$id] = $users[$id];
3805 return $sortedusers;
3809 * Gets all the users assigned this role in this context or higher
3811 * Note that moodle is based on capabilities and it is usually better
3812 * to check permissions than to check role ids as the capabilities
3813 * system is more flexible. If you really need, you can to use this
3814 * function but consider has_capability() as a possible substitute.
3816 * All $sort fields are added into $fields if not present there yet.
3818 * If $roleid is an array or is empty (all roles) you need to set $fields
3819 * (and $sort by extension) params according to it, as the first field
3820 * returned by the database should be unique (ra.id is the best candidate).
3822 * @param int $roleid (can also be an array of ints!)
3823 * @param context $context
3824 * @param bool $parent if true, get list of users assigned in higher context too
3825 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3826 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3827 * null => use default sort from users_order_by_sql.
3828 * @param bool $all true means all, false means limit to enrolled users
3829 * @param string $group defaults to ''
3830 * @param mixed $limitfrom defaults to ''
3831 * @param mixed $limitnum defaults to ''
3832 * @param string $extrawheretest defaults to ''
3833 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3834 * @return array
3836 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3837 $sort = null, $all = true, $group = '',
3838 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3839 global $DB;
3841 if (empty($fields)) {
3842 $allnames = get_all_user_name_fields(true, 'u');
3843 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
3844 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3845 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3846 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3847 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3850 // Prevent wrong function uses.
3851 if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
3852 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
3853 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
3855 if (!empty($roleid)) {
3856 // Solving partially the issue when specifying multiple roles.
3857 $users = array();
3858 foreach ($roleid as $id) {
3859 // Ignoring duplicated keys keeping the first user appearance.
3860 $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
3861 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
3863 return $users;
3867 $parentcontexts = '';
3868 if ($parent) {
3869 $parentcontexts = substr($context->path, 1); // kill leading slash
3870 $parentcontexts = str_replace('/', ',', $parentcontexts);
3871 if ($parentcontexts !== '') {
3872 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3876 if ($roleid) {
3877 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
3878 $roleselect = "AND ra.roleid $rids";
3879 } else {
3880 $params = array();
3881 $roleselect = '';
3884 if ($coursecontext = $context->get_course_context(false)) {
3885 $params['coursecontext'] = $coursecontext->id;
3886 } else {
3887 $params['coursecontext'] = 0;
3890 if ($group) {
3891 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3892 $groupselect = " AND gm.groupid = :groupid ";
3893 $params['groupid'] = $group;
3894 } else {
3895 $groupjoin = '';
3896 $groupselect = '';
3899 $params['contextid'] = $context->id;
3901 if ($extrawheretest) {
3902 $extrawheretest = ' AND ' . $extrawheretest;
3905 if ($whereorsortparams) {
3906 $params = array_merge($params, $whereorsortparams);
3909 if (!$sort) {
3910 list($sort, $sortparams) = users_order_by_sql('u');
3911 $params = array_merge($params, $sortparams);
3914 // Adding the fields from $sort that are not present in $fields.
3915 $sortarray = preg_split('/,\s*/', $sort);
3916 $fieldsarray = preg_split('/,\s*/', $fields);
3918 // Discarding aliases from the fields.
3919 $fieldnames = array();
3920 foreach ($fieldsarray as $key => $field) {
3921 list($fieldnames[$key]) = explode(' ', $field);
3924 $addedfields = array();
3925 foreach ($sortarray as $sortfield) {
3926 // Throw away any additional arguments to the sort (e.g. ASC/DESC).
3927 list($sortfield) = explode(' ', $sortfield);
3928 list($tableprefix) = explode('.', $sortfield);
3929 $fieldpresent = false;
3930 foreach ($fieldnames as $fieldname) {
3931 if ($fieldname === $sortfield || $fieldname === $tableprefix.'.*') {
3932 $fieldpresent = true;
3933 break;
3937 if (!$fieldpresent) {
3938 $fieldsarray[] = $sortfield;
3939 $addedfields[] = $sortfield;
3943 $fields = implode(', ', $fieldsarray);
3944 if (!empty($addedfields)) {
3945 $addedfields = implode(', ', $addedfields);
3946 debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
3949 if ($all === null) {
3950 // Previously null was used to indicate that parameter was not used.
3951 $all = true;
3953 if (!$all and $coursecontext) {
3954 // Do not use get_enrolled_sql() here for performance reasons.
3955 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
3956 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
3957 $params['ecourseid'] = $coursecontext->instanceid;
3958 } else {
3959 $ejoin = "";
3962 $sql = "SELECT DISTINCT $fields, ra.roleid
3963 FROM {role_assignments} ra
3964 JOIN {user} u ON u.id = ra.userid
3965 JOIN {role} r ON ra.roleid = r.id
3966 $ejoin
3967 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3968 $groupjoin
3969 WHERE (ra.contextid = :contextid $parentcontexts)
3970 $roleselect
3971 $groupselect
3972 $extrawheretest
3973 ORDER BY $sort"; // join now so that we can just use fullname() later
3975 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3979 * Counts all the users assigned this role in this context or higher
3981 * @param int|array $roleid either int or an array of ints
3982 * @param context $context
3983 * @param bool $parent if true, get list of users assigned in higher context too
3984 * @return int Returns the result count
3986 function count_role_users($roleid, context $context, $parent = false) {
3987 global $DB;
3989 if ($parent) {
3990 if ($contexts = $context->get_parent_context_ids()) {
3991 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3992 } else {
3993 $parentcontexts = '';
3995 } else {
3996 $parentcontexts = '';
3999 if ($roleid) {
4000 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
4001 $roleselect = "AND r.roleid $rids";
4002 } else {
4003 $params = array();
4004 $roleselect = '';
4007 array_unshift($params, $context->id);
4009 $sql = "SELECT COUNT(DISTINCT u.id)
4010 FROM {role_assignments} r
4011 JOIN {user} u ON u.id = r.userid
4012 WHERE (r.contextid = ? $parentcontexts)
4013 $roleselect
4014 AND u.deleted = 0";
4016 return $DB->count_records_sql($sql, $params);
4020 * This function gets the list of courses that this user has a particular capability in.
4022 * It is now reasonably efficient, but bear in mind that if there are users who have the capability
4023 * everywhere, it may return an array of all courses.
4025 * @param string $capability Capability in question
4026 * @param int $userid User ID or null for current user
4027 * @param bool $doanything True if 'doanything' is permitted (default)
4028 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4029 * otherwise use a comma-separated list of the fields you require, not including id.
4030 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
4031 * @param string $orderby If set, use a comma-separated list of fields from course
4032 * table with sql modifiers (DESC) if needed
4033 * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
4034 * @return array|bool Array of courses, if none found false is returned.
4036 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '',
4037 $limit = 0) {
4038 global $DB, $USER;
4040 // Default to current user.
4041 if (!$userid) {
4042 $userid = $USER->id;
4045 if ($doanything && is_siteadmin($userid)) {
4046 // If the user is a site admin and $doanything is enabled then there is no need to restrict
4047 // the list of courses.
4048 $contextlimitsql = '';
4049 $contextlimitparams = [];
4050 } else {
4051 // Gets SQL to limit contexts ('x' table) to those where the user has this capability.
4052 list ($contextlimitsql, $contextlimitparams) = \core\access\get_user_capability_course_helper::get_sql(
4053 $userid, $capability);
4054 if (!$contextlimitsql) {
4055 // If the does not have this capability in any context, return false without querying.
4056 return false;
4059 $contextlimitsql = 'WHERE' . $contextlimitsql;
4062 // Convert fields list and ordering
4063 $fieldlist = '';
4064 if ($fieldsexceptid) {
4065 $fields = array_map('trim', explode(',', $fieldsexceptid));
4066 foreach($fields as $field) {
4067 // Context fields have a different alias.
4068 if (strpos($field, 'ctx') === 0) {
4069 switch($field) {
4070 case 'ctxlevel' :
4071 $realfield = 'contextlevel';
4072 break;
4073 case 'ctxinstance' :
4074 $realfield = 'instanceid';
4075 break;
4076 default:
4077 $realfield = substr($field, 3);
4078 break;
4080 $fieldlist .= ',x.' . $realfield . ' AS ' . $field;
4081 } else {
4082 $fieldlist .= ',c.'.$field;
4086 if ($orderby) {
4087 $fields = explode(',', $orderby);
4088 $orderby = '';
4089 foreach($fields as $field) {
4090 if ($orderby) {
4091 $orderby .= ',';
4093 $orderby .= 'c.'.$field;
4095 $orderby = 'ORDER BY '.$orderby;
4098 $courses = array();
4099 $rs = $DB->get_recordset_sql("
4100 SELECT c.id $fieldlist
4101 FROM {course} c
4102 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
4103 $contextlimitsql
4104 $orderby", array_merge([CONTEXT_COURSE], $contextlimitparams));
4105 foreach ($rs as $course) {
4106 $courses[] = $course;
4107 $limit--;
4108 if ($limit == 0) {
4109 break;
4112 $rs->close();
4113 return empty($courses) ? false : $courses;
4117 * Switches the current user to another role for the current session and only
4118 * in the given context.
4120 * The caller *must* check
4121 * - that this op is allowed
4122 * - that the requested role can be switched to in this context (use get_switchable_roles)
4123 * - that the requested role is NOT $CFG->defaultuserroleid
4125 * To "unswitch" pass 0 as the roleid.
4127 * This function *will* modify $USER->access - beware
4129 * @param integer $roleid the role to switch to.
4130 * @param context $context the context in which to perform the switch.
4131 * @return bool success or failure.
4133 function role_switch($roleid, context $context) {
4134 global $USER;
4136 // Add the ghost RA to $USER->access as $USER->access['rsw'][$path] = $roleid.
4137 // To un-switch just unset($USER->access['rsw'][$path]).
4139 // Note: it is not possible to switch to roles that do not have course:view
4141 if (!isset($USER->access)) {
4142 load_all_capabilities();
4145 // Add the switch RA
4146 if ($roleid == 0) {
4147 unset($USER->access['rsw'][$context->path]);
4148 return true;
4151 $USER->access['rsw'][$context->path] = $roleid;
4153 return true;
4157 * Checks if the user has switched roles within the given course.
4159 * Note: You can only switch roles within the course, hence it takes a course id
4160 * rather than a context. On that note Petr volunteered to implement this across
4161 * all other contexts, all requests for this should be forwarded to him ;)
4163 * @param int $courseid The id of the course to check
4164 * @return bool True if the user has switched roles within the course.
4166 function is_role_switched($courseid) {
4167 global $USER;
4168 $context = context_course::instance($courseid, MUST_EXIST);
4169 return (!empty($USER->access['rsw'][$context->path]));
4173 * Get any role that has an override on exact context
4175 * @param context $context The context to check
4176 * @return array An array of roles
4178 function get_roles_with_override_on_context(context $context) {
4179 global $DB;
4181 return $DB->get_records_sql("SELECT r.*
4182 FROM {role_capabilities} rc, {role} r
4183 WHERE rc.roleid = r.id AND rc.contextid = ?",
4184 array($context->id));
4188 * Get all capabilities for this role on this context (overrides)
4190 * @param stdClass $role
4191 * @param context $context
4192 * @return array
4194 function get_capabilities_from_role_on_context($role, context $context) {
4195 global $DB;
4197 return $DB->get_records_sql("SELECT *
4198 FROM {role_capabilities}
4199 WHERE contextid = ? AND roleid = ?",
4200 array($context->id, $role->id));
4204 * Find all user assignment of users for this role, on this context
4206 * @param stdClass $role
4207 * @param context $context
4208 * @return array
4210 function get_users_from_role_on_context($role, context $context) {
4211 global $DB;
4213 return $DB->get_records_sql("SELECT *
4214 FROM {role_assignments}
4215 WHERE contextid = ? AND roleid = ?",
4216 array($context->id, $role->id));
4220 * Simple function returning a boolean true if user has roles
4221 * in context or parent contexts, otherwise false.
4223 * @param int $userid
4224 * @param int $roleid
4225 * @param int $contextid empty means any context
4226 * @return bool
4228 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4229 global $DB;
4231 if ($contextid) {
4232 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4233 return false;
4235 $parents = $context->get_parent_context_ids(true);
4236 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4237 $params['userid'] = $userid;
4238 $params['roleid'] = $roleid;
4240 $sql = "SELECT COUNT(ra.id)
4241 FROM {role_assignments} ra
4242 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4244 $count = $DB->get_field_sql($sql, $params);
4245 return ($count > 0);
4247 } else {
4248 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4253 * Get localised role name or alias if exists and format the text.
4255 * @param stdClass $role role object
4256 * - optional 'coursealias' property should be included for performance reasons if course context used
4257 * - description property is not required here
4258 * @param context|bool $context empty means system context
4259 * @param int $rolenamedisplay type of role name
4260 * @return string localised role name or course role name alias
4262 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4263 global $DB;
4265 if ($rolenamedisplay == ROLENAME_SHORT) {
4266 return $role->shortname;
4269 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4270 $coursecontext = null;
4273 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4274 $role = clone($role); // Do not modify parameters.
4275 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4276 $role->coursealias = $r->name;
4277 } else {
4278 $role->coursealias = null;
4282 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4283 if ($coursecontext) {
4284 return $role->coursealias;
4285 } else {
4286 return null;
4290 if (trim($role->name) !== '') {
4291 // For filtering always use context where was the thing defined - system for roles here.
4292 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4294 } else {
4295 // Empty role->name means we want to see localised role name based on shortname,
4296 // only default roles are supposed to be localised.
4297 switch ($role->shortname) {
4298 case 'manager': $original = get_string('manager', 'role'); break;
4299 case 'coursecreator': $original = get_string('coursecreators'); break;
4300 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4301 case 'teacher': $original = get_string('noneditingteacher'); break;
4302 case 'student': $original = get_string('defaultcoursestudent'); break;
4303 case 'guest': $original = get_string('guest'); break;
4304 case 'user': $original = get_string('authenticateduser'); break;
4305 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4306 // We should not get here, the role UI should require the name for custom roles!
4307 default: $original = $role->shortname; break;
4311 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4312 return $original;
4315 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4316 return "$original ($role->shortname)";
4319 if ($rolenamedisplay == ROLENAME_ALIAS) {
4320 if ($coursecontext and trim($role->coursealias) !== '') {
4321 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4322 } else {
4323 return $original;
4327 if ($rolenamedisplay == ROLENAME_BOTH) {
4328 if ($coursecontext and trim($role->coursealias) !== '') {
4329 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4330 } else {
4331 return $original;
4335 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4339 * Returns localised role description if available.
4340 * If the name is empty it tries to find the default role name using
4341 * hardcoded list of default role names or other methods in the future.
4343 * @param stdClass $role
4344 * @return string localised role name
4346 function role_get_description(stdClass $role) {
4347 if (!html_is_blank($role->description)) {
4348 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4351 switch ($role->shortname) {
4352 case 'manager': return get_string('managerdescription', 'role');
4353 case 'coursecreator': return get_string('coursecreatorsdescription');
4354 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4355 case 'teacher': return get_string('noneditingteacherdescription');
4356 case 'student': return get_string('defaultcoursestudentdescription');
4357 case 'guest': return get_string('guestdescription');
4358 case 'user': return get_string('authenticateduserdescription');
4359 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4360 default: return '';
4365 * Get all the localised role names for a context.
4367 * In new installs default roles have empty names, this function
4368 * add localised role names using current language pack.
4370 * @param context $context the context, null means system context
4371 * @param array of role objects with a ->localname field containing the context-specific role name.
4372 * @param int $rolenamedisplay
4373 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4374 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4376 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4377 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4381 * Prepare list of roles for display, apply aliases and localise default role names.
4383 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4384 * @param context $context the context, null means system context
4385 * @param int $rolenamedisplay
4386 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4387 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4389 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4390 global $DB;
4392 if (empty($roleoptions)) {
4393 return array();
4396 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4397 $coursecontext = null;
4400 // We usually need all role columns...
4401 $first = reset($roleoptions);
4402 if ($returnmenu === null) {
4403 $returnmenu = !is_object($first);
4406 if (!is_object($first) or !property_exists($first, 'shortname')) {
4407 $allroles = get_all_roles($context);
4408 foreach ($roleoptions as $rid => $unused) {
4409 $roleoptions[$rid] = $allroles[$rid];
4413 // Inject coursealias if necessary.
4414 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4415 $first = reset($roleoptions);
4416 if (!property_exists($first, 'coursealias')) {
4417 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4418 foreach ($aliasnames as $alias) {
4419 if (isset($roleoptions[$alias->roleid])) {
4420 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4426 // Add localname property.
4427 foreach ($roleoptions as $rid => $role) {
4428 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4431 if (!$returnmenu) {
4432 return $roleoptions;
4435 $menu = array();
4436 foreach ($roleoptions as $rid => $role) {
4437 $menu[$rid] = $role->localname;
4440 return $menu;
4444 * Aids in detecting if a new line is required when reading a new capability
4446 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4447 * when we read in a new capability.
4448 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4449 * but when we are in grade, all reports/import/export capabilities should be together
4451 * @param string $cap component string a
4452 * @param string $comp component string b
4453 * @param int $contextlevel
4454 * @return bool whether 2 component are in different "sections"
4456 function component_level_changed($cap, $comp, $contextlevel) {
4458 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4459 $compsa = explode('/', $cap->component);
4460 $compsb = explode('/', $comp);
4462 // list of system reports
4463 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4464 return false;
4467 // we are in gradebook, still
4468 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4469 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4470 return false;
4473 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4474 return false;
4478 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4482 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4483 * and return an array of roleids in order.
4485 * @param array $allroles array of roles, as returned by get_all_roles();
4486 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4488 function fix_role_sortorder($allroles) {
4489 global $DB;
4491 $rolesort = array();
4492 $i = 0;
4493 foreach ($allroles as $role) {
4494 $rolesort[$i] = $role->id;
4495 if ($role->sortorder != $i) {
4496 $r = new stdClass();
4497 $r->id = $role->id;
4498 $r->sortorder = $i;
4499 $DB->update_record('role', $r);
4500 $allroles[$role->id]->sortorder = $i;
4502 $i++;
4504 return $rolesort;
4508 * Switch the sort order of two roles (used in admin/roles/manage.php).
4510 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4511 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4512 * @return boolean success or failure
4514 function switch_roles($first, $second) {
4515 global $DB;
4516 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4517 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4518 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4519 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4520 return $result;
4524 * Duplicates all the base definitions of a role
4526 * @param stdClass $sourcerole role to copy from
4527 * @param int $targetrole id of role to copy to
4529 function role_cap_duplicate($sourcerole, $targetrole) {
4530 global $DB;
4532 $systemcontext = context_system::instance();
4533 $caps = $DB->get_records_sql("SELECT *
4534 FROM {role_capabilities}
4535 WHERE roleid = ? AND contextid = ?",
4536 array($sourcerole->id, $systemcontext->id));
4537 // adding capabilities
4538 foreach ($caps as $cap) {
4539 unset($cap->id);
4540 $cap->roleid = $targetrole;
4541 $DB->insert_record('role_capabilities', $cap);
4544 // Reset any cache of this role, including MUC.
4545 accesslib_clear_role_cache($targetrole);
4549 * Returns two lists, this can be used to find out if user has capability.
4550 * Having any needed role and no forbidden role in this context means
4551 * user has this capability in this context.
4552 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4554 * @param stdClass $context
4555 * @param string $capability
4556 * @return array($neededroles, $forbiddenroles)
4558 function get_roles_with_cap_in_context($context, $capability) {
4559 global $DB;
4561 $ctxids = trim($context->path, '/'); // kill leading slash
4562 $ctxids = str_replace('/', ',', $ctxids);
4564 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4565 FROM {role_capabilities} rc
4566 JOIN {context} ctx ON ctx.id = rc.contextid
4567 JOIN {capabilities} cap ON rc.capability = cap.name
4568 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4569 ORDER BY rc.roleid ASC, ctx.depth DESC";
4570 $params = array('cap'=>$capability);
4572 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4573 // no cap definitions --> no capability
4574 return array(array(), array());
4577 $forbidden = array();
4578 $needed = array();
4579 foreach($capdefs as $def) {
4580 if (isset($forbidden[$def->roleid])) {
4581 continue;
4583 if ($def->permission == CAP_PROHIBIT) {
4584 $forbidden[$def->roleid] = $def->roleid;
4585 unset($needed[$def->roleid]);
4586 continue;
4588 if (!isset($needed[$def->roleid])) {
4589 if ($def->permission == CAP_ALLOW) {
4590 $needed[$def->roleid] = true;
4591 } else if ($def->permission == CAP_PREVENT) {
4592 $needed[$def->roleid] = false;
4596 unset($capdefs);
4598 // remove all those roles not allowing
4599 foreach($needed as $key=>$value) {
4600 if (!$value) {
4601 unset($needed[$key]);
4602 } else {
4603 $needed[$key] = $key;
4607 return array($needed, $forbidden);
4611 * Returns an array of role IDs that have ALL of the the supplied capabilities
4612 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4614 * @param stdClass $context
4615 * @param array $capabilities An array of capabilities
4616 * @return array of roles with all of the required capabilities
4618 function get_roles_with_caps_in_context($context, $capabilities) {
4619 $neededarr = array();
4620 $forbiddenarr = array();
4621 foreach($capabilities as $caprequired) {
4622 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4625 $rolesthatcanrate = array();
4626 if (!empty($neededarr)) {
4627 foreach ($neededarr as $needed) {
4628 if (empty($rolesthatcanrate)) {
4629 $rolesthatcanrate = $needed;
4630 } else {
4631 //only want roles that have all caps
4632 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4636 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4637 foreach ($forbiddenarr as $forbidden) {
4638 //remove any roles that are forbidden any of the caps
4639 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4642 return $rolesthatcanrate;
4646 * Returns an array of role names that have ALL of the the supplied capabilities
4647 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4649 * @param stdClass $context
4650 * @param array $capabilities An array of capabilities
4651 * @return array of roles with all of the required capabilities
4653 function get_role_names_with_caps_in_context($context, $capabilities) {
4654 global $DB;
4656 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4657 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4659 $roles = array();
4660 foreach ($rolesthatcanrate as $r) {
4661 $roles[$r] = $allroles[$r];
4664 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4668 * This function verifies the prohibit comes from this context
4669 * and there are no more prohibits in parent contexts.
4671 * @param int $roleid
4672 * @param context $context
4673 * @param string $capability name
4674 * @return bool
4676 function prohibit_is_removable($roleid, context $context, $capability) {
4677 global $DB;
4679 $ctxids = trim($context->path, '/'); // kill leading slash
4680 $ctxids = str_replace('/', ',', $ctxids);
4682 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4684 $sql = "SELECT ctx.id
4685 FROM {role_capabilities} rc
4686 JOIN {context} ctx ON ctx.id = rc.contextid
4687 JOIN {capabilities} cap ON rc.capability = cap.name
4688 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4689 ORDER BY ctx.depth DESC";
4691 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4692 // no prohibits == nothing to remove
4693 return true;
4696 if (count($prohibits) > 1) {
4697 // more prohibits can not be removed
4698 return false;
4701 return !empty($prohibits[$context->id]);
4705 * More user friendly role permission changing,
4706 * it should produce as few overrides as possible.
4708 * @param int $roleid
4709 * @param stdClass $context
4710 * @param string $capname capability name
4711 * @param int $permission
4712 * @return void
4714 function role_change_permission($roleid, $context, $capname, $permission) {
4715 global $DB;
4717 if ($permission == CAP_INHERIT) {
4718 unassign_capability($capname, $roleid, $context->id);
4719 return;
4722 $ctxids = trim($context->path, '/'); // kill leading slash
4723 $ctxids = str_replace('/', ',', $ctxids);
4725 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4727 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4728 FROM {role_capabilities} rc
4729 JOIN {context} ctx ON ctx.id = rc.contextid
4730 JOIN {capabilities} cap ON rc.capability = cap.name
4731 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4732 ORDER BY ctx.depth DESC";
4734 if ($existing = $DB->get_records_sql($sql, $params)) {
4735 foreach($existing as $e) {
4736 if ($e->permission == CAP_PROHIBIT) {
4737 // prohibit can not be overridden, no point in changing anything
4738 return;
4741 $lowest = array_shift($existing);
4742 if ($lowest->permission == $permission) {
4743 // permission already set in this context or parent - nothing to do
4744 return;
4746 if ($existing) {
4747 $parent = array_shift($existing);
4748 if ($parent->permission == $permission) {
4749 // permission already set in parent context or parent - just unset in this context
4750 // we do this because we want as few overrides as possible for performance reasons
4751 unassign_capability($capname, $roleid, $context->id);
4752 return;
4756 } else {
4757 if ($permission == CAP_PREVENT) {
4758 // nothing means role does not have permission
4759 return;
4763 // assign the needed capability
4764 assign_capability($capname, $permission, $roleid, $context->id, true);
4769 * Basic moodle context abstraction class.
4771 * Google confirms that no other important framework is using "context" class,
4772 * we could use something else like mcontext or moodle_context, but we need to type
4773 * this very often which would be annoying and it would take too much space...
4775 * This class is derived from stdClass for backwards compatibility with
4776 * odl $context record that was returned from DML $DB->get_record()
4778 * @package core_access
4779 * @category access
4780 * @copyright Petr Skoda {@link http://skodak.org}
4781 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4782 * @since Moodle 2.2
4784 * @property-read int $id context id
4785 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4786 * @property-read int $instanceid id of related instance in each context
4787 * @property-read string $path path to context, starts with system context
4788 * @property-read int $depth
4790 abstract class context extends stdClass implements IteratorAggregate {
4793 * The context id
4794 * Can be accessed publicly through $context->id
4795 * @var int
4797 protected $_id;
4800 * The context level
4801 * Can be accessed publicly through $context->contextlevel
4802 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4804 protected $_contextlevel;
4807 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4808 * Can be accessed publicly through $context->instanceid
4809 * @var int
4811 protected $_instanceid;
4814 * The path to the context always starting from the system context
4815 * Can be accessed publicly through $context->path
4816 * @var string
4818 protected $_path;
4821 * The depth of the context in relation to parent contexts
4822 * Can be accessed publicly through $context->depth
4823 * @var int
4825 protected $_depth;
4828 * Whether this context is locked or not.
4830 * Can be accessed publicly through $context->locked.
4832 * @var int
4834 protected $_locked;
4837 * @var array Context caching info
4839 private static $cache_contextsbyid = array();
4842 * @var array Context caching info
4844 private static $cache_contexts = array();
4847 * Context count
4848 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4849 * @var int
4851 protected static $cache_count = 0;
4854 * @var array Context caching info
4856 protected static $cache_preloaded = array();
4859 * @var context_system The system context once initialised
4861 protected static $systemcontext = null;
4864 * Resets the cache to remove all data.
4865 * @static
4867 protected static function reset_caches() {
4868 self::$cache_contextsbyid = array();
4869 self::$cache_contexts = array();
4870 self::$cache_count = 0;
4871 self::$cache_preloaded = array();
4873 self::$systemcontext = null;
4877 * Adds a context to the cache. If the cache is full, discards a batch of
4878 * older entries.
4880 * @static
4881 * @param context $context New context to add
4882 * @return void
4884 protected static function cache_add(context $context) {
4885 if (isset(self::$cache_contextsbyid[$context->id])) {
4886 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4887 return;
4890 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4891 $i = 0;
4892 foreach(self::$cache_contextsbyid as $ctx) {
4893 $i++;
4894 if ($i <= 100) {
4895 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4896 continue;
4898 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4899 // we remove oldest third of the contexts to make room for more contexts
4900 break;
4902 unset(self::$cache_contextsbyid[$ctx->id]);
4903 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4904 self::$cache_count--;
4908 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4909 self::$cache_contextsbyid[$context->id] = $context;
4910 self::$cache_count++;
4914 * Removes a context from the cache.
4916 * @static
4917 * @param context $context Context object to remove
4918 * @return void
4920 protected static function cache_remove(context $context) {
4921 if (!isset(self::$cache_contextsbyid[$context->id])) {
4922 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4923 return;
4925 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4926 unset(self::$cache_contextsbyid[$context->id]);
4928 self::$cache_count--;
4930 if (self::$cache_count < 0) {
4931 self::$cache_count = 0;
4936 * Gets a context from the cache.
4938 * @static
4939 * @param int $contextlevel Context level
4940 * @param int $instance Instance ID
4941 * @return context|bool Context or false if not in cache
4943 protected static function cache_get($contextlevel, $instance) {
4944 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4945 return self::$cache_contexts[$contextlevel][$instance];
4947 return false;
4951 * Gets a context from the cache based on its id.
4953 * @static
4954 * @param int $id Context ID
4955 * @return context|bool Context or false if not in cache
4957 protected static function cache_get_by_id($id) {
4958 if (isset(self::$cache_contextsbyid[$id])) {
4959 return self::$cache_contextsbyid[$id];
4961 return false;
4965 * Preloads context information from db record and strips the cached info.
4967 * @static
4968 * @param stdClass $rec
4969 * @return void (modifies $rec)
4971 protected static function preload_from_record(stdClass $rec) {
4972 $notenoughdata = false;
4973 $notenoughdata = $notenoughdata || empty($rec->ctxid);
4974 $notenoughdata = $notenoughdata || empty($rec->ctxlevel);
4975 $notenoughdata = $notenoughdata || !isset($rec->ctxinstance);
4976 $notenoughdata = $notenoughdata || empty($rec->ctxpath);
4977 $notenoughdata = $notenoughdata || empty($rec->ctxdepth);
4978 $notenoughdata = $notenoughdata || !isset($rec->ctxlocked);
4979 if ($notenoughdata) {
4980 // The record does not have enough data, passed here repeatedly or context does not exist yet.
4981 if (isset($rec->ctxid) && !isset($rec->ctxlocked)) {
4982 debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER);
4984 return;
4987 $record = (object) [
4988 'id' => $rec->ctxid,
4989 'contextlevel' => $rec->ctxlevel,
4990 'instanceid' => $rec->ctxinstance,
4991 'path' => $rec->ctxpath,
4992 'depth' => $rec->ctxdepth,
4993 'locked' => $rec->ctxlocked,
4996 unset($rec->ctxid);
4997 unset($rec->ctxlevel);
4998 unset($rec->ctxinstance);
4999 unset($rec->ctxpath);
5000 unset($rec->ctxdepth);
5001 unset($rec->ctxlocked);
5003 return context::create_instance_from_record($record);
5007 // ====== magic methods =======
5010 * Magic setter method, we do not want anybody to modify properties from the outside
5011 * @param string $name
5012 * @param mixed $value
5014 public function __set($name, $value) {
5015 debugging('Can not change context instance properties!');
5019 * Magic method getter, redirects to read only values.
5020 * @param string $name
5021 * @return mixed
5023 public function __get($name) {
5024 switch ($name) {
5025 case 'id':
5026 return $this->_id;
5027 case 'contextlevel':
5028 return $this->_contextlevel;
5029 case 'instanceid':
5030 return $this->_instanceid;
5031 case 'path':
5032 return $this->_path;
5033 case 'depth':
5034 return $this->_depth;
5035 case 'locked':
5036 return $this->is_locked();
5038 default:
5039 debugging('Invalid context property accessed! '.$name);
5040 return null;
5045 * Full support for isset on our magic read only properties.
5046 * @param string $name
5047 * @return bool
5049 public function __isset($name) {
5050 switch ($name) {
5051 case 'id':
5052 return isset($this->_id);
5053 case 'contextlevel':
5054 return isset($this->_contextlevel);
5055 case 'instanceid':
5056 return isset($this->_instanceid);
5057 case 'path':
5058 return isset($this->_path);
5059 case 'depth':
5060 return isset($this->_depth);
5061 case 'locked':
5062 // Locked is always set.
5063 return true;
5064 default:
5065 return false;
5070 * All properties are read only, sorry.
5071 * @param string $name
5073 public function __unset($name) {
5074 debugging('Can not unset context instance properties!');
5077 // ====== implementing method from interface IteratorAggregate ======
5080 * Create an iterator because magic vars can't be seen by 'foreach'.
5082 * Now we can convert context object to array using convert_to_array(),
5083 * and feed it properly to json_encode().
5085 public function getIterator() {
5086 $ret = array(
5087 'id' => $this->id,
5088 'contextlevel' => $this->contextlevel,
5089 'instanceid' => $this->instanceid,
5090 'path' => $this->path,
5091 'depth' => $this->depth,
5092 'locked' => $this->locked,
5094 return new ArrayIterator($ret);
5097 // ====== general context methods ======
5100 * Constructor is protected so that devs are forced to
5101 * use context_xxx::instance() or context::instance_by_id().
5103 * @param stdClass $record
5105 protected function __construct(stdClass $record) {
5106 $this->_id = (int)$record->id;
5107 $this->_contextlevel = (int)$record->contextlevel;
5108 $this->_instanceid = $record->instanceid;
5109 $this->_path = $record->path;
5110 $this->_depth = $record->depth;
5112 if (isset($record->locked)) {
5113 $this->_locked = $record->locked;
5114 } else if (!during_initial_install() && !moodle_needs_upgrading()) {
5115 debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER);
5120 * This function is also used to work around 'protected' keyword problems in context_helper.
5121 * @static
5122 * @param stdClass $record
5123 * @return context instance
5125 protected static function create_instance_from_record(stdClass $record) {
5126 $classname = context_helper::get_class_for_level($record->contextlevel);
5128 if ($context = context::cache_get_by_id($record->id)) {
5129 return $context;
5132 $context = new $classname($record);
5133 context::cache_add($context);
5135 return $context;
5139 * Copy prepared new contexts from temp table to context table,
5140 * we do this in db specific way for perf reasons only.
5141 * @static
5143 protected static function merge_context_temp_table() {
5144 global $DB;
5146 /* MDL-11347:
5147 * - mysql does not allow to use FROM in UPDATE statements
5148 * - using two tables after UPDATE works in mysql, but might give unexpected
5149 * results in pg 8 (depends on configuration)
5150 * - using table alias in UPDATE does not work in pg < 8.2
5152 * Different code for each database - mostly for performance reasons
5155 $dbfamily = $DB->get_dbfamily();
5156 if ($dbfamily == 'mysql') {
5157 $updatesql = "UPDATE {context} ct, {context_temp} temp
5158 SET ct.path = temp.path,
5159 ct.depth = temp.depth,
5160 ct.locked = temp.locked
5161 WHERE ct.id = temp.id";
5162 } else if ($dbfamily == 'oracle') {
5163 $updatesql = "UPDATE {context} ct
5164 SET (ct.path, ct.depth, ct.locked) =
5165 (SELECT temp.path, temp.depth, temp.locked
5166 FROM {context_temp} temp
5167 WHERE temp.id=ct.id)
5168 WHERE EXISTS (SELECT 'x'
5169 FROM {context_temp} temp
5170 WHERE temp.id = ct.id)";
5171 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5172 $updatesql = "UPDATE {context}
5173 SET path = temp.path,
5174 depth = temp.depth,
5175 locked = temp.locked
5176 FROM {context_temp} temp
5177 WHERE temp.id={context}.id";
5178 } else {
5179 // sqlite and others
5180 $updatesql = "UPDATE {context}
5181 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5182 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id),
5183 locked = (SELECT locked FROM {context_temp} WHERE id = {context}.id)
5184 WHERE id IN (SELECT id FROM {context_temp})";
5187 $DB->execute($updatesql);
5191 * Get a context instance as an object, from a given context id.
5193 * @static
5194 * @param int $id context id
5195 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5196 * MUST_EXIST means throw exception if no record found
5197 * @return context|bool the context object or false if not found
5199 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5200 global $DB;
5202 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5203 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5204 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5207 if ($id == SYSCONTEXTID) {
5208 return context_system::instance(0, $strictness);
5211 if (is_array($id) or is_object($id) or empty($id)) {
5212 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5215 if ($context = context::cache_get_by_id($id)) {
5216 return $context;
5219 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5220 return context::create_instance_from_record($record);
5223 return false;
5227 * Update context info after moving context in the tree structure.
5229 * @param context $newparent
5230 * @return void
5232 public function update_moved(context $newparent) {
5233 global $DB;
5235 $frompath = $this->_path;
5236 $newpath = $newparent->path . '/' . $this->_id;
5238 $trans = $DB->start_delegated_transaction();
5240 $setdepth = '';
5241 if (($newparent->depth +1) != $this->_depth) {
5242 $diff = $newparent->depth - $this->_depth + 1;
5243 $setdepth = ", depth = depth + $diff";
5245 $sql = "UPDATE {context}
5246 SET path = ?
5247 $setdepth
5248 WHERE id = ?";
5249 $params = array($newpath, $this->_id);
5250 $DB->execute($sql, $params);
5252 $this->_path = $newpath;
5253 $this->_depth = $newparent->depth + 1;
5255 $sql = "UPDATE {context}
5256 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5257 $setdepth
5258 WHERE path LIKE ?";
5259 $params = array($newpath, "{$frompath}/%");
5260 $DB->execute($sql, $params);
5262 $this->mark_dirty();
5264 context::reset_caches();
5266 $trans->allow_commit();
5270 * Set whether this context has been locked or not.
5272 * @param bool $locked
5273 * @return $this
5275 public function set_locked(bool $locked) {
5276 global $DB;
5278 if ($this->_locked == $locked) {
5279 return $this;
5282 $this->_locked = $locked;
5283 $DB->set_field('context', 'locked', (int) $locked, ['id' => $this->id]);
5284 $this->mark_dirty();
5286 if ($locked) {
5287 $eventname = '\\core\\event\\context_locked';
5288 } else {
5289 $eventname = '\\core\\event\\context_unlocked';
5291 $event = $eventname::create(['context' => $this, 'objectid' => $this->id]);
5292 $event->trigger();
5294 self::reset_caches();
5296 return $this;
5300 * Remove all context path info and optionally rebuild it.
5302 * @param bool $rebuild
5303 * @return void
5305 public function reset_paths($rebuild = true) {
5306 global $DB;
5308 if ($this->_path) {
5309 $this->mark_dirty();
5311 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5312 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5313 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5314 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5315 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5316 $this->_depth = 0;
5317 $this->_path = null;
5320 if ($rebuild) {
5321 context_helper::build_all_paths(false);
5324 context::reset_caches();
5328 * Delete all data linked to content, do not delete the context record itself
5330 public function delete_content() {
5331 global $CFG, $DB;
5333 blocks_delete_all_for_context($this->_id);
5334 filter_delete_all_for_context($this->_id);
5336 require_once($CFG->dirroot . '/comment/lib.php');
5337 comment::delete_comments(array('contextid'=>$this->_id));
5339 require_once($CFG->dirroot.'/rating/lib.php');
5340 $delopt = new stdclass();
5341 $delopt->contextid = $this->_id;
5342 $rm = new rating_manager();
5343 $rm->delete_ratings($delopt);
5345 // delete all files attached to this context
5346 $fs = get_file_storage();
5347 $fs->delete_area_files($this->_id);
5349 // Delete all repository instances attached to this context.
5350 require_once($CFG->dirroot . '/repository/lib.php');
5351 repository::delete_all_for_context($this->_id);
5353 // delete all advanced grading data attached to this context
5354 require_once($CFG->dirroot.'/grade/grading/lib.php');
5355 grading_manager::delete_all_for_context($this->_id);
5357 // now delete stuff from role related tables, role_unassign_all
5358 // and unenrol should be called earlier to do proper cleanup
5359 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5360 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5361 $this->delete_capabilities();
5365 * Unassign all capabilities from a context.
5367 public function delete_capabilities() {
5368 global $DB;
5370 $ids = $DB->get_fieldset_select('role_capabilities', 'DISTINCT roleid', 'contextid = ?', array($this->_id));
5371 if ($ids) {
5372 $DB->delete_records('role_capabilities', array('contextid' => $this->_id));
5374 // Reset any cache of these roles, including MUC.
5375 accesslib_clear_role_cache($ids);
5380 * Delete the context content and the context record itself
5382 public function delete() {
5383 global $DB;
5385 if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5386 throw new coding_exception('Cannot delete system context');
5389 // double check the context still exists
5390 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5391 context::cache_remove($this);
5392 return;
5395 $this->delete_content();
5396 $DB->delete_records('context', array('id'=>$this->_id));
5397 // purge static context cache if entry present
5398 context::cache_remove($this);
5400 // Inform search engine to delete data related to this context.
5401 \core_search\manager::context_deleted($this);
5404 // ====== context level related methods ======
5407 * Utility method for context creation
5409 * @static
5410 * @param int $contextlevel
5411 * @param int $instanceid
5412 * @param string $parentpath
5413 * @return stdClass context record
5415 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5416 global $DB;
5418 $record = new stdClass();
5419 $record->contextlevel = $contextlevel;
5420 $record->instanceid = $instanceid;
5421 $record->depth = 0;
5422 $record->path = null; //not known before insert
5423 $record->locked = 0;
5425 $record->id = $DB->insert_record('context', $record);
5427 // now add path if known - it can be added later
5428 if (!is_null($parentpath)) {
5429 $record->path = $parentpath.'/'.$record->id;
5430 $record->depth = substr_count($record->path, '/');
5431 $DB->update_record('context', $record);
5434 return $record;
5438 * Returns human readable context identifier.
5440 * @param boolean $withprefix whether to prefix the name of the context with the
5441 * type of context, e.g. User, Course, Forum, etc.
5442 * @param boolean $short whether to use the short name of the thing. Only applies
5443 * to course contexts
5444 * @return string the human readable context name.
5446 public function get_context_name($withprefix = true, $short = false) {
5447 // must be implemented in all context levels
5448 throw new coding_exception('can not get name of abstract context');
5452 * Whether the current context is locked.
5454 * @return bool
5456 public function is_locked() {
5457 if ($this->_locked) {
5458 return true;
5461 if ($parent = $this->get_parent_context()) {
5462 return $parent->is_locked();
5465 return false;
5469 * Returns the most relevant URL for this context.
5471 * @return moodle_url
5473 public abstract function get_url();
5476 * Returns array of relevant context capability records.
5478 * @return array
5480 public abstract function get_capabilities();
5483 * Recursive function which, given a context, find all its children context ids.
5485 * For course category contexts it will return immediate children and all subcategory contexts.
5486 * It will NOT recurse into courses or subcategories categories.
5487 * If you want to do that, call it on the returned courses/categories.
5489 * When called for a course context, it will return the modules and blocks
5490 * displayed in the course page and blocks displayed on the module pages.
5492 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5493 * contexts ;-)
5495 * @return array Array of child records
5497 public function get_child_contexts() {
5498 global $DB;
5500 if (empty($this->_path) or empty($this->_depth)) {
5501 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5502 return array();
5505 $sql = "SELECT ctx.*
5506 FROM {context} ctx
5507 WHERE ctx.path LIKE ?";
5508 $params = array($this->_path.'/%');
5509 $records = $DB->get_records_sql($sql, $params);
5511 $result = array();
5512 foreach ($records as $record) {
5513 $result[$record->id] = context::create_instance_from_record($record);
5516 return $result;
5520 * Returns parent contexts of this context in reversed order, i.e. parent first,
5521 * then grand parent, etc.
5523 * @param bool $includeself true means include self too
5524 * @return array of context instances
5526 public function get_parent_contexts($includeself = false) {
5527 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5528 return array();
5531 // Preload the contexts to reduce DB calls.
5532 context_helper::preload_contexts_by_id($contextids);
5534 $result = array();
5535 foreach ($contextids as $contextid) {
5536 $parent = context::instance_by_id($contextid, MUST_EXIST);
5537 $result[$parent->id] = $parent;
5540 return $result;
5544 * Returns parent context ids of this context in reversed order, i.e. parent first,
5545 * then grand parent, etc.
5547 * @param bool $includeself true means include self too
5548 * @return array of context ids
5550 public function get_parent_context_ids($includeself = false) {
5551 if (empty($this->_path)) {
5552 return array();
5555 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5556 $parentcontexts = explode('/', $parentcontexts);
5557 if (!$includeself) {
5558 array_pop($parentcontexts); // and remove its own id
5561 return array_reverse($parentcontexts);
5565 * Returns parent context paths of this context.
5567 * @param bool $includeself true means include self too
5568 * @return array of context paths
5570 public function get_parent_context_paths($includeself = false) {
5571 if (empty($this->_path)) {
5572 return array();
5575 $contextids = explode('/', $this->_path);
5577 $path = '';
5578 $paths = array();
5579 foreach ($contextids as $contextid) {
5580 if ($contextid) {
5581 $path .= '/' . $contextid;
5582 $paths[$contextid] = $path;
5586 if (!$includeself) {
5587 unset($paths[$this->_id]);
5590 return $paths;
5594 * Returns parent context
5596 * @return context
5598 public function get_parent_context() {
5599 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5600 return false;
5603 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5604 $parentcontexts = explode('/', $parentcontexts);
5605 array_pop($parentcontexts); // self
5606 $contextid = array_pop($parentcontexts); // immediate parent
5608 return context::instance_by_id($contextid, MUST_EXIST);
5612 * Is this context part of any course? If yes return course context.
5614 * @param bool $strict true means throw exception if not found, false means return false if not found
5615 * @return context_course context of the enclosing course, null if not found or exception
5617 public function get_course_context($strict = true) {
5618 if ($strict) {
5619 throw new coding_exception('Context does not belong to any course.');
5620 } else {
5621 return false;
5626 * Returns sql necessary for purging of stale context instances.
5628 * @static
5629 * @return string cleanup SQL
5631 protected static function get_cleanup_sql() {
5632 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5636 * Rebuild context paths and depths at context level.
5638 * @static
5639 * @param bool $force
5640 * @return void
5642 protected static function build_paths($force) {
5643 throw new coding_exception('build_paths() method must be implemented in all context levels');
5647 * Create missing context instances at given level
5649 * @static
5650 * @return void
5652 protected static function create_level_instances() {
5653 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5657 * Reset all cached permissions and definitions if the necessary.
5658 * @return void
5660 public function reload_if_dirty() {
5661 global $ACCESSLIB_PRIVATE, $USER;
5663 // Load dirty contexts list if needed
5664 if (CLI_SCRIPT) {
5665 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5666 // we do not load dirty flags in CLI and cron
5667 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5669 } else {
5670 if (!isset($USER->access['time'])) {
5671 // Nothing has been loaded yet, so we do not need to check dirty flags now.
5672 return;
5675 // From skodak: No idea why -2 is there, server cluster time difference maybe...
5676 $changedsince = $USER->access['time'] - 2;
5678 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5679 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $changedsince);
5682 if (!isset($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
5683 $ACCESSLIB_PRIVATE->dirtyusers[$USER->id] = get_cache_flag('accesslib/dirtyusers', $USER->id, $changedsince);
5687 $dirty = false;
5689 if (!empty($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
5690 $dirty = true;
5691 } else if (!empty($ACCESSLIB_PRIVATE->dirtycontexts)) {
5692 $paths = $this->get_parent_context_paths(true);
5694 foreach ($paths as $path) {
5695 if (isset($ACCESSLIB_PRIVATE->dirtycontexts[$path])) {
5696 $dirty = true;
5697 break;
5702 if ($dirty) {
5703 // Reload all capabilities of USER and others - preserving loginas, roleswitches, etc.
5704 // Then cleanup any marks of dirtyness... at least from our short term memory!
5705 reload_all_capabilities();
5710 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5712 public function mark_dirty() {
5713 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5715 if (during_initial_install()) {
5716 return;
5719 // only if it is a non-empty string
5720 if (is_string($this->_path) && $this->_path !== '') {
5721 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5722 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5723 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5724 } else {
5725 if (CLI_SCRIPT) {
5726 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5727 } else {
5728 if (isset($USER->access['time'])) {
5729 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5730 } else {
5731 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5733 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5742 * Context maintenance and helper methods.
5744 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5745 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5746 * level implementation from the rest of code, the code completion returns what developers need.
5748 * Thank you Tim Hunt for helping me with this nasty trick.
5750 * @package core_access
5751 * @category access
5752 * @copyright Petr Skoda {@link http://skodak.org}
5753 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5754 * @since Moodle 2.2
5756 class context_helper extends context {
5759 * @var array An array mapping context levels to classes
5761 private static $alllevels;
5764 * Instance does not make sense here, only static use
5766 protected function __construct() {
5770 * Reset internal context levels array.
5772 public static function reset_levels() {
5773 self::$alllevels = null;
5777 * Initialise context levels, call before using self::$alllevels.
5779 private static function init_levels() {
5780 global $CFG;
5782 if (isset(self::$alllevels)) {
5783 return;
5785 self::$alllevels = array(
5786 CONTEXT_SYSTEM => 'context_system',
5787 CONTEXT_USER => 'context_user',
5788 CONTEXT_COURSECAT => 'context_coursecat',
5789 CONTEXT_COURSE => 'context_course',
5790 CONTEXT_MODULE => 'context_module',
5791 CONTEXT_BLOCK => 'context_block',
5794 if (empty($CFG->custom_context_classes)) {
5795 return;
5798 $levels = $CFG->custom_context_classes;
5799 if (!is_array($levels)) {
5800 $levels = @unserialize($levels);
5802 if (!is_array($levels)) {
5803 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
5804 return;
5807 // Unsupported custom levels, use with care!!!
5808 foreach ($levels as $level => $classname) {
5809 self::$alllevels[$level] = $classname;
5811 ksort(self::$alllevels);
5815 * Returns a class name of the context level class
5817 * @static
5818 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5819 * @return string class name of the context class
5821 public static function get_class_for_level($contextlevel) {
5822 self::init_levels();
5823 if (isset(self::$alllevels[$contextlevel])) {
5824 return self::$alllevels[$contextlevel];
5825 } else {
5826 throw new coding_exception('Invalid context level specified');
5831 * Returns a list of all context levels
5833 * @static
5834 * @return array int=>string (level=>level class name)
5836 public static function get_all_levels() {
5837 self::init_levels();
5838 return self::$alllevels;
5842 * Remove stale contexts that belonged to deleted instances.
5843 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5845 * @static
5846 * @return void
5848 public static function cleanup_instances() {
5849 global $DB;
5850 self::init_levels();
5852 $sqls = array();
5853 foreach (self::$alllevels as $level=>$classname) {
5854 $sqls[] = $classname::get_cleanup_sql();
5857 $sql = implode(" UNION ", $sqls);
5859 // it is probably better to use transactions, it might be faster too
5860 $transaction = $DB->start_delegated_transaction();
5862 $rs = $DB->get_recordset_sql($sql);
5863 foreach ($rs as $record) {
5864 $context = context::create_instance_from_record($record);
5865 $context->delete();
5867 $rs->close();
5869 $transaction->allow_commit();
5873 * Create all context instances at the given level and above.
5875 * @static
5876 * @param int $contextlevel null means all levels
5877 * @param bool $buildpaths
5878 * @return void
5880 public static function create_instances($contextlevel = null, $buildpaths = true) {
5881 self::init_levels();
5882 foreach (self::$alllevels as $level=>$classname) {
5883 if ($contextlevel and $level > $contextlevel) {
5884 // skip potential sub-contexts
5885 continue;
5887 $classname::create_level_instances();
5888 if ($buildpaths) {
5889 $classname::build_paths(false);
5895 * Rebuild paths and depths in all context levels.
5897 * @static
5898 * @param bool $force false means add missing only
5899 * @return void
5901 public static function build_all_paths($force = false) {
5902 self::init_levels();
5903 foreach (self::$alllevels as $classname) {
5904 $classname::build_paths($force);
5907 // reset static course cache - it might have incorrect cached data
5908 accesslib_clear_all_caches(true);
5912 * Resets the cache to remove all data.
5913 * @static
5915 public static function reset_caches() {
5916 context::reset_caches();
5920 * Returns all fields necessary for context preloading from user $rec.
5922 * This helps with performance when dealing with hundreds of contexts.
5924 * @static
5925 * @param string $tablealias context table alias in the query
5926 * @return array (table.column=>alias, ...)
5928 public static function get_preload_record_columns($tablealias) {
5929 return [
5930 "$tablealias.id" => "ctxid",
5931 "$tablealias.path" => "ctxpath",
5932 "$tablealias.depth" => "ctxdepth",
5933 "$tablealias.contextlevel" => "ctxlevel",
5934 "$tablealias.instanceid" => "ctxinstance",
5935 "$tablealias.locked" => "ctxlocked",
5940 * Returns all fields necessary for context preloading from user $rec.
5942 * This helps with performance when dealing with hundreds of contexts.
5944 * @static
5945 * @param string $tablealias context table alias in the query
5946 * @return string
5948 public static function get_preload_record_columns_sql($tablealias) {
5949 return "$tablealias.id AS ctxid, " .
5950 "$tablealias.path AS ctxpath, " .
5951 "$tablealias.depth AS ctxdepth, " .
5952 "$tablealias.contextlevel AS ctxlevel, " .
5953 "$tablealias.instanceid AS ctxinstance, " .
5954 "$tablealias.locked AS ctxlocked";
5958 * Preloads context information from db record and strips the cached info.
5960 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5962 * @static
5963 * @param stdClass $rec
5964 * @return void (modifies $rec)
5966 public static function preload_from_record(stdClass $rec) {
5967 context::preload_from_record($rec);
5971 * Preload a set of contexts using their contextid.
5973 * @param array $contextids
5975 public static function preload_contexts_by_id(array $contextids) {
5976 global $DB;
5978 // Determine which contexts are not already cached.
5979 $tofetch = [];
5980 foreach ($contextids as $contextid) {
5981 if (!self::cache_get_by_id($contextid)) {
5982 $tofetch[] = $contextid;
5986 if (count($tofetch) > 1) {
5987 // There are at least two to fetch.
5988 // There is no point only fetching a single context as this would be no more efficient than calling the existing code.
5989 list($insql, $inparams) = $DB->get_in_or_equal($tofetch, SQL_PARAMS_NAMED);
5990 $ctxs = $DB->get_records_select('context', "id {$insql}", $inparams, '',
5991 \context_helper::get_preload_record_columns_sql('{context}'));
5992 foreach ($ctxs as $ctx) {
5993 self::preload_from_record($ctx);
5999 * Preload all contexts instances from course.
6001 * To be used if you expect multiple queries for course activities...
6003 * @static
6004 * @param int $courseid
6006 public static function preload_course($courseid) {
6007 // Users can call this multiple times without doing any harm
6008 if (isset(context::$cache_preloaded[$courseid])) {
6009 return;
6011 $coursecontext = context_course::instance($courseid);
6012 $coursecontext->get_child_contexts();
6014 context::$cache_preloaded[$courseid] = true;
6018 * Delete context instance
6020 * @static
6021 * @param int $contextlevel
6022 * @param int $instanceid
6023 * @return void
6025 public static function delete_instance($contextlevel, $instanceid) {
6026 global $DB;
6028 // double check the context still exists
6029 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
6030 $context = context::create_instance_from_record($record);
6031 $context->delete();
6032 } else {
6033 // we should try to purge the cache anyway
6038 * Returns the name of specified context level
6040 * @static
6041 * @param int $contextlevel
6042 * @return string name of the context level
6044 public static function get_level_name($contextlevel) {
6045 $classname = context_helper::get_class_for_level($contextlevel);
6046 return $classname::get_level_name();
6050 * not used
6052 public function get_url() {
6056 * not used
6058 public function get_capabilities() {
6064 * System context class
6066 * @package core_access
6067 * @category access
6068 * @copyright Petr Skoda {@link http://skodak.org}
6069 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6070 * @since Moodle 2.2
6072 class context_system extends context {
6074 * Please use context_system::instance() if you need the instance of context.
6076 * @param stdClass $record
6078 protected function __construct(stdClass $record) {
6079 parent::__construct($record);
6080 if ($record->contextlevel != CONTEXT_SYSTEM) {
6081 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
6086 * Returns human readable context level name.
6088 * @static
6089 * @return string the human readable context level name.
6091 public static function get_level_name() {
6092 return get_string('coresystem');
6096 * Returns human readable context identifier.
6098 * @param boolean $withprefix does not apply to system context
6099 * @param boolean $short does not apply to system context
6100 * @return string the human readable context name.
6102 public function get_context_name($withprefix = true, $short = false) {
6103 return self::get_level_name();
6107 * Returns the most relevant URL for this context.
6109 * @return moodle_url
6111 public function get_url() {
6112 return new moodle_url('/');
6116 * Returns array of relevant context capability records.
6118 * @return array
6120 public function get_capabilities() {
6121 global $DB;
6123 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6125 $params = array();
6126 $sql = "SELECT *
6127 FROM {capabilities}";
6129 return $DB->get_records_sql($sql.' '.$sort, $params);
6133 * Create missing context instances at system context
6134 * @static
6136 protected static function create_level_instances() {
6137 // nothing to do here, the system context is created automatically in installer
6138 self::instance(0);
6142 * Returns system context instance.
6144 * @static
6145 * @param int $instanceid should be 0
6146 * @param int $strictness
6147 * @param bool $cache
6148 * @return context_system context instance
6150 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
6151 global $DB;
6153 if ($instanceid != 0) {
6154 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
6157 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
6158 if (!isset(context::$systemcontext)) {
6159 $record = new stdClass();
6160 $record->id = SYSCONTEXTID;
6161 $record->contextlevel = CONTEXT_SYSTEM;
6162 $record->instanceid = 0;
6163 $record->path = '/'.SYSCONTEXTID;
6164 $record->depth = 1;
6165 $record->locked = 0;
6166 context::$systemcontext = new context_system($record);
6168 return context::$systemcontext;
6171 try {
6172 // We ignore the strictness completely because system context must exist except during install.
6173 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6174 } catch (dml_exception $e) {
6175 //table or record does not exist
6176 if (!during_initial_install()) {
6177 // do not mess with system context after install, it simply must exist
6178 throw $e;
6180 $record = null;
6183 if (!$record) {
6184 $record = new stdClass();
6185 $record->contextlevel = CONTEXT_SYSTEM;
6186 $record->instanceid = 0;
6187 $record->depth = 1;
6188 $record->path = null; // Not known before insert.
6189 $record->locked = 0;
6191 try {
6192 if ($DB->count_records('context')) {
6193 // contexts already exist, this is very weird, system must be first!!!
6194 return null;
6196 if (defined('SYSCONTEXTID')) {
6197 // this would happen only in unittest on sites that went through weird 1.7 upgrade
6198 $record->id = SYSCONTEXTID;
6199 $DB->import_record('context', $record);
6200 $DB->get_manager()->reset_sequence('context');
6201 } else {
6202 $record->id = $DB->insert_record('context', $record);
6204 } catch (dml_exception $e) {
6205 // can not create context - table does not exist yet, sorry
6206 return null;
6210 if ($record->instanceid != 0) {
6211 // this is very weird, somebody must be messing with context table
6212 debugging('Invalid system context detected');
6215 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6216 // fix path if necessary, initial install or path reset
6217 $record->depth = 1;
6218 $record->path = '/'.$record->id;
6219 $DB->update_record('context', $record);
6222 if (empty($record->locked)) {
6223 $record->locked = 0;
6226 if (!defined('SYSCONTEXTID')) {
6227 define('SYSCONTEXTID', $record->id);
6230 context::$systemcontext = new context_system($record);
6231 return context::$systemcontext;
6235 * Returns all site contexts except the system context, DO NOT call on production servers!!
6237 * Contexts are not cached.
6239 * @return array
6241 public function get_child_contexts() {
6242 global $DB;
6244 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6246 // Just get all the contexts except for CONTEXT_SYSTEM level
6247 // and hope we don't OOM in the process - don't cache
6248 $sql = "SELECT c.*
6249 FROM {context} c
6250 WHERE contextlevel > ".CONTEXT_SYSTEM;
6251 $records = $DB->get_records_sql($sql);
6253 $result = array();
6254 foreach ($records as $record) {
6255 $result[$record->id] = context::create_instance_from_record($record);
6258 return $result;
6262 * Returns sql necessary for purging of stale context instances.
6264 * @static
6265 * @return string cleanup SQL
6267 protected static function get_cleanup_sql() {
6268 $sql = "
6269 SELECT c.*
6270 FROM {context} c
6271 WHERE 1=2
6274 return $sql;
6278 * Rebuild context paths and depths at system context level.
6280 * @static
6281 * @param bool $force
6283 protected static function build_paths($force) {
6284 global $DB;
6286 /* note: ignore $force here, we always do full test of system context */
6288 // exactly one record must exist
6289 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6291 if ($record->instanceid != 0) {
6292 debugging('Invalid system context detected');
6295 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6296 debugging('Invalid SYSCONTEXTID detected');
6299 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6300 // fix path if necessary, initial install or path reset
6301 $record->depth = 1;
6302 $record->path = '/'.$record->id;
6303 $DB->update_record('context', $record);
6308 * Set whether this context has been locked or not.
6310 * @param bool $locked
6311 * @return $this
6313 public function set_locked(bool $locked) {
6314 throw new \coding_exception('It is not possible to lock the system context');
6316 return $this;
6322 * User context class
6324 * @package core_access
6325 * @category access
6326 * @copyright Petr Skoda {@link http://skodak.org}
6327 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6328 * @since Moodle 2.2
6330 class context_user extends context {
6332 * Please use context_user::instance($userid) if you need the instance of context.
6333 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6335 * @param stdClass $record
6337 protected function __construct(stdClass $record) {
6338 parent::__construct($record);
6339 if ($record->contextlevel != CONTEXT_USER) {
6340 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6345 * Returns human readable context level name.
6347 * @static
6348 * @return string the human readable context level name.
6350 public static function get_level_name() {
6351 return get_string('user');
6355 * Returns human readable context identifier.
6357 * @param boolean $withprefix whether to prefix the name of the context with User
6358 * @param boolean $short does not apply to user context
6359 * @return string the human readable context name.
6361 public function get_context_name($withprefix = true, $short = false) {
6362 global $DB;
6364 $name = '';
6365 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6366 if ($withprefix){
6367 $name = get_string('user').': ';
6369 $name .= fullname($user);
6371 return $name;
6375 * Returns the most relevant URL for this context.
6377 * @return moodle_url
6379 public function get_url() {
6380 global $COURSE;
6382 if ($COURSE->id == SITEID) {
6383 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6384 } else {
6385 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6387 return $url;
6391 * Returns array of relevant context capability records.
6393 * @return array
6395 public function get_capabilities() {
6396 global $DB;
6398 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6400 $extracaps = array('moodle/grade:viewall');
6401 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6402 $sql = "SELECT *
6403 FROM {capabilities}
6404 WHERE contextlevel = ".CONTEXT_USER."
6405 OR name $extra";
6407 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6411 * Returns user context instance.
6413 * @static
6414 * @param int $userid id from {user} table
6415 * @param int $strictness
6416 * @return context_user context instance
6418 public static function instance($userid, $strictness = MUST_EXIST) {
6419 global $DB;
6421 if ($context = context::cache_get(CONTEXT_USER, $userid)) {
6422 return $context;
6425 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER, 'instanceid' => $userid))) {
6426 if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6427 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6431 if ($record) {
6432 $context = new context_user($record);
6433 context::cache_add($context);
6434 return $context;
6437 return false;
6441 * Create missing context instances at user context level
6442 * @static
6444 protected static function create_level_instances() {
6445 global $DB;
6447 $sql = "SELECT ".CONTEXT_USER.", u.id
6448 FROM {user} u
6449 WHERE u.deleted = 0
6450 AND NOT EXISTS (SELECT 'x'
6451 FROM {context} cx
6452 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6453 $contextdata = $DB->get_recordset_sql($sql);
6454 foreach ($contextdata as $context) {
6455 context::insert_context_record(CONTEXT_USER, $context->id, null);
6457 $contextdata->close();
6461 * Returns sql necessary for purging of stale context instances.
6463 * @static
6464 * @return string cleanup SQL
6466 protected static function get_cleanup_sql() {
6467 $sql = "
6468 SELECT c.*
6469 FROM {context} c
6470 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6471 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6474 return $sql;
6478 * Rebuild context paths and depths at user context level.
6480 * @static
6481 * @param bool $force
6483 protected static function build_paths($force) {
6484 global $DB;
6486 // First update normal users.
6487 $path = $DB->sql_concat('?', 'id');
6488 $pathstart = '/' . SYSCONTEXTID . '/';
6489 $params = array($pathstart);
6491 if ($force) {
6492 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6493 $params[] = $pathstart;
6494 } else {
6495 $where = "depth = 0 OR path IS NULL";
6498 $sql = "UPDATE {context}
6499 SET depth = 2,
6500 path = {$path}
6501 WHERE contextlevel = " . CONTEXT_USER . "
6502 AND ($where)";
6503 $DB->execute($sql, $params);
6509 * Course category context class
6511 * @package core_access
6512 * @category access
6513 * @copyright Petr Skoda {@link http://skodak.org}
6514 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6515 * @since Moodle 2.2
6517 class context_coursecat extends context {
6519 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6520 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6522 * @param stdClass $record
6524 protected function __construct(stdClass $record) {
6525 parent::__construct($record);
6526 if ($record->contextlevel != CONTEXT_COURSECAT) {
6527 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6532 * Returns human readable context level name.
6534 * @static
6535 * @return string the human readable context level name.
6537 public static function get_level_name() {
6538 return get_string('category');
6542 * Returns human readable context identifier.
6544 * @param boolean $withprefix whether to prefix the name of the context with Category
6545 * @param boolean $short does not apply to course categories
6546 * @return string the human readable context name.
6548 public function get_context_name($withprefix = true, $short = false) {
6549 global $DB;
6551 $name = '';
6552 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6553 if ($withprefix){
6554 $name = get_string('category').': ';
6556 $name .= format_string($category->name, true, array('context' => $this));
6558 return $name;
6562 * Returns the most relevant URL for this context.
6564 * @return moodle_url
6566 public function get_url() {
6567 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6571 * Returns array of relevant context capability records.
6573 * @return array
6575 public function get_capabilities() {
6576 global $DB;
6578 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6580 $params = array();
6581 $sql = "SELECT *
6582 FROM {capabilities}
6583 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6585 return $DB->get_records_sql($sql.' '.$sort, $params);
6589 * Returns course category context instance.
6591 * @static
6592 * @param int $categoryid id from {course_categories} table
6593 * @param int $strictness
6594 * @return context_coursecat context instance
6596 public static function instance($categoryid, $strictness = MUST_EXIST) {
6597 global $DB;
6599 if ($context = context::cache_get(CONTEXT_COURSECAT, $categoryid)) {
6600 return $context;
6603 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT, 'instanceid' => $categoryid))) {
6604 if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6605 if ($category->parent) {
6606 $parentcontext = context_coursecat::instance($category->parent);
6607 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6608 } else {
6609 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6614 if ($record) {
6615 $context = new context_coursecat($record);
6616 context::cache_add($context);
6617 return $context;
6620 return false;
6624 * Returns immediate child contexts of category and all subcategories,
6625 * children of subcategories and courses are not returned.
6627 * @return array
6629 public function get_child_contexts() {
6630 global $DB;
6632 if (empty($this->_path) or empty($this->_depth)) {
6633 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6634 return array();
6637 $sql = "SELECT ctx.*
6638 FROM {context} ctx
6639 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6640 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6641 $records = $DB->get_records_sql($sql, $params);
6643 $result = array();
6644 foreach ($records as $record) {
6645 $result[$record->id] = context::create_instance_from_record($record);
6648 return $result;
6652 * Create missing context instances at course category context level
6653 * @static
6655 protected static function create_level_instances() {
6656 global $DB;
6658 $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6659 FROM {course_categories} cc
6660 WHERE NOT EXISTS (SELECT 'x'
6661 FROM {context} cx
6662 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6663 $contextdata = $DB->get_recordset_sql($sql);
6664 foreach ($contextdata as $context) {
6665 context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6667 $contextdata->close();
6671 * Returns sql necessary for purging of stale context instances.
6673 * @static
6674 * @return string cleanup SQL
6676 protected static function get_cleanup_sql() {
6677 $sql = "
6678 SELECT c.*
6679 FROM {context} c
6680 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6681 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6684 return $sql;
6688 * Rebuild context paths and depths at course category context level.
6690 * @static
6691 * @param bool $force
6693 protected static function build_paths($force) {
6694 global $DB;
6696 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6697 if ($force) {
6698 $ctxemptyclause = $emptyclause = '';
6699 } else {
6700 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6701 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6704 $base = '/'.SYSCONTEXTID;
6706 // Normal top level categories
6707 $sql = "UPDATE {context}
6708 SET depth=2,
6709 path=".$DB->sql_concat("'$base/'", 'id')."
6710 WHERE contextlevel=".CONTEXT_COURSECAT."
6711 AND EXISTS (SELECT 'x'
6712 FROM {course_categories} cc
6713 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6714 $emptyclause";
6715 $DB->execute($sql);
6717 // Deeper categories - one query per depthlevel
6718 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6719 for ($n=2; $n<=$maxdepth; $n++) {
6720 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
6721 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
6722 FROM {context} ctx
6723 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6724 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6725 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6726 $ctxemptyclause";
6727 $trans = $DB->start_delegated_transaction();
6728 $DB->delete_records('context_temp');
6729 $DB->execute($sql);
6730 context::merge_context_temp_table();
6731 $DB->delete_records('context_temp');
6732 $trans->allow_commit();
6741 * Course context class
6743 * @package core_access
6744 * @category access
6745 * @copyright Petr Skoda {@link http://skodak.org}
6746 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6747 * @since Moodle 2.2
6749 class context_course extends context {
6751 * Please use context_course::instance($courseid) if you need the instance of context.
6752 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6754 * @param stdClass $record
6756 protected function __construct(stdClass $record) {
6757 parent::__construct($record);
6758 if ($record->contextlevel != CONTEXT_COURSE) {
6759 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6764 * Returns human readable context level name.
6766 * @static
6767 * @return string the human readable context level name.
6769 public static function get_level_name() {
6770 return get_string('course');
6774 * Returns human readable context identifier.
6776 * @param boolean $withprefix whether to prefix the name of the context with Course
6777 * @param boolean $short whether to use the short name of the thing.
6778 * @return string the human readable context name.
6780 public function get_context_name($withprefix = true, $short = false) {
6781 global $DB;
6783 $name = '';
6784 if ($this->_instanceid == SITEID) {
6785 $name = get_string('frontpage', 'admin');
6786 } else {
6787 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6788 if ($withprefix){
6789 $name = get_string('course').': ';
6791 if ($short){
6792 $name .= format_string($course->shortname, true, array('context' => $this));
6793 } else {
6794 $name .= format_string(get_course_display_name_for_list($course));
6798 return $name;
6802 * Returns the most relevant URL for this context.
6804 * @return moodle_url
6806 public function get_url() {
6807 if ($this->_instanceid != SITEID) {
6808 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6811 return new moodle_url('/');
6815 * Returns array of relevant context capability records.
6817 * @return array
6819 public function get_capabilities() {
6820 global $DB;
6822 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6824 $params = array();
6825 $sql = "SELECT *
6826 FROM {capabilities}
6827 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6829 return $DB->get_records_sql($sql.' '.$sort, $params);
6833 * Is this context part of any course? If yes return course context.
6835 * @param bool $strict true means throw exception if not found, false means return false if not found
6836 * @return context_course context of the enclosing course, null if not found or exception
6838 public function get_course_context($strict = true) {
6839 return $this;
6843 * Returns course context instance.
6845 * @static
6846 * @param int $courseid id from {course} table
6847 * @param int $strictness
6848 * @return context_course context instance
6850 public static function instance($courseid, $strictness = MUST_EXIST) {
6851 global $DB;
6853 if ($context = context::cache_get(CONTEXT_COURSE, $courseid)) {
6854 return $context;
6857 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $courseid))) {
6858 if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
6859 if ($course->category) {
6860 $parentcontext = context_coursecat::instance($course->category);
6861 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6862 } else {
6863 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6868 if ($record) {
6869 $context = new context_course($record);
6870 context::cache_add($context);
6871 return $context;
6874 return false;
6878 * Create missing context instances at course context level
6879 * @static
6881 protected static function create_level_instances() {
6882 global $DB;
6884 $sql = "SELECT ".CONTEXT_COURSE.", c.id
6885 FROM {course} c
6886 WHERE NOT EXISTS (SELECT 'x'
6887 FROM {context} cx
6888 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6889 $contextdata = $DB->get_recordset_sql($sql);
6890 foreach ($contextdata as $context) {
6891 context::insert_context_record(CONTEXT_COURSE, $context->id, null);
6893 $contextdata->close();
6897 * Returns sql necessary for purging of stale context instances.
6899 * @static
6900 * @return string cleanup SQL
6902 protected static function get_cleanup_sql() {
6903 $sql = "
6904 SELECT c.*
6905 FROM {context} c
6906 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6907 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6910 return $sql;
6914 * Rebuild context paths and depths at course context level.
6916 * @static
6917 * @param bool $force
6919 protected static function build_paths($force) {
6920 global $DB;
6922 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6923 if ($force) {
6924 $ctxemptyclause = $emptyclause = '';
6925 } else {
6926 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6927 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6930 $base = '/'.SYSCONTEXTID;
6932 // Standard frontpage
6933 $sql = "UPDATE {context}
6934 SET depth = 2,
6935 path = ".$DB->sql_concat("'$base/'", 'id')."
6936 WHERE contextlevel = ".CONTEXT_COURSE."
6937 AND EXISTS (SELECT 'x'
6938 FROM {course} c
6939 WHERE c.id = {context}.instanceid AND c.category = 0)
6940 $emptyclause";
6941 $DB->execute($sql);
6943 // standard courses
6944 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
6945 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
6946 FROM {context} ctx
6947 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6948 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6949 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6950 $ctxemptyclause";
6951 $trans = $DB->start_delegated_transaction();
6952 $DB->delete_records('context_temp');
6953 $DB->execute($sql);
6954 context::merge_context_temp_table();
6955 $DB->delete_records('context_temp');
6956 $trans->allow_commit();
6963 * Course module context class
6965 * @package core_access
6966 * @category access
6967 * @copyright Petr Skoda {@link http://skodak.org}
6968 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6969 * @since Moodle 2.2
6971 class context_module extends context {
6973 * Please use context_module::instance($cmid) if you need the instance of context.
6974 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6976 * @param stdClass $record
6978 protected function __construct(stdClass $record) {
6979 parent::__construct($record);
6980 if ($record->contextlevel != CONTEXT_MODULE) {
6981 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6986 * Returns human readable context level name.
6988 * @static
6989 * @return string the human readable context level name.
6991 public static function get_level_name() {
6992 return get_string('activitymodule');
6996 * Returns human readable context identifier.
6998 * @param boolean $withprefix whether to prefix the name of the context with the
6999 * module name, e.g. Forum, Glossary, etc.
7000 * @param boolean $short does not apply to module context
7001 * @return string the human readable context name.
7003 public function get_context_name($withprefix = true, $short = false) {
7004 global $DB;
7006 $name = '';
7007 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
7008 FROM {course_modules} cm
7009 JOIN {modules} md ON md.id = cm.module
7010 WHERE cm.id = ?", array($this->_instanceid))) {
7011 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
7012 if ($withprefix){
7013 $name = get_string('modulename', $cm->modname).': ';
7015 $name .= format_string($mod->name, true, array('context' => $this));
7018 return $name;
7022 * Returns the most relevant URL for this context.
7024 * @return moodle_url
7026 public function get_url() {
7027 global $DB;
7029 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
7030 FROM {course_modules} cm
7031 JOIN {modules} md ON md.id = cm.module
7032 WHERE cm.id = ?", array($this->_instanceid))) {
7033 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
7036 return new moodle_url('/');
7040 * Returns array of relevant context capability records.
7042 * @return array
7044 public function get_capabilities() {
7045 global $DB, $CFG;
7047 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7049 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
7050 $module = $DB->get_record('modules', array('id'=>$cm->module));
7052 $subcaps = array();
7054 $modulepath = "{$CFG->dirroot}/mod/{$module->name}";
7055 if (file_exists("{$modulepath}/db/subplugins.json")) {
7056 $subplugins = (array) json_decode(file_get_contents("{$modulepath}/db/subplugins.json"))->plugintypes;
7057 } else if (file_exists("{$modulepath}/db/subplugins.php")) {
7058 debugging('Use of subplugins.php has been deprecated. ' .
7059 'Please update your plugin to provide a subplugins.json file instead.',
7060 DEBUG_DEVELOPER);
7061 $subplugins = array(); // should be redefined in the file
7062 include("{$modulepath}/db/subplugins.php");
7065 if (!empty($subplugins)) {
7066 foreach (array_keys($subplugins) as $subplugintype) {
7067 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
7068 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
7073 $modfile = "{$modulepath}/lib.php";
7074 $extracaps = array();
7075 if (file_exists($modfile)) {
7076 include_once($modfile);
7077 $modfunction = $module->name.'_get_extra_capabilities';
7078 if (function_exists($modfunction)) {
7079 $extracaps = $modfunction();
7083 $extracaps = array_merge($subcaps, $extracaps);
7084 $extra = '';
7085 list($extra, $params) = $DB->get_in_or_equal(
7086 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
7087 if (!empty($extra)) {
7088 $extra = "OR name $extra";
7091 // Fetch the list of modules, and remove this one.
7092 $components = \core_component::get_component_list();
7093 $componentnames = $components['mod'];
7094 unset($componentnames["mod_{$module->name}"]);
7095 $componentnames = array_keys($componentnames);
7097 // Exclude all other modules.
7098 list($notcompsql, $notcompparams) = $DB->get_in_or_equal($componentnames, SQL_PARAMS_NAMED, 'notcomp', false);
7099 $params = array_merge($params, $notcompparams);
7102 // Exclude other component submodules.
7103 $i = 0;
7104 $ignorecomponents = [];
7105 foreach ($componentnames as $mod) {
7106 if ($subplugins = \core_component::get_subplugins($mod)) {
7107 foreach (array_keys($subplugins) as $subplugintype) {
7108 $paramname = "notlike{$i}";
7109 $ignorecomponents[] = $DB->sql_like('component', ":{$paramname}", true, true, true);
7110 $params[$paramname] = "{$subplugintype}_%";
7111 $i++;
7115 $notlikesql = "(" . implode(' AND ', $ignorecomponents) . ")";
7117 $sql = "SELECT *
7118 FROM {capabilities}
7119 WHERE (contextlevel = ".CONTEXT_MODULE."
7120 AND component {$notcompsql}
7121 AND {$notlikesql})
7122 $extra";
7124 return $DB->get_records_sql($sql.' '.$sort, $params);
7128 * Is this context part of any course? If yes return course context.
7130 * @param bool $strict true means throw exception if not found, false means return false if not found
7131 * @return context_course context of the enclosing course, null if not found or exception
7133 public function get_course_context($strict = true) {
7134 return $this->get_parent_context();
7138 * Returns module context instance.
7140 * @static
7141 * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
7142 * @param int $strictness
7143 * @return context_module context instance
7145 public static function instance($cmid, $strictness = MUST_EXIST) {
7146 global $DB;
7148 if ($context = context::cache_get(CONTEXT_MODULE, $cmid)) {
7149 return $context;
7152 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE, 'instanceid' => $cmid))) {
7153 if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
7154 $parentcontext = context_course::instance($cm->course);
7155 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
7159 if ($record) {
7160 $context = new context_module($record);
7161 context::cache_add($context);
7162 return $context;
7165 return false;
7169 * Create missing context instances at module context level
7170 * @static
7172 protected static function create_level_instances() {
7173 global $DB;
7175 $sql = "SELECT ".CONTEXT_MODULE.", cm.id
7176 FROM {course_modules} cm
7177 WHERE NOT EXISTS (SELECT 'x'
7178 FROM {context} cx
7179 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
7180 $contextdata = $DB->get_recordset_sql($sql);
7181 foreach ($contextdata as $context) {
7182 context::insert_context_record(CONTEXT_MODULE, $context->id, null);
7184 $contextdata->close();
7188 * Returns sql necessary for purging of stale context instances.
7190 * @static
7191 * @return string cleanup SQL
7193 protected static function get_cleanup_sql() {
7194 $sql = "
7195 SELECT c.*
7196 FROM {context} c
7197 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
7198 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
7201 return $sql;
7205 * Rebuild context paths and depths at module context level.
7207 * @static
7208 * @param bool $force
7210 protected static function build_paths($force) {
7211 global $DB;
7213 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
7214 if ($force) {
7215 $ctxemptyclause = '';
7216 } else {
7217 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7220 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7221 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7222 FROM {context} ctx
7223 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
7224 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
7225 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7226 $ctxemptyclause";
7227 $trans = $DB->start_delegated_transaction();
7228 $DB->delete_records('context_temp');
7229 $DB->execute($sql);
7230 context::merge_context_temp_table();
7231 $DB->delete_records('context_temp');
7232 $trans->allow_commit();
7239 * Block context class
7241 * @package core_access
7242 * @category access
7243 * @copyright Petr Skoda {@link http://skodak.org}
7244 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7245 * @since Moodle 2.2
7247 class context_block extends context {
7249 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
7250 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7252 * @param stdClass $record
7254 protected function __construct(stdClass $record) {
7255 parent::__construct($record);
7256 if ($record->contextlevel != CONTEXT_BLOCK) {
7257 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
7262 * Returns human readable context level name.
7264 * @static
7265 * @return string the human readable context level name.
7267 public static function get_level_name() {
7268 return get_string('block');
7272 * Returns human readable context identifier.
7274 * @param boolean $withprefix whether to prefix the name of the context with Block
7275 * @param boolean $short does not apply to block context
7276 * @return string the human readable context name.
7278 public function get_context_name($withprefix = true, $short = false) {
7279 global $DB, $CFG;
7281 $name = '';
7282 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
7283 global $CFG;
7284 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7285 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7286 $blockname = "block_$blockinstance->blockname";
7287 if ($blockobject = new $blockname()) {
7288 if ($withprefix){
7289 $name = get_string('block').': ';
7291 $name .= $blockobject->title;
7295 return $name;
7299 * Returns the most relevant URL for this context.
7301 * @return moodle_url
7303 public function get_url() {
7304 $parentcontexts = $this->get_parent_context();
7305 return $parentcontexts->get_url();
7309 * Returns array of relevant context capability records.
7311 * @return array
7313 public function get_capabilities() {
7314 global $DB;
7316 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7318 $params = array();
7319 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
7321 $extra = '';
7322 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7323 if ($extracaps) {
7324 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7325 $extra = "OR name $extra";
7328 $sql = "SELECT *
7329 FROM {capabilities}
7330 WHERE (contextlevel = ".CONTEXT_BLOCK."
7331 AND component = :component)
7332 $extra";
7333 $params['component'] = 'block_' . $bi->blockname;
7335 return $DB->get_records_sql($sql.' '.$sort, $params);
7339 * Is this context part of any course? If yes return course context.
7341 * @param bool $strict true means throw exception if not found, false means return false if not found
7342 * @return context_course context of the enclosing course, null if not found or exception
7344 public function get_course_context($strict = true) {
7345 $parentcontext = $this->get_parent_context();
7346 return $parentcontext->get_course_context($strict);
7350 * Returns block context instance.
7352 * @static
7353 * @param int $blockinstanceid id from {block_instances} table.
7354 * @param int $strictness
7355 * @return context_block context instance
7357 public static function instance($blockinstanceid, $strictness = MUST_EXIST) {
7358 global $DB;
7360 if ($context = context::cache_get(CONTEXT_BLOCK, $blockinstanceid)) {
7361 return $context;
7364 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $blockinstanceid))) {
7365 if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
7366 $parentcontext = context::instance_by_id($bi->parentcontextid);
7367 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7371 if ($record) {
7372 $context = new context_block($record);
7373 context::cache_add($context);
7374 return $context;
7377 return false;
7381 * Block do not have child contexts...
7382 * @return array
7384 public function get_child_contexts() {
7385 return array();
7389 * Create missing context instances at block context level
7390 * @static
7392 protected static function create_level_instances() {
7393 global $DB;
7395 $sql = "SELECT ".CONTEXT_BLOCK.", bi.id
7396 FROM {block_instances} bi
7397 WHERE NOT EXISTS (SELECT 'x'
7398 FROM {context} cx
7399 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7400 $contextdata = $DB->get_recordset_sql($sql);
7401 foreach ($contextdata as $context) {
7402 context::insert_context_record(CONTEXT_BLOCK, $context->id, null);
7404 $contextdata->close();
7408 * Returns sql necessary for purging of stale context instances.
7410 * @static
7411 * @return string cleanup SQL
7413 protected static function get_cleanup_sql() {
7414 $sql = "
7415 SELECT c.*
7416 FROM {context} c
7417 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7418 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7421 return $sql;
7425 * Rebuild context paths and depths at block context level.
7427 * @static
7428 * @param bool $force
7430 protected static function build_paths($force) {
7431 global $DB;
7433 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7434 if ($force) {
7435 $ctxemptyclause = '';
7436 } else {
7437 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7440 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7441 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7442 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7443 FROM {context} ctx
7444 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7445 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7446 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7447 $ctxemptyclause";
7448 $trans = $DB->start_delegated_transaction();
7449 $DB->delete_records('context_temp');
7450 $DB->execute($sql);
7451 context::merge_context_temp_table();
7452 $DB->delete_records('context_temp');
7453 $trans->allow_commit();
7459 // ============== DEPRECATED FUNCTIONS ==========================================
7460 // Old context related functions were deprecated in 2.0, it is recommended
7461 // to use context classes in new code. Old function can be used when
7462 // creating patches that are supposed to be backported to older stable branches.
7463 // These deprecated functions will not be removed in near future,
7464 // before removing devs will be warned with a debugging message first,
7465 // then we will add error message and only after that we can remove the functions
7466 // completely.
7469 * Runs get_records select on context table and returns the result
7470 * Does get_records_select on the context table, and returns the results ordered
7471 * by contextlevel, and then the natural sort order within each level.
7472 * for the purpose of $select, you need to know that the context table has been
7473 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7475 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7476 * @param array $params any parameters required by $select.
7477 * @return array the requested context records.
7479 function get_sorted_contexts($select, $params = array()) {
7481 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7483 global $DB;
7484 if ($select) {
7485 $select = 'WHERE ' . $select;
7487 return $DB->get_records_sql("
7488 SELECT ctx.*
7489 FROM {context} ctx
7490 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7491 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7492 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7493 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7494 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7495 $select
7496 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7497 ", $params);
7501 * Given context and array of users, returns array of users whose enrolment status is suspended,
7502 * or enrolment has expired or has not started. Also removes those users from the given array
7504 * @param context $context context in which suspended users should be extracted.
7505 * @param array $users list of users.
7506 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7507 * @return array list of suspended users.
7509 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7510 global $DB;
7512 // Get active enrolled users.
7513 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7514 $activeusers = $DB->get_records_sql($sql, $params);
7516 // Move suspended users to a separate array & remove from the initial one.
7517 $susers = array();
7518 if (sizeof($activeusers)) {
7519 foreach ($users as $userid => $user) {
7520 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7521 $susers[$userid] = $user;
7522 unset($users[$userid]);
7526 return $susers;
7530 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7531 * or enrolment has expired or not started.
7533 * @param context $context context in which user enrolment is checked.
7534 * @param bool $usecache Enable or disable (default) the request cache
7535 * @return array list of suspended user id's.
7537 function get_suspended_userids(context $context, $usecache = false) {
7538 global $DB;
7540 if ($usecache) {
7541 $cache = cache::make('core', 'suspended_userids');
7542 $susers = $cache->get($context->id);
7543 if ($susers !== false) {
7544 return $susers;
7548 $coursecontext = $context->get_course_context();
7549 $susers = array();
7551 // Front page users are always enrolled, so suspended list is empty.
7552 if ($coursecontext->instanceid != SITEID) {
7553 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7554 $susers = $DB->get_fieldset_sql($sql, $params);
7555 $susers = array_combine($susers, $susers);
7558 // Cache results for the remainder of this request.
7559 if ($usecache) {
7560 $cache->set($context->id, $susers);
7563 return $susers;
7567 * Gets sql for finding users with capability in the given context
7569 * @param context $context
7570 * @param string|array $capability Capability name or array of names.
7571 * If an array is provided then this is the equivalent of a logical 'OR',
7572 * i.e. the user needs to have one of these capabilities.
7573 * @return array($sql, $params)
7575 function get_with_capability_sql(context $context, $capability) {
7576 static $i = 0;
7577 $i++;
7578 $prefix = 'cu' . $i . '_';
7580 $capjoin = get_with_capability_join($context, $capability, $prefix . 'u.id');
7582 $sql = "SELECT DISTINCT {$prefix}u.id
7583 FROM {user} {$prefix}u
7584 $capjoin->joins
7585 WHERE {$prefix}u.deleted = 0 AND $capjoin->wheres";
7587 return array($sql, $capjoin->params);
7591 * Gets sql joins for finding users with capability in the given context
7593 * @param context $context Context for the join
7594 * @param string|array $capability Capability name or array of names.
7595 * If an array is provided then this is the equivalent of a logical 'OR',
7596 * i.e. the user needs to have one of these capabilities.
7597 * @param string $useridcolumn e.g. 'u.id'
7598 * @return \core\dml\sql_join Contains joins, wheres, params
7600 function get_with_capability_join(context $context, $capability, $useridcolumn) {
7601 global $DB, $CFG;
7603 // Use unique prefix just in case somebody makes some SQL magic with the result.
7604 static $i = 0;
7605 $i++;
7606 $prefix = 'eu' . $i . '_';
7608 // First find the course context.
7609 $coursecontext = $context->get_course_context();
7611 $isfrontpage = ($coursecontext->instanceid == SITEID);
7613 $joins = array();
7614 $wheres = array();
7615 $params = array();
7617 list($contextids, $contextpaths) = get_context_info_list($context);
7619 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
7621 list($incaps, $capsparams) = $DB->get_in_or_equal($capability, SQL_PARAMS_NAMED, 'cap');
7623 // Check whether context locking is enabled.
7624 // Filter out any write capability if this is the case.
7625 $excludelockedcaps = '';
7626 $excludelockedcapsparams = [];
7627 if (!empty($CFG->contextlocking) && $context->locked) {
7628 $excludelockedcaps = 'AND (cap.captype = :capread OR cap.name = :managelockscap)';
7629 $excludelockedcapsparams['capread'] = 'read';
7630 $excludelockedcapsparams['managelockscap'] = 'moodle/site:managecontextlocks';
7633 $defs = array();
7634 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
7635 FROM {role_capabilities} rc
7636 JOIN {capabilities} cap ON rc.capability = cap.name
7637 JOIN {context} ctx on rc.contextid = ctx.id
7638 WHERE rc.contextid $incontexts AND rc.capability $incaps $excludelockedcaps";
7639 $rcs = $DB->get_records_sql($sql, array_merge($cparams, $capsparams, $excludelockedcapsparams));
7640 foreach ($rcs as $rc) {
7641 $defs[$rc->path][$rc->roleid] = $rc->permission;
7644 $access = array();
7645 if (!empty($defs)) {
7646 foreach ($contextpaths as $path) {
7647 if (empty($defs[$path])) {
7648 continue;
7650 foreach ($defs[$path] as $roleid => $perm) {
7651 if ($perm == CAP_PROHIBIT) {
7652 $access[$roleid] = CAP_PROHIBIT;
7653 continue;
7655 if (!isset($access[$roleid])) {
7656 $access[$roleid] = (int) $perm;
7662 unset($defs);
7664 // Make lists of roles that are needed and prohibited.
7665 $needed = array(); // One of these is enough.
7666 $prohibited = array(); // Must not have any of these.
7667 foreach ($access as $roleid => $perm) {
7668 if ($perm == CAP_PROHIBIT) {
7669 unset($needed[$roleid]);
7670 $prohibited[$roleid] = true;
7671 } else {
7672 if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
7673 $needed[$roleid] = true;
7678 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
7679 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
7681 $nobody = false;
7683 if ($isfrontpage) {
7684 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
7685 $nobody = true;
7686 } else {
7687 if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
7688 // Everybody not having prohibit has the capability.
7689 $needed = array();
7690 } else {
7691 if (empty($needed)) {
7692 $nobody = true;
7696 } else {
7697 if (!empty($prohibited[$defaultuserroleid])) {
7698 $nobody = true;
7699 } else {
7700 if (!empty($needed[$defaultuserroleid])) {
7701 // Everybody not having prohibit has the capability.
7702 $needed = array();
7703 } else {
7704 if (empty($needed)) {
7705 $nobody = true;
7711 if ($nobody) {
7712 // Nobody can match so return some SQL that does not return any results.
7713 $wheres[] = "1 = 2";
7715 } else {
7717 if ($needed) {
7718 $ctxids = implode(',', $contextids);
7719 $roleids = implode(',', array_keys($needed));
7720 $joins[] = "JOIN {role_assignments} {$prefix}ra3
7721 ON ({$prefix}ra3.userid = $useridcolumn
7722 AND {$prefix}ra3.roleid IN ($roleids)
7723 AND {$prefix}ra3.contextid IN ($ctxids))";
7726 if ($prohibited) {
7727 $ctxids = implode(',', $contextids);
7728 $roleids = implode(',', array_keys($prohibited));
7729 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4
7730 ON ({$prefix}ra4.userid = $useridcolumn
7731 AND {$prefix}ra4.roleid IN ($roleids)
7732 AND {$prefix}ra4.contextid IN ($ctxids))";
7733 $wheres[] = "{$prefix}ra4.id IS NULL";
7738 $wheres[] = "$useridcolumn <> :{$prefix}guestid";
7739 $params["{$prefix}guestid"] = $CFG->siteguest;
7741 $joins = implode("\n", $joins);
7742 $wheres = "(" . implode(" AND ", $wheres) . ")";
7744 return new \core\dml\sql_join($joins, $wheres, $params);