MDL-66397 filter_h5p: converts H5P URLs to embed code
[moodle.git] / lib / accesslib.php
blobcd3058f7429ba4891b26b147776c106301fa96d8
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' or $component === 'core') {
2564 switch ($contextlevel) {
2565 // TODO MDL-46123: this should probably use context level names instead
2566 case CONTEXT_SYSTEM: return get_string('coresystem');
2567 case CONTEXT_USER: return get_string('users');
2568 case CONTEXT_COURSECAT: return get_string('categories');
2569 case CONTEXT_COURSE: return get_string('course');
2570 case CONTEXT_MODULE: return get_string('activities');
2571 case CONTEXT_BLOCK: return get_string('block');
2572 default: print_error('unknowncontext');
2576 list($type, $name) = core_component::normalize_component($component);
2577 $dir = core_component::get_plugin_directory($type, $name);
2578 if (!file_exists($dir)) {
2579 // plugin not installed, bad luck, there is no way to find the name
2580 return $component.' ???';
2583 switch ($type) {
2584 // TODO MDL-46123: this is really hacky and should be improved.
2585 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2586 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2587 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2588 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2589 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2590 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2591 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2592 case 'mod':
2593 if (get_string_manager()->string_exists('pluginname', $component)) {
2594 return get_string('activity').': '.get_string('pluginname', $component);
2595 } else {
2596 return get_string('activity').': '.get_string('modulename', $component);
2598 default: return get_string('pluginname', $component);
2603 * Gets the list of roles assigned to this context and up (parents)
2604 * from the aggregation of:
2605 * a) the list of roles that are visible on user profile page and participants page (profileroles setting) and;
2606 * b) if applicable, those roles that are assigned in the context.
2608 * @param context $context
2609 * @return array
2611 function get_profile_roles(context $context) {
2612 global $CFG, $DB;
2613 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2614 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2615 if (has_capability('moodle/role:assign', $context)) {
2616 $rolesinscope = array_keys(get_all_roles($context));
2617 } else {
2618 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2621 if (empty($rolesinscope)) {
2622 return [];
2625 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2626 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2627 $params = array_merge($params, $cparams);
2629 if ($coursecontext = $context->get_course_context(false)) {
2630 $params['coursecontext'] = $coursecontext->id;
2631 } else {
2632 $params['coursecontext'] = 0;
2635 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2636 FROM {role_assignments} ra, {role} r
2637 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2638 WHERE r.id = ra.roleid
2639 AND ra.contextid $contextlist
2640 AND r.id $rallowed
2641 ORDER BY r.sortorder ASC";
2643 return $DB->get_records_sql($sql, $params);
2647 * Gets the list of roles assigned to this context and up (parents)
2649 * @param context $context
2650 * @param boolean $includeparents, false means without parents.
2651 * @return array
2653 function get_roles_used_in_context(context $context, $includeparents = true) {
2654 global $DB;
2656 if ($includeparents === true) {
2657 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2658 } else {
2659 list($contextlist, $params) = $DB->get_in_or_equal($context->id, SQL_PARAMS_NAMED, 'cl');
2662 if ($coursecontext = $context->get_course_context(false)) {
2663 $params['coursecontext'] = $coursecontext->id;
2664 } else {
2665 $params['coursecontext'] = 0;
2668 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2669 FROM {role_assignments} ra, {role} r
2670 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2671 WHERE r.id = ra.roleid
2672 AND ra.contextid $contextlist
2673 ORDER BY r.sortorder ASC";
2675 return $DB->get_records_sql($sql, $params);
2679 * This function is used to print roles column in user profile page.
2680 * It is using the CFG->profileroles to limit the list to only interesting roles.
2681 * (The permission tab has full details of user role assignments.)
2683 * @param int $userid
2684 * @param int $courseid
2685 * @return string
2687 function get_user_roles_in_course($userid, $courseid) {
2688 global $CFG, $DB;
2689 if ($courseid == SITEID) {
2690 $context = context_system::instance();
2691 } else {
2692 $context = context_course::instance($courseid);
2694 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2695 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2696 if (has_capability('moodle/role:assign', $context)) {
2697 $rolesinscope = array_keys(get_all_roles($context));
2698 } else {
2699 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2701 if (empty($rolesinscope)) {
2702 return '';
2705 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2706 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2707 $params = array_merge($params, $cparams);
2709 if ($coursecontext = $context->get_course_context(false)) {
2710 $params['coursecontext'] = $coursecontext->id;
2711 } else {
2712 $params['coursecontext'] = 0;
2715 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2716 FROM {role_assignments} ra, {role} r
2717 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2718 WHERE r.id = ra.roleid
2719 AND ra.contextid $contextlist
2720 AND r.id $rallowed
2721 AND ra.userid = :userid
2722 ORDER BY r.sortorder ASC";
2723 $params['userid'] = $userid;
2725 $rolestring = '';
2727 if ($roles = $DB->get_records_sql($sql, $params)) {
2728 $viewableroles = get_viewable_roles($context, $userid);
2730 $rolenames = array();
2731 foreach ($roles as $roleid => $unused) {
2732 if (isset($viewableroles[$roleid])) {
2733 $url = new moodle_url('/user/index.php', ['contextid' => $context->id, 'roleid' => $roleid]);
2734 $rolenames[] = '<a href="' . $url . '">' . $viewableroles[$roleid] . '</a>';
2737 $rolestring = implode(',', $rolenames);
2740 return $rolestring;
2744 * Checks if a user can assign users to a particular role in this context
2746 * @param context $context
2747 * @param int $targetroleid - the id of the role you want to assign users to
2748 * @return boolean
2750 function user_can_assign(context $context, $targetroleid) {
2751 global $DB;
2753 // First check to see if the user is a site administrator.
2754 if (is_siteadmin()) {
2755 return true;
2758 // Check if user has override capability.
2759 // If not return false.
2760 if (!has_capability('moodle/role:assign', $context)) {
2761 return false;
2763 // pull out all active roles of this user from this context(or above)
2764 if ($userroles = get_user_roles($context)) {
2765 foreach ($userroles as $userrole) {
2766 // if any in the role_allow_override table, then it's ok
2767 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2768 return true;
2773 return false;
2777 * Returns all site roles in correct sort order.
2779 * Note: this method does not localise role names or descriptions,
2780 * use role_get_names() if you need role names.
2782 * @param context $context optional context for course role name aliases
2783 * @return array of role records with optional coursealias property
2785 function get_all_roles(context $context = null) {
2786 global $DB;
2788 if (!$context or !$coursecontext = $context->get_course_context(false)) {
2789 $coursecontext = null;
2792 if ($coursecontext) {
2793 $sql = "SELECT r.*, rn.name AS coursealias
2794 FROM {role} r
2795 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2796 ORDER BY r.sortorder ASC";
2797 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
2799 } else {
2800 return $DB->get_records('role', array(), 'sortorder ASC');
2805 * Returns roles of a specified archetype
2807 * @param string $archetype
2808 * @return array of full role records
2810 function get_archetype_roles($archetype) {
2811 global $DB;
2812 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2816 * Gets all the user roles assigned in this context, or higher contexts for a list of users.
2818 * If you try using the combination $userids = [], $checkparentcontexts = true then this is likely
2819 * to cause an out-of-memory error on large Moodle sites, so this combination is deprecated and
2820 * outputs a warning, even though it is the default.
2822 * @param context $context
2823 * @param array $userids. An empty list means fetch all role assignments for the context.
2824 * @param bool $checkparentcontexts defaults to true
2825 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2826 * @return array
2828 function get_users_roles(context $context, $userids = [], $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2829 global $DB;
2831 if (!$userids && $checkparentcontexts) {
2832 debugging('Please do not call get_users_roles() with $checkparentcontexts = true ' .
2833 'and $userids array not set. This combination causes large Moodle sites ' .
2834 'with lots of site-wide role assignemnts to run out of memory.', DEBUG_DEVELOPER);
2837 if ($checkparentcontexts) {
2838 $contextids = $context->get_parent_context_ids();
2839 } else {
2840 $contextids = array();
2842 $contextids[] = $context->id;
2844 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
2846 // If userids was passed as an empty array, we fetch all role assignments for the course.
2847 if (empty($userids)) {
2848 $useridlist = ' IS NOT NULL ';
2849 $uparams = [];
2850 } else {
2851 list($useridlist, $uparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'uids');
2854 $sql = "SELECT ra.*, r.name, r.shortname, ra.userid
2855 FROM {role_assignments} ra, {role} r, {context} c
2856 WHERE ra.userid $useridlist
2857 AND ra.roleid = r.id
2858 AND ra.contextid = c.id
2859 AND ra.contextid $contextids
2860 ORDER BY $order";
2862 $all = $DB->get_records_sql($sql , array_merge($params, $uparams));
2864 // Return results grouped by userid.
2865 $result = [];
2866 foreach ($all as $id => $record) {
2867 if (!isset($result[$record->userid])) {
2868 $result[$record->userid] = [];
2870 $result[$record->userid][$record->id] = $record;
2873 // Make sure all requested users are included in the result, even if they had no role assignments.
2874 foreach ($userids as $id) {
2875 if (!isset($result[$id])) {
2876 $result[$id] = [];
2880 return $result;
2885 * Gets all the user roles assigned in this context, or higher contexts
2886 * this is mainly used when checking if a user can assign a role, or overriding a role
2887 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2888 * allow_override tables
2890 * @param context $context
2891 * @param int $userid
2892 * @param bool $checkparentcontexts defaults to true
2893 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2894 * @return array
2896 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2897 global $USER, $DB;
2899 if (empty($userid)) {
2900 if (empty($USER->id)) {
2901 return array();
2903 $userid = $USER->id;
2906 if ($checkparentcontexts) {
2907 $contextids = $context->get_parent_context_ids();
2908 } else {
2909 $contextids = array();
2911 $contextids[] = $context->id;
2913 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2915 array_unshift($params, $userid);
2917 $sql = "SELECT ra.*, r.name, r.shortname
2918 FROM {role_assignments} ra, {role} r, {context} c
2919 WHERE ra.userid = ?
2920 AND ra.roleid = r.id
2921 AND ra.contextid = c.id
2922 AND ra.contextid $contextids
2923 ORDER BY $order";
2925 return $DB->get_records_sql($sql ,$params);
2929 * Like get_user_roles, but adds in the authenticated user role, and the front
2930 * page roles, if applicable.
2932 * @param context $context the context.
2933 * @param int $userid optional. Defaults to $USER->id
2934 * @return array of objects with fields ->userid, ->contextid and ->roleid.
2936 function get_user_roles_with_special(context $context, $userid = 0) {
2937 global $CFG, $USER;
2939 if (empty($userid)) {
2940 if (empty($USER->id)) {
2941 return array();
2943 $userid = $USER->id;
2946 $ras = get_user_roles($context, $userid);
2948 // Add front-page role if relevant.
2949 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2950 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
2951 is_inside_frontpage($context);
2952 if ($defaultfrontpageroleid && $isfrontpage) {
2953 $frontpagecontext = context_course::instance(SITEID);
2954 $ra = new stdClass();
2955 $ra->userid = $userid;
2956 $ra->contextid = $frontpagecontext->id;
2957 $ra->roleid = $defaultfrontpageroleid;
2958 $ras[] = $ra;
2961 // Add authenticated user role if relevant.
2962 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2963 if ($defaultuserroleid && !isguestuser($userid)) {
2964 $systemcontext = context_system::instance();
2965 $ra = new stdClass();
2966 $ra->userid = $userid;
2967 $ra->contextid = $systemcontext->id;
2968 $ra->roleid = $defaultuserroleid;
2969 $ras[] = $ra;
2972 return $ras;
2976 * Creates a record in the role_allow_override table
2978 * @param int $fromroleid source roleid
2979 * @param int $targetroleid target roleid
2980 * @return void
2982 function core_role_set_override_allowed($fromroleid, $targetroleid) {
2983 global $DB;
2985 $record = new stdClass();
2986 $record->roleid = $fromroleid;
2987 $record->allowoverride = $targetroleid;
2988 $DB->insert_record('role_allow_override', $record);
2992 * Creates a record in the role_allow_assign table
2994 * @param int $fromroleid source roleid
2995 * @param int $targetroleid target roleid
2996 * @return void
2998 function core_role_set_assign_allowed($fromroleid, $targetroleid) {
2999 global $DB;
3001 $record = new stdClass();
3002 $record->roleid = $fromroleid;
3003 $record->allowassign = $targetroleid;
3004 $DB->insert_record('role_allow_assign', $record);
3008 * Creates a record in the role_allow_switch table
3010 * @param int $fromroleid source roleid
3011 * @param int $targetroleid target roleid
3012 * @return void
3014 function core_role_set_switch_allowed($fromroleid, $targetroleid) {
3015 global $DB;
3017 $record = new stdClass();
3018 $record->roleid = $fromroleid;
3019 $record->allowswitch = $targetroleid;
3020 $DB->insert_record('role_allow_switch', $record);
3024 * Creates a record in the role_allow_view table
3026 * @param int $fromroleid source roleid
3027 * @param int $targetroleid target roleid
3028 * @return void
3030 function core_role_set_view_allowed($fromroleid, $targetroleid) {
3031 global $DB;
3033 $record = new stdClass();
3034 $record->roleid = $fromroleid;
3035 $record->allowview = $targetroleid;
3036 $DB->insert_record('role_allow_view', $record);
3040 * Gets a list of roles that this user can assign in this context
3042 * @param context $context the context.
3043 * @param int $rolenamedisplay the type of role name to display. One of the
3044 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3045 * @param bool $withusercounts if true, count the number of users with each role.
3046 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3047 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3048 * if $withusercounts is true, returns a list of three arrays,
3049 * $rolenames, $rolecounts, and $nameswithcounts.
3051 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3052 global $USER, $DB;
3054 // make sure there is a real user specified
3055 if ($user === null) {
3056 $userid = isset($USER->id) ? $USER->id : 0;
3057 } else {
3058 $userid = is_object($user) ? $user->id : $user;
3061 if (!has_capability('moodle/role:assign', $context, $userid)) {
3062 if ($withusercounts) {
3063 return array(array(), array(), array());
3064 } else {
3065 return array();
3069 $params = array();
3070 $extrafields = '';
3072 if ($withusercounts) {
3073 $extrafields = ', (SELECT COUNT(DISTINCT u.id)
3074 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3075 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3076 ) AS usercount';
3077 $params['conid'] = $context->id;
3080 if (is_siteadmin($userid)) {
3081 // show all roles allowed in this context to admins
3082 $assignrestriction = "";
3083 } else {
3084 $parents = $context->get_parent_context_ids(true);
3085 $contexts = implode(',' , $parents);
3086 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3087 FROM {role_allow_assign} raa
3088 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3089 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3090 ) ar ON ar.id = r.id";
3091 $params['userid'] = $userid;
3093 $params['contextlevel'] = $context->contextlevel;
3095 if ($coursecontext = $context->get_course_context(false)) {
3096 $params['coursecontext'] = $coursecontext->id;
3097 } else {
3098 $params['coursecontext'] = 0; // no course aliases
3099 $coursecontext = null;
3101 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3102 FROM {role} r
3103 $assignrestriction
3104 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3105 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3106 ORDER BY r.sortorder ASC";
3107 $roles = $DB->get_records_sql($sql, $params);
3109 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3111 if (!$withusercounts) {
3112 return $rolenames;
3115 $rolecounts = array();
3116 $nameswithcounts = array();
3117 foreach ($roles as $role) {
3118 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3119 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3121 return array($rolenames, $rolecounts, $nameswithcounts);
3125 * Gets a list of roles that this user can switch to in a context
3127 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3128 * This function just process the contents of the role_allow_switch table. You also need to
3129 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3131 * @param context $context a context.
3132 * @return array an array $roleid => $rolename.
3134 function get_switchable_roles(context $context) {
3135 global $USER, $DB;
3137 // You can't switch roles without this capability.
3138 if (!has_capability('moodle/role:switchroles', $context)) {
3139 return [];
3142 $params = array();
3143 $extrajoins = '';
3144 $extrawhere = '';
3145 if (!is_siteadmin()) {
3146 // Admins are allowed to switch to any role with.
3147 // Others are subject to the additional constraint that the switch-to role must be allowed by
3148 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3149 $parents = $context->get_parent_context_ids(true);
3150 $contexts = implode(',' , $parents);
3152 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3153 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3154 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3155 $params['userid'] = $USER->id;
3158 if ($coursecontext = $context->get_course_context(false)) {
3159 $params['coursecontext'] = $coursecontext->id;
3160 } else {
3161 $params['coursecontext'] = 0; // no course aliases
3162 $coursecontext = null;
3165 $query = "
3166 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3167 FROM (SELECT DISTINCT rc.roleid
3168 FROM {role_capabilities} rc
3170 $extrajoins
3171 $extrawhere) idlist
3172 JOIN {role} r ON r.id = idlist.roleid
3173 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3174 ORDER BY r.sortorder";
3175 $roles = $DB->get_records_sql($query, $params);
3177 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3181 * Gets a list of roles that this user can view in a context
3183 * @param context $context a context.
3184 * @param int $userid id of user.
3185 * @return array an array $roleid => $rolename.
3187 function get_viewable_roles(context $context, $userid = null) {
3188 global $USER, $DB;
3190 if ($userid == null) {
3191 $userid = $USER->id;
3194 $params = array();
3195 $extrajoins = '';
3196 $extrawhere = '';
3197 if (!is_siteadmin()) {
3198 // Admins are allowed to view any role.
3199 // Others are subject to the additional constraint that the view role must be allowed by
3200 // 'role_allow_view' for some role they have assigned in this context or any parent.
3201 $contexts = $context->get_parent_context_ids(true);
3202 list($insql, $inparams) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED);
3204 $extrajoins = "JOIN {role_allow_view} ras ON ras.allowview = r.id
3205 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3206 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid $insql";
3208 $params += $inparams;
3209 $params['userid'] = $userid;
3212 if ($coursecontext = $context->get_course_context(false)) {
3213 $params['coursecontext'] = $coursecontext->id;
3214 } else {
3215 $params['coursecontext'] = 0; // No course aliases.
3216 $coursecontext = null;
3219 $query = "
3220 SELECT r.id, r.name, r.shortname, rn.name AS coursealias, r.sortorder
3221 FROM {role} r
3222 $extrajoins
3223 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3224 $extrawhere
3225 GROUP BY r.id, r.name, r.shortname, rn.name, r.sortorder
3226 ORDER BY r.sortorder";
3227 $roles = $DB->get_records_sql($query, $params);
3229 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3233 * Gets a list of roles that this user can override in this context.
3235 * @param context $context the context.
3236 * @param int $rolenamedisplay the type of role name to display. One of the
3237 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3238 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3239 * @return array if $withcounts is false, then an array $roleid => $rolename.
3240 * if $withusercounts is true, returns a list of three arrays,
3241 * $rolenames, $rolecounts, and $nameswithcounts.
3243 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3244 global $USER, $DB;
3246 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3247 if ($withcounts) {
3248 return array(array(), array(), array());
3249 } else {
3250 return array();
3254 $parents = $context->get_parent_context_ids(true);
3255 $contexts = implode(',' , $parents);
3257 $params = array();
3258 $extrafields = '';
3260 $params['userid'] = $USER->id;
3261 if ($withcounts) {
3262 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3263 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3264 $params['conid'] = $context->id;
3267 if ($coursecontext = $context->get_course_context(false)) {
3268 $params['coursecontext'] = $coursecontext->id;
3269 } else {
3270 $params['coursecontext'] = 0; // no course aliases
3271 $coursecontext = null;
3274 if (is_siteadmin()) {
3275 // show all roles to admins
3276 $roles = $DB->get_records_sql("
3277 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3278 FROM {role} ro
3279 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3280 ORDER BY ro.sortorder ASC", $params);
3282 } else {
3283 $roles = $DB->get_records_sql("
3284 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3285 FROM {role} ro
3286 JOIN (SELECT DISTINCT r.id
3287 FROM {role} r
3288 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3289 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3290 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3291 ) inline_view ON ro.id = inline_view.id
3292 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3293 ORDER BY ro.sortorder ASC", $params);
3296 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3298 if (!$withcounts) {
3299 return $rolenames;
3302 $rolecounts = array();
3303 $nameswithcounts = array();
3304 foreach ($roles as $role) {
3305 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3306 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3308 return array($rolenames, $rolecounts, $nameswithcounts);
3312 * Create a role menu suitable for default role selection in enrol plugins.
3314 * @package core_enrol
3316 * @param context $context
3317 * @param int $addroleid current or default role - always added to list
3318 * @return array roleid=>localised role name
3320 function get_default_enrol_roles(context $context, $addroleid = null) {
3321 global $DB;
3323 $params = array('contextlevel'=>CONTEXT_COURSE);
3325 if ($coursecontext = $context->get_course_context(false)) {
3326 $params['coursecontext'] = $coursecontext->id;
3327 } else {
3328 $params['coursecontext'] = 0; // no course names
3329 $coursecontext = null;
3332 if ($addroleid) {
3333 $addrole = "OR r.id = :addroleid";
3334 $params['addroleid'] = $addroleid;
3335 } else {
3336 $addrole = "";
3339 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3340 FROM {role} r
3341 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3342 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3343 WHERE rcl.id IS NOT NULL $addrole
3344 ORDER BY sortorder DESC";
3346 $roles = $DB->get_records_sql($sql, $params);
3348 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3352 * Return context levels where this role is assignable.
3354 * @param integer $roleid the id of a role.
3355 * @return array list of the context levels at which this role may be assigned.
3357 function get_role_contextlevels($roleid) {
3358 global $DB;
3359 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3360 'contextlevel', 'id,contextlevel');
3364 * Return roles suitable for assignment at the specified context level.
3366 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3368 * @param integer $contextlevel a contextlevel.
3369 * @return array list of role ids that are assignable at this context level.
3371 function get_roles_for_contextlevels($contextlevel) {
3372 global $DB;
3373 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3374 '', 'id,roleid');
3378 * Returns default context levels where roles can be assigned.
3380 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3381 * from the array returned by get_role_archetypes();
3382 * @return array list of the context levels at which this type of role may be assigned by default.
3384 function get_default_contextlevels($rolearchetype) {
3385 static $defaults = array(
3386 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3387 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3388 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3389 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3390 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3391 'guest' => array(),
3392 'user' => array(),
3393 'frontpage' => array());
3395 if (isset($defaults[$rolearchetype])) {
3396 return $defaults[$rolearchetype];
3397 } else {
3398 return array();
3403 * Set the context levels at which a particular role can be assigned.
3404 * Throws exceptions in case of error.
3406 * @param integer $roleid the id of a role.
3407 * @param array $contextlevels the context levels at which this role should be assignable,
3408 * duplicate levels are removed.
3409 * @return void
3411 function set_role_contextlevels($roleid, array $contextlevels) {
3412 global $DB;
3413 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3414 $rcl = new stdClass();
3415 $rcl->roleid = $roleid;
3416 $contextlevels = array_unique($contextlevels);
3417 foreach ($contextlevels as $level) {
3418 $rcl->contextlevel = $level;
3419 $DB->insert_record('role_context_levels', $rcl, false, true);
3424 * Who has this capability in this context?
3426 * This can be a very expensive call - use sparingly and keep
3427 * the results if you are going to need them again soon.
3429 * Note if $fields is empty this function attempts to get u.*
3430 * which can get rather large - and has a serious perf impact
3431 * on some DBs.
3433 * @param context $context
3434 * @param string|array $capability - capability name(s)
3435 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3436 * @param string $sort - the sort order. Default is lastaccess time.
3437 * @param mixed $limitfrom - number of records to skip (offset)
3438 * @param mixed $limitnum - number of records to fetch
3439 * @param string|array $groups - single group or array of groups - only return
3440 * users who are in one of these group(s).
3441 * @param string|array $exceptions - list of users to exclude, comma separated or array
3442 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3443 * @param bool $view_ignored - use get_enrolled_sql() instead
3444 * @param bool $useviewallgroups if $groups is set the return users who
3445 * have capability both $capability and moodle/site:accessallgroups
3446 * in this context, as well as users who have $capability and who are
3447 * in $groups.
3448 * @return array of user records
3450 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3451 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3452 global $CFG, $DB;
3454 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3455 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3457 $ctxids = trim($context->path, '/');
3458 $ctxids = str_replace('/', ',', $ctxids);
3460 // Context is the frontpage
3461 $iscoursepage = false; // coursepage other than fp
3462 $isfrontpage = false;
3463 if ($context->contextlevel == CONTEXT_COURSE) {
3464 if ($context->instanceid == SITEID) {
3465 $isfrontpage = true;
3466 } else {
3467 $iscoursepage = true;
3470 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3472 $caps = (array)$capability;
3474 // construct list of context paths bottom-->top
3475 list($contextids, $paths) = get_context_info_list($context);
3477 // we need to find out all roles that have these capabilities either in definition or in overrides
3478 $defs = array();
3479 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3480 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3482 // Check whether context locking is enabled.
3483 // Filter out any write capability if this is the case.
3484 $excludelockedcaps = '';
3485 $excludelockedcapsparams = [];
3486 if (!empty($CFG->contextlocking) && $context->locked) {
3487 $excludelockedcaps = 'AND (cap.captype = :capread OR cap.name = :managelockscap)';
3488 $excludelockedcapsparams['capread'] = 'read';
3489 $excludelockedcapsparams['managelockscap'] = 'moodle/site:managecontextlocks';
3492 $params = array_merge($params, $params2, $excludelockedcapsparams);
3493 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3494 FROM {role_capabilities} rc
3495 JOIN {capabilities} cap ON rc.capability = cap.name
3496 JOIN {context} ctx on rc.contextid = ctx.id
3497 WHERE rc.contextid $incontexts AND rc.capability $incaps $excludelockedcaps";
3499 $rcs = $DB->get_records_sql($sql, $params);
3500 foreach ($rcs as $rc) {
3501 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3504 // go through the permissions bottom-->top direction to evaluate the current permission,
3505 // first one wins (prohibit is an exception that always wins)
3506 $access = array();
3507 foreach ($caps as $cap) {
3508 foreach ($paths as $path) {
3509 if (empty($defs[$cap][$path])) {
3510 continue;
3512 foreach($defs[$cap][$path] as $roleid => $perm) {
3513 if ($perm == CAP_PROHIBIT) {
3514 $access[$cap][$roleid] = CAP_PROHIBIT;
3515 continue;
3517 if (!isset($access[$cap][$roleid])) {
3518 $access[$cap][$roleid] = (int)$perm;
3524 // make lists of roles that are needed and prohibited in this context
3525 $needed = array(); // one of these is enough
3526 $prohibited = array(); // must not have any of these
3527 foreach ($caps as $cap) {
3528 if (empty($access[$cap])) {
3529 continue;
3531 foreach ($access[$cap] as $roleid => $perm) {
3532 if ($perm == CAP_PROHIBIT) {
3533 unset($needed[$cap][$roleid]);
3534 $prohibited[$cap][$roleid] = true;
3535 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3536 $needed[$cap][$roleid] = true;
3539 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3540 // easy, nobody has the permission
3541 unset($needed[$cap]);
3542 unset($prohibited[$cap]);
3543 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3544 // everybody is disqualified on the frontpage
3545 unset($needed[$cap]);
3546 unset($prohibited[$cap]);
3548 if (empty($prohibited[$cap])) {
3549 unset($prohibited[$cap]);
3553 if (empty($needed)) {
3554 // there can not be anybody if no roles match this request
3555 return array();
3558 if (empty($prohibited)) {
3559 // we can compact the needed roles
3560 $n = array();
3561 foreach ($needed as $cap) {
3562 foreach ($cap as $roleid=>$unused) {
3563 $n[$roleid] = true;
3566 $needed = array('any'=>$n);
3567 unset($n);
3570 // ***** Set up default fields ******
3571 if (empty($fields)) {
3572 if ($iscoursepage) {
3573 $fields = 'u.*, ul.timeaccess AS lastaccess';
3574 } else {
3575 $fields = 'u.*';
3577 } else {
3578 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3579 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3583 // Set up default sort
3584 if (empty($sort)) { // default to course lastaccess or just lastaccess
3585 if ($iscoursepage) {
3586 $sort = 'ul.timeaccess';
3587 } else {
3588 $sort = 'u.lastaccess';
3592 // Prepare query clauses
3593 $wherecond = array();
3594 $params = array();
3595 $joins = array();
3597 // User lastaccess JOIN
3598 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3599 // user_lastaccess is not required MDL-13810
3600 } else {
3601 if ($iscoursepage) {
3602 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3603 } else {
3604 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3608 // We never return deleted users or guest account.
3609 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3610 $params['guestid'] = $CFG->siteguest;
3612 // Groups
3613 if ($groups) {
3614 $groups = (array)$groups;
3615 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3616 $joins[] = "LEFT OUTER JOIN (SELECT DISTINCT userid
3617 FROM {groups_members}
3618 WHERE groupid $grouptest
3619 ) gm ON gm.userid = u.id";
3621 $params = array_merge($params, $grpparams);
3623 $grouptest = 'gm.userid IS NOT NULL';
3624 if ($useviewallgroups) {
3625 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3626 if (!empty($viewallgroupsusers)) {
3627 $grouptest .= ' OR u.id IN (' . implode(',', array_keys($viewallgroupsusers)) . ')';
3630 $wherecond[] = "($grouptest)";
3633 // User exceptions
3634 if (!empty($exceptions)) {
3635 $exceptions = (array)$exceptions;
3636 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3637 $params = array_merge($params, $exparams);
3638 $wherecond[] = "u.id $exsql";
3641 // now add the needed and prohibited roles conditions as joins
3642 if (!empty($needed['any'])) {
3643 // simple case - there are no prohibits involved
3644 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3645 // everybody
3646 } else {
3647 $joins[] = "JOIN (SELECT DISTINCT userid
3648 FROM {role_assignments}
3649 WHERE contextid IN ($ctxids)
3650 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3651 ) ra ON ra.userid = u.id";
3653 } else {
3654 $unions = array();
3655 $everybody = false;
3656 foreach ($needed as $cap=>$unused) {
3657 if (empty($prohibited[$cap])) {
3658 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3659 $everybody = true;
3660 break;
3661 } else {
3662 $unions[] = "SELECT userid
3663 FROM {role_assignments}
3664 WHERE contextid IN ($ctxids)
3665 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3667 } else {
3668 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3669 // nobody can have this cap because it is prevented in default roles
3670 continue;
3672 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3673 // everybody except the prohibitted - hiding does not matter
3674 $unions[] = "SELECT id AS userid
3675 FROM {user}
3676 WHERE id NOT IN (SELECT userid
3677 FROM {role_assignments}
3678 WHERE contextid IN ($ctxids)
3679 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3681 } else {
3682 $unions[] = "SELECT userid
3683 FROM {role_assignments}
3684 WHERE contextid IN ($ctxids) AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3685 AND userid NOT IN (
3686 SELECT userid
3687 FROM {role_assignments}
3688 WHERE contextid IN ($ctxids)
3689 AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . ")
3694 if (!$everybody) {
3695 if ($unions) {
3696 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3697 } else {
3698 // only prohibits found - nobody can be matched
3699 $wherecond[] = "1 = 2";
3704 // Collect WHERE conditions and needed joins
3705 $where = implode(' AND ', $wherecond);
3706 if ($where !== '') {
3707 $where = 'WHERE ' . $where;
3709 $joins = implode("\n", $joins);
3711 // Ok, let's get the users!
3712 $sql = "SELECT $fields
3713 FROM {user} u
3714 $joins
3715 $where
3716 ORDER BY $sort";
3718 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3722 * Re-sort a users array based on a sorting policy
3724 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3725 * based on a sorting policy. This is to support the odd practice of
3726 * sorting teachers by 'authority', where authority was "lowest id of the role
3727 * assignment".
3729 * Will execute 1 database query. Only suitable for small numbers of users, as it
3730 * uses an u.id IN() clause.
3732 * Notes about the sorting criteria.
3734 * As a default, we cannot rely on role.sortorder because then
3735 * admins/coursecreators will always win. That is why the sane
3736 * rule "is locality matters most", with sortorder as 2nd
3737 * consideration.
3739 * If you want role.sortorder, use the 'sortorder' policy, and
3740 * name explicitly what roles you want to cover. It's probably
3741 * a good idea to see what roles have the capabilities you want
3742 * (array_diff() them against roiles that have 'can-do-anything'
3743 * to weed out admin-ish roles. Or fetch a list of roles from
3744 * variables like $CFG->coursecontact .
3746 * @param array $users Users array, keyed on userid
3747 * @param context $context
3748 * @param array $roles ids of the roles to include, optional
3749 * @param string $sortpolicy defaults to locality, more about
3750 * @return array sorted copy of the array
3752 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3753 global $DB;
3755 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3756 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3757 if (empty($roles)) {
3758 $roleswhere = '';
3759 } else {
3760 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3763 $sql = "SELECT ra.userid
3764 FROM {role_assignments} ra
3765 JOIN {role} r
3766 ON ra.roleid=r.id
3767 JOIN {context} ctx
3768 ON ra.contextid=ctx.id
3769 WHERE $userswhere
3770 $contextwhere
3771 $roleswhere";
3773 // Default 'locality' policy -- read PHPDoc notes
3774 // about sort policies...
3775 $orderby = 'ORDER BY '
3776 .'ctx.depth DESC, ' /* locality wins */
3777 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3778 .'ra.id'; /* role assignment order tie-breaker */
3779 if ($sortpolicy === 'sortorder') {
3780 $orderby = 'ORDER BY '
3781 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3782 .'ra.id'; /* role assignment order tie-breaker */
3785 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3786 $sortedusers = array();
3787 $seen = array();
3789 foreach ($sortedids as $id) {
3790 // Avoid duplicates
3791 if (isset($seen[$id])) {
3792 continue;
3794 $seen[$id] = true;
3796 // assign
3797 $sortedusers[$id] = $users[$id];
3799 return $sortedusers;
3803 * Gets all the users assigned this role in this context or higher
3805 * Note that moodle is based on capabilities and it is usually better
3806 * to check permissions than to check role ids as the capabilities
3807 * system is more flexible. If you really need, you can to use this
3808 * function but consider has_capability() as a possible substitute.
3810 * All $sort fields are added into $fields if not present there yet.
3812 * If $roleid is an array or is empty (all roles) you need to set $fields
3813 * (and $sort by extension) params according to it, as the first field
3814 * returned by the database should be unique (ra.id is the best candidate).
3816 * @param int $roleid (can also be an array of ints!)
3817 * @param context $context
3818 * @param bool $parent if true, get list of users assigned in higher context too
3819 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3820 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3821 * null => use default sort from users_order_by_sql.
3822 * @param bool $all true means all, false means limit to enrolled users
3823 * @param string $group defaults to ''
3824 * @param mixed $limitfrom defaults to ''
3825 * @param mixed $limitnum defaults to ''
3826 * @param string $extrawheretest defaults to ''
3827 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3828 * @return array
3830 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3831 $sort = null, $all = true, $group = '',
3832 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3833 global $DB;
3835 if (empty($fields)) {
3836 $allnames = get_all_user_name_fields(true, 'u');
3837 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
3838 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3839 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3840 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3841 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3844 // Prevent wrong function uses.
3845 if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
3846 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
3847 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
3849 if (!empty($roleid)) {
3850 // Solving partially the issue when specifying multiple roles.
3851 $users = array();
3852 foreach ($roleid as $id) {
3853 // Ignoring duplicated keys keeping the first user appearance.
3854 $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
3855 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
3857 return $users;
3861 $parentcontexts = '';
3862 if ($parent) {
3863 $parentcontexts = substr($context->path, 1); // kill leading slash
3864 $parentcontexts = str_replace('/', ',', $parentcontexts);
3865 if ($parentcontexts !== '') {
3866 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3870 if ($roleid) {
3871 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
3872 $roleselect = "AND ra.roleid $rids";
3873 } else {
3874 $params = array();
3875 $roleselect = '';
3878 if ($coursecontext = $context->get_course_context(false)) {
3879 $params['coursecontext'] = $coursecontext->id;
3880 } else {
3881 $params['coursecontext'] = 0;
3884 if ($group) {
3885 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3886 $groupselect = " AND gm.groupid = :groupid ";
3887 $params['groupid'] = $group;
3888 } else {
3889 $groupjoin = '';
3890 $groupselect = '';
3893 $params['contextid'] = $context->id;
3895 if ($extrawheretest) {
3896 $extrawheretest = ' AND ' . $extrawheretest;
3899 if ($whereorsortparams) {
3900 $params = array_merge($params, $whereorsortparams);
3903 if (!$sort) {
3904 list($sort, $sortparams) = users_order_by_sql('u');
3905 $params = array_merge($params, $sortparams);
3908 // Adding the fields from $sort that are not present in $fields.
3909 $sortarray = preg_split('/,\s*/', $sort);
3910 $fieldsarray = preg_split('/,\s*/', $fields);
3912 // Discarding aliases from the fields.
3913 $fieldnames = array();
3914 foreach ($fieldsarray as $key => $field) {
3915 list($fieldnames[$key]) = explode(' ', $field);
3918 $addedfields = array();
3919 foreach ($sortarray as $sortfield) {
3920 // Throw away any additional arguments to the sort (e.g. ASC/DESC).
3921 list($sortfield) = explode(' ', $sortfield);
3922 list($tableprefix) = explode('.', $sortfield);
3923 $fieldpresent = false;
3924 foreach ($fieldnames as $fieldname) {
3925 if ($fieldname === $sortfield || $fieldname === $tableprefix.'.*') {
3926 $fieldpresent = true;
3927 break;
3931 if (!$fieldpresent) {
3932 $fieldsarray[] = $sortfield;
3933 $addedfields[] = $sortfield;
3937 $fields = implode(', ', $fieldsarray);
3938 if (!empty($addedfields)) {
3939 $addedfields = implode(', ', $addedfields);
3940 debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
3943 if ($all === null) {
3944 // Previously null was used to indicate that parameter was not used.
3945 $all = true;
3947 if (!$all and $coursecontext) {
3948 // Do not use get_enrolled_sql() here for performance reasons.
3949 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
3950 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
3951 $params['ecourseid'] = $coursecontext->instanceid;
3952 } else {
3953 $ejoin = "";
3956 $sql = "SELECT DISTINCT $fields, ra.roleid
3957 FROM {role_assignments} ra
3958 JOIN {user} u ON u.id = ra.userid
3959 JOIN {role} r ON ra.roleid = r.id
3960 $ejoin
3961 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3962 $groupjoin
3963 WHERE (ra.contextid = :contextid $parentcontexts)
3964 $roleselect
3965 $groupselect
3966 $extrawheretest
3967 ORDER BY $sort"; // join now so that we can just use fullname() later
3969 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3973 * Counts all the users assigned this role in this context or higher
3975 * @param int|array $roleid either int or an array of ints
3976 * @param context $context
3977 * @param bool $parent if true, get list of users assigned in higher context too
3978 * @return int Returns the result count
3980 function count_role_users($roleid, context $context, $parent = false) {
3981 global $DB;
3983 if ($parent) {
3984 if ($contexts = $context->get_parent_context_ids()) {
3985 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3986 } else {
3987 $parentcontexts = '';
3989 } else {
3990 $parentcontexts = '';
3993 if ($roleid) {
3994 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3995 $roleselect = "AND r.roleid $rids";
3996 } else {
3997 $params = array();
3998 $roleselect = '';
4001 array_unshift($params, $context->id);
4003 $sql = "SELECT COUNT(DISTINCT u.id)
4004 FROM {role_assignments} r
4005 JOIN {user} u ON u.id = r.userid
4006 WHERE (r.contextid = ? $parentcontexts)
4007 $roleselect
4008 AND u.deleted = 0";
4010 return $DB->count_records_sql($sql, $params);
4014 * This function gets the list of courses that this user has a particular capability in.
4016 * It is now reasonably efficient, but bear in mind that if there are users who have the capability
4017 * everywhere, it may return an array of all courses.
4019 * @param string $capability Capability in question
4020 * @param int $userid User ID or null for current user
4021 * @param bool $doanything True if 'doanything' is permitted (default)
4022 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4023 * otherwise use a comma-separated list of the fields you require, not including id.
4024 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
4025 * @param string $orderby If set, use a comma-separated list of fields from course
4026 * table with sql modifiers (DESC) if needed
4027 * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
4028 * @return array|bool Array of courses, if none found false is returned.
4030 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '',
4031 $limit = 0) {
4032 global $DB, $USER;
4034 // Default to current user.
4035 if (!$userid) {
4036 $userid = $USER->id;
4039 if ($doanything && is_siteadmin($userid)) {
4040 // If the user is a site admin and $doanything is enabled then there is no need to restrict
4041 // the list of courses.
4042 $contextlimitsql = '';
4043 $contextlimitparams = [];
4044 } else {
4045 // Gets SQL to limit contexts ('x' table) to those where the user has this capability.
4046 list ($contextlimitsql, $contextlimitparams) = \core\access\get_user_capability_course_helper::get_sql(
4047 $userid, $capability);
4048 if (!$contextlimitsql) {
4049 // If the does not have this capability in any context, return false without querying.
4050 return false;
4053 $contextlimitsql = 'WHERE' . $contextlimitsql;
4056 // Convert fields list and ordering
4057 $fieldlist = '';
4058 if ($fieldsexceptid) {
4059 $fields = array_map('trim', explode(',', $fieldsexceptid));
4060 foreach($fields as $field) {
4061 // Context fields have a different alias.
4062 if (strpos($field, 'ctx') === 0) {
4063 switch($field) {
4064 case 'ctxlevel' :
4065 $realfield = 'contextlevel';
4066 break;
4067 case 'ctxinstance' :
4068 $realfield = 'instanceid';
4069 break;
4070 default:
4071 $realfield = substr($field, 3);
4072 break;
4074 $fieldlist .= ',x.' . $realfield . ' AS ' . $field;
4075 } else {
4076 $fieldlist .= ',c.'.$field;
4080 if ($orderby) {
4081 $fields = explode(',', $orderby);
4082 $orderby = '';
4083 foreach($fields as $field) {
4084 if ($orderby) {
4085 $orderby .= ',';
4087 $orderby .= 'c.'.$field;
4089 $orderby = 'ORDER BY '.$orderby;
4092 $courses = array();
4093 $rs = $DB->get_recordset_sql("
4094 SELECT c.id $fieldlist
4095 FROM {course} c
4096 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
4097 $contextlimitsql
4098 $orderby", array_merge([CONTEXT_COURSE], $contextlimitparams));
4099 foreach ($rs as $course) {
4100 $courses[] = $course;
4101 $limit--;
4102 if ($limit == 0) {
4103 break;
4106 $rs->close();
4107 return empty($courses) ? false : $courses;
4111 * Switches the current user to another role for the current session and only
4112 * in the given context.
4114 * The caller *must* check
4115 * - that this op is allowed
4116 * - that the requested role can be switched to in this context (use get_switchable_roles)
4117 * - that the requested role is NOT $CFG->defaultuserroleid
4119 * To "unswitch" pass 0 as the roleid.
4121 * This function *will* modify $USER->access - beware
4123 * @param integer $roleid the role to switch to.
4124 * @param context $context the context in which to perform the switch.
4125 * @return bool success or failure.
4127 function role_switch($roleid, context $context) {
4128 global $USER;
4130 // Add the ghost RA to $USER->access as $USER->access['rsw'][$path] = $roleid.
4131 // To un-switch just unset($USER->access['rsw'][$path]).
4133 // Note: it is not possible to switch to roles that do not have course:view
4135 if (!isset($USER->access)) {
4136 load_all_capabilities();
4139 // Add the switch RA
4140 if ($roleid == 0) {
4141 unset($USER->access['rsw'][$context->path]);
4142 return true;
4145 $USER->access['rsw'][$context->path] = $roleid;
4147 return true;
4151 * Checks if the user has switched roles within the given course.
4153 * Note: You can only switch roles within the course, hence it takes a course id
4154 * rather than a context. On that note Petr volunteered to implement this across
4155 * all other contexts, all requests for this should be forwarded to him ;)
4157 * @param int $courseid The id of the course to check
4158 * @return bool True if the user has switched roles within the course.
4160 function is_role_switched($courseid) {
4161 global $USER;
4162 $context = context_course::instance($courseid, MUST_EXIST);
4163 return (!empty($USER->access['rsw'][$context->path]));
4167 * Get any role that has an override on exact context
4169 * @param context $context The context to check
4170 * @return array An array of roles
4172 function get_roles_with_override_on_context(context $context) {
4173 global $DB;
4175 return $DB->get_records_sql("SELECT r.*
4176 FROM {role_capabilities} rc, {role} r
4177 WHERE rc.roleid = r.id AND rc.contextid = ?",
4178 array($context->id));
4182 * Get all capabilities for this role on this context (overrides)
4184 * @param stdClass $role
4185 * @param context $context
4186 * @return array
4188 function get_capabilities_from_role_on_context($role, context $context) {
4189 global $DB;
4191 return $DB->get_records_sql("SELECT *
4192 FROM {role_capabilities}
4193 WHERE contextid = ? AND roleid = ?",
4194 array($context->id, $role->id));
4198 * Find all user assignment of users for this role, on this context
4200 * @param stdClass $role
4201 * @param context $context
4202 * @return array
4204 function get_users_from_role_on_context($role, context $context) {
4205 global $DB;
4207 return $DB->get_records_sql("SELECT *
4208 FROM {role_assignments}
4209 WHERE contextid = ? AND roleid = ?",
4210 array($context->id, $role->id));
4214 * Simple function returning a boolean true if user has roles
4215 * in context or parent contexts, otherwise false.
4217 * @param int $userid
4218 * @param int $roleid
4219 * @param int $contextid empty means any context
4220 * @return bool
4222 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4223 global $DB;
4225 if ($contextid) {
4226 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4227 return false;
4229 $parents = $context->get_parent_context_ids(true);
4230 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4231 $params['userid'] = $userid;
4232 $params['roleid'] = $roleid;
4234 $sql = "SELECT COUNT(ra.id)
4235 FROM {role_assignments} ra
4236 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4238 $count = $DB->get_field_sql($sql, $params);
4239 return ($count > 0);
4241 } else {
4242 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4247 * Get localised role name or alias if exists and format the text.
4249 * @param stdClass $role role object
4250 * - optional 'coursealias' property should be included for performance reasons if course context used
4251 * - description property is not required here
4252 * @param context|bool $context empty means system context
4253 * @param int $rolenamedisplay type of role name
4254 * @return string localised role name or course role name alias
4256 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4257 global $DB;
4259 if ($rolenamedisplay == ROLENAME_SHORT) {
4260 return $role->shortname;
4263 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4264 $coursecontext = null;
4267 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4268 $role = clone($role); // Do not modify parameters.
4269 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4270 $role->coursealias = $r->name;
4271 } else {
4272 $role->coursealias = null;
4276 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4277 if ($coursecontext) {
4278 return $role->coursealias;
4279 } else {
4280 return null;
4284 if (trim($role->name) !== '') {
4285 // For filtering always use context where was the thing defined - system for roles here.
4286 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4288 } else {
4289 // Empty role->name means we want to see localised role name based on shortname,
4290 // only default roles are supposed to be localised.
4291 switch ($role->shortname) {
4292 case 'manager': $original = get_string('manager', 'role'); break;
4293 case 'coursecreator': $original = get_string('coursecreators'); break;
4294 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4295 case 'teacher': $original = get_string('noneditingteacher'); break;
4296 case 'student': $original = get_string('defaultcoursestudent'); break;
4297 case 'guest': $original = get_string('guest'); break;
4298 case 'user': $original = get_string('authenticateduser'); break;
4299 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4300 // We should not get here, the role UI should require the name for custom roles!
4301 default: $original = $role->shortname; break;
4305 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4306 return $original;
4309 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4310 return "$original ($role->shortname)";
4313 if ($rolenamedisplay == ROLENAME_ALIAS) {
4314 if ($coursecontext and trim($role->coursealias) !== '') {
4315 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4316 } else {
4317 return $original;
4321 if ($rolenamedisplay == ROLENAME_BOTH) {
4322 if ($coursecontext and trim($role->coursealias) !== '') {
4323 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4324 } else {
4325 return $original;
4329 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4333 * Returns localised role description if available.
4334 * If the name is empty it tries to find the default role name using
4335 * hardcoded list of default role names or other methods in the future.
4337 * @param stdClass $role
4338 * @return string localised role name
4340 function role_get_description(stdClass $role) {
4341 if (!html_is_blank($role->description)) {
4342 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4345 switch ($role->shortname) {
4346 case 'manager': return get_string('managerdescription', 'role');
4347 case 'coursecreator': return get_string('coursecreatorsdescription');
4348 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4349 case 'teacher': return get_string('noneditingteacherdescription');
4350 case 'student': return get_string('defaultcoursestudentdescription');
4351 case 'guest': return get_string('guestdescription');
4352 case 'user': return get_string('authenticateduserdescription');
4353 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4354 default: return '';
4359 * Get all the localised role names for a context.
4361 * In new installs default roles have empty names, this function
4362 * add localised role names using current language pack.
4364 * @param context $context the context, null means system context
4365 * @param array of role objects with a ->localname field containing the context-specific role name.
4366 * @param int $rolenamedisplay
4367 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4368 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4370 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4371 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4375 * Prepare list of roles for display, apply aliases and localise default role names.
4377 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4378 * @param context $context the context, null means system context
4379 * @param int $rolenamedisplay
4380 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4381 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4383 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4384 global $DB;
4386 if (empty($roleoptions)) {
4387 return array();
4390 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4391 $coursecontext = null;
4394 // We usually need all role columns...
4395 $first = reset($roleoptions);
4396 if ($returnmenu === null) {
4397 $returnmenu = !is_object($first);
4400 if (!is_object($first) or !property_exists($first, 'shortname')) {
4401 $allroles = get_all_roles($context);
4402 foreach ($roleoptions as $rid => $unused) {
4403 $roleoptions[$rid] = $allroles[$rid];
4407 // Inject coursealias if necessary.
4408 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4409 $first = reset($roleoptions);
4410 if (!property_exists($first, 'coursealias')) {
4411 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4412 foreach ($aliasnames as $alias) {
4413 if (isset($roleoptions[$alias->roleid])) {
4414 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4420 // Add localname property.
4421 foreach ($roleoptions as $rid => $role) {
4422 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4425 if (!$returnmenu) {
4426 return $roleoptions;
4429 $menu = array();
4430 foreach ($roleoptions as $rid => $role) {
4431 $menu[$rid] = $role->localname;
4434 return $menu;
4438 * Aids in detecting if a new line is required when reading a new capability
4440 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4441 * when we read in a new capability.
4442 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4443 * but when we are in grade, all reports/import/export capabilities should be together
4445 * @param string $cap component string a
4446 * @param string $comp component string b
4447 * @param int $contextlevel
4448 * @return bool whether 2 component are in different "sections"
4450 function component_level_changed($cap, $comp, $contextlevel) {
4452 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4453 $compsa = explode('/', $cap->component);
4454 $compsb = explode('/', $comp);
4456 // list of system reports
4457 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4458 return false;
4461 // we are in gradebook, still
4462 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4463 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4464 return false;
4467 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4468 return false;
4472 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4476 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4477 * and return an array of roleids in order.
4479 * @param array $allroles array of roles, as returned by get_all_roles();
4480 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4482 function fix_role_sortorder($allroles) {
4483 global $DB;
4485 $rolesort = array();
4486 $i = 0;
4487 foreach ($allroles as $role) {
4488 $rolesort[$i] = $role->id;
4489 if ($role->sortorder != $i) {
4490 $r = new stdClass();
4491 $r->id = $role->id;
4492 $r->sortorder = $i;
4493 $DB->update_record('role', $r);
4494 $allroles[$role->id]->sortorder = $i;
4496 $i++;
4498 return $rolesort;
4502 * Switch the sort order of two roles (used in admin/roles/manage.php).
4504 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4505 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4506 * @return boolean success or failure
4508 function switch_roles($first, $second) {
4509 global $DB;
4510 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4511 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4512 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4513 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4514 return $result;
4518 * Duplicates all the base definitions of a role
4520 * @param stdClass $sourcerole role to copy from
4521 * @param int $targetrole id of role to copy to
4523 function role_cap_duplicate($sourcerole, $targetrole) {
4524 global $DB;
4526 $systemcontext = context_system::instance();
4527 $caps = $DB->get_records_sql("SELECT *
4528 FROM {role_capabilities}
4529 WHERE roleid = ? AND contextid = ?",
4530 array($sourcerole->id, $systemcontext->id));
4531 // adding capabilities
4532 foreach ($caps as $cap) {
4533 unset($cap->id);
4534 $cap->roleid = $targetrole;
4535 $DB->insert_record('role_capabilities', $cap);
4538 // Reset any cache of this role, including MUC.
4539 accesslib_clear_role_cache($targetrole);
4543 * Returns two lists, this can be used to find out if user has capability.
4544 * Having any needed role and no forbidden role in this context means
4545 * user has this capability in this context.
4546 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4548 * @param stdClass $context
4549 * @param string $capability
4550 * @return array($neededroles, $forbiddenroles)
4552 function get_roles_with_cap_in_context($context, $capability) {
4553 global $DB;
4555 $ctxids = trim($context->path, '/'); // kill leading slash
4556 $ctxids = str_replace('/', ',', $ctxids);
4558 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4559 FROM {role_capabilities} rc
4560 JOIN {context} ctx ON ctx.id = rc.contextid
4561 JOIN {capabilities} cap ON rc.capability = cap.name
4562 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4563 ORDER BY rc.roleid ASC, ctx.depth DESC";
4564 $params = array('cap'=>$capability);
4566 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4567 // no cap definitions --> no capability
4568 return array(array(), array());
4571 $forbidden = array();
4572 $needed = array();
4573 foreach($capdefs as $def) {
4574 if (isset($forbidden[$def->roleid])) {
4575 continue;
4577 if ($def->permission == CAP_PROHIBIT) {
4578 $forbidden[$def->roleid] = $def->roleid;
4579 unset($needed[$def->roleid]);
4580 continue;
4582 if (!isset($needed[$def->roleid])) {
4583 if ($def->permission == CAP_ALLOW) {
4584 $needed[$def->roleid] = true;
4585 } else if ($def->permission == CAP_PREVENT) {
4586 $needed[$def->roleid] = false;
4590 unset($capdefs);
4592 // remove all those roles not allowing
4593 foreach($needed as $key=>$value) {
4594 if (!$value) {
4595 unset($needed[$key]);
4596 } else {
4597 $needed[$key] = $key;
4601 return array($needed, $forbidden);
4605 * Returns an array of role IDs that have ALL of the the supplied capabilities
4606 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4608 * @param stdClass $context
4609 * @param array $capabilities An array of capabilities
4610 * @return array of roles with all of the required capabilities
4612 function get_roles_with_caps_in_context($context, $capabilities) {
4613 $neededarr = array();
4614 $forbiddenarr = array();
4615 foreach($capabilities as $caprequired) {
4616 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4619 $rolesthatcanrate = array();
4620 if (!empty($neededarr)) {
4621 foreach ($neededarr as $needed) {
4622 if (empty($rolesthatcanrate)) {
4623 $rolesthatcanrate = $needed;
4624 } else {
4625 //only want roles that have all caps
4626 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4630 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4631 foreach ($forbiddenarr as $forbidden) {
4632 //remove any roles that are forbidden any of the caps
4633 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4636 return $rolesthatcanrate;
4640 * Returns an array of role names that have ALL of the the supplied capabilities
4641 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4643 * @param stdClass $context
4644 * @param array $capabilities An array of capabilities
4645 * @return array of roles with all of the required capabilities
4647 function get_role_names_with_caps_in_context($context, $capabilities) {
4648 global $DB;
4650 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4651 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4653 $roles = array();
4654 foreach ($rolesthatcanrate as $r) {
4655 $roles[$r] = $allroles[$r];
4658 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4662 * This function verifies the prohibit comes from this context
4663 * and there are no more prohibits in parent contexts.
4665 * @param int $roleid
4666 * @param context $context
4667 * @param string $capability name
4668 * @return bool
4670 function prohibit_is_removable($roleid, context $context, $capability) {
4671 global $DB;
4673 $ctxids = trim($context->path, '/'); // kill leading slash
4674 $ctxids = str_replace('/', ',', $ctxids);
4676 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4678 $sql = "SELECT ctx.id
4679 FROM {role_capabilities} rc
4680 JOIN {context} ctx ON ctx.id = rc.contextid
4681 JOIN {capabilities} cap ON rc.capability = cap.name
4682 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4683 ORDER BY ctx.depth DESC";
4685 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4686 // no prohibits == nothing to remove
4687 return true;
4690 if (count($prohibits) > 1) {
4691 // more prohibits can not be removed
4692 return false;
4695 return !empty($prohibits[$context->id]);
4699 * More user friendly role permission changing,
4700 * it should produce as few overrides as possible.
4702 * @param int $roleid
4703 * @param stdClass $context
4704 * @param string $capname capability name
4705 * @param int $permission
4706 * @return void
4708 function role_change_permission($roleid, $context, $capname, $permission) {
4709 global $DB;
4711 if ($permission == CAP_INHERIT) {
4712 unassign_capability($capname, $roleid, $context->id);
4713 return;
4716 $ctxids = trim($context->path, '/'); // kill leading slash
4717 $ctxids = str_replace('/', ',', $ctxids);
4719 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4721 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4722 FROM {role_capabilities} rc
4723 JOIN {context} ctx ON ctx.id = rc.contextid
4724 JOIN {capabilities} cap ON rc.capability = cap.name
4725 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4726 ORDER BY ctx.depth DESC";
4728 if ($existing = $DB->get_records_sql($sql, $params)) {
4729 foreach($existing as $e) {
4730 if ($e->permission == CAP_PROHIBIT) {
4731 // prohibit can not be overridden, no point in changing anything
4732 return;
4735 $lowest = array_shift($existing);
4736 if ($lowest->permission == $permission) {
4737 // permission already set in this context or parent - nothing to do
4738 return;
4740 if ($existing) {
4741 $parent = array_shift($existing);
4742 if ($parent->permission == $permission) {
4743 // permission already set in parent context or parent - just unset in this context
4744 // we do this because we want as few overrides as possible for performance reasons
4745 unassign_capability($capname, $roleid, $context->id);
4746 return;
4750 } else {
4751 if ($permission == CAP_PREVENT) {
4752 // nothing means role does not have permission
4753 return;
4757 // assign the needed capability
4758 assign_capability($capname, $permission, $roleid, $context->id, true);
4763 * Basic moodle context abstraction class.
4765 * Google confirms that no other important framework is using "context" class,
4766 * we could use something else like mcontext or moodle_context, but we need to type
4767 * this very often which would be annoying and it would take too much space...
4769 * This class is derived from stdClass for backwards compatibility with
4770 * odl $context record that was returned from DML $DB->get_record()
4772 * @package core_access
4773 * @category access
4774 * @copyright Petr Skoda {@link http://skodak.org}
4775 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4776 * @since Moodle 2.2
4778 * @property-read int $id context id
4779 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4780 * @property-read int $instanceid id of related instance in each context
4781 * @property-read string $path path to context, starts with system context
4782 * @property-read int $depth
4784 abstract class context extends stdClass implements IteratorAggregate {
4787 * The context id
4788 * Can be accessed publicly through $context->id
4789 * @var int
4791 protected $_id;
4794 * The context level
4795 * Can be accessed publicly through $context->contextlevel
4796 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4798 protected $_contextlevel;
4801 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4802 * Can be accessed publicly through $context->instanceid
4803 * @var int
4805 protected $_instanceid;
4808 * The path to the context always starting from the system context
4809 * Can be accessed publicly through $context->path
4810 * @var string
4812 protected $_path;
4815 * The depth of the context in relation to parent contexts
4816 * Can be accessed publicly through $context->depth
4817 * @var int
4819 protected $_depth;
4822 * Whether this context is locked or not.
4824 * Can be accessed publicly through $context->locked.
4826 * @var int
4828 protected $_locked;
4831 * @var array Context caching info
4833 private static $cache_contextsbyid = array();
4836 * @var array Context caching info
4838 private static $cache_contexts = array();
4841 * Context count
4842 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4843 * @var int
4845 protected static $cache_count = 0;
4848 * @var array Context caching info
4850 protected static $cache_preloaded = array();
4853 * @var context_system The system context once initialised
4855 protected static $systemcontext = null;
4858 * Resets the cache to remove all data.
4859 * @static
4861 protected static function reset_caches() {
4862 self::$cache_contextsbyid = array();
4863 self::$cache_contexts = array();
4864 self::$cache_count = 0;
4865 self::$cache_preloaded = array();
4867 self::$systemcontext = null;
4871 * Adds a context to the cache. If the cache is full, discards a batch of
4872 * older entries.
4874 * @static
4875 * @param context $context New context to add
4876 * @return void
4878 protected static function cache_add(context $context) {
4879 if (isset(self::$cache_contextsbyid[$context->id])) {
4880 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4881 return;
4884 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4885 $i = 0;
4886 foreach(self::$cache_contextsbyid as $ctx) {
4887 $i++;
4888 if ($i <= 100) {
4889 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4890 continue;
4892 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4893 // we remove oldest third of the contexts to make room for more contexts
4894 break;
4896 unset(self::$cache_contextsbyid[$ctx->id]);
4897 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4898 self::$cache_count--;
4902 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4903 self::$cache_contextsbyid[$context->id] = $context;
4904 self::$cache_count++;
4908 * Removes a context from the cache.
4910 * @static
4911 * @param context $context Context object to remove
4912 * @return void
4914 protected static function cache_remove(context $context) {
4915 if (!isset(self::$cache_contextsbyid[$context->id])) {
4916 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4917 return;
4919 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4920 unset(self::$cache_contextsbyid[$context->id]);
4922 self::$cache_count--;
4924 if (self::$cache_count < 0) {
4925 self::$cache_count = 0;
4930 * Gets a context from the cache.
4932 * @static
4933 * @param int $contextlevel Context level
4934 * @param int $instance Instance ID
4935 * @return context|bool Context or false if not in cache
4937 protected static function cache_get($contextlevel, $instance) {
4938 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4939 return self::$cache_contexts[$contextlevel][$instance];
4941 return false;
4945 * Gets a context from the cache based on its id.
4947 * @static
4948 * @param int $id Context ID
4949 * @return context|bool Context or false if not in cache
4951 protected static function cache_get_by_id($id) {
4952 if (isset(self::$cache_contextsbyid[$id])) {
4953 return self::$cache_contextsbyid[$id];
4955 return false;
4959 * Preloads context information from db record and strips the cached info.
4961 * @static
4962 * @param stdClass $rec
4963 * @return void (modifies $rec)
4965 protected static function preload_from_record(stdClass $rec) {
4966 $notenoughdata = false;
4967 $notenoughdata = $notenoughdata || empty($rec->ctxid);
4968 $notenoughdata = $notenoughdata || empty($rec->ctxlevel);
4969 $notenoughdata = $notenoughdata || !isset($rec->ctxinstance);
4970 $notenoughdata = $notenoughdata || empty($rec->ctxpath);
4971 $notenoughdata = $notenoughdata || empty($rec->ctxdepth);
4972 $notenoughdata = $notenoughdata || !isset($rec->ctxlocked);
4973 if ($notenoughdata) {
4974 // The record does not have enough data, passed here repeatedly or context does not exist yet.
4975 if (isset($rec->ctxid) && !isset($rec->ctxlocked)) {
4976 debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER);
4978 return;
4981 $record = (object) [
4982 'id' => $rec->ctxid,
4983 'contextlevel' => $rec->ctxlevel,
4984 'instanceid' => $rec->ctxinstance,
4985 'path' => $rec->ctxpath,
4986 'depth' => $rec->ctxdepth,
4987 'locked' => $rec->ctxlocked,
4990 unset($rec->ctxid);
4991 unset($rec->ctxlevel);
4992 unset($rec->ctxinstance);
4993 unset($rec->ctxpath);
4994 unset($rec->ctxdepth);
4995 unset($rec->ctxlocked);
4997 return context::create_instance_from_record($record);
5001 // ====== magic methods =======
5004 * Magic setter method, we do not want anybody to modify properties from the outside
5005 * @param string $name
5006 * @param mixed $value
5008 public function __set($name, $value) {
5009 debugging('Can not change context instance properties!');
5013 * Magic method getter, redirects to read only values.
5014 * @param string $name
5015 * @return mixed
5017 public function __get($name) {
5018 switch ($name) {
5019 case 'id':
5020 return $this->_id;
5021 case 'contextlevel':
5022 return $this->_contextlevel;
5023 case 'instanceid':
5024 return $this->_instanceid;
5025 case 'path':
5026 return $this->_path;
5027 case 'depth':
5028 return $this->_depth;
5029 case 'locked':
5030 return $this->is_locked();
5032 default:
5033 debugging('Invalid context property accessed! '.$name);
5034 return null;
5039 * Full support for isset on our magic read only properties.
5040 * @param string $name
5041 * @return bool
5043 public function __isset($name) {
5044 switch ($name) {
5045 case 'id':
5046 return isset($this->_id);
5047 case 'contextlevel':
5048 return isset($this->_contextlevel);
5049 case 'instanceid':
5050 return isset($this->_instanceid);
5051 case 'path':
5052 return isset($this->_path);
5053 case 'depth':
5054 return isset($this->_depth);
5055 case 'locked':
5056 // Locked is always set.
5057 return true;
5058 default:
5059 return false;
5064 * All properties are read only, sorry.
5065 * @param string $name
5067 public function __unset($name) {
5068 debugging('Can not unset context instance properties!');
5071 // ====== implementing method from interface IteratorAggregate ======
5074 * Create an iterator because magic vars can't be seen by 'foreach'.
5076 * Now we can convert context object to array using convert_to_array(),
5077 * and feed it properly to json_encode().
5079 public function getIterator() {
5080 $ret = array(
5081 'id' => $this->id,
5082 'contextlevel' => $this->contextlevel,
5083 'instanceid' => $this->instanceid,
5084 'path' => $this->path,
5085 'depth' => $this->depth,
5086 'locked' => $this->locked,
5088 return new ArrayIterator($ret);
5091 // ====== general context methods ======
5094 * Constructor is protected so that devs are forced to
5095 * use context_xxx::instance() or context::instance_by_id().
5097 * @param stdClass $record
5099 protected function __construct(stdClass $record) {
5100 $this->_id = (int)$record->id;
5101 $this->_contextlevel = (int)$record->contextlevel;
5102 $this->_instanceid = $record->instanceid;
5103 $this->_path = $record->path;
5104 $this->_depth = $record->depth;
5106 if (isset($record->locked)) {
5107 $this->_locked = $record->locked;
5108 } else if (!during_initial_install() && !moodle_needs_upgrading()) {
5109 debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER);
5114 * This function is also used to work around 'protected' keyword problems in context_helper.
5115 * @static
5116 * @param stdClass $record
5117 * @return context instance
5119 protected static function create_instance_from_record(stdClass $record) {
5120 $classname = context_helper::get_class_for_level($record->contextlevel);
5122 if ($context = context::cache_get_by_id($record->id)) {
5123 return $context;
5126 $context = new $classname($record);
5127 context::cache_add($context);
5129 return $context;
5133 * Copy prepared new contexts from temp table to context table,
5134 * we do this in db specific way for perf reasons only.
5135 * @static
5137 protected static function merge_context_temp_table() {
5138 global $DB;
5140 /* MDL-11347:
5141 * - mysql does not allow to use FROM in UPDATE statements
5142 * - using two tables after UPDATE works in mysql, but might give unexpected
5143 * results in pg 8 (depends on configuration)
5144 * - using table alias in UPDATE does not work in pg < 8.2
5146 * Different code for each database - mostly for performance reasons
5149 $dbfamily = $DB->get_dbfamily();
5150 if ($dbfamily == 'mysql') {
5151 $updatesql = "UPDATE {context} ct, {context_temp} temp
5152 SET ct.path = temp.path,
5153 ct.depth = temp.depth,
5154 ct.locked = temp.locked
5155 WHERE ct.id = temp.id";
5156 } else if ($dbfamily == 'oracle') {
5157 $updatesql = "UPDATE {context} ct
5158 SET (ct.path, ct.depth, ct.locked) =
5159 (SELECT temp.path, temp.depth, temp.locked
5160 FROM {context_temp} temp
5161 WHERE temp.id=ct.id)
5162 WHERE EXISTS (SELECT 'x'
5163 FROM {context_temp} temp
5164 WHERE temp.id = ct.id)";
5165 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5166 $updatesql = "UPDATE {context}
5167 SET path = temp.path,
5168 depth = temp.depth,
5169 locked = temp.locked
5170 FROM {context_temp} temp
5171 WHERE temp.id={context}.id";
5172 } else {
5173 // sqlite and others
5174 $updatesql = "UPDATE {context}
5175 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5176 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id),
5177 locked = (SELECT locked FROM {context_temp} WHERE id = {context}.id)
5178 WHERE id IN (SELECT id FROM {context_temp})";
5181 $DB->execute($updatesql);
5185 * Get a context instance as an object, from a given context id.
5187 * @static
5188 * @param int $id context id
5189 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5190 * MUST_EXIST means throw exception if no record found
5191 * @return context|bool the context object or false if not found
5193 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5194 global $DB;
5196 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5197 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5198 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5201 if ($id == SYSCONTEXTID) {
5202 return context_system::instance(0, $strictness);
5205 if (is_array($id) or is_object($id) or empty($id)) {
5206 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5209 if ($context = context::cache_get_by_id($id)) {
5210 return $context;
5213 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5214 return context::create_instance_from_record($record);
5217 return false;
5221 * Update context info after moving context in the tree structure.
5223 * @param context $newparent
5224 * @return void
5226 public function update_moved(context $newparent) {
5227 global $DB;
5229 $frompath = $this->_path;
5230 $newpath = $newparent->path . '/' . $this->_id;
5232 $trans = $DB->start_delegated_transaction();
5234 $setdepth = '';
5235 if (($newparent->depth +1) != $this->_depth) {
5236 $diff = $newparent->depth - $this->_depth + 1;
5237 $setdepth = ", depth = depth + $diff";
5239 $sql = "UPDATE {context}
5240 SET path = ?
5241 $setdepth
5242 WHERE id = ?";
5243 $params = array($newpath, $this->_id);
5244 $DB->execute($sql, $params);
5246 $this->_path = $newpath;
5247 $this->_depth = $newparent->depth + 1;
5249 $sql = "UPDATE {context}
5250 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5251 $setdepth
5252 WHERE path LIKE ?";
5253 $params = array($newpath, "{$frompath}/%");
5254 $DB->execute($sql, $params);
5256 $this->mark_dirty();
5258 context::reset_caches();
5260 $trans->allow_commit();
5264 * Set whether this context has been locked or not.
5266 * @param bool $locked
5267 * @return $this
5269 public function set_locked(bool $locked) {
5270 global $DB;
5272 if ($this->_locked == $locked) {
5273 return $this;
5276 $this->_locked = $locked;
5277 $DB->set_field('context', 'locked', (int) $locked, ['id' => $this->id]);
5278 $this->mark_dirty();
5280 if ($locked) {
5281 $eventname = '\\core\\event\\context_locked';
5282 } else {
5283 $eventname = '\\core\\event\\context_unlocked';
5285 $event = $eventname::create(['context' => $this, 'objectid' => $this->id]);
5286 $event->trigger();
5288 self::reset_caches();
5290 return $this;
5294 * Remove all context path info and optionally rebuild it.
5296 * @param bool $rebuild
5297 * @return void
5299 public function reset_paths($rebuild = true) {
5300 global $DB;
5302 if ($this->_path) {
5303 $this->mark_dirty();
5305 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5306 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5307 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5308 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5309 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5310 $this->_depth = 0;
5311 $this->_path = null;
5314 if ($rebuild) {
5315 context_helper::build_all_paths(false);
5318 context::reset_caches();
5322 * Delete all data linked to content, do not delete the context record itself
5324 public function delete_content() {
5325 global $CFG, $DB;
5327 blocks_delete_all_for_context($this->_id);
5328 filter_delete_all_for_context($this->_id);
5330 require_once($CFG->dirroot . '/comment/lib.php');
5331 comment::delete_comments(array('contextid'=>$this->_id));
5333 require_once($CFG->dirroot.'/rating/lib.php');
5334 $delopt = new stdclass();
5335 $delopt->contextid = $this->_id;
5336 $rm = new rating_manager();
5337 $rm->delete_ratings($delopt);
5339 // delete all files attached to this context
5340 $fs = get_file_storage();
5341 $fs->delete_area_files($this->_id);
5343 // Delete all repository instances attached to this context.
5344 require_once($CFG->dirroot . '/repository/lib.php');
5345 repository::delete_all_for_context($this->_id);
5347 // delete all advanced grading data attached to this context
5348 require_once($CFG->dirroot.'/grade/grading/lib.php');
5349 grading_manager::delete_all_for_context($this->_id);
5351 // now delete stuff from role related tables, role_unassign_all
5352 // and unenrol should be called earlier to do proper cleanup
5353 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5354 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5355 $this->delete_capabilities();
5359 * Unassign all capabilities from a context.
5361 public function delete_capabilities() {
5362 global $DB;
5364 $ids = $DB->get_fieldset_select('role_capabilities', 'DISTINCT roleid', 'contextid = ?', array($this->_id));
5365 if ($ids) {
5366 $DB->delete_records('role_capabilities', array('contextid' => $this->_id));
5368 // Reset any cache of these roles, including MUC.
5369 accesslib_clear_role_cache($ids);
5374 * Delete the context content and the context record itself
5376 public function delete() {
5377 global $DB;
5379 if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5380 throw new coding_exception('Cannot delete system context');
5383 // double check the context still exists
5384 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5385 context::cache_remove($this);
5386 return;
5389 $this->delete_content();
5390 $DB->delete_records('context', array('id'=>$this->_id));
5391 // purge static context cache if entry present
5392 context::cache_remove($this);
5394 // Inform search engine to delete data related to this context.
5395 \core_search\manager::context_deleted($this);
5398 // ====== context level related methods ======
5401 * Utility method for context creation
5403 * @static
5404 * @param int $contextlevel
5405 * @param int $instanceid
5406 * @param string $parentpath
5407 * @return stdClass context record
5409 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5410 global $DB;
5412 $record = new stdClass();
5413 $record->contextlevel = $contextlevel;
5414 $record->instanceid = $instanceid;
5415 $record->depth = 0;
5416 $record->path = null; //not known before insert
5417 $record->locked = 0;
5419 $record->id = $DB->insert_record('context', $record);
5421 // now add path if known - it can be added later
5422 if (!is_null($parentpath)) {
5423 $record->path = $parentpath.'/'.$record->id;
5424 $record->depth = substr_count($record->path, '/');
5425 $DB->update_record('context', $record);
5428 return $record;
5432 * Returns human readable context identifier.
5434 * @param boolean $withprefix whether to prefix the name of the context with the
5435 * type of context, e.g. User, Course, Forum, etc.
5436 * @param boolean $short whether to use the short name of the thing. Only applies
5437 * to course contexts
5438 * @return string the human readable context name.
5440 public function get_context_name($withprefix = true, $short = false) {
5441 // must be implemented in all context levels
5442 throw new coding_exception('can not get name of abstract context');
5446 * Whether the current context is locked.
5448 * @return bool
5450 public function is_locked() {
5451 if ($this->_locked) {
5452 return true;
5455 if ($parent = $this->get_parent_context()) {
5456 return $parent->is_locked();
5459 return false;
5463 * Returns the most relevant URL for this context.
5465 * @return moodle_url
5467 public abstract function get_url();
5470 * Returns array of relevant context capability records.
5472 * @return array
5474 public abstract function get_capabilities();
5477 * Recursive function which, given a context, find all its children context ids.
5479 * For course category contexts it will return immediate children and all subcategory contexts.
5480 * It will NOT recurse into courses or subcategories categories.
5481 * If you want to do that, call it on the returned courses/categories.
5483 * When called for a course context, it will return the modules and blocks
5484 * displayed in the course page and blocks displayed on the module pages.
5486 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5487 * contexts ;-)
5489 * @return array Array of child records
5491 public function get_child_contexts() {
5492 global $DB;
5494 if (empty($this->_path) or empty($this->_depth)) {
5495 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5496 return array();
5499 $sql = "SELECT ctx.*
5500 FROM {context} ctx
5501 WHERE ctx.path LIKE ?";
5502 $params = array($this->_path.'/%');
5503 $records = $DB->get_records_sql($sql, $params);
5505 $result = array();
5506 foreach ($records as $record) {
5507 $result[$record->id] = context::create_instance_from_record($record);
5510 return $result;
5514 * Returns parent contexts of this context in reversed order, i.e. parent first,
5515 * then grand parent, etc.
5517 * @param bool $includeself true means include self too
5518 * @return array of context instances
5520 public function get_parent_contexts($includeself = false) {
5521 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5522 return array();
5525 // Preload the contexts to reduce DB calls.
5526 context_helper::preload_contexts_by_id($contextids);
5528 $result = array();
5529 foreach ($contextids as $contextid) {
5530 $parent = context::instance_by_id($contextid, MUST_EXIST);
5531 $result[$parent->id] = $parent;
5534 return $result;
5538 * Returns parent context ids of this context in reversed order, i.e. parent first,
5539 * then grand parent, etc.
5541 * @param bool $includeself true means include self too
5542 * @return array of context ids
5544 public function get_parent_context_ids($includeself = false) {
5545 if (empty($this->_path)) {
5546 return array();
5549 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5550 $parentcontexts = explode('/', $parentcontexts);
5551 if (!$includeself) {
5552 array_pop($parentcontexts); // and remove its own id
5555 return array_reverse($parentcontexts);
5559 * Returns parent context paths of this context.
5561 * @param bool $includeself true means include self too
5562 * @return array of context paths
5564 public function get_parent_context_paths($includeself = false) {
5565 if (empty($this->_path)) {
5566 return array();
5569 $contextids = explode('/', $this->_path);
5571 $path = '';
5572 $paths = array();
5573 foreach ($contextids as $contextid) {
5574 if ($contextid) {
5575 $path .= '/' . $contextid;
5576 $paths[$contextid] = $path;
5580 if (!$includeself) {
5581 unset($paths[$this->_id]);
5584 return $paths;
5588 * Returns parent context
5590 * @return context
5592 public function get_parent_context() {
5593 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5594 return false;
5597 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5598 $parentcontexts = explode('/', $parentcontexts);
5599 array_pop($parentcontexts); // self
5600 $contextid = array_pop($parentcontexts); // immediate parent
5602 return context::instance_by_id($contextid, MUST_EXIST);
5606 * Is this context part of any course? If yes return course context.
5608 * @param bool $strict true means throw exception if not found, false means return false if not found
5609 * @return context_course context of the enclosing course, null if not found or exception
5611 public function get_course_context($strict = true) {
5612 if ($strict) {
5613 throw new coding_exception('Context does not belong to any course.');
5614 } else {
5615 return false;
5620 * Returns sql necessary for purging of stale context instances.
5622 * @static
5623 * @return string cleanup SQL
5625 protected static function get_cleanup_sql() {
5626 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5630 * Rebuild context paths and depths at context level.
5632 * @static
5633 * @param bool $force
5634 * @return void
5636 protected static function build_paths($force) {
5637 throw new coding_exception('build_paths() method must be implemented in all context levels');
5641 * Create missing context instances at given level
5643 * @static
5644 * @return void
5646 protected static function create_level_instances() {
5647 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5651 * Reset all cached permissions and definitions if the necessary.
5652 * @return void
5654 public function reload_if_dirty() {
5655 global $ACCESSLIB_PRIVATE, $USER;
5657 // Load dirty contexts list if needed
5658 if (CLI_SCRIPT) {
5659 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5660 // we do not load dirty flags in CLI and cron
5661 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5663 } else {
5664 if (!isset($USER->access['time'])) {
5665 // Nothing has been loaded yet, so we do not need to check dirty flags now.
5666 return;
5669 // From skodak: No idea why -2 is there, server cluster time difference maybe...
5670 $changedsince = $USER->access['time'] - 2;
5672 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5673 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $changedsince);
5676 if (!isset($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
5677 $ACCESSLIB_PRIVATE->dirtyusers[$USER->id] = get_cache_flag('accesslib/dirtyusers', $USER->id, $changedsince);
5681 $dirty = false;
5683 if (!empty($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
5684 $dirty = true;
5685 } else if (!empty($ACCESSLIB_PRIVATE->dirtycontexts)) {
5686 $paths = $this->get_parent_context_paths(true);
5688 foreach ($paths as $path) {
5689 if (isset($ACCESSLIB_PRIVATE->dirtycontexts[$path])) {
5690 $dirty = true;
5691 break;
5696 if ($dirty) {
5697 // Reload all capabilities of USER and others - preserving loginas, roleswitches, etc.
5698 // Then cleanup any marks of dirtyness... at least from our short term memory!
5699 reload_all_capabilities();
5704 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5706 public function mark_dirty() {
5707 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5709 if (during_initial_install()) {
5710 return;
5713 // only if it is a non-empty string
5714 if (is_string($this->_path) && $this->_path !== '') {
5715 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5716 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5717 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5718 } else {
5719 if (CLI_SCRIPT) {
5720 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5721 } else {
5722 if (isset($USER->access['time'])) {
5723 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5724 } else {
5725 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5727 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5736 * Context maintenance and helper methods.
5738 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5739 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5740 * level implementation from the rest of code, the code completion returns what developers need.
5742 * Thank you Tim Hunt for helping me with this nasty trick.
5744 * @package core_access
5745 * @category access
5746 * @copyright Petr Skoda {@link http://skodak.org}
5747 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5748 * @since Moodle 2.2
5750 class context_helper extends context {
5753 * @var array An array mapping context levels to classes
5755 private static $alllevels;
5758 * Instance does not make sense here, only static use
5760 protected function __construct() {
5764 * Reset internal context levels array.
5766 public static function reset_levels() {
5767 self::$alllevels = null;
5771 * Initialise context levels, call before using self::$alllevels.
5773 private static function init_levels() {
5774 global $CFG;
5776 if (isset(self::$alllevels)) {
5777 return;
5779 self::$alllevels = array(
5780 CONTEXT_SYSTEM => 'context_system',
5781 CONTEXT_USER => 'context_user',
5782 CONTEXT_COURSECAT => 'context_coursecat',
5783 CONTEXT_COURSE => 'context_course',
5784 CONTEXT_MODULE => 'context_module',
5785 CONTEXT_BLOCK => 'context_block',
5788 if (empty($CFG->custom_context_classes)) {
5789 return;
5792 $levels = $CFG->custom_context_classes;
5793 if (!is_array($levels)) {
5794 $levels = @unserialize($levels);
5796 if (!is_array($levels)) {
5797 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
5798 return;
5801 // Unsupported custom levels, use with care!!!
5802 foreach ($levels as $level => $classname) {
5803 self::$alllevels[$level] = $classname;
5805 ksort(self::$alllevels);
5809 * Returns a class name of the context level class
5811 * @static
5812 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5813 * @return string class name of the context class
5815 public static function get_class_for_level($contextlevel) {
5816 self::init_levels();
5817 if (isset(self::$alllevels[$contextlevel])) {
5818 return self::$alllevels[$contextlevel];
5819 } else {
5820 throw new coding_exception('Invalid context level specified');
5825 * Returns a list of all context levels
5827 * @static
5828 * @return array int=>string (level=>level class name)
5830 public static function get_all_levels() {
5831 self::init_levels();
5832 return self::$alllevels;
5836 * Remove stale contexts that belonged to deleted instances.
5837 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5839 * @static
5840 * @return void
5842 public static function cleanup_instances() {
5843 global $DB;
5844 self::init_levels();
5846 $sqls = array();
5847 foreach (self::$alllevels as $level=>$classname) {
5848 $sqls[] = $classname::get_cleanup_sql();
5851 $sql = implode(" UNION ", $sqls);
5853 // it is probably better to use transactions, it might be faster too
5854 $transaction = $DB->start_delegated_transaction();
5856 $rs = $DB->get_recordset_sql($sql);
5857 foreach ($rs as $record) {
5858 $context = context::create_instance_from_record($record);
5859 $context->delete();
5861 $rs->close();
5863 $transaction->allow_commit();
5867 * Create all context instances at the given level and above.
5869 * @static
5870 * @param int $contextlevel null means all levels
5871 * @param bool $buildpaths
5872 * @return void
5874 public static function create_instances($contextlevel = null, $buildpaths = true) {
5875 self::init_levels();
5876 foreach (self::$alllevels as $level=>$classname) {
5877 if ($contextlevel and $level > $contextlevel) {
5878 // skip potential sub-contexts
5879 continue;
5881 $classname::create_level_instances();
5882 if ($buildpaths) {
5883 $classname::build_paths(false);
5889 * Rebuild paths and depths in all context levels.
5891 * @static
5892 * @param bool $force false means add missing only
5893 * @return void
5895 public static function build_all_paths($force = false) {
5896 self::init_levels();
5897 foreach (self::$alllevels as $classname) {
5898 $classname::build_paths($force);
5901 // reset static course cache - it might have incorrect cached data
5902 accesslib_clear_all_caches(true);
5906 * Resets the cache to remove all data.
5907 * @static
5909 public static function reset_caches() {
5910 context::reset_caches();
5914 * Returns all fields necessary for context preloading from user $rec.
5916 * This helps with performance when dealing with hundreds of contexts.
5918 * @static
5919 * @param string $tablealias context table alias in the query
5920 * @return array (table.column=>alias, ...)
5922 public static function get_preload_record_columns($tablealias) {
5923 return [
5924 "$tablealias.id" => "ctxid",
5925 "$tablealias.path" => "ctxpath",
5926 "$tablealias.depth" => "ctxdepth",
5927 "$tablealias.contextlevel" => "ctxlevel",
5928 "$tablealias.instanceid" => "ctxinstance",
5929 "$tablealias.locked" => "ctxlocked",
5934 * Returns all fields necessary for context preloading from user $rec.
5936 * This helps with performance when dealing with hundreds of contexts.
5938 * @static
5939 * @param string $tablealias context table alias in the query
5940 * @return string
5942 public static function get_preload_record_columns_sql($tablealias) {
5943 return "$tablealias.id AS ctxid, " .
5944 "$tablealias.path AS ctxpath, " .
5945 "$tablealias.depth AS ctxdepth, " .
5946 "$tablealias.contextlevel AS ctxlevel, " .
5947 "$tablealias.instanceid AS ctxinstance, " .
5948 "$tablealias.locked AS ctxlocked";
5952 * Preloads context information from db record and strips the cached info.
5954 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5956 * @static
5957 * @param stdClass $rec
5958 * @return void (modifies $rec)
5960 public static function preload_from_record(stdClass $rec) {
5961 context::preload_from_record($rec);
5965 * Preload a set of contexts using their contextid.
5967 * @param array $contextids
5969 public static function preload_contexts_by_id(array $contextids) {
5970 global $DB;
5972 // Determine which contexts are not already cached.
5973 $tofetch = [];
5974 foreach ($contextids as $contextid) {
5975 if (!self::cache_get_by_id($contextid)) {
5976 $tofetch[] = $contextid;
5980 if (count($tofetch) > 1) {
5981 // There are at least two to fetch.
5982 // There is no point only fetching a single context as this would be no more efficient than calling the existing code.
5983 list($insql, $inparams) = $DB->get_in_or_equal($tofetch, SQL_PARAMS_NAMED);
5984 $ctxs = $DB->get_records_select('context', "id {$insql}", $inparams, '',
5985 \context_helper::get_preload_record_columns_sql('{context}'));
5986 foreach ($ctxs as $ctx) {
5987 self::preload_from_record($ctx);
5993 * Preload all contexts instances from course.
5995 * To be used if you expect multiple queries for course activities...
5997 * @static
5998 * @param int $courseid
6000 public static function preload_course($courseid) {
6001 // Users can call this multiple times without doing any harm
6002 if (isset(context::$cache_preloaded[$courseid])) {
6003 return;
6005 $coursecontext = context_course::instance($courseid);
6006 $coursecontext->get_child_contexts();
6008 context::$cache_preloaded[$courseid] = true;
6012 * Delete context instance
6014 * @static
6015 * @param int $contextlevel
6016 * @param int $instanceid
6017 * @return void
6019 public static function delete_instance($contextlevel, $instanceid) {
6020 global $DB;
6022 // double check the context still exists
6023 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
6024 $context = context::create_instance_from_record($record);
6025 $context->delete();
6026 } else {
6027 // we should try to purge the cache anyway
6032 * Returns the name of specified context level
6034 * @static
6035 * @param int $contextlevel
6036 * @return string name of the context level
6038 public static function get_level_name($contextlevel) {
6039 $classname = context_helper::get_class_for_level($contextlevel);
6040 return $classname::get_level_name();
6044 * not used
6046 public function get_url() {
6050 * not used
6052 public function get_capabilities() {
6058 * System context class
6060 * @package core_access
6061 * @category access
6062 * @copyright Petr Skoda {@link http://skodak.org}
6063 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6064 * @since Moodle 2.2
6066 class context_system extends context {
6068 * Please use context_system::instance() if you need the instance of context.
6070 * @param stdClass $record
6072 protected function __construct(stdClass $record) {
6073 parent::__construct($record);
6074 if ($record->contextlevel != CONTEXT_SYSTEM) {
6075 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
6080 * Returns human readable context level name.
6082 * @static
6083 * @return string the human readable context level name.
6085 public static function get_level_name() {
6086 return get_string('coresystem');
6090 * Returns human readable context identifier.
6092 * @param boolean $withprefix does not apply to system context
6093 * @param boolean $short does not apply to system context
6094 * @return string the human readable context name.
6096 public function get_context_name($withprefix = true, $short = false) {
6097 return self::get_level_name();
6101 * Returns the most relevant URL for this context.
6103 * @return moodle_url
6105 public function get_url() {
6106 return new moodle_url('/');
6110 * Returns array of relevant context capability records.
6112 * @return array
6114 public function get_capabilities() {
6115 global $DB;
6117 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6119 $params = array();
6120 $sql = "SELECT *
6121 FROM {capabilities}";
6123 return $DB->get_records_sql($sql.' '.$sort, $params);
6127 * Create missing context instances at system context
6128 * @static
6130 protected static function create_level_instances() {
6131 // nothing to do here, the system context is created automatically in installer
6132 self::instance(0);
6136 * Returns system context instance.
6138 * @static
6139 * @param int $instanceid should be 0
6140 * @param int $strictness
6141 * @param bool $cache
6142 * @return context_system context instance
6144 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
6145 global $DB;
6147 if ($instanceid != 0) {
6148 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
6151 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
6152 if (!isset(context::$systemcontext)) {
6153 $record = new stdClass();
6154 $record->id = SYSCONTEXTID;
6155 $record->contextlevel = CONTEXT_SYSTEM;
6156 $record->instanceid = 0;
6157 $record->path = '/'.SYSCONTEXTID;
6158 $record->depth = 1;
6159 $record->locked = 0;
6160 context::$systemcontext = new context_system($record);
6162 return context::$systemcontext;
6165 try {
6166 // We ignore the strictness completely because system context must exist except during install.
6167 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6168 } catch (dml_exception $e) {
6169 //table or record does not exist
6170 if (!during_initial_install()) {
6171 // do not mess with system context after install, it simply must exist
6172 throw $e;
6174 $record = null;
6177 if (!$record) {
6178 $record = new stdClass();
6179 $record->contextlevel = CONTEXT_SYSTEM;
6180 $record->instanceid = 0;
6181 $record->depth = 1;
6182 $record->path = null; // Not known before insert.
6183 $record->locked = 0;
6185 try {
6186 if ($DB->count_records('context')) {
6187 // contexts already exist, this is very weird, system must be first!!!
6188 return null;
6190 if (defined('SYSCONTEXTID')) {
6191 // this would happen only in unittest on sites that went through weird 1.7 upgrade
6192 $record->id = SYSCONTEXTID;
6193 $DB->import_record('context', $record);
6194 $DB->get_manager()->reset_sequence('context');
6195 } else {
6196 $record->id = $DB->insert_record('context', $record);
6198 } catch (dml_exception $e) {
6199 // can not create context - table does not exist yet, sorry
6200 return null;
6204 if ($record->instanceid != 0) {
6205 // this is very weird, somebody must be messing with context table
6206 debugging('Invalid system context detected');
6209 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6210 // fix path if necessary, initial install or path reset
6211 $record->depth = 1;
6212 $record->path = '/'.$record->id;
6213 $DB->update_record('context', $record);
6216 if (empty($record->locked)) {
6217 $record->locked = 0;
6220 if (!defined('SYSCONTEXTID')) {
6221 define('SYSCONTEXTID', $record->id);
6224 context::$systemcontext = new context_system($record);
6225 return context::$systemcontext;
6229 * Returns all site contexts except the system context, DO NOT call on production servers!!
6231 * Contexts are not cached.
6233 * @return array
6235 public function get_child_contexts() {
6236 global $DB;
6238 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6240 // Just get all the contexts except for CONTEXT_SYSTEM level
6241 // and hope we don't OOM in the process - don't cache
6242 $sql = "SELECT c.*
6243 FROM {context} c
6244 WHERE contextlevel > ".CONTEXT_SYSTEM;
6245 $records = $DB->get_records_sql($sql);
6247 $result = array();
6248 foreach ($records as $record) {
6249 $result[$record->id] = context::create_instance_from_record($record);
6252 return $result;
6256 * Returns sql necessary for purging of stale context instances.
6258 * @static
6259 * @return string cleanup SQL
6261 protected static function get_cleanup_sql() {
6262 $sql = "
6263 SELECT c.*
6264 FROM {context} c
6265 WHERE 1=2
6268 return $sql;
6272 * Rebuild context paths and depths at system context level.
6274 * @static
6275 * @param bool $force
6277 protected static function build_paths($force) {
6278 global $DB;
6280 /* note: ignore $force here, we always do full test of system context */
6282 // exactly one record must exist
6283 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6285 if ($record->instanceid != 0) {
6286 debugging('Invalid system context detected');
6289 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6290 debugging('Invalid SYSCONTEXTID detected');
6293 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6294 // fix path if necessary, initial install or path reset
6295 $record->depth = 1;
6296 $record->path = '/'.$record->id;
6297 $DB->update_record('context', $record);
6302 * Set whether this context has been locked or not.
6304 * @param bool $locked
6305 * @return $this
6307 public function set_locked(bool $locked) {
6308 throw new \coding_exception('It is not possible to lock the system context');
6310 return $this;
6316 * User context class
6318 * @package core_access
6319 * @category access
6320 * @copyright Petr Skoda {@link http://skodak.org}
6321 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6322 * @since Moodle 2.2
6324 class context_user extends context {
6326 * Please use context_user::instance($userid) if you need the instance of context.
6327 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6329 * @param stdClass $record
6331 protected function __construct(stdClass $record) {
6332 parent::__construct($record);
6333 if ($record->contextlevel != CONTEXT_USER) {
6334 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6339 * Returns human readable context level name.
6341 * @static
6342 * @return string the human readable context level name.
6344 public static function get_level_name() {
6345 return get_string('user');
6349 * Returns human readable context identifier.
6351 * @param boolean $withprefix whether to prefix the name of the context with User
6352 * @param boolean $short does not apply to user context
6353 * @return string the human readable context name.
6355 public function get_context_name($withprefix = true, $short = false) {
6356 global $DB;
6358 $name = '';
6359 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6360 if ($withprefix){
6361 $name = get_string('user').': ';
6363 $name .= fullname($user);
6365 return $name;
6369 * Returns the most relevant URL for this context.
6371 * @return moodle_url
6373 public function get_url() {
6374 global $COURSE;
6376 if ($COURSE->id == SITEID) {
6377 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6378 } else {
6379 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6381 return $url;
6385 * Returns array of relevant context capability records.
6387 * @return array
6389 public function get_capabilities() {
6390 global $DB;
6392 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6394 $extracaps = array('moodle/grade:viewall');
6395 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6396 $sql = "SELECT *
6397 FROM {capabilities}
6398 WHERE contextlevel = ".CONTEXT_USER."
6399 OR name $extra";
6401 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6405 * Returns user context instance.
6407 * @static
6408 * @param int $userid id from {user} table
6409 * @param int $strictness
6410 * @return context_user context instance
6412 public static function instance($userid, $strictness = MUST_EXIST) {
6413 global $DB;
6415 if ($context = context::cache_get(CONTEXT_USER, $userid)) {
6416 return $context;
6419 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER, 'instanceid' => $userid))) {
6420 if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6421 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6425 if ($record) {
6426 $context = new context_user($record);
6427 context::cache_add($context);
6428 return $context;
6431 return false;
6435 * Create missing context instances at user context level
6436 * @static
6438 protected static function create_level_instances() {
6439 global $DB;
6441 $sql = "SELECT ".CONTEXT_USER.", u.id
6442 FROM {user} u
6443 WHERE u.deleted = 0
6444 AND NOT EXISTS (SELECT 'x'
6445 FROM {context} cx
6446 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6447 $contextdata = $DB->get_recordset_sql($sql);
6448 foreach ($contextdata as $context) {
6449 context::insert_context_record(CONTEXT_USER, $context->id, null);
6451 $contextdata->close();
6455 * Returns sql necessary for purging of stale context instances.
6457 * @static
6458 * @return string cleanup SQL
6460 protected static function get_cleanup_sql() {
6461 $sql = "
6462 SELECT c.*
6463 FROM {context} c
6464 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6465 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6468 return $sql;
6472 * Rebuild context paths and depths at user context level.
6474 * @static
6475 * @param bool $force
6477 protected static function build_paths($force) {
6478 global $DB;
6480 // First update normal users.
6481 $path = $DB->sql_concat('?', 'id');
6482 $pathstart = '/' . SYSCONTEXTID . '/';
6483 $params = array($pathstart);
6485 if ($force) {
6486 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6487 $params[] = $pathstart;
6488 } else {
6489 $where = "depth = 0 OR path IS NULL";
6492 $sql = "UPDATE {context}
6493 SET depth = 2,
6494 path = {$path}
6495 WHERE contextlevel = " . CONTEXT_USER . "
6496 AND ($where)";
6497 $DB->execute($sql, $params);
6503 * Course category context class
6505 * @package core_access
6506 * @category access
6507 * @copyright Petr Skoda {@link http://skodak.org}
6508 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6509 * @since Moodle 2.2
6511 class context_coursecat extends context {
6513 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6514 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6516 * @param stdClass $record
6518 protected function __construct(stdClass $record) {
6519 parent::__construct($record);
6520 if ($record->contextlevel != CONTEXT_COURSECAT) {
6521 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6526 * Returns human readable context level name.
6528 * @static
6529 * @return string the human readable context level name.
6531 public static function get_level_name() {
6532 return get_string('category');
6536 * Returns human readable context identifier.
6538 * @param boolean $withprefix whether to prefix the name of the context with Category
6539 * @param boolean $short does not apply to course categories
6540 * @return string the human readable context name.
6542 public function get_context_name($withprefix = true, $short = false) {
6543 global $DB;
6545 $name = '';
6546 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6547 if ($withprefix){
6548 $name = get_string('category').': ';
6550 $name .= format_string($category->name, true, array('context' => $this));
6552 return $name;
6556 * Returns the most relevant URL for this context.
6558 * @return moodle_url
6560 public function get_url() {
6561 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6565 * Returns array of relevant context capability records.
6567 * @return array
6569 public function get_capabilities() {
6570 global $DB;
6572 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6574 $params = array();
6575 $sql = "SELECT *
6576 FROM {capabilities}
6577 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6579 return $DB->get_records_sql($sql.' '.$sort, $params);
6583 * Returns course category context instance.
6585 * @static
6586 * @param int $categoryid id from {course_categories} table
6587 * @param int $strictness
6588 * @return context_coursecat context instance
6590 public static function instance($categoryid, $strictness = MUST_EXIST) {
6591 global $DB;
6593 if ($context = context::cache_get(CONTEXT_COURSECAT, $categoryid)) {
6594 return $context;
6597 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT, 'instanceid' => $categoryid))) {
6598 if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6599 if ($category->parent) {
6600 $parentcontext = context_coursecat::instance($category->parent);
6601 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6602 } else {
6603 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6608 if ($record) {
6609 $context = new context_coursecat($record);
6610 context::cache_add($context);
6611 return $context;
6614 return false;
6618 * Returns immediate child contexts of category and all subcategories,
6619 * children of subcategories and courses are not returned.
6621 * @return array
6623 public function get_child_contexts() {
6624 global $DB;
6626 if (empty($this->_path) or empty($this->_depth)) {
6627 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6628 return array();
6631 $sql = "SELECT ctx.*
6632 FROM {context} ctx
6633 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6634 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6635 $records = $DB->get_records_sql($sql, $params);
6637 $result = array();
6638 foreach ($records as $record) {
6639 $result[$record->id] = context::create_instance_from_record($record);
6642 return $result;
6646 * Create missing context instances at course category context level
6647 * @static
6649 protected static function create_level_instances() {
6650 global $DB;
6652 $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6653 FROM {course_categories} cc
6654 WHERE NOT EXISTS (SELECT 'x'
6655 FROM {context} cx
6656 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6657 $contextdata = $DB->get_recordset_sql($sql);
6658 foreach ($contextdata as $context) {
6659 context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6661 $contextdata->close();
6665 * Returns sql necessary for purging of stale context instances.
6667 * @static
6668 * @return string cleanup SQL
6670 protected static function get_cleanup_sql() {
6671 $sql = "
6672 SELECT c.*
6673 FROM {context} c
6674 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6675 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6678 return $sql;
6682 * Rebuild context paths and depths at course category context level.
6684 * @static
6685 * @param bool $force
6687 protected static function build_paths($force) {
6688 global $DB;
6690 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6691 if ($force) {
6692 $ctxemptyclause = $emptyclause = '';
6693 } else {
6694 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6695 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6698 $base = '/'.SYSCONTEXTID;
6700 // Normal top level categories
6701 $sql = "UPDATE {context}
6702 SET depth=2,
6703 path=".$DB->sql_concat("'$base/'", 'id')."
6704 WHERE contextlevel=".CONTEXT_COURSECAT."
6705 AND EXISTS (SELECT 'x'
6706 FROM {course_categories} cc
6707 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6708 $emptyclause";
6709 $DB->execute($sql);
6711 // Deeper categories - one query per depthlevel
6712 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6713 for ($n=2; $n<=$maxdepth; $n++) {
6714 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
6715 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
6716 FROM {context} ctx
6717 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6718 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6719 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6720 $ctxemptyclause";
6721 $trans = $DB->start_delegated_transaction();
6722 $DB->delete_records('context_temp');
6723 $DB->execute($sql);
6724 context::merge_context_temp_table();
6725 $DB->delete_records('context_temp');
6726 $trans->allow_commit();
6735 * Course context class
6737 * @package core_access
6738 * @category access
6739 * @copyright Petr Skoda {@link http://skodak.org}
6740 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6741 * @since Moodle 2.2
6743 class context_course extends context {
6745 * Please use context_course::instance($courseid) if you need the instance of context.
6746 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6748 * @param stdClass $record
6750 protected function __construct(stdClass $record) {
6751 parent::__construct($record);
6752 if ($record->contextlevel != CONTEXT_COURSE) {
6753 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6758 * Returns human readable context level name.
6760 * @static
6761 * @return string the human readable context level name.
6763 public static function get_level_name() {
6764 return get_string('course');
6768 * Returns human readable context identifier.
6770 * @param boolean $withprefix whether to prefix the name of the context with Course
6771 * @param boolean $short whether to use the short name of the thing.
6772 * @return string the human readable context name.
6774 public function get_context_name($withprefix = true, $short = false) {
6775 global $DB;
6777 $name = '';
6778 if ($this->_instanceid == SITEID) {
6779 $name = get_string('frontpage', 'admin');
6780 } else {
6781 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6782 if ($withprefix){
6783 $name = get_string('course').': ';
6785 if ($short){
6786 $name .= format_string($course->shortname, true, array('context' => $this));
6787 } else {
6788 $name .= format_string(get_course_display_name_for_list($course));
6792 return $name;
6796 * Returns the most relevant URL for this context.
6798 * @return moodle_url
6800 public function get_url() {
6801 if ($this->_instanceid != SITEID) {
6802 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6805 return new moodle_url('/');
6809 * Returns array of relevant context capability records.
6811 * @return array
6813 public function get_capabilities() {
6814 global $DB;
6816 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6818 $params = array();
6819 $sql = "SELECT *
6820 FROM {capabilities}
6821 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6823 return $DB->get_records_sql($sql.' '.$sort, $params);
6827 * Is this context part of any course? If yes return course context.
6829 * @param bool $strict true means throw exception if not found, false means return false if not found
6830 * @return context_course context of the enclosing course, null if not found or exception
6832 public function get_course_context($strict = true) {
6833 return $this;
6837 * Returns course context instance.
6839 * @static
6840 * @param int $courseid id from {course} table
6841 * @param int $strictness
6842 * @return context_course context instance
6844 public static function instance($courseid, $strictness = MUST_EXIST) {
6845 global $DB;
6847 if ($context = context::cache_get(CONTEXT_COURSE, $courseid)) {
6848 return $context;
6851 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $courseid))) {
6852 if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
6853 if ($course->category) {
6854 $parentcontext = context_coursecat::instance($course->category);
6855 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6856 } else {
6857 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6862 if ($record) {
6863 $context = new context_course($record);
6864 context::cache_add($context);
6865 return $context;
6868 return false;
6872 * Create missing context instances at course context level
6873 * @static
6875 protected static function create_level_instances() {
6876 global $DB;
6878 $sql = "SELECT ".CONTEXT_COURSE.", c.id
6879 FROM {course} c
6880 WHERE NOT EXISTS (SELECT 'x'
6881 FROM {context} cx
6882 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6883 $contextdata = $DB->get_recordset_sql($sql);
6884 foreach ($contextdata as $context) {
6885 context::insert_context_record(CONTEXT_COURSE, $context->id, null);
6887 $contextdata->close();
6891 * Returns sql necessary for purging of stale context instances.
6893 * @static
6894 * @return string cleanup SQL
6896 protected static function get_cleanup_sql() {
6897 $sql = "
6898 SELECT c.*
6899 FROM {context} c
6900 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6901 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6904 return $sql;
6908 * Rebuild context paths and depths at course context level.
6910 * @static
6911 * @param bool $force
6913 protected static function build_paths($force) {
6914 global $DB;
6916 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6917 if ($force) {
6918 $ctxemptyclause = $emptyclause = '';
6919 } else {
6920 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6921 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6924 $base = '/'.SYSCONTEXTID;
6926 // Standard frontpage
6927 $sql = "UPDATE {context}
6928 SET depth = 2,
6929 path = ".$DB->sql_concat("'$base/'", 'id')."
6930 WHERE contextlevel = ".CONTEXT_COURSE."
6931 AND EXISTS (SELECT 'x'
6932 FROM {course} c
6933 WHERE c.id = {context}.instanceid AND c.category = 0)
6934 $emptyclause";
6935 $DB->execute($sql);
6937 // standard courses
6938 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
6939 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
6940 FROM {context} ctx
6941 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6942 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6943 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6944 $ctxemptyclause";
6945 $trans = $DB->start_delegated_transaction();
6946 $DB->delete_records('context_temp');
6947 $DB->execute($sql);
6948 context::merge_context_temp_table();
6949 $DB->delete_records('context_temp');
6950 $trans->allow_commit();
6957 * Course module context class
6959 * @package core_access
6960 * @category access
6961 * @copyright Petr Skoda {@link http://skodak.org}
6962 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6963 * @since Moodle 2.2
6965 class context_module extends context {
6967 * Please use context_module::instance($cmid) if you need the instance of context.
6968 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6970 * @param stdClass $record
6972 protected function __construct(stdClass $record) {
6973 parent::__construct($record);
6974 if ($record->contextlevel != CONTEXT_MODULE) {
6975 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6980 * Returns human readable context level name.
6982 * @static
6983 * @return string the human readable context level name.
6985 public static function get_level_name() {
6986 return get_string('activitymodule');
6990 * Returns human readable context identifier.
6992 * @param boolean $withprefix whether to prefix the name of the context with the
6993 * module name, e.g. Forum, Glossary, etc.
6994 * @param boolean $short does not apply to module context
6995 * @return string the human readable context name.
6997 public function get_context_name($withprefix = true, $short = false) {
6998 global $DB;
7000 $name = '';
7001 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
7002 FROM {course_modules} cm
7003 JOIN {modules} md ON md.id = cm.module
7004 WHERE cm.id = ?", array($this->_instanceid))) {
7005 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
7006 if ($withprefix){
7007 $name = get_string('modulename', $cm->modname).': ';
7009 $name .= format_string($mod->name, true, array('context' => $this));
7012 return $name;
7016 * Returns the most relevant URL for this context.
7018 * @return moodle_url
7020 public function get_url() {
7021 global $DB;
7023 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
7024 FROM {course_modules} cm
7025 JOIN {modules} md ON md.id = cm.module
7026 WHERE cm.id = ?", array($this->_instanceid))) {
7027 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
7030 return new moodle_url('/');
7034 * Returns array of relevant context capability records.
7036 * @return array
7038 public function get_capabilities() {
7039 global $DB, $CFG;
7041 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7043 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
7044 $module = $DB->get_record('modules', array('id'=>$cm->module));
7046 $subcaps = array();
7048 $modulepath = "{$CFG->dirroot}/mod/{$module->name}";
7049 if (file_exists("{$modulepath}/db/subplugins.json")) {
7050 $subplugins = (array) json_decode(file_get_contents("{$modulepath}/db/subplugins.json"))->plugintypes;
7051 } else if (file_exists("{$modulepath}/db/subplugins.php")) {
7052 debugging('Use of subplugins.php has been deprecated. ' .
7053 'Please update your plugin to provide a subplugins.json file instead.',
7054 DEBUG_DEVELOPER);
7055 $subplugins = array(); // should be redefined in the file
7056 include("{$modulepath}/db/subplugins.php");
7059 if (!empty($subplugins)) {
7060 foreach (array_keys($subplugins) as $subplugintype) {
7061 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
7062 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
7067 $modfile = "{$modulepath}/lib.php";
7068 $extracaps = array();
7069 if (file_exists($modfile)) {
7070 include_once($modfile);
7071 $modfunction = $module->name.'_get_extra_capabilities';
7072 if (function_exists($modfunction)) {
7073 $extracaps = $modfunction();
7077 $extracaps = array_merge($subcaps, $extracaps);
7078 $extra = '';
7079 list($extra, $params) = $DB->get_in_or_equal(
7080 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
7081 if (!empty($extra)) {
7082 $extra = "OR name $extra";
7085 // Fetch the list of modules, and remove this one.
7086 $components = \core_component::get_component_list();
7087 $componentnames = $components['mod'];
7088 unset($componentnames["mod_{$module->name}"]);
7089 $componentnames = array_keys($componentnames);
7091 // Exclude all other modules.
7092 list($notcompsql, $notcompparams) = $DB->get_in_or_equal($componentnames, SQL_PARAMS_NAMED, 'notcomp', false);
7093 $params = array_merge($params, $notcompparams);
7096 // Exclude other component submodules.
7097 $i = 0;
7098 $ignorecomponents = [];
7099 foreach ($componentnames as $mod) {
7100 if ($subplugins = \core_component::get_subplugins($mod)) {
7101 foreach (array_keys($subplugins) as $subplugintype) {
7102 $paramname = "notlike{$i}";
7103 $ignorecomponents[] = $DB->sql_like('component', ":{$paramname}", true, true, true);
7104 $params[$paramname] = "{$subplugintype}_%";
7105 $i++;
7109 $notlikesql = "(" . implode(' AND ', $ignorecomponents) . ")";
7111 $sql = "SELECT *
7112 FROM {capabilities}
7113 WHERE (contextlevel = ".CONTEXT_MODULE."
7114 AND component {$notcompsql}
7115 AND {$notlikesql})
7116 $extra";
7118 return $DB->get_records_sql($sql.' '.$sort, $params);
7122 * Is this context part of any course? If yes return course context.
7124 * @param bool $strict true means throw exception if not found, false means return false if not found
7125 * @return context_course context of the enclosing course, null if not found or exception
7127 public function get_course_context($strict = true) {
7128 return $this->get_parent_context();
7132 * Returns module context instance.
7134 * @static
7135 * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
7136 * @param int $strictness
7137 * @return context_module context instance
7139 public static function instance($cmid, $strictness = MUST_EXIST) {
7140 global $DB;
7142 if ($context = context::cache_get(CONTEXT_MODULE, $cmid)) {
7143 return $context;
7146 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE, 'instanceid' => $cmid))) {
7147 if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
7148 $parentcontext = context_course::instance($cm->course);
7149 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
7153 if ($record) {
7154 $context = new context_module($record);
7155 context::cache_add($context);
7156 return $context;
7159 return false;
7163 * Create missing context instances at module context level
7164 * @static
7166 protected static function create_level_instances() {
7167 global $DB;
7169 $sql = "SELECT ".CONTEXT_MODULE.", cm.id
7170 FROM {course_modules} cm
7171 WHERE NOT EXISTS (SELECT 'x'
7172 FROM {context} cx
7173 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
7174 $contextdata = $DB->get_recordset_sql($sql);
7175 foreach ($contextdata as $context) {
7176 context::insert_context_record(CONTEXT_MODULE, $context->id, null);
7178 $contextdata->close();
7182 * Returns sql necessary for purging of stale context instances.
7184 * @static
7185 * @return string cleanup SQL
7187 protected static function get_cleanup_sql() {
7188 $sql = "
7189 SELECT c.*
7190 FROM {context} c
7191 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
7192 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
7195 return $sql;
7199 * Rebuild context paths and depths at module context level.
7201 * @static
7202 * @param bool $force
7204 protected static function build_paths($force) {
7205 global $DB;
7207 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
7208 if ($force) {
7209 $ctxemptyclause = '';
7210 } else {
7211 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7214 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7215 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7216 FROM {context} ctx
7217 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
7218 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
7219 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7220 $ctxemptyclause";
7221 $trans = $DB->start_delegated_transaction();
7222 $DB->delete_records('context_temp');
7223 $DB->execute($sql);
7224 context::merge_context_temp_table();
7225 $DB->delete_records('context_temp');
7226 $trans->allow_commit();
7233 * Block context class
7235 * @package core_access
7236 * @category access
7237 * @copyright Petr Skoda {@link http://skodak.org}
7238 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7239 * @since Moodle 2.2
7241 class context_block extends context {
7243 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
7244 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7246 * @param stdClass $record
7248 protected function __construct(stdClass $record) {
7249 parent::__construct($record);
7250 if ($record->contextlevel != CONTEXT_BLOCK) {
7251 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
7256 * Returns human readable context level name.
7258 * @static
7259 * @return string the human readable context level name.
7261 public static function get_level_name() {
7262 return get_string('block');
7266 * Returns human readable context identifier.
7268 * @param boolean $withprefix whether to prefix the name of the context with Block
7269 * @param boolean $short does not apply to block context
7270 * @return string the human readable context name.
7272 public function get_context_name($withprefix = true, $short = false) {
7273 global $DB, $CFG;
7275 $name = '';
7276 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
7277 global $CFG;
7278 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7279 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7280 $blockname = "block_$blockinstance->blockname";
7281 if ($blockobject = new $blockname()) {
7282 if ($withprefix){
7283 $name = get_string('block').': ';
7285 $name .= $blockobject->title;
7289 return $name;
7293 * Returns the most relevant URL for this context.
7295 * @return moodle_url
7297 public function get_url() {
7298 $parentcontexts = $this->get_parent_context();
7299 return $parentcontexts->get_url();
7303 * Returns array of relevant context capability records.
7305 * @return array
7307 public function get_capabilities() {
7308 global $DB;
7310 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7312 $params = array();
7313 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
7315 $extra = '';
7316 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7317 if ($extracaps) {
7318 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7319 $extra = "OR name $extra";
7322 $sql = "SELECT *
7323 FROM {capabilities}
7324 WHERE (contextlevel = ".CONTEXT_BLOCK."
7325 AND component = :component)
7326 $extra";
7327 $params['component'] = 'block_' . $bi->blockname;
7329 return $DB->get_records_sql($sql.' '.$sort, $params);
7333 * Is this context part of any course? If yes return course context.
7335 * @param bool $strict true means throw exception if not found, false means return false if not found
7336 * @return context_course context of the enclosing course, null if not found or exception
7338 public function get_course_context($strict = true) {
7339 $parentcontext = $this->get_parent_context();
7340 return $parentcontext->get_course_context($strict);
7344 * Returns block context instance.
7346 * @static
7347 * @param int $blockinstanceid id from {block_instances} table.
7348 * @param int $strictness
7349 * @return context_block context instance
7351 public static function instance($blockinstanceid, $strictness = MUST_EXIST) {
7352 global $DB;
7354 if ($context = context::cache_get(CONTEXT_BLOCK, $blockinstanceid)) {
7355 return $context;
7358 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $blockinstanceid))) {
7359 if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
7360 $parentcontext = context::instance_by_id($bi->parentcontextid);
7361 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7365 if ($record) {
7366 $context = new context_block($record);
7367 context::cache_add($context);
7368 return $context;
7371 return false;
7375 * Block do not have child contexts...
7376 * @return array
7378 public function get_child_contexts() {
7379 return array();
7383 * Create missing context instances at block context level
7384 * @static
7386 protected static function create_level_instances() {
7387 global $DB;
7389 $sql = "SELECT ".CONTEXT_BLOCK.", bi.id
7390 FROM {block_instances} bi
7391 WHERE NOT EXISTS (SELECT 'x'
7392 FROM {context} cx
7393 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7394 $contextdata = $DB->get_recordset_sql($sql);
7395 foreach ($contextdata as $context) {
7396 context::insert_context_record(CONTEXT_BLOCK, $context->id, null);
7398 $contextdata->close();
7402 * Returns sql necessary for purging of stale context instances.
7404 * @static
7405 * @return string cleanup SQL
7407 protected static function get_cleanup_sql() {
7408 $sql = "
7409 SELECT c.*
7410 FROM {context} c
7411 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7412 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7415 return $sql;
7419 * Rebuild context paths and depths at block context level.
7421 * @static
7422 * @param bool $force
7424 protected static function build_paths($force) {
7425 global $DB;
7427 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7428 if ($force) {
7429 $ctxemptyclause = '';
7430 } else {
7431 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7434 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7435 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7436 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7437 FROM {context} ctx
7438 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7439 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7440 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7441 $ctxemptyclause";
7442 $trans = $DB->start_delegated_transaction();
7443 $DB->delete_records('context_temp');
7444 $DB->execute($sql);
7445 context::merge_context_temp_table();
7446 $DB->delete_records('context_temp');
7447 $trans->allow_commit();
7453 // ============== DEPRECATED FUNCTIONS ==========================================
7454 // Old context related functions were deprecated in 2.0, it is recommended
7455 // to use context classes in new code. Old function can be used when
7456 // creating patches that are supposed to be backported to older stable branches.
7457 // These deprecated functions will not be removed in near future,
7458 // before removing devs will be warned with a debugging message first,
7459 // then we will add error message and only after that we can remove the functions
7460 // completely.
7463 * Runs get_records select on context table and returns the result
7464 * Does get_records_select on the context table, and returns the results ordered
7465 * by contextlevel, and then the natural sort order within each level.
7466 * for the purpose of $select, you need to know that the context table has been
7467 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7469 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7470 * @param array $params any parameters required by $select.
7471 * @return array the requested context records.
7473 function get_sorted_contexts($select, $params = array()) {
7475 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7477 global $DB;
7478 if ($select) {
7479 $select = 'WHERE ' . $select;
7481 return $DB->get_records_sql("
7482 SELECT ctx.*
7483 FROM {context} ctx
7484 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7485 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7486 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7487 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7488 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7489 $select
7490 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7491 ", $params);
7495 * Given context and array of users, returns array of users whose enrolment status is suspended,
7496 * or enrolment has expired or has not started. Also removes those users from the given array
7498 * @param context $context context in which suspended users should be extracted.
7499 * @param array $users list of users.
7500 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7501 * @return array list of suspended users.
7503 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7504 global $DB;
7506 // Get active enrolled users.
7507 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7508 $activeusers = $DB->get_records_sql($sql, $params);
7510 // Move suspended users to a separate array & remove from the initial one.
7511 $susers = array();
7512 if (sizeof($activeusers)) {
7513 foreach ($users as $userid => $user) {
7514 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7515 $susers[$userid] = $user;
7516 unset($users[$userid]);
7520 return $susers;
7524 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7525 * or enrolment has expired or not started.
7527 * @param context $context context in which user enrolment is checked.
7528 * @param bool $usecache Enable or disable (default) the request cache
7529 * @return array list of suspended user id's.
7531 function get_suspended_userids(context $context, $usecache = false) {
7532 global $DB;
7534 if ($usecache) {
7535 $cache = cache::make('core', 'suspended_userids');
7536 $susers = $cache->get($context->id);
7537 if ($susers !== false) {
7538 return $susers;
7542 $coursecontext = $context->get_course_context();
7543 $susers = array();
7545 // Front page users are always enrolled, so suspended list is empty.
7546 if ($coursecontext->instanceid != SITEID) {
7547 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7548 $susers = $DB->get_fieldset_sql($sql, $params);
7549 $susers = array_combine($susers, $susers);
7552 // Cache results for the remainder of this request.
7553 if ($usecache) {
7554 $cache->set($context->id, $susers);
7557 return $susers;
7561 * Gets sql for finding users with capability in the given context
7563 * @param context $context
7564 * @param string|array $capability Capability name or array of names.
7565 * If an array is provided then this is the equivalent of a logical 'OR',
7566 * i.e. the user needs to have one of these capabilities.
7567 * @return array($sql, $params)
7569 function get_with_capability_sql(context $context, $capability) {
7570 static $i = 0;
7571 $i++;
7572 $prefix = 'cu' . $i . '_';
7574 $capjoin = get_with_capability_join($context, $capability, $prefix . 'u.id');
7576 $sql = "SELECT DISTINCT {$prefix}u.id
7577 FROM {user} {$prefix}u
7578 $capjoin->joins
7579 WHERE {$prefix}u.deleted = 0 AND $capjoin->wheres";
7581 return array($sql, $capjoin->params);
7585 * Gets sql joins for finding users with capability in the given context
7587 * @param context $context Context for the join
7588 * @param string|array $capability Capability name or array of names.
7589 * If an array is provided then this is the equivalent of a logical 'OR',
7590 * i.e. the user needs to have one of these capabilities.
7591 * @param string $useridcolumn e.g. 'u.id'
7592 * @return \core\dml\sql_join Contains joins, wheres, params
7594 function get_with_capability_join(context $context, $capability, $useridcolumn) {
7595 global $DB, $CFG;
7597 // Use unique prefix just in case somebody makes some SQL magic with the result.
7598 static $i = 0;
7599 $i++;
7600 $prefix = 'eu' . $i . '_';
7602 // First find the course context.
7603 $coursecontext = $context->get_course_context();
7605 $isfrontpage = ($coursecontext->instanceid == SITEID);
7607 $joins = array();
7608 $wheres = array();
7609 $params = array();
7611 list($contextids, $contextpaths) = get_context_info_list($context);
7613 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
7615 list($incaps, $capsparams) = $DB->get_in_or_equal($capability, SQL_PARAMS_NAMED, 'cap');
7617 // Check whether context locking is enabled.
7618 // Filter out any write capability if this is the case.
7619 $excludelockedcaps = '';
7620 $excludelockedcapsparams = [];
7621 if (!empty($CFG->contextlocking) && $context->locked) {
7622 $excludelockedcaps = 'AND (cap.captype = :capread OR cap.name = :managelockscap)';
7623 $excludelockedcapsparams['capread'] = 'read';
7624 $excludelockedcapsparams['managelockscap'] = 'moodle/site:managecontextlocks';
7627 $defs = array();
7628 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
7629 FROM {role_capabilities} rc
7630 JOIN {capabilities} cap ON rc.capability = cap.name
7631 JOIN {context} ctx on rc.contextid = ctx.id
7632 WHERE rc.contextid $incontexts AND rc.capability $incaps $excludelockedcaps";
7633 $rcs = $DB->get_records_sql($sql, array_merge($cparams, $capsparams, $excludelockedcapsparams));
7634 foreach ($rcs as $rc) {
7635 $defs[$rc->path][$rc->roleid] = $rc->permission;
7638 $access = array();
7639 if (!empty($defs)) {
7640 foreach ($contextpaths as $path) {
7641 if (empty($defs[$path])) {
7642 continue;
7644 foreach ($defs[$path] as $roleid => $perm) {
7645 if ($perm == CAP_PROHIBIT) {
7646 $access[$roleid] = CAP_PROHIBIT;
7647 continue;
7649 if (!isset($access[$roleid])) {
7650 $access[$roleid] = (int) $perm;
7656 unset($defs);
7658 // Make lists of roles that are needed and prohibited.
7659 $needed = array(); // One of these is enough.
7660 $prohibited = array(); // Must not have any of these.
7661 foreach ($access as $roleid => $perm) {
7662 if ($perm == CAP_PROHIBIT) {
7663 unset($needed[$roleid]);
7664 $prohibited[$roleid] = true;
7665 } else {
7666 if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
7667 $needed[$roleid] = true;
7672 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
7673 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
7675 $nobody = false;
7677 if ($isfrontpage) {
7678 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
7679 $nobody = true;
7680 } else {
7681 if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
7682 // Everybody not having prohibit has the capability.
7683 $needed = array();
7684 } else {
7685 if (empty($needed)) {
7686 $nobody = true;
7690 } else {
7691 if (!empty($prohibited[$defaultuserroleid])) {
7692 $nobody = true;
7693 } else {
7694 if (!empty($needed[$defaultuserroleid])) {
7695 // Everybody not having prohibit has the capability.
7696 $needed = array();
7697 } else {
7698 if (empty($needed)) {
7699 $nobody = true;
7705 if ($nobody) {
7706 // Nobody can match so return some SQL that does not return any results.
7707 $wheres[] = "1 = 2";
7709 } else {
7711 if ($needed) {
7712 $ctxids = implode(',', $contextids);
7713 $roleids = implode(',', array_keys($needed));
7714 $joins[] = "JOIN {role_assignments} {$prefix}ra3
7715 ON ({$prefix}ra3.userid = $useridcolumn
7716 AND {$prefix}ra3.roleid IN ($roleids)
7717 AND {$prefix}ra3.contextid IN ($ctxids))";
7720 if ($prohibited) {
7721 $ctxids = implode(',', $contextids);
7722 $roleids = implode(',', array_keys($prohibited));
7723 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4
7724 ON ({$prefix}ra4.userid = $useridcolumn
7725 AND {$prefix}ra4.roleid IN ($roleids)
7726 AND {$prefix}ra4.contextid IN ($ctxids))";
7727 $wheres[] = "{$prefix}ra4.id IS NULL";
7732 $wheres[] = "$useridcolumn <> :{$prefix}guestid";
7733 $params["{$prefix}guestid"] = $CFG->siteguest;
7735 $joins = implode("\n", $joins);
7736 $wheres = "(" . implode(" AND ", $wheres) . ")";
7738 return new \core\dml\sql_join($joins, $wheres, $params);