MDL-63303 message: add functions to message_repository.js
[moodle.git] / lib / accesslib.php
blob9d6dc4f2aa2bc4eaeca3b593362743fdb8830331
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 WHERE rc.roleid $sql";
353 $rs = $DB->get_recordset_sql($sql, $params);
355 // Store the capabilities into the expected data structure.
356 foreach ($rs as $rd) {
357 if (!isset($rdefs[$rd->roleid][$rd->path])) {
358 $rdefs[$rd->roleid][$rd->path] = array();
360 $rdefs[$rd->roleid][$rd->path][$rd->capability] = (int) $rd->permission;
363 $rs->close();
365 // Sometimes (e.g. get_user_capability_course_helper::get_capability_info_at_each_context)
366 // we process role definitinons in a way that requires we see parent contexts
367 // before child contexts. This sort ensures that works (and is faster than
368 // sorting in the SQL query).
369 foreach ($rdefs as $roleid => $rdef) {
370 ksort($rdefs[$roleid]);
373 return $rdefs;
377 * Get the default guest role, this is used for guest account,
378 * search engine spiders, etc.
380 * @return stdClass role record
382 function get_guest_role() {
383 global $CFG, $DB;
385 if (empty($CFG->guestroleid)) {
386 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
387 $guestrole = array_shift($roles); // Pick the first one
388 set_config('guestroleid', $guestrole->id);
389 return $guestrole;
390 } else {
391 debugging('Can not find any guest role!');
392 return false;
394 } else {
395 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
396 return $guestrole;
397 } else {
398 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
399 set_config('guestroleid', '');
400 return get_guest_role();
406 * Check whether a user has a particular capability in a given context.
408 * For example:
409 * $context = context_module::instance($cm->id);
410 * has_capability('mod/forum:replypost', $context)
412 * By default checks the capabilities of the current user, but you can pass a
413 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
415 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
416 * or capabilities with XSS, config or data loss risks.
418 * @category access
420 * @param string $capability the name of the capability to check. For example mod/forum:view
421 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
422 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
423 * @param boolean $doanything If false, ignores effect of admin role assignment
424 * @return boolean true if the user has this capability. Otherwise false.
426 function has_capability($capability, context $context, $user = null, $doanything = true) {
427 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
429 if (during_initial_install()) {
430 if ($SCRIPT === "/$CFG->admin/index.php"
431 or $SCRIPT === "/$CFG->admin/cli/install.php"
432 or $SCRIPT === "/$CFG->admin/cli/install_database.php"
433 or (defined('BEHAT_UTIL') and BEHAT_UTIL)
434 or (defined('PHPUNIT_UTIL') and PHPUNIT_UTIL)) {
435 // we are in an installer - roles can not work yet
436 return true;
437 } else {
438 return false;
442 if (strpos($capability, 'moodle/legacy:') === 0) {
443 throw new coding_exception('Legacy capabilities can not be used any more!');
446 if (!is_bool($doanything)) {
447 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
450 // capability must exist
451 if (!$capinfo = get_capability_info($capability)) {
452 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
453 return false;
456 if (!isset($USER->id)) {
457 // should never happen
458 $USER->id = 0;
459 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER);
462 // make sure there is a real user specified
463 if ($user === null) {
464 $userid = $USER->id;
465 } else {
466 $userid = is_object($user) ? $user->id : $user;
469 // make sure forcelogin cuts off not-logged-in users if enabled
470 if (!empty($CFG->forcelogin) and $userid == 0) {
471 return false;
474 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
475 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
476 if (isguestuser($userid) or $userid == 0) {
477 return false;
481 // Check whether context locking is enabled.
482 if (!empty($CFG->contextlocking)) {
483 if ($capinfo->captype === 'write' && $context->locked) {
484 // Context locking applies to any write capability in a locked context.
485 // It does not apply to moodle/site:managecontextlocks - this is to allow context locking to be unlocked.
486 if ($capinfo->name !== 'moodle/site:managecontextlocks') {
487 // It applies to all users who are not site admins.
488 // It also applies to site admins when contextlockappliestoadmin is set.
489 if (!is_siteadmin($userid) || !empty($CFG->contextlockappliestoadmin)) {
490 return false;
496 // somehow make sure the user is not deleted and actually exists
497 if ($userid != 0) {
498 if ($userid == $USER->id and isset($USER->deleted)) {
499 // this prevents one query per page, it is a bit of cheating,
500 // but hopefully session is terminated properly once user is deleted
501 if ($USER->deleted) {
502 return false;
504 } else {
505 if (!context_user::instance($userid, IGNORE_MISSING)) {
506 // no user context == invalid userid
507 return false;
512 // context path/depth must be valid
513 if (empty($context->path) or $context->depth == 0) {
514 // this should not happen often, each upgrade tries to rebuild the context paths
515 debugging('Context id '.$context->id.' does not have valid path, please use context_helper::build_all_paths()');
516 if (is_siteadmin($userid)) {
517 return true;
518 } else {
519 return false;
523 // Find out if user is admin - it is not possible to override the doanything in any way
524 // and it is not possible to switch to admin role either.
525 if ($doanything) {
526 if (is_siteadmin($userid)) {
527 if ($userid != $USER->id) {
528 return true;
530 // make sure switchrole is not used in this context
531 if (empty($USER->access['rsw'])) {
532 return true;
534 $parts = explode('/', trim($context->path, '/'));
535 $path = '';
536 $switched = false;
537 foreach ($parts as $part) {
538 $path .= '/' . $part;
539 if (!empty($USER->access['rsw'][$path])) {
540 $switched = true;
541 break;
544 if (!$switched) {
545 return true;
547 //ok, admin switched role in this context, let's use normal access control rules
551 // Careful check for staleness...
552 $context->reload_if_dirty();
554 if ($USER->id == $userid) {
555 if (!isset($USER->access)) {
556 load_all_capabilities();
558 $access =& $USER->access;
560 } else {
561 // make sure user accessdata is really loaded
562 get_user_accessdata($userid, true);
563 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
566 return has_capability_in_accessdata($capability, $context, $access);
570 * Check if the user has any one of several capabilities from a list.
572 * This is just a utility method that calls has_capability in a loop. Try to put
573 * the capabilities that most users are likely to have first in the list for best
574 * performance.
576 * @category access
577 * @see has_capability()
579 * @param array $capabilities an array of capability names.
580 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
581 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
582 * @param boolean $doanything If false, ignore effect of admin role assignment
583 * @return boolean true if the user has any of these capabilities. Otherwise false.
585 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
586 foreach ($capabilities as $capability) {
587 if (has_capability($capability, $context, $user, $doanything)) {
588 return true;
591 return false;
595 * Check if the user has all the capabilities in a list.
597 * This is just a utility method that calls has_capability in a loop. Try to put
598 * the capabilities that fewest users are likely to have first in the list for best
599 * performance.
601 * @category access
602 * @see has_capability()
604 * @param array $capabilities an array of capability names.
605 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
606 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
607 * @param boolean $doanything If false, ignore effect of admin role assignment
608 * @return boolean true if the user has all of these capabilities. Otherwise false.
610 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
611 foreach ($capabilities as $capability) {
612 if (!has_capability($capability, $context, $user, $doanything)) {
613 return false;
616 return true;
620 * Is course creator going to have capability in a new course?
622 * This is intended to be used in enrolment plugins before or during course creation,
623 * do not use after the course is fully created.
625 * @category access
627 * @param string $capability the name of the capability to check.
628 * @param context $context course or category context where is course going to be created
629 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
630 * @return boolean true if the user will have this capability.
632 * @throws coding_exception if different type of context submitted
634 function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) {
635 global $CFG;
637 if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) {
638 throw new coding_exception('Only course or course category context expected');
641 if (has_capability($capability, $context, $user)) {
642 // User already has the capability, it could be only removed if CAP_PROHIBIT
643 // was involved here, but we ignore that.
644 return true;
647 if (!has_capability('moodle/course:create', $context, $user)) {
648 return false;
651 if (!enrol_is_enabled('manual')) {
652 return false;
655 if (empty($CFG->creatornewroleid)) {
656 return false;
659 if ($context->contextlevel == CONTEXT_COURSE) {
660 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
661 return false;
663 } else {
664 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
665 return false;
669 // Most likely they will be enrolled after the course creation is finished,
670 // does the new role have the required capability?
671 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
672 return isset($neededroles[$CFG->creatornewroleid]);
676 * Check if the user is an admin at the site level.
678 * Please note that use of proper capabilities is always encouraged,
679 * this function is supposed to be used from core or for temporary hacks.
681 * @category access
683 * @param int|stdClass $user_or_id user id or user object
684 * @return bool true if user is one of the administrators, false otherwise
686 function is_siteadmin($user_or_id = null) {
687 global $CFG, $USER;
689 if ($user_or_id === null) {
690 $user_or_id = $USER;
693 if (empty($user_or_id)) {
694 return false;
696 if (!empty($user_or_id->id)) {
697 $userid = $user_or_id->id;
698 } else {
699 $userid = $user_or_id;
702 // Because this script is called many times (150+ for course page) with
703 // the same parameters, it is worth doing minor optimisations. This static
704 // cache stores the value for a single userid, saving about 2ms from course
705 // page load time without using significant memory. As the static cache
706 // also includes the value it depends on, this cannot break unit tests.
707 static $knownid, $knownresult, $knownsiteadmins;
708 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
709 return $knownresult;
711 $knownid = $userid;
712 $knownsiteadmins = $CFG->siteadmins;
714 $siteadmins = explode(',', $CFG->siteadmins);
715 $knownresult = in_array($userid, $siteadmins);
716 return $knownresult;
720 * Returns true if user has at least one role assign
721 * of 'coursecontact' role (is potentially listed in some course descriptions).
723 * @param int $userid
724 * @return bool
726 function has_coursecontact_role($userid) {
727 global $DB, $CFG;
729 if (empty($CFG->coursecontact)) {
730 return false;
732 $sql = "SELECT 1
733 FROM {role_assignments}
734 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
735 return $DB->record_exists_sql($sql, array('userid'=>$userid));
739 * Does the user have a capability to do something?
741 * Walk the accessdata array and return true/false.
742 * Deals with prohibits, role switching, aggregating
743 * capabilities, etc.
745 * The main feature of here is being FAST and with no
746 * side effects.
748 * Notes:
750 * Switch Role merges with default role
751 * ------------------------------------
752 * If you are a teacher in course X, you have at least
753 * teacher-in-X + defaultloggedinuser-sitewide. So in the
754 * course you'll have techer+defaultloggedinuser.
755 * We try to mimic that in switchrole.
757 * Permission evaluation
758 * ---------------------
759 * Originally there was an extremely complicated way
760 * to determine the user access that dealt with
761 * "locality" or role assignments and role overrides.
762 * Now we simply evaluate access for each role separately
763 * and then verify if user has at least one role with allow
764 * and at the same time no role with prohibit.
766 * @access private
767 * @param string $capability
768 * @param context $context
769 * @param array $accessdata
770 * @return bool
772 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
773 global $CFG;
775 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
776 $path = $context->path;
777 $paths = array($path);
778 while($path = rtrim($path, '0123456789')) {
779 $path = rtrim($path, '/');
780 if ($path === '') {
781 break;
783 $paths[] = $path;
786 $roles = array();
787 $switchedrole = false;
789 // Find out if role switched
790 if (!empty($accessdata['rsw'])) {
791 // From the bottom up...
792 foreach ($paths as $path) {
793 if (isset($accessdata['rsw'][$path])) {
794 // Found a switchrole assignment - check for that role _plus_ the default user role
795 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
796 $switchedrole = true;
797 break;
802 if (!$switchedrole) {
803 // get all users roles in this context and above
804 foreach ($paths as $path) {
805 if (isset($accessdata['ra'][$path])) {
806 foreach ($accessdata['ra'][$path] as $roleid) {
807 $roles[$roleid] = null;
813 // Now find out what access is given to each role, going bottom-->up direction
814 $rdefs = get_role_definitions(array_keys($roles));
815 $allowed = false;
817 foreach ($roles as $roleid => $ignored) {
818 foreach ($paths as $path) {
819 if (isset($rdefs[$roleid][$path][$capability])) {
820 $perm = (int)$rdefs[$roleid][$path][$capability];
821 if ($perm === CAP_PROHIBIT) {
822 // any CAP_PROHIBIT found means no permission for the user
823 return false;
825 if (is_null($roles[$roleid])) {
826 $roles[$roleid] = $perm;
830 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
831 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
834 return $allowed;
838 * A convenience function that tests has_capability, and displays an error if
839 * the user does not have that capability.
841 * NOTE before Moodle 2.0, this function attempted to make an appropriate
842 * require_login call before checking the capability. This is no longer the case.
843 * You must call require_login (or one of its variants) if you want to check the
844 * user is logged in, before you call this function.
846 * @see has_capability()
848 * @param string $capability the name of the capability to check. For example mod/forum:view
849 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
850 * @param int $userid A user id. By default (null) checks the permissions of the current user.
851 * @param bool $doanything If false, ignore effect of admin role assignment
852 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
853 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
854 * @return void terminates with an error if the user does not have the given capability.
856 function require_capability($capability, context $context, $userid = null, $doanything = true,
857 $errormessage = 'nopermissions', $stringfile = '') {
858 if (!has_capability($capability, $context, $userid, $doanything)) {
859 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
864 * Return a nested array showing all role assignments for the user.
865 * [ra] => [contextpath][roleid] = roleid
867 * @access private
868 * @param int $userid - the id of the user
869 * @return array access info array
871 function get_user_roles_sitewide_accessdata($userid) {
872 global $CFG, $DB;
874 $accessdata = get_empty_accessdata();
876 // start with the default role
877 if (!empty($CFG->defaultuserroleid)) {
878 $syscontext = context_system::instance();
879 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
882 // load the "default frontpage role"
883 if (!empty($CFG->defaultfrontpageroleid)) {
884 $frontpagecontext = context_course::instance(get_site()->id);
885 if ($frontpagecontext->path) {
886 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
890 // Preload every assigned role.
891 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
892 FROM {role_assignments} ra
893 JOIN {context} ctx ON ctx.id = ra.contextid
894 WHERE ra.userid = :userid";
896 $rs = $DB->get_recordset_sql($sql, array('userid' => $userid));
898 foreach ($rs as $ra) {
899 // RAs leafs are arrays to support multi-role assignments...
900 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
903 $rs->close();
905 return $accessdata;
909 * Returns empty accessdata structure.
911 * @access private
912 * @return array empt accessdata
914 function get_empty_accessdata() {
915 $accessdata = array(); // named list
916 $accessdata['ra'] = array();
917 $accessdata['time'] = time();
918 $accessdata['rsw'] = array();
920 return $accessdata;
924 * Get accessdata for a given user.
926 * @access private
927 * @param int $userid
928 * @param bool $preloadonly true means do not return access array
929 * @return array accessdata
931 function get_user_accessdata($userid, $preloadonly=false) {
932 global $CFG, $ACCESSLIB_PRIVATE, $USER;
934 if (isset($USER->access)) {
935 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->access;
938 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
939 if (empty($userid)) {
940 if (!empty($CFG->notloggedinroleid)) {
941 $accessdata = get_role_access($CFG->notloggedinroleid);
942 } else {
943 // weird
944 return get_empty_accessdata();
947 } else if (isguestuser($userid)) {
948 if ($guestrole = get_guest_role()) {
949 $accessdata = get_role_access($guestrole->id);
950 } else {
951 //weird
952 return get_empty_accessdata();
955 } else {
956 // Includes default role and frontpage role.
957 $accessdata = get_user_roles_sitewide_accessdata($userid);
960 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
963 if ($preloadonly) {
964 return;
965 } else {
966 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
971 * A convenience function to completely load all the capabilities
972 * for the current user. It is called from has_capability() and functions change permissions.
974 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
975 * @see check_enrolment_plugins()
977 * @access private
978 * @return void
980 function load_all_capabilities() {
981 global $USER;
983 // roles not installed yet - we are in the middle of installation
984 if (during_initial_install()) {
985 return;
988 if (!isset($USER->id)) {
989 // this should not happen
990 $USER->id = 0;
993 unset($USER->access);
994 $USER->access = get_user_accessdata($USER->id);
996 // Clear to force a refresh
997 unset($USER->mycourses);
999 // init/reset internal enrol caches - active course enrolments and temp access
1000 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1004 * A convenience function to completely reload all the capabilities
1005 * for the current user when roles have been updated in a relevant
1006 * context -- but PRESERVING switchroles and loginas.
1007 * This function resets all accesslib and context caches.
1009 * That is - completely transparent to the user.
1011 * Note: reloads $USER->access completely.
1013 * @access private
1014 * @return void
1016 function reload_all_capabilities() {
1017 global $USER, $DB, $ACCESSLIB_PRIVATE;
1019 // copy switchroles
1020 $sw = array();
1021 if (!empty($USER->access['rsw'])) {
1022 $sw = $USER->access['rsw'];
1025 accesslib_clear_all_caches(true);
1026 unset($USER->access);
1028 // Prevent dirty flags refetching on this page.
1029 $ACCESSLIB_PRIVATE->dirtycontexts = array();
1030 $ACCESSLIB_PRIVATE->dirtyusers = array($USER->id => false);
1032 load_all_capabilities();
1034 foreach ($sw as $path => $roleid) {
1035 if ($record = $DB->get_record('context', array('path'=>$path))) {
1036 $context = context::instance_by_id($record->id);
1037 if (has_capability('moodle/role:switchroles', $context)) {
1038 role_switch($roleid, $context);
1045 * Adds a temp role to current USER->access array.
1047 * Useful for the "temporary guest" access we grant to logged-in users.
1048 * This is useful for enrol plugins only.
1050 * @since Moodle 2.2
1051 * @param context_course $coursecontext
1052 * @param int $roleid
1053 * @return void
1055 function load_temp_course_role(context_course $coursecontext, $roleid) {
1056 global $USER, $SITE;
1058 if (empty($roleid)) {
1059 debugging('invalid role specified in load_temp_course_role()');
1060 return;
1063 if ($coursecontext->instanceid == $SITE->id) {
1064 debugging('Can not use temp roles on the frontpage');
1065 return;
1068 if (!isset($USER->access)) {
1069 load_all_capabilities();
1072 $coursecontext->reload_if_dirty();
1074 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1075 return;
1078 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1082 * Removes any extra guest roles from current USER->access array.
1083 * This is useful for enrol plugins only.
1085 * @since Moodle 2.2
1086 * @param context_course $coursecontext
1087 * @return void
1089 function remove_temp_course_roles(context_course $coursecontext) {
1090 global $DB, $USER, $SITE;
1092 if ($coursecontext->instanceid == $SITE->id) {
1093 debugging('Can not use temp roles on the frontpage');
1094 return;
1097 if (empty($USER->access['ra'][$coursecontext->path])) {
1098 //no roles here, weird
1099 return;
1102 $sql = "SELECT DISTINCT ra.roleid AS id
1103 FROM {role_assignments} ra
1104 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1105 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1107 $USER->access['ra'][$coursecontext->path] = array();
1108 foreach($ras as $r) {
1109 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1114 * Returns array of all role archetypes.
1116 * @return array
1118 function get_role_archetypes() {
1119 return array(
1120 'manager' => 'manager',
1121 'coursecreator' => 'coursecreator',
1122 'editingteacher' => 'editingteacher',
1123 'teacher' => 'teacher',
1124 'student' => 'student',
1125 'guest' => 'guest',
1126 'user' => 'user',
1127 'frontpage' => 'frontpage'
1132 * Assign the defaults found in this capability definition to roles that have
1133 * the corresponding legacy capabilities assigned to them.
1135 * @param string $capability
1136 * @param array $legacyperms an array in the format (example):
1137 * 'guest' => CAP_PREVENT,
1138 * 'student' => CAP_ALLOW,
1139 * 'teacher' => CAP_ALLOW,
1140 * 'editingteacher' => CAP_ALLOW,
1141 * 'coursecreator' => CAP_ALLOW,
1142 * 'manager' => CAP_ALLOW
1143 * @return boolean success or failure.
1145 function assign_legacy_capabilities($capability, $legacyperms) {
1147 $archetypes = get_role_archetypes();
1149 foreach ($legacyperms as $type => $perm) {
1151 $systemcontext = context_system::instance();
1152 if ($type === 'admin') {
1153 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1154 $type = 'manager';
1157 if (!array_key_exists($type, $archetypes)) {
1158 print_error('invalidlegacy', '', '', $type);
1161 if ($roles = get_archetype_roles($type)) {
1162 foreach ($roles as $role) {
1163 // Assign a site level capability.
1164 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1165 return false;
1170 return true;
1174 * Verify capability risks.
1176 * @param stdClass $capability a capability - a row from the capabilities table.
1177 * @return boolean whether this capability is safe - that is, whether people with the
1178 * safeoverrides capability should be allowed to change it.
1180 function is_safe_capability($capability) {
1181 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1185 * Get the local override (if any) for a given capability in a role in a context
1187 * @param int $roleid
1188 * @param int $contextid
1189 * @param string $capability
1190 * @return stdClass local capability override
1192 function get_local_override($roleid, $contextid, $capability) {
1193 global $DB;
1194 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1198 * Returns context instance plus related course and cm instances
1200 * @param int $contextid
1201 * @return array of ($context, $course, $cm)
1203 function get_context_info_array($contextid) {
1204 global $DB;
1206 $context = context::instance_by_id($contextid, MUST_EXIST);
1207 $course = null;
1208 $cm = null;
1210 if ($context->contextlevel == CONTEXT_COURSE) {
1211 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1213 } else if ($context->contextlevel == CONTEXT_MODULE) {
1214 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1215 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1217 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1218 $parent = $context->get_parent_context();
1220 if ($parent->contextlevel == CONTEXT_COURSE) {
1221 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1222 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1223 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1224 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1228 return array($context, $course, $cm);
1232 * Function that creates a role
1234 * @param string $name role name
1235 * @param string $shortname role short name
1236 * @param string $description role description
1237 * @param string $archetype
1238 * @return int id or dml_exception
1240 function create_role($name, $shortname, $description, $archetype = '') {
1241 global $DB;
1243 if (strpos($archetype, 'moodle/legacy:') !== false) {
1244 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1247 // verify role archetype actually exists
1248 $archetypes = get_role_archetypes();
1249 if (empty($archetypes[$archetype])) {
1250 $archetype = '';
1253 // Insert the role record.
1254 $role = new stdClass();
1255 $role->name = $name;
1256 $role->shortname = $shortname;
1257 $role->description = $description;
1258 $role->archetype = $archetype;
1260 //find free sortorder number
1261 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1262 if (empty($role->sortorder)) {
1263 $role->sortorder = 1;
1265 $id = $DB->insert_record('role', $role);
1267 return $id;
1271 * Function that deletes a role and cleanups up after it
1273 * @param int $roleid id of role to delete
1274 * @return bool always true
1276 function delete_role($roleid) {
1277 global $DB;
1279 // first unssign all users
1280 role_unassign_all(array('roleid'=>$roleid));
1282 // cleanup all references to this role, ignore errors
1283 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1284 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1285 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1286 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1287 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1288 $DB->delete_records('role_names', array('roleid'=>$roleid));
1289 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1291 // Get role record before it's deleted.
1292 $role = $DB->get_record('role', array('id'=>$roleid));
1294 // Finally delete the role itself.
1295 $DB->delete_records('role', array('id'=>$roleid));
1297 // Trigger event.
1298 $event = \core\event\role_deleted::create(
1299 array(
1300 'context' => context_system::instance(),
1301 'objectid' => $roleid,
1302 'other' =>
1303 array(
1304 'shortname' => $role->shortname,
1305 'description' => $role->description,
1306 'archetype' => $role->archetype
1310 $event->add_record_snapshot('role', $role);
1311 $event->trigger();
1313 // Reset any cache of this role, including MUC.
1314 accesslib_clear_role_cache($roleid);
1316 return true;
1320 * Function to write context specific overrides, or default capabilities.
1322 * @param string $capability string name
1323 * @param int $permission CAP_ constants
1324 * @param int $roleid role id
1325 * @param int|context $contextid context id
1326 * @param bool $overwrite
1327 * @return bool always true or exception
1329 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1330 global $USER, $DB;
1332 if ($contextid instanceof context) {
1333 $context = $contextid;
1334 } else {
1335 $context = context::instance_by_id($contextid);
1338 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1339 unassign_capability($capability, $roleid, $context->id);
1340 return true;
1343 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1345 if ($existing and !$overwrite) { // We want to keep whatever is there already
1346 return true;
1349 $cap = new stdClass();
1350 $cap->contextid = $context->id;
1351 $cap->roleid = $roleid;
1352 $cap->capability = $capability;
1353 $cap->permission = $permission;
1354 $cap->timemodified = time();
1355 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1357 if ($existing) {
1358 $cap->id = $existing->id;
1359 $DB->update_record('role_capabilities', $cap);
1360 } else {
1361 if ($DB->record_exists('context', array('id'=>$context->id))) {
1362 $DB->insert_record('role_capabilities', $cap);
1366 // Reset any cache of this role, including MUC.
1367 accesslib_clear_role_cache($roleid);
1369 return true;
1373 * Unassign a capability from a role.
1375 * @param string $capability the name of the capability
1376 * @param int $roleid the role id
1377 * @param int|context $contextid null means all contexts
1378 * @return boolean true or exception
1380 function unassign_capability($capability, $roleid, $contextid = null) {
1381 global $DB;
1383 if (!empty($contextid)) {
1384 if ($contextid instanceof context) {
1385 $context = $contextid;
1386 } else {
1387 $context = context::instance_by_id($contextid);
1389 // delete from context rel, if this is the last override in this context
1390 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1391 } else {
1392 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1395 // Reset any cache of this role, including MUC.
1396 accesslib_clear_role_cache($roleid);
1398 return true;
1402 * Get the roles that have a given capability assigned to it
1404 * This function does not resolve the actual permission of the capability.
1405 * It just checks for permissions and overrides.
1406 * Use get_roles_with_cap_in_context() if resolution is required.
1408 * @param string $capability capability name (string)
1409 * @param string $permission optional, the permission defined for this capability
1410 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1411 * @param stdClass $context null means any
1412 * @return array of role records
1414 function get_roles_with_capability($capability, $permission = null, $context = null) {
1415 global $DB;
1417 if ($context) {
1418 $contexts = $context->get_parent_context_ids(true);
1419 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1420 $contextsql = "AND rc.contextid $insql";
1421 } else {
1422 $params = array();
1423 $contextsql = '';
1426 if ($permission) {
1427 $permissionsql = " AND rc.permission = :permission";
1428 $params['permission'] = $permission;
1429 } else {
1430 $permissionsql = '';
1433 $sql = "SELECT r.*
1434 FROM {role} r
1435 WHERE r.id IN (SELECT rc.roleid
1436 FROM {role_capabilities} rc
1437 WHERE rc.capability = :capname
1438 $contextsql
1439 $permissionsql)";
1440 $params['capname'] = $capability;
1443 return $DB->get_records_sql($sql, $params);
1447 * This function makes a role-assignment (a role for a user in a particular context)
1449 * @param int $roleid the role of the id
1450 * @param int $userid userid
1451 * @param int|context $contextid id of the context
1452 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1453 * @param int $itemid id of enrolment/auth plugin
1454 * @param string $timemodified defaults to current time
1455 * @return int new/existing id of the assignment
1457 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1458 global $USER, $DB;
1460 // first of all detect if somebody is using old style parameters
1461 if ($contextid === 0 or is_numeric($component)) {
1462 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1465 // now validate all parameters
1466 if (empty($roleid)) {
1467 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1470 if (empty($userid)) {
1471 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1474 if ($itemid) {
1475 if (strpos($component, '_') === false) {
1476 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1478 } else {
1479 $itemid = 0;
1480 if ($component !== '' and strpos($component, '_') === false) {
1481 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1485 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1486 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1489 if ($contextid instanceof context) {
1490 $context = $contextid;
1491 } else {
1492 $context = context::instance_by_id($contextid, MUST_EXIST);
1495 if (!$timemodified) {
1496 $timemodified = time();
1499 // Check for existing entry
1500 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1502 if ($ras) {
1503 // role already assigned - this should not happen
1504 if (count($ras) > 1) {
1505 // very weird - remove all duplicates!
1506 $ra = array_shift($ras);
1507 foreach ($ras as $r) {
1508 $DB->delete_records('role_assignments', array('id'=>$r->id));
1510 } else {
1511 $ra = reset($ras);
1514 // actually there is no need to update, reset anything or trigger any event, so just return
1515 return $ra->id;
1518 // Create a new entry
1519 $ra = new stdClass();
1520 $ra->roleid = $roleid;
1521 $ra->contextid = $context->id;
1522 $ra->userid = $userid;
1523 $ra->component = $component;
1524 $ra->itemid = $itemid;
1525 $ra->timemodified = $timemodified;
1526 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1527 $ra->sortorder = 0;
1529 $ra->id = $DB->insert_record('role_assignments', $ra);
1531 // Role assignments have changed, so mark user as dirty.
1532 mark_user_dirty($userid);
1534 core_course_category::role_assignment_changed($roleid, $context);
1536 $event = \core\event\role_assigned::create(array(
1537 'context' => $context,
1538 'objectid' => $ra->roleid,
1539 'relateduserid' => $ra->userid,
1540 'other' => array(
1541 'id' => $ra->id,
1542 'component' => $ra->component,
1543 'itemid' => $ra->itemid
1546 $event->add_record_snapshot('role_assignments', $ra);
1547 $event->trigger();
1549 return $ra->id;
1553 * Removes one role assignment
1555 * @param int $roleid
1556 * @param int $userid
1557 * @param int $contextid
1558 * @param string $component
1559 * @param int $itemid
1560 * @return void
1562 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1563 // first make sure the params make sense
1564 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1565 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1568 if ($itemid) {
1569 if (strpos($component, '_') === false) {
1570 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1572 } else {
1573 $itemid = 0;
1574 if ($component !== '' and strpos($component, '_') === false) {
1575 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1579 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1583 * Removes multiple role assignments, parameters may contain:
1584 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1586 * @param array $params role assignment parameters
1587 * @param bool $subcontexts unassign in subcontexts too
1588 * @param bool $includemanual include manual role assignments too
1589 * @return void
1591 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1592 global $USER, $CFG, $DB;
1594 if (!$params) {
1595 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1598 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1599 foreach ($params as $key=>$value) {
1600 if (!in_array($key, $allowed)) {
1601 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1605 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1606 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1609 if ($includemanual) {
1610 if (!isset($params['component']) or $params['component'] === '') {
1611 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1615 if ($subcontexts) {
1616 if (empty($params['contextid'])) {
1617 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1621 $ras = $DB->get_records('role_assignments', $params);
1622 foreach($ras as $ra) {
1623 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1624 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1625 // Role assignments have changed, so mark user as dirty.
1626 mark_user_dirty($ra->userid);
1628 $event = \core\event\role_unassigned::create(array(
1629 'context' => $context,
1630 'objectid' => $ra->roleid,
1631 'relateduserid' => $ra->userid,
1632 'other' => array(
1633 'id' => $ra->id,
1634 'component' => $ra->component,
1635 'itemid' => $ra->itemid
1638 $event->add_record_snapshot('role_assignments', $ra);
1639 $event->trigger();
1640 core_course_category::role_assignment_changed($ra->roleid, $context);
1643 unset($ras);
1645 // process subcontexts
1646 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1647 if ($params['contextid'] instanceof context) {
1648 $context = $params['contextid'];
1649 } else {
1650 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1653 if ($context) {
1654 $contexts = $context->get_child_contexts();
1655 $mparams = $params;
1656 foreach($contexts as $context) {
1657 $mparams['contextid'] = $context->id;
1658 $ras = $DB->get_records('role_assignments', $mparams);
1659 foreach($ras as $ra) {
1660 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1661 // Role assignments have changed, so mark user as dirty.
1662 mark_user_dirty($ra->userid);
1664 $event = \core\event\role_unassigned::create(
1665 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1666 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1667 $event->add_record_snapshot('role_assignments', $ra);
1668 $event->trigger();
1669 core_course_category::role_assignment_changed($ra->roleid, $context);
1675 // do this once more for all manual role assignments
1676 if ($includemanual) {
1677 $params['component'] = '';
1678 role_unassign_all($params, $subcontexts, false);
1683 * Mark a user as dirty (with timestamp) so as to force reloading of the user session.
1685 * @param int $userid
1686 * @return void
1688 function mark_user_dirty($userid) {
1689 global $CFG, $ACCESSLIB_PRIVATE;
1691 if (during_initial_install()) {
1692 return;
1695 // Throw exception if invalid userid is provided.
1696 if (empty($userid)) {
1697 throw new coding_exception('Invalid user parameter supplied for mark_user_dirty() function!');
1700 // Set dirty flag in database, set dirty field locally, and clear local accessdata cache.
1701 set_cache_flag('accesslib/dirtyusers', $userid, 1, time() + $CFG->sessiontimeout);
1702 $ACCESSLIB_PRIVATE->dirtyusers[$userid] = 1;
1703 unset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
1707 * Determines if a user is currently logged in
1709 * @category access
1711 * @return bool
1713 function isloggedin() {
1714 global $USER;
1716 return (!empty($USER->id));
1720 * Determines if a user is logged in as real guest user with username 'guest'.
1722 * @category access
1724 * @param int|object $user mixed user object or id, $USER if not specified
1725 * @return bool true if user is the real guest user, false if not logged in or other user
1727 function isguestuser($user = null) {
1728 global $USER, $DB, $CFG;
1730 // make sure we have the user id cached in config table, because we are going to use it a lot
1731 if (empty($CFG->siteguest)) {
1732 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1733 // guest does not exist yet, weird
1734 return false;
1736 set_config('siteguest', $guestid);
1738 if ($user === null) {
1739 $user = $USER;
1742 if ($user === null) {
1743 // happens when setting the $USER
1744 return false;
1746 } else if (is_numeric($user)) {
1747 return ($CFG->siteguest == $user);
1749 } else if (is_object($user)) {
1750 if (empty($user->id)) {
1751 return false; // not logged in means is not be guest
1752 } else {
1753 return ($CFG->siteguest == $user->id);
1756 } else {
1757 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1762 * Does user have a (temporary or real) guest access to course?
1764 * @category access
1766 * @param context $context
1767 * @param stdClass|int $user
1768 * @return bool
1770 function is_guest(context $context, $user = null) {
1771 global $USER;
1773 // first find the course context
1774 $coursecontext = $context->get_course_context();
1776 // make sure there is a real user specified
1777 if ($user === null) {
1778 $userid = isset($USER->id) ? $USER->id : 0;
1779 } else {
1780 $userid = is_object($user) ? $user->id : $user;
1783 if (isguestuser($userid)) {
1784 // can not inspect or be enrolled
1785 return true;
1788 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1789 // viewing users appear out of nowhere, they are neither guests nor participants
1790 return false;
1793 // consider only real active enrolments here
1794 if (is_enrolled($coursecontext, $user, '', true)) {
1795 return false;
1798 return true;
1802 * Returns true if the user has moodle/course:view capability in the course,
1803 * this is intended for admins, managers (aka small admins), inspectors, etc.
1805 * @category access
1807 * @param context $context
1808 * @param int|stdClass $user if null $USER is used
1809 * @param string $withcapability extra capability name
1810 * @return bool
1812 function is_viewing(context $context, $user = null, $withcapability = '') {
1813 // first find the course context
1814 $coursecontext = $context->get_course_context();
1816 if (isguestuser($user)) {
1817 // can not inspect
1818 return false;
1821 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1822 // admins are allowed to inspect courses
1823 return false;
1826 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1827 // site admins always have the capability, but the enrolment above blocks
1828 return false;
1831 return true;
1835 * Returns true if the user is able to access the course.
1837 * This function is in no way, shape, or form a substitute for require_login.
1838 * It should only be used in circumstances where it is not possible to call require_login
1839 * such as the navigation.
1841 * This function checks many of the methods of access to a course such as the view
1842 * capability, enrollments, and guest access. It also makes use of the cache
1843 * generated by require_login for guest access.
1845 * The flags within the $USER object that are used here should NEVER be used outside
1846 * of this function can_access_course and require_login. Doing so WILL break future
1847 * versions.
1849 * @param stdClass $course record
1850 * @param stdClass|int|null $user user record or id, current user if null
1851 * @param string $withcapability Check for this capability as well.
1852 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1853 * @return boolean Returns true if the user is able to access the course
1855 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
1856 global $DB, $USER;
1858 // this function originally accepted $coursecontext parameter
1859 if ($course instanceof context) {
1860 if ($course instanceof context_course) {
1861 debugging('deprecated context parameter, please use $course record');
1862 $coursecontext = $course;
1863 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
1864 } else {
1865 debugging('Invalid context parameter, please use $course record');
1866 return false;
1868 } else {
1869 $coursecontext = context_course::instance($course->id);
1872 if (!isset($USER->id)) {
1873 // should never happen
1874 $USER->id = 0;
1875 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
1878 // make sure there is a user specified
1879 if ($user === null) {
1880 $userid = $USER->id;
1881 } else {
1882 $userid = is_object($user) ? $user->id : $user;
1884 unset($user);
1886 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
1887 return false;
1890 if ($userid == $USER->id) {
1891 if (!empty($USER->access['rsw'][$coursecontext->path])) {
1892 // the fact that somebody switched role means they can access the course no matter to what role they switched
1893 return true;
1897 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
1898 return false;
1901 if (is_viewing($coursecontext, $userid)) {
1902 return true;
1905 if ($userid != $USER->id) {
1906 // for performance reasons we do not verify temporary guest access for other users, sorry...
1907 return is_enrolled($coursecontext, $userid, '', $onlyactive);
1910 // === from here we deal only with $USER ===
1912 $coursecontext->reload_if_dirty();
1914 if (isset($USER->enrol['enrolled'][$course->id])) {
1915 if ($USER->enrol['enrolled'][$course->id] > time()) {
1916 return true;
1919 if (isset($USER->enrol['tempguest'][$course->id])) {
1920 if ($USER->enrol['tempguest'][$course->id] > time()) {
1921 return true;
1925 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
1926 return true;
1929 // if not enrolled try to gain temporary guest access
1930 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
1931 $enrols = enrol_get_plugins(true);
1932 foreach($instances as $instance) {
1933 if (!isset($enrols[$instance->enrol])) {
1934 continue;
1936 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
1937 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
1938 if ($until !== false and $until > time()) {
1939 $USER->enrol['tempguest'][$course->id] = $until;
1940 return true;
1943 if (isset($USER->enrol['tempguest'][$course->id])) {
1944 unset($USER->enrol['tempguest'][$course->id]);
1945 remove_temp_course_roles($coursecontext);
1948 return false;
1952 * Loads the capability definitions for the component (from file).
1954 * Loads the capability definitions for the component (from file). If no
1955 * capabilities are defined for the component, we simply return an empty array.
1957 * @access private
1958 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
1959 * @return array array of capabilities
1961 function load_capability_def($component) {
1962 $defpath = core_component::get_component_directory($component).'/db/access.php';
1964 $capabilities = array();
1965 if (file_exists($defpath)) {
1966 require($defpath);
1967 if (!empty(${$component.'_capabilities'})) {
1968 // BC capability array name
1969 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
1970 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
1971 $capabilities = ${$component.'_capabilities'};
1975 return $capabilities;
1979 * Gets the capabilities that have been cached in the database for this component.
1981 * @access private
1982 * @param string $component - examples: 'moodle', 'mod_forum'
1983 * @return array array of capabilities
1985 function get_cached_capabilities($component = 'moodle') {
1986 global $DB;
1987 $caps = get_all_capabilities();
1988 $componentcaps = array();
1989 foreach ($caps as $cap) {
1990 if ($cap['component'] == $component) {
1991 $componentcaps[] = (object) $cap;
1994 return $componentcaps;
1998 * Returns default capabilities for given role archetype.
2000 * @param string $archetype role archetype
2001 * @return array
2003 function get_default_capabilities($archetype) {
2004 global $DB;
2006 if (!$archetype) {
2007 return array();
2010 $alldefs = array();
2011 $defaults = array();
2012 $components = array();
2013 $allcaps = get_all_capabilities();
2015 foreach ($allcaps as $cap) {
2016 if (!in_array($cap['component'], $components)) {
2017 $components[] = $cap['component'];
2018 $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
2021 foreach($alldefs as $name=>$def) {
2022 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2023 if (isset($def['archetypes'])) {
2024 if (isset($def['archetypes'][$archetype])) {
2025 $defaults[$name] = $def['archetypes'][$archetype];
2027 // 'legacy' is for backward compatibility with 1.9 access.php
2028 } else {
2029 if (isset($def['legacy'][$archetype])) {
2030 $defaults[$name] = $def['legacy'][$archetype];
2035 return $defaults;
2039 * Return default roles that can be assigned, overridden or switched
2040 * by give role archetype.
2042 * @param string $type assign|override|switch|view
2043 * @param string $archetype
2044 * @return array of role ids
2046 function get_default_role_archetype_allows($type, $archetype) {
2047 global $DB;
2049 if (empty($archetype)) {
2050 return array();
2053 $roles = $DB->get_records('role');
2054 $archetypemap = array();
2055 foreach ($roles as $role) {
2056 if ($role->archetype) {
2057 $archetypemap[$role->archetype][$role->id] = $role->id;
2061 $defaults = array(
2062 'assign' => array(
2063 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2064 'coursecreator' => array(),
2065 'editingteacher' => array('teacher', 'student'),
2066 'teacher' => array(),
2067 'student' => array(),
2068 'guest' => array(),
2069 'user' => array(),
2070 'frontpage' => array(),
2072 'override' => array(
2073 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2074 'coursecreator' => array(),
2075 'editingteacher' => array('teacher', 'student', 'guest'),
2076 'teacher' => array(),
2077 'student' => array(),
2078 'guest' => array(),
2079 'user' => array(),
2080 'frontpage' => array(),
2082 'switch' => array(
2083 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2084 'coursecreator' => array(),
2085 'editingteacher' => array('teacher', 'student', 'guest'),
2086 'teacher' => array('student', 'guest'),
2087 'student' => array(),
2088 'guest' => array(),
2089 'user' => array(),
2090 'frontpage' => array(),
2092 'view' => array(
2093 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2094 'coursecreator' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2095 'editingteacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2096 'teacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2097 'student' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2098 'guest' => array(),
2099 'user' => array(),
2100 'frontpage' => array(),
2104 if (!isset($defaults[$type][$archetype])) {
2105 debugging("Unknown type '$type'' or archetype '$archetype''");
2106 return array();
2109 $return = array();
2110 foreach ($defaults[$type][$archetype] as $at) {
2111 if (isset($archetypemap[$at])) {
2112 foreach ($archetypemap[$at] as $roleid) {
2113 $return[$roleid] = $roleid;
2118 return $return;
2122 * Reset role capabilities to default according to selected role archetype.
2123 * If no archetype selected, removes all capabilities.
2125 * This applies to capabilities that are assigned to the role (that you could
2126 * edit in the 'define roles' interface), and not to any capability overrides
2127 * in different locations.
2129 * @param int $roleid ID of role to reset capabilities for
2131 function reset_role_capabilities($roleid) {
2132 global $DB;
2134 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2135 $defaultcaps = get_default_capabilities($role->archetype);
2137 $systemcontext = context_system::instance();
2139 $DB->delete_records('role_capabilities',
2140 array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2142 foreach($defaultcaps as $cap=>$permission) {
2143 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2146 // Reset any cache of this role, including MUC.
2147 accesslib_clear_role_cache($roleid);
2151 * Updates the capabilities table with the component capability definitions.
2152 * If no parameters are given, the function updates the core moodle
2153 * capabilities.
2155 * Note that the absence of the db/access.php capabilities definition file
2156 * will cause any stored capabilities for the component to be removed from
2157 * the database.
2159 * @access private
2160 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2161 * @return boolean true if success, exception in case of any problems
2163 function update_capabilities($component = 'moodle') {
2164 global $DB, $OUTPUT;
2166 $storedcaps = array();
2168 $filecaps = load_capability_def($component);
2169 foreach($filecaps as $capname=>$unused) {
2170 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2171 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2175 // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2176 // So ensure our updating is based on fresh data.
2177 cache::make('core', 'capabilities')->delete('core_capabilities');
2179 $cachedcaps = get_cached_capabilities($component);
2180 if ($cachedcaps) {
2181 foreach ($cachedcaps as $cachedcap) {
2182 array_push($storedcaps, $cachedcap->name);
2183 // update risk bitmasks and context levels in existing capabilities if needed
2184 if (array_key_exists($cachedcap->name, $filecaps)) {
2185 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2186 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2188 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2189 $updatecap = new stdClass();
2190 $updatecap->id = $cachedcap->id;
2191 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2192 $DB->update_record('capabilities', $updatecap);
2194 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2195 $updatecap = new stdClass();
2196 $updatecap->id = $cachedcap->id;
2197 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2198 $DB->update_record('capabilities', $updatecap);
2201 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2202 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2204 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2205 $updatecap = new stdClass();
2206 $updatecap->id = $cachedcap->id;
2207 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2208 $DB->update_record('capabilities', $updatecap);
2214 // Flush the cached again, as we have changed DB.
2215 cache::make('core', 'capabilities')->delete('core_capabilities');
2217 // Are there new capabilities in the file definition?
2218 $newcaps = array();
2220 foreach ($filecaps as $filecap => $def) {
2221 if (!$storedcaps ||
2222 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2223 if (!array_key_exists('riskbitmask', $def)) {
2224 $def['riskbitmask'] = 0; // no risk if not specified
2226 $newcaps[$filecap] = $def;
2229 // Add new capabilities to the stored definition.
2230 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2231 foreach ($newcaps as $capname => $capdef) {
2232 $capability = new stdClass();
2233 $capability->name = $capname;
2234 $capability->captype = $capdef['captype'];
2235 $capability->contextlevel = $capdef['contextlevel'];
2236 $capability->component = $component;
2237 $capability->riskbitmask = $capdef['riskbitmask'];
2239 $DB->insert_record('capabilities', $capability, false);
2241 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2242 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2243 foreach ($rolecapabilities as $rolecapability){
2244 //assign_capability will update rather than insert if capability exists
2245 if (!assign_capability($capname, $rolecapability->permission,
2246 $rolecapability->roleid, $rolecapability->contextid, true)){
2247 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2251 // we ignore archetype key if we have cloned permissions
2252 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2253 assign_legacy_capabilities($capname, $capdef['archetypes']);
2254 // 'legacy' is for backward compatibility with 1.9 access.php
2255 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2256 assign_legacy_capabilities($capname, $capdef['legacy']);
2259 // Are there any capabilities that have been removed from the file
2260 // definition that we need to delete from the stored capabilities and
2261 // role assignments?
2262 capabilities_cleanup($component, $filecaps);
2264 // reset static caches
2265 accesslib_reset_role_cache();
2267 // Flush the cached again, as we have changed DB.
2268 cache::make('core', 'capabilities')->delete('core_capabilities');
2270 return true;
2274 * Deletes cached capabilities that are no longer needed by the component.
2275 * Also unassigns these capabilities from any roles that have them.
2276 * NOTE: this function is called from lib/db/upgrade.php
2278 * @access private
2279 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2280 * @param array $newcapdef array of the new capability definitions that will be
2281 * compared with the cached capabilities
2282 * @return int number of deprecated capabilities that have been removed
2284 function capabilities_cleanup($component, $newcapdef = null) {
2285 global $DB;
2287 $removedcount = 0;
2289 if ($cachedcaps = get_cached_capabilities($component)) {
2290 foreach ($cachedcaps as $cachedcap) {
2291 if (empty($newcapdef) ||
2292 array_key_exists($cachedcap->name, $newcapdef) === false) {
2294 // Remove from capabilities cache.
2295 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2296 $removedcount++;
2297 // Delete from roles.
2298 if ($roles = get_roles_with_capability($cachedcap->name)) {
2299 foreach($roles as $role) {
2300 if (!unassign_capability($cachedcap->name, $role->id)) {
2301 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2305 } // End if.
2308 if ($removedcount) {
2309 cache::make('core', 'capabilities')->delete('core_capabilities');
2311 return $removedcount;
2315 * Returns an array of all the known types of risk
2316 * The array keys can be used, for example as CSS class names, or in calls to
2317 * print_risk_icon. The values are the corresponding RISK_ constants.
2319 * @return array all the known types of risk.
2321 function get_all_risks() {
2322 return array(
2323 'riskmanagetrust' => RISK_MANAGETRUST,
2324 'riskconfig' => RISK_CONFIG,
2325 'riskxss' => RISK_XSS,
2326 'riskpersonal' => RISK_PERSONAL,
2327 'riskspam' => RISK_SPAM,
2328 'riskdataloss' => RISK_DATALOSS,
2333 * Return a link to moodle docs for a given capability name
2335 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2336 * @return string the human-readable capability name as a link to Moodle Docs.
2338 function get_capability_docs_link($capability) {
2339 $url = get_docs_url('Capabilities/' . $capability->name);
2340 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2344 * This function pulls out all the resolved capabilities (overrides and
2345 * defaults) of a role used in capability overrides in contexts at a given
2346 * context.
2348 * @param int $roleid
2349 * @param context $context
2350 * @param string $cap capability, optional, defaults to ''
2351 * @return array Array of capabilities
2353 function role_context_capabilities($roleid, context $context, $cap = '') {
2354 global $DB;
2356 $contexts = $context->get_parent_context_ids(true);
2357 $contexts = '('.implode(',', $contexts).')';
2359 $params = array($roleid);
2361 if ($cap) {
2362 $search = " AND rc.capability = ? ";
2363 $params[] = $cap;
2364 } else {
2365 $search = '';
2368 $sql = "SELECT rc.*
2369 FROM {role_capabilities} rc, {context} c
2370 WHERE rc.contextid in $contexts
2371 AND rc.roleid = ?
2372 AND rc.contextid = c.id $search
2373 ORDER BY c.contextlevel DESC, rc.capability DESC";
2375 $capabilities = array();
2377 if ($records = $DB->get_records_sql($sql, $params)) {
2378 // We are traversing via reverse order.
2379 foreach ($records as $record) {
2380 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2381 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2382 $capabilities[$record->capability] = $record->permission;
2386 return $capabilities;
2390 * Constructs array with contextids as first parameter and context paths,
2391 * in both cases bottom top including self.
2393 * @access private
2394 * @param context $context
2395 * @return array
2397 function get_context_info_list(context $context) {
2398 $contextids = explode('/', ltrim($context->path, '/'));
2399 $contextpaths = array();
2400 $contextids2 = $contextids;
2401 while ($contextids2) {
2402 $contextpaths[] = '/' . implode('/', $contextids2);
2403 array_pop($contextids2);
2405 return array($contextids, $contextpaths);
2409 * Check if context is the front page context or a context inside it
2411 * Returns true if this context is the front page context, or a context inside it,
2412 * otherwise false.
2414 * @param context $context a context object.
2415 * @return bool
2417 function is_inside_frontpage(context $context) {
2418 $frontpagecontext = context_course::instance(SITEID);
2419 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2423 * Returns capability information (cached)
2425 * @param string $capabilityname
2426 * @return stdClass or null if capability not found
2428 function get_capability_info($capabilityname) {
2429 $caps = get_all_capabilities();
2431 if (!isset($caps[$capabilityname])) {
2432 return null;
2435 return (object) $caps[$capabilityname];
2439 * Returns all capabilitiy records, preferably from MUC and not database.
2441 * @return array All capability records indexed by capability name
2443 function get_all_capabilities() {
2444 global $DB;
2445 $cache = cache::make('core', 'capabilities');
2446 if (!$allcaps = $cache->get('core_capabilities')) {
2447 $rs = $DB->get_recordset('capabilities');
2448 $allcaps = array();
2449 foreach ($rs as $capability) {
2450 $capability->riskbitmask = (int) $capability->riskbitmask;
2451 $allcaps[$capability->name] = (array) $capability;
2453 $rs->close();
2454 $cache->set('core_capabilities', $allcaps);
2456 return $allcaps;
2460 * Returns the human-readable, translated version of the capability.
2461 * Basically a big switch statement.
2463 * @param string $capabilityname e.g. mod/choice:readresponses
2464 * @return string
2466 function get_capability_string($capabilityname) {
2468 // Typical capability name is 'plugintype/pluginname:capabilityname'
2469 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2471 if ($type === 'moodle') {
2472 $component = 'core_role';
2473 } else if ($type === 'quizreport') {
2474 //ugly hack!!
2475 $component = 'quiz_'.$name;
2476 } else {
2477 $component = $type.'_'.$name;
2480 $stringname = $name.':'.$capname;
2482 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2483 return get_string($stringname, $component);
2486 $dir = core_component::get_component_directory($component);
2487 if (!file_exists($dir)) {
2488 // plugin broken or does not exist, do not bother with printing of debug message
2489 return $capabilityname.' ???';
2492 // something is wrong in plugin, better print debug
2493 return get_string($stringname, $component);
2497 * This gets the mod/block/course/core etc strings.
2499 * @param string $component
2500 * @param int $contextlevel
2501 * @return string|bool String is success, false if failed
2503 function get_component_string($component, $contextlevel) {
2505 if ($component === 'moodle' or $component === 'core') {
2506 switch ($contextlevel) {
2507 // TODO MDL-46123: this should probably use context level names instead
2508 case CONTEXT_SYSTEM: return get_string('coresystem');
2509 case CONTEXT_USER: return get_string('users');
2510 case CONTEXT_COURSECAT: return get_string('categories');
2511 case CONTEXT_COURSE: return get_string('course');
2512 case CONTEXT_MODULE: return get_string('activities');
2513 case CONTEXT_BLOCK: return get_string('block');
2514 default: print_error('unknowncontext');
2518 list($type, $name) = core_component::normalize_component($component);
2519 $dir = core_component::get_plugin_directory($type, $name);
2520 if (!file_exists($dir)) {
2521 // plugin not installed, bad luck, there is no way to find the name
2522 return $component.' ???';
2525 switch ($type) {
2526 // TODO MDL-46123: this is really hacky and should be improved.
2527 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2528 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2529 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2530 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2531 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2532 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2533 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2534 case 'mod':
2535 if (get_string_manager()->string_exists('pluginname', $component)) {
2536 return get_string('activity').': '.get_string('pluginname', $component);
2537 } else {
2538 return get_string('activity').': '.get_string('modulename', $component);
2540 default: return get_string('pluginname', $component);
2545 * Gets the list of roles assigned to this context and up (parents)
2546 * from the aggregation of:
2547 * a) the list of roles that are visible on user profile page and participants page (profileroles setting) and;
2548 * b) if applicable, those roles that are assigned in the context.
2550 * @param context $context
2551 * @return array
2553 function get_profile_roles(context $context) {
2554 global $CFG, $DB;
2555 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2556 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2557 if (has_capability('moodle/role:assign', $context)) {
2558 $rolesinscope = array_keys(get_all_roles($context));
2559 } else {
2560 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2563 if (empty($rolesinscope)) {
2564 return [];
2567 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2568 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2569 $params = array_merge($params, $cparams);
2571 if ($coursecontext = $context->get_course_context(false)) {
2572 $params['coursecontext'] = $coursecontext->id;
2573 } else {
2574 $params['coursecontext'] = 0;
2577 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2578 FROM {role_assignments} ra, {role} r
2579 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2580 WHERE r.id = ra.roleid
2581 AND ra.contextid $contextlist
2582 AND r.id $rallowed
2583 ORDER BY r.sortorder ASC";
2585 return $DB->get_records_sql($sql, $params);
2589 * Gets the list of roles assigned to this context and up (parents)
2591 * @param context $context
2592 * @param boolean $includeparents, false means without parents.
2593 * @return array
2595 function get_roles_used_in_context(context $context, $includeparents = true) {
2596 global $DB;
2598 if ($includeparents === true) {
2599 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2600 } else {
2601 list($contextlist, $params) = $DB->get_in_or_equal($context->id, SQL_PARAMS_NAMED, 'cl');
2604 if ($coursecontext = $context->get_course_context(false)) {
2605 $params['coursecontext'] = $coursecontext->id;
2606 } else {
2607 $params['coursecontext'] = 0;
2610 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2611 FROM {role_assignments} ra, {role} r
2612 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2613 WHERE r.id = ra.roleid
2614 AND ra.contextid $contextlist
2615 ORDER BY r.sortorder ASC";
2617 return $DB->get_records_sql($sql, $params);
2621 * This function is used to print roles column in user profile page.
2622 * It is using the CFG->profileroles to limit the list to only interesting roles.
2623 * (The permission tab has full details of user role assignments.)
2625 * @param int $userid
2626 * @param int $courseid
2627 * @return string
2629 function get_user_roles_in_course($userid, $courseid) {
2630 global $CFG, $DB;
2631 if ($courseid == SITEID) {
2632 $context = context_system::instance();
2633 } else {
2634 $context = context_course::instance($courseid);
2636 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2637 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2638 if (has_capability('moodle/role:assign', $context)) {
2639 $rolesinscope = array_keys(get_all_roles($context));
2640 } else {
2641 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2643 if (empty($rolesinscope)) {
2644 return '';
2647 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2648 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2649 $params = array_merge($params, $cparams);
2651 if ($coursecontext = $context->get_course_context(false)) {
2652 $params['coursecontext'] = $coursecontext->id;
2653 } else {
2654 $params['coursecontext'] = 0;
2657 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2658 FROM {role_assignments} ra, {role} r
2659 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2660 WHERE r.id = ra.roleid
2661 AND ra.contextid $contextlist
2662 AND r.id $rallowed
2663 AND ra.userid = :userid
2664 ORDER BY r.sortorder ASC";
2665 $params['userid'] = $userid;
2667 $rolestring = '';
2669 if ($roles = $DB->get_records_sql($sql, $params)) {
2670 $viewableroles = get_viewable_roles($context, $userid);
2672 $rolenames = array();
2673 foreach ($roles as $roleid => $unused) {
2674 if (isset($viewableroles[$roleid])) {
2675 $url = new moodle_url('/user/index.php', ['contextid' => $context->id, 'roleid' => $roleid]);
2676 $rolenames[] = '<a href="' . $url . '">' . $viewableroles[$roleid] . '</a>';
2679 $rolestring = implode(',', $rolenames);
2682 return $rolestring;
2686 * Checks if a user can assign users to a particular role in this context
2688 * @param context $context
2689 * @param int $targetroleid - the id of the role you want to assign users to
2690 * @return boolean
2692 function user_can_assign(context $context, $targetroleid) {
2693 global $DB;
2695 // First check to see if the user is a site administrator.
2696 if (is_siteadmin()) {
2697 return true;
2700 // Check if user has override capability.
2701 // If not return false.
2702 if (!has_capability('moodle/role:assign', $context)) {
2703 return false;
2705 // pull out all active roles of this user from this context(or above)
2706 if ($userroles = get_user_roles($context)) {
2707 foreach ($userroles as $userrole) {
2708 // if any in the role_allow_override table, then it's ok
2709 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2710 return true;
2715 return false;
2719 * Returns all site roles in correct sort order.
2721 * Note: this method does not localise role names or descriptions,
2722 * use role_get_names() if you need role names.
2724 * @param context $context optional context for course role name aliases
2725 * @return array of role records with optional coursealias property
2727 function get_all_roles(context $context = null) {
2728 global $DB;
2730 if (!$context or !$coursecontext = $context->get_course_context(false)) {
2731 $coursecontext = null;
2734 if ($coursecontext) {
2735 $sql = "SELECT r.*, rn.name AS coursealias
2736 FROM {role} r
2737 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2738 ORDER BY r.sortorder ASC";
2739 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
2741 } else {
2742 return $DB->get_records('role', array(), 'sortorder ASC');
2747 * Returns roles of a specified archetype
2749 * @param string $archetype
2750 * @return array of full role records
2752 function get_archetype_roles($archetype) {
2753 global $DB;
2754 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2758 * Gets all the user roles assigned in this context, or higher contexts for a list of users.
2760 * If you try using the combination $userids = [], $checkparentcontexts = true then this is likely
2761 * to cause an out-of-memory error on large Moodle sites, so this combination is deprecated and
2762 * outputs a warning, even though it is the default.
2764 * @param context $context
2765 * @param array $userids. An empty list means fetch all role assignments for the context.
2766 * @param bool $checkparentcontexts defaults to true
2767 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2768 * @return array
2770 function get_users_roles(context $context, $userids = [], $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2771 global $DB;
2773 if (!$userids && $checkparentcontexts) {
2774 debugging('Please do not call get_users_roles() with $checkparentcontexts = true ' .
2775 'and $userids array not set. This combination causes large Moodle sites ' .
2776 'with lots of site-wide role assignemnts to run out of memory.', DEBUG_DEVELOPER);
2779 if ($checkparentcontexts) {
2780 $contextids = $context->get_parent_context_ids();
2781 } else {
2782 $contextids = array();
2784 $contextids[] = $context->id;
2786 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
2788 // If userids was passed as an empty array, we fetch all role assignments for the course.
2789 if (empty($userids)) {
2790 $useridlist = ' IS NOT NULL ';
2791 $uparams = [];
2792 } else {
2793 list($useridlist, $uparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'uids');
2796 $sql = "SELECT ra.*, r.name, r.shortname, ra.userid
2797 FROM {role_assignments} ra, {role} r, {context} c
2798 WHERE ra.userid $useridlist
2799 AND ra.roleid = r.id
2800 AND ra.contextid = c.id
2801 AND ra.contextid $contextids
2802 ORDER BY $order";
2804 $all = $DB->get_records_sql($sql , array_merge($params, $uparams));
2806 // Return results grouped by userid.
2807 $result = [];
2808 foreach ($all as $id => $record) {
2809 if (!isset($result[$record->userid])) {
2810 $result[$record->userid] = [];
2812 $result[$record->userid][$record->id] = $record;
2815 // Make sure all requested users are included in the result, even if they had no role assignments.
2816 foreach ($userids as $id) {
2817 if (!isset($result[$id])) {
2818 $result[$id] = [];
2822 return $result;
2827 * Gets all the user roles assigned in this context, or higher contexts
2828 * this is mainly used when checking if a user can assign a role, or overriding a role
2829 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2830 * allow_override tables
2832 * @param context $context
2833 * @param int $userid
2834 * @param bool $checkparentcontexts defaults to true
2835 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2836 * @return array
2838 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2839 global $USER, $DB;
2841 if (empty($userid)) {
2842 if (empty($USER->id)) {
2843 return array();
2845 $userid = $USER->id;
2848 if ($checkparentcontexts) {
2849 $contextids = $context->get_parent_context_ids();
2850 } else {
2851 $contextids = array();
2853 $contextids[] = $context->id;
2855 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2857 array_unshift($params, $userid);
2859 $sql = "SELECT ra.*, r.name, r.shortname
2860 FROM {role_assignments} ra, {role} r, {context} c
2861 WHERE ra.userid = ?
2862 AND ra.roleid = r.id
2863 AND ra.contextid = c.id
2864 AND ra.contextid $contextids
2865 ORDER BY $order";
2867 return $DB->get_records_sql($sql ,$params);
2871 * Like get_user_roles, but adds in the authenticated user role, and the front
2872 * page roles, if applicable.
2874 * @param context $context the context.
2875 * @param int $userid optional. Defaults to $USER->id
2876 * @return array of objects with fields ->userid, ->contextid and ->roleid.
2878 function get_user_roles_with_special(context $context, $userid = 0) {
2879 global $CFG, $USER;
2881 if (empty($userid)) {
2882 if (empty($USER->id)) {
2883 return array();
2885 $userid = $USER->id;
2888 $ras = get_user_roles($context, $userid);
2890 // Add front-page role if relevant.
2891 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2892 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
2893 is_inside_frontpage($context);
2894 if ($defaultfrontpageroleid && $isfrontpage) {
2895 $frontpagecontext = context_course::instance(SITEID);
2896 $ra = new stdClass();
2897 $ra->userid = $userid;
2898 $ra->contextid = $frontpagecontext->id;
2899 $ra->roleid = $defaultfrontpageroleid;
2900 $ras[] = $ra;
2903 // Add authenticated user role if relevant.
2904 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2905 if ($defaultuserroleid && !isguestuser($userid)) {
2906 $systemcontext = context_system::instance();
2907 $ra = new stdClass();
2908 $ra->userid = $userid;
2909 $ra->contextid = $systemcontext->id;
2910 $ra->roleid = $defaultuserroleid;
2911 $ras[] = $ra;
2914 return $ras;
2918 * Creates a record in the role_allow_override table
2920 * @param int $fromroleid source roleid
2921 * @param int $targetroleid target roleid
2922 * @return void
2924 function core_role_set_override_allowed($fromroleid, $targetroleid) {
2925 global $DB;
2927 $record = new stdClass();
2928 $record->roleid = $fromroleid;
2929 $record->allowoverride = $targetroleid;
2930 $DB->insert_record('role_allow_override', $record);
2934 * Creates a record in the role_allow_assign table
2936 * @param int $fromroleid source roleid
2937 * @param int $targetroleid target roleid
2938 * @return void
2940 function core_role_set_assign_allowed($fromroleid, $targetroleid) {
2941 global $DB;
2943 $record = new stdClass();
2944 $record->roleid = $fromroleid;
2945 $record->allowassign = $targetroleid;
2946 $DB->insert_record('role_allow_assign', $record);
2950 * Creates a record in the role_allow_switch table
2952 * @param int $fromroleid source roleid
2953 * @param int $targetroleid target roleid
2954 * @return void
2956 function core_role_set_switch_allowed($fromroleid, $targetroleid) {
2957 global $DB;
2959 $record = new stdClass();
2960 $record->roleid = $fromroleid;
2961 $record->allowswitch = $targetroleid;
2962 $DB->insert_record('role_allow_switch', $record);
2966 * Creates a record in the role_allow_view table
2968 * @param int $fromroleid source roleid
2969 * @param int $targetroleid target roleid
2970 * @return void
2972 function core_role_set_view_allowed($fromroleid, $targetroleid) {
2973 global $DB;
2975 $record = new stdClass();
2976 $record->roleid = $fromroleid;
2977 $record->allowview = $targetroleid;
2978 $DB->insert_record('role_allow_view', $record);
2982 * Gets a list of roles that this user can assign in this context
2984 * @param context $context the context.
2985 * @param int $rolenamedisplay the type of role name to display. One of the
2986 * ROLENAME_X constants. Default ROLENAME_ALIAS.
2987 * @param bool $withusercounts if true, count the number of users with each role.
2988 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
2989 * @return array if $withusercounts is false, then an array $roleid => $rolename.
2990 * if $withusercounts is true, returns a list of three arrays,
2991 * $rolenames, $rolecounts, and $nameswithcounts.
2993 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
2994 global $USER, $DB;
2996 // make sure there is a real user specified
2997 if ($user === null) {
2998 $userid = isset($USER->id) ? $USER->id : 0;
2999 } else {
3000 $userid = is_object($user) ? $user->id : $user;
3003 if (!has_capability('moodle/role:assign', $context, $userid)) {
3004 if ($withusercounts) {
3005 return array(array(), array(), array());
3006 } else {
3007 return array();
3011 $params = array();
3012 $extrafields = '';
3014 if ($withusercounts) {
3015 $extrafields = ', (SELECT count(u.id)
3016 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3017 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3018 ) AS usercount';
3019 $params['conid'] = $context->id;
3022 if (is_siteadmin($userid)) {
3023 // show all roles allowed in this context to admins
3024 $assignrestriction = "";
3025 } else {
3026 $parents = $context->get_parent_context_ids(true);
3027 $contexts = implode(',' , $parents);
3028 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3029 FROM {role_allow_assign} raa
3030 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3031 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3032 ) ar ON ar.id = r.id";
3033 $params['userid'] = $userid;
3035 $params['contextlevel'] = $context->contextlevel;
3037 if ($coursecontext = $context->get_course_context(false)) {
3038 $params['coursecontext'] = $coursecontext->id;
3039 } else {
3040 $params['coursecontext'] = 0; // no course aliases
3041 $coursecontext = null;
3043 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3044 FROM {role} r
3045 $assignrestriction
3046 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3047 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3048 ORDER BY r.sortorder ASC";
3049 $roles = $DB->get_records_sql($sql, $params);
3051 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3053 if (!$withusercounts) {
3054 return $rolenames;
3057 $rolecounts = array();
3058 $nameswithcounts = array();
3059 foreach ($roles as $role) {
3060 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3061 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3063 return array($rolenames, $rolecounts, $nameswithcounts);
3067 * Gets a list of roles that this user can switch to in a context
3069 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3070 * This function just process the contents of the role_allow_switch table. You also need to
3071 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3073 * @param context $context a context.
3074 * @return array an array $roleid => $rolename.
3076 function get_switchable_roles(context $context) {
3077 global $USER, $DB;
3079 // You can't switch roles without this capability.
3080 if (!has_capability('moodle/role:switchroles', $context)) {
3081 return [];
3084 $params = array();
3085 $extrajoins = '';
3086 $extrawhere = '';
3087 if (!is_siteadmin()) {
3088 // Admins are allowed to switch to any role with.
3089 // Others are subject to the additional constraint that the switch-to role must be allowed by
3090 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3091 $parents = $context->get_parent_context_ids(true);
3092 $contexts = implode(',' , $parents);
3094 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3095 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3096 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3097 $params['userid'] = $USER->id;
3100 if ($coursecontext = $context->get_course_context(false)) {
3101 $params['coursecontext'] = $coursecontext->id;
3102 } else {
3103 $params['coursecontext'] = 0; // no course aliases
3104 $coursecontext = null;
3107 $query = "
3108 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3109 FROM (SELECT DISTINCT rc.roleid
3110 FROM {role_capabilities} rc
3111 $extrajoins
3112 $extrawhere) idlist
3113 JOIN {role} r ON r.id = idlist.roleid
3114 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3115 ORDER BY r.sortorder";
3116 $roles = $DB->get_records_sql($query, $params);
3118 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3122 * Gets a list of roles that this user can view in a context
3124 * @param context $context a context.
3125 * @param int $userid id of user.
3126 * @return array an array $roleid => $rolename.
3128 function get_viewable_roles(context $context, $userid = null) {
3129 global $USER, $DB;
3131 if ($userid == null) {
3132 $userid = $USER->id;
3135 $params = array();
3136 $extrajoins = '';
3137 $extrawhere = '';
3138 if (!is_siteadmin()) {
3139 // Admins are allowed to view any role.
3140 // Others are subject to the additional constraint that the view role must be allowed by
3141 // 'role_allow_view' for some role they have assigned in this context or any parent.
3142 $contexts = $context->get_parent_context_ids(true);
3143 list($insql, $inparams) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED);
3145 $extrajoins = "JOIN {role_allow_view} ras ON ras.allowview = r.id
3146 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3147 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid $insql";
3149 $params += $inparams;
3150 $params['userid'] = $userid;
3153 if ($coursecontext = $context->get_course_context(false)) {
3154 $params['coursecontext'] = $coursecontext->id;
3155 } else {
3156 $params['coursecontext'] = 0; // No course aliases.
3157 $coursecontext = null;
3160 $query = "
3161 SELECT r.id, r.name, r.shortname, rn.name AS coursealias, r.sortorder
3162 FROM {role} r
3163 $extrajoins
3164 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3165 $extrawhere
3166 GROUP BY r.id, r.name, r.shortname, rn.name, r.sortorder
3167 ORDER BY r.sortorder";
3168 $roles = $DB->get_records_sql($query, $params);
3170 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3174 * Gets a list of roles that this user can override in this context.
3176 * @param context $context the context.
3177 * @param int $rolenamedisplay the type of role name to display. One of the
3178 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3179 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3180 * @return array if $withcounts is false, then an array $roleid => $rolename.
3181 * if $withusercounts is true, returns a list of three arrays,
3182 * $rolenames, $rolecounts, and $nameswithcounts.
3184 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3185 global $USER, $DB;
3187 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3188 if ($withcounts) {
3189 return array(array(), array(), array());
3190 } else {
3191 return array();
3195 $parents = $context->get_parent_context_ids(true);
3196 $contexts = implode(',' , $parents);
3198 $params = array();
3199 $extrafields = '';
3201 $params['userid'] = $USER->id;
3202 if ($withcounts) {
3203 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3204 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3205 $params['conid'] = $context->id;
3208 if ($coursecontext = $context->get_course_context(false)) {
3209 $params['coursecontext'] = $coursecontext->id;
3210 } else {
3211 $params['coursecontext'] = 0; // no course aliases
3212 $coursecontext = null;
3215 if (is_siteadmin()) {
3216 // show all roles to admins
3217 $roles = $DB->get_records_sql("
3218 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3219 FROM {role} ro
3220 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3221 ORDER BY ro.sortorder ASC", $params);
3223 } else {
3224 $roles = $DB->get_records_sql("
3225 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3226 FROM {role} ro
3227 JOIN (SELECT DISTINCT r.id
3228 FROM {role} r
3229 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3230 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3231 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3232 ) inline_view ON ro.id = inline_view.id
3233 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3234 ORDER BY ro.sortorder ASC", $params);
3237 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3239 if (!$withcounts) {
3240 return $rolenames;
3243 $rolecounts = array();
3244 $nameswithcounts = array();
3245 foreach ($roles as $role) {
3246 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3247 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3249 return array($rolenames, $rolecounts, $nameswithcounts);
3253 * Create a role menu suitable for default role selection in enrol plugins.
3255 * @package core_enrol
3257 * @param context $context
3258 * @param int $addroleid current or default role - always added to list
3259 * @return array roleid=>localised role name
3261 function get_default_enrol_roles(context $context, $addroleid = null) {
3262 global $DB;
3264 $params = array('contextlevel'=>CONTEXT_COURSE);
3266 if ($coursecontext = $context->get_course_context(false)) {
3267 $params['coursecontext'] = $coursecontext->id;
3268 } else {
3269 $params['coursecontext'] = 0; // no course names
3270 $coursecontext = null;
3273 if ($addroleid) {
3274 $addrole = "OR r.id = :addroleid";
3275 $params['addroleid'] = $addroleid;
3276 } else {
3277 $addrole = "";
3280 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3281 FROM {role} r
3282 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3283 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3284 WHERE rcl.id IS NOT NULL $addrole
3285 ORDER BY sortorder DESC";
3287 $roles = $DB->get_records_sql($sql, $params);
3289 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3293 * Return context levels where this role is assignable.
3295 * @param integer $roleid the id of a role.
3296 * @return array list of the context levels at which this role may be assigned.
3298 function get_role_contextlevels($roleid) {
3299 global $DB;
3300 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3301 'contextlevel', 'id,contextlevel');
3305 * Return roles suitable for assignment at the specified context level.
3307 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3309 * @param integer $contextlevel a contextlevel.
3310 * @return array list of role ids that are assignable at this context level.
3312 function get_roles_for_contextlevels($contextlevel) {
3313 global $DB;
3314 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3315 '', 'id,roleid');
3319 * Returns default context levels where roles can be assigned.
3321 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3322 * from the array returned by get_role_archetypes();
3323 * @return array list of the context levels at which this type of role may be assigned by default.
3325 function get_default_contextlevels($rolearchetype) {
3326 static $defaults = array(
3327 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3328 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3329 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3330 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3331 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3332 'guest' => array(),
3333 'user' => array(),
3334 'frontpage' => array());
3336 if (isset($defaults[$rolearchetype])) {
3337 return $defaults[$rolearchetype];
3338 } else {
3339 return array();
3344 * Set the context levels at which a particular role can be assigned.
3345 * Throws exceptions in case of error.
3347 * @param integer $roleid the id of a role.
3348 * @param array $contextlevels the context levels at which this role should be assignable,
3349 * duplicate levels are removed.
3350 * @return void
3352 function set_role_contextlevels($roleid, array $contextlevels) {
3353 global $DB;
3354 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3355 $rcl = new stdClass();
3356 $rcl->roleid = $roleid;
3357 $contextlevels = array_unique($contextlevels);
3358 foreach ($contextlevels as $level) {
3359 $rcl->contextlevel = $level;
3360 $DB->insert_record('role_context_levels', $rcl, false, true);
3365 * Who has this capability in this context?
3367 * This can be a very expensive call - use sparingly and keep
3368 * the results if you are going to need them again soon.
3370 * Note if $fields is empty this function attempts to get u.*
3371 * which can get rather large - and has a serious perf impact
3372 * on some DBs.
3374 * @param context $context
3375 * @param string|array $capability - capability name(s)
3376 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3377 * @param string $sort - the sort order. Default is lastaccess time.
3378 * @param mixed $limitfrom - number of records to skip (offset)
3379 * @param mixed $limitnum - number of records to fetch
3380 * @param string|array $groups - single group or array of groups - only return
3381 * users who are in one of these group(s).
3382 * @param string|array $exceptions - list of users to exclude, comma separated or array
3383 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3384 * @param bool $view_ignored - use get_enrolled_sql() instead
3385 * @param bool $useviewallgroups if $groups is set the return users who
3386 * have capability both $capability and moodle/site:accessallgroups
3387 * in this context, as well as users who have $capability and who are
3388 * in $groups.
3389 * @return array of user records
3391 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3392 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3393 global $CFG, $DB;
3395 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3396 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3398 $ctxids = trim($context->path, '/');
3399 $ctxids = str_replace('/', ',', $ctxids);
3401 // Context is the frontpage
3402 $iscoursepage = false; // coursepage other than fp
3403 $isfrontpage = false;
3404 if ($context->contextlevel == CONTEXT_COURSE) {
3405 if ($context->instanceid == SITEID) {
3406 $isfrontpage = true;
3407 } else {
3408 $iscoursepage = true;
3411 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3413 $caps = (array)$capability;
3415 // construct list of context paths bottom-->top
3416 list($contextids, $paths) = get_context_info_list($context);
3418 // we need to find out all roles that have these capabilities either in definition or in overrides
3419 $defs = array();
3420 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3421 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3422 $params = array_merge($params, $params2);
3423 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3424 FROM {role_capabilities} rc
3425 JOIN {context} ctx on rc.contextid = ctx.id
3426 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3428 $rcs = $DB->get_records_sql($sql, $params);
3429 foreach ($rcs as $rc) {
3430 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3433 // go through the permissions bottom-->top direction to evaluate the current permission,
3434 // first one wins (prohibit is an exception that always wins)
3435 $access = array();
3436 foreach ($caps as $cap) {
3437 foreach ($paths as $path) {
3438 if (empty($defs[$cap][$path])) {
3439 continue;
3441 foreach($defs[$cap][$path] as $roleid => $perm) {
3442 if ($perm == CAP_PROHIBIT) {
3443 $access[$cap][$roleid] = CAP_PROHIBIT;
3444 continue;
3446 if (!isset($access[$cap][$roleid])) {
3447 $access[$cap][$roleid] = (int)$perm;
3453 // make lists of roles that are needed and prohibited in this context
3454 $needed = array(); // one of these is enough
3455 $prohibited = array(); // must not have any of these
3456 foreach ($caps as $cap) {
3457 if (empty($access[$cap])) {
3458 continue;
3460 foreach ($access[$cap] as $roleid => $perm) {
3461 if ($perm == CAP_PROHIBIT) {
3462 unset($needed[$cap][$roleid]);
3463 $prohibited[$cap][$roleid] = true;
3464 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3465 $needed[$cap][$roleid] = true;
3468 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3469 // easy, nobody has the permission
3470 unset($needed[$cap]);
3471 unset($prohibited[$cap]);
3472 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3473 // everybody is disqualified on the frontpage
3474 unset($needed[$cap]);
3475 unset($prohibited[$cap]);
3477 if (empty($prohibited[$cap])) {
3478 unset($prohibited[$cap]);
3482 if (empty($needed)) {
3483 // there can not be anybody if no roles match this request
3484 return array();
3487 if (empty($prohibited)) {
3488 // we can compact the needed roles
3489 $n = array();
3490 foreach ($needed as $cap) {
3491 foreach ($cap as $roleid=>$unused) {
3492 $n[$roleid] = true;
3495 $needed = array('any'=>$n);
3496 unset($n);
3499 // ***** Set up default fields ******
3500 if (empty($fields)) {
3501 if ($iscoursepage) {
3502 $fields = 'u.*, ul.timeaccess AS lastaccess';
3503 } else {
3504 $fields = 'u.*';
3506 } else {
3507 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3508 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3512 // Set up default sort
3513 if (empty($sort)) { // default to course lastaccess or just lastaccess
3514 if ($iscoursepage) {
3515 $sort = 'ul.timeaccess';
3516 } else {
3517 $sort = 'u.lastaccess';
3521 // Prepare query clauses
3522 $wherecond = array();
3523 $params = array();
3524 $joins = array();
3526 // User lastaccess JOIN
3527 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3528 // user_lastaccess is not required MDL-13810
3529 } else {
3530 if ($iscoursepage) {
3531 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3532 } else {
3533 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3537 // We never return deleted users or guest account.
3538 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3539 $params['guestid'] = $CFG->siteguest;
3541 // Groups
3542 if ($groups) {
3543 $groups = (array)$groups;
3544 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3545 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3546 $params = array_merge($params, $grpparams);
3548 if ($useviewallgroups) {
3549 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3550 if (!empty($viewallgroupsusers)) {
3551 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3552 } else {
3553 $wherecond[] = "($grouptest)";
3555 } else {
3556 $wherecond[] = "($grouptest)";
3560 // User exceptions
3561 if (!empty($exceptions)) {
3562 $exceptions = (array)$exceptions;
3563 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3564 $params = array_merge($params, $exparams);
3565 $wherecond[] = "u.id $exsql";
3568 // now add the needed and prohibited roles conditions as joins
3569 if (!empty($needed['any'])) {
3570 // simple case - there are no prohibits involved
3571 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3572 // everybody
3573 } else {
3574 $joins[] = "JOIN (SELECT DISTINCT userid
3575 FROM {role_assignments}
3576 WHERE contextid IN ($ctxids)
3577 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3578 ) ra ON ra.userid = u.id";
3580 } else {
3581 $unions = array();
3582 $everybody = false;
3583 foreach ($needed as $cap=>$unused) {
3584 if (empty($prohibited[$cap])) {
3585 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3586 $everybody = true;
3587 break;
3588 } else {
3589 $unions[] = "SELECT userid
3590 FROM {role_assignments}
3591 WHERE contextid IN ($ctxids)
3592 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3594 } else {
3595 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3596 // nobody can have this cap because it is prevented in default roles
3597 continue;
3599 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3600 // everybody except the prohibitted - hiding does not matter
3601 $unions[] = "SELECT id AS userid
3602 FROM {user}
3603 WHERE id NOT IN (SELECT userid
3604 FROM {role_assignments}
3605 WHERE contextid IN ($ctxids)
3606 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3608 } else {
3609 $unions[] = "SELECT userid
3610 FROM {role_assignments}
3611 WHERE contextid IN ($ctxids) AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3612 AND userid NOT IN (
3613 SELECT userid
3614 FROM {role_assignments}
3615 WHERE contextid IN ($ctxids)
3616 AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . ")
3621 if (!$everybody) {
3622 if ($unions) {
3623 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3624 } else {
3625 // only prohibits found - nobody can be matched
3626 $wherecond[] = "1 = 2";
3631 // Collect WHERE conditions and needed joins
3632 $where = implode(' AND ', $wherecond);
3633 if ($where !== '') {
3634 $where = 'WHERE ' . $where;
3636 $joins = implode("\n", $joins);
3638 // Ok, let's get the users!
3639 $sql = "SELECT $fields
3640 FROM {user} u
3641 $joins
3642 $where
3643 ORDER BY $sort";
3645 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3649 * Re-sort a users array based on a sorting policy
3651 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3652 * based on a sorting policy. This is to support the odd practice of
3653 * sorting teachers by 'authority', where authority was "lowest id of the role
3654 * assignment".
3656 * Will execute 1 database query. Only suitable for small numbers of users, as it
3657 * uses an u.id IN() clause.
3659 * Notes about the sorting criteria.
3661 * As a default, we cannot rely on role.sortorder because then
3662 * admins/coursecreators will always win. That is why the sane
3663 * rule "is locality matters most", with sortorder as 2nd
3664 * consideration.
3666 * If you want role.sortorder, use the 'sortorder' policy, and
3667 * name explicitly what roles you want to cover. It's probably
3668 * a good idea to see what roles have the capabilities you want
3669 * (array_diff() them against roiles that have 'can-do-anything'
3670 * to weed out admin-ish roles. Or fetch a list of roles from
3671 * variables like $CFG->coursecontact .
3673 * @param array $users Users array, keyed on userid
3674 * @param context $context
3675 * @param array $roles ids of the roles to include, optional
3676 * @param string $sortpolicy defaults to locality, more about
3677 * @return array sorted copy of the array
3679 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3680 global $DB;
3682 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3683 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3684 if (empty($roles)) {
3685 $roleswhere = '';
3686 } else {
3687 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3690 $sql = "SELECT ra.userid
3691 FROM {role_assignments} ra
3692 JOIN {role} r
3693 ON ra.roleid=r.id
3694 JOIN {context} ctx
3695 ON ra.contextid=ctx.id
3696 WHERE $userswhere
3697 $contextwhere
3698 $roleswhere";
3700 // Default 'locality' policy -- read PHPDoc notes
3701 // about sort policies...
3702 $orderby = 'ORDER BY '
3703 .'ctx.depth DESC, ' /* locality wins */
3704 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3705 .'ra.id'; /* role assignment order tie-breaker */
3706 if ($sortpolicy === 'sortorder') {
3707 $orderby = 'ORDER BY '
3708 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3709 .'ra.id'; /* role assignment order tie-breaker */
3712 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3713 $sortedusers = array();
3714 $seen = array();
3716 foreach ($sortedids as $id) {
3717 // Avoid duplicates
3718 if (isset($seen[$id])) {
3719 continue;
3721 $seen[$id] = true;
3723 // assign
3724 $sortedusers[$id] = $users[$id];
3726 return $sortedusers;
3730 * Gets all the users assigned this role in this context or higher
3732 * Note that moodle is based on capabilities and it is usually better
3733 * to check permissions than to check role ids as the capabilities
3734 * system is more flexible. If you really need, you can to use this
3735 * function but consider has_capability() as a possible substitute.
3737 * All $sort fields are added into $fields if not present there yet.
3739 * If $roleid is an array or is empty (all roles) you need to set $fields
3740 * (and $sort by extension) params according to it, as the first field
3741 * returned by the database should be unique (ra.id is the best candidate).
3743 * @param int $roleid (can also be an array of ints!)
3744 * @param context $context
3745 * @param bool $parent if true, get list of users assigned in higher context too
3746 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3747 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3748 * null => use default sort from users_order_by_sql.
3749 * @param bool $all true means all, false means limit to enrolled users
3750 * @param string $group defaults to ''
3751 * @param mixed $limitfrom defaults to ''
3752 * @param mixed $limitnum defaults to ''
3753 * @param string $extrawheretest defaults to ''
3754 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3755 * @return array
3757 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3758 $sort = null, $all = true, $group = '',
3759 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3760 global $DB;
3762 if (empty($fields)) {
3763 $allnames = get_all_user_name_fields(true, 'u');
3764 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
3765 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3766 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3767 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3768 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3771 // Prevent wrong function uses.
3772 if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
3773 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
3774 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
3776 if (!empty($roleid)) {
3777 // Solving partially the issue when specifying multiple roles.
3778 $users = array();
3779 foreach ($roleid as $id) {
3780 // Ignoring duplicated keys keeping the first user appearance.
3781 $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
3782 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
3784 return $users;
3788 $parentcontexts = '';
3789 if ($parent) {
3790 $parentcontexts = substr($context->path, 1); // kill leading slash
3791 $parentcontexts = str_replace('/', ',', $parentcontexts);
3792 if ($parentcontexts !== '') {
3793 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3797 if ($roleid) {
3798 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
3799 $roleselect = "AND ra.roleid $rids";
3800 } else {
3801 $params = array();
3802 $roleselect = '';
3805 if ($coursecontext = $context->get_course_context(false)) {
3806 $params['coursecontext'] = $coursecontext->id;
3807 } else {
3808 $params['coursecontext'] = 0;
3811 if ($group) {
3812 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3813 $groupselect = " AND gm.groupid = :groupid ";
3814 $params['groupid'] = $group;
3815 } else {
3816 $groupjoin = '';
3817 $groupselect = '';
3820 $params['contextid'] = $context->id;
3822 if ($extrawheretest) {
3823 $extrawheretest = ' AND ' . $extrawheretest;
3826 if ($whereorsortparams) {
3827 $params = array_merge($params, $whereorsortparams);
3830 if (!$sort) {
3831 list($sort, $sortparams) = users_order_by_sql('u');
3832 $params = array_merge($params, $sortparams);
3835 // Adding the fields from $sort that are not present in $fields.
3836 $sortarray = preg_split('/,\s*/', $sort);
3837 $fieldsarray = preg_split('/,\s*/', $fields);
3839 // Discarding aliases from the fields.
3840 $fieldnames = array();
3841 foreach ($fieldsarray as $key => $field) {
3842 list($fieldnames[$key]) = explode(' ', $field);
3845 $addedfields = array();
3846 foreach ($sortarray as $sortfield) {
3847 // Throw away any additional arguments to the sort (e.g. ASC/DESC).
3848 list($sortfield) = explode(' ', $sortfield);
3849 list($tableprefix) = explode('.', $sortfield);
3850 $fieldpresent = false;
3851 foreach ($fieldnames as $fieldname) {
3852 if ($fieldname === $sortfield || $fieldname === $tableprefix.'.*') {
3853 $fieldpresent = true;
3854 break;
3858 if (!$fieldpresent) {
3859 $fieldsarray[] = $sortfield;
3860 $addedfields[] = $sortfield;
3864 $fields = implode(', ', $fieldsarray);
3865 if (!empty($addedfields)) {
3866 $addedfields = implode(', ', $addedfields);
3867 debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
3870 if ($all === null) {
3871 // Previously null was used to indicate that parameter was not used.
3872 $all = true;
3874 if (!$all and $coursecontext) {
3875 // Do not use get_enrolled_sql() here for performance reasons.
3876 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
3877 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
3878 $params['ecourseid'] = $coursecontext->instanceid;
3879 } else {
3880 $ejoin = "";
3883 $sql = "SELECT DISTINCT $fields, ra.roleid
3884 FROM {role_assignments} ra
3885 JOIN {user} u ON u.id = ra.userid
3886 JOIN {role} r ON ra.roleid = r.id
3887 $ejoin
3888 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3889 $groupjoin
3890 WHERE (ra.contextid = :contextid $parentcontexts)
3891 $roleselect
3892 $groupselect
3893 $extrawheretest
3894 ORDER BY $sort"; // join now so that we can just use fullname() later
3896 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3900 * Counts all the users assigned this role in this context or higher
3902 * @param int|array $roleid either int or an array of ints
3903 * @param context $context
3904 * @param bool $parent if true, get list of users assigned in higher context too
3905 * @return int Returns the result count
3907 function count_role_users($roleid, context $context, $parent = false) {
3908 global $DB;
3910 if ($parent) {
3911 if ($contexts = $context->get_parent_context_ids()) {
3912 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3913 } else {
3914 $parentcontexts = '';
3916 } else {
3917 $parentcontexts = '';
3920 if ($roleid) {
3921 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3922 $roleselect = "AND r.roleid $rids";
3923 } else {
3924 $params = array();
3925 $roleselect = '';
3928 array_unshift($params, $context->id);
3930 $sql = "SELECT COUNT(DISTINCT u.id)
3931 FROM {role_assignments} r
3932 JOIN {user} u ON u.id = r.userid
3933 WHERE (r.contextid = ? $parentcontexts)
3934 $roleselect
3935 AND u.deleted = 0";
3937 return $DB->count_records_sql($sql, $params);
3941 * This function gets the list of courses that this user has a particular capability in.
3943 * It is now reasonably efficient, but bear in mind that if there are users who have the capability
3944 * everywhere, it may return an array of all courses.
3946 * @param string $capability Capability in question
3947 * @param int $userid User ID or null for current user
3948 * @param bool $doanything True if 'doanything' is permitted (default)
3949 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3950 * otherwise use a comma-separated list of the fields you require, not including id.
3951 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
3952 * @param string $orderby If set, use a comma-separated list of fields from course
3953 * table with sql modifiers (DESC) if needed
3954 * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
3955 * @return array|bool Array of courses, if none found false is returned.
3957 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '',
3958 $limit = 0) {
3959 global $DB, $USER;
3961 // Default to current user.
3962 if (!$userid) {
3963 $userid = $USER->id;
3966 if ($doanything && is_siteadmin($userid)) {
3967 // If the user is a site admin and $doanything is enabled then there is no need to restrict
3968 // the list of courses.
3969 $contextlimitsql = '';
3970 $contextlimitparams = [];
3971 } else {
3972 // Gets SQL to limit contexts ('x' table) to those where the user has this capability.
3973 list ($contextlimitsql, $contextlimitparams) = \core\access\get_user_capability_course_helper::get_sql(
3974 $userid, $capability);
3975 if (!$contextlimitsql) {
3976 // If the does not have this capability in any context, return false without querying.
3977 return false;
3980 $contextlimitsql = 'WHERE' . $contextlimitsql;
3983 // Convert fields list and ordering
3984 $fieldlist = '';
3985 if ($fieldsexceptid) {
3986 $fields = array_map('trim', explode(',', $fieldsexceptid));
3987 foreach($fields as $field) {
3988 // Context fields have a different alias.
3989 if (strpos($field, 'ctx') === 0) {
3990 switch($field) {
3991 case 'ctxlevel' :
3992 $realfield = 'contextlevel';
3993 break;
3994 case 'ctxinstance' :
3995 $realfield = 'instanceid';
3996 break;
3997 default:
3998 $realfield = substr($field, 3);
3999 break;
4001 $fieldlist .= ',x.' . $realfield . ' AS ' . $field;
4002 } else {
4003 $fieldlist .= ',c.'.$field;
4007 if ($orderby) {
4008 $fields = explode(',', $orderby);
4009 $orderby = '';
4010 foreach($fields as $field) {
4011 if ($orderby) {
4012 $orderby .= ',';
4014 $orderby .= 'c.'.$field;
4016 $orderby = 'ORDER BY '.$orderby;
4019 $courses = array();
4020 $rs = $DB->get_recordset_sql("
4021 SELECT c.id $fieldlist
4022 FROM {course} c
4023 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
4024 $contextlimitsql
4025 $orderby", array_merge([CONTEXT_COURSE], $contextlimitparams));
4026 foreach ($rs as $course) {
4027 $courses[] = $course;
4028 $limit--;
4029 if ($limit == 0) {
4030 break;
4033 $rs->close();
4034 return empty($courses) ? false : $courses;
4038 * Switches the current user to another role for the current session and only
4039 * in the given context.
4041 * The caller *must* check
4042 * - that this op is allowed
4043 * - that the requested role can be switched to in this context (use get_switchable_roles)
4044 * - that the requested role is NOT $CFG->defaultuserroleid
4046 * To "unswitch" pass 0 as the roleid.
4048 * This function *will* modify $USER->access - beware
4050 * @param integer $roleid the role to switch to.
4051 * @param context $context the context in which to perform the switch.
4052 * @return bool success or failure.
4054 function role_switch($roleid, context $context) {
4055 global $USER;
4057 // Add the ghost RA to $USER->access as $USER->access['rsw'][$path] = $roleid.
4058 // To un-switch just unset($USER->access['rsw'][$path]).
4060 // Note: it is not possible to switch to roles that do not have course:view
4062 if (!isset($USER->access)) {
4063 load_all_capabilities();
4066 // Add the switch RA
4067 if ($roleid == 0) {
4068 unset($USER->access['rsw'][$context->path]);
4069 return true;
4072 $USER->access['rsw'][$context->path] = $roleid;
4074 return true;
4078 * Checks if the user has switched roles within the given course.
4080 * Note: You can only switch roles within the course, hence it takes a course id
4081 * rather than a context. On that note Petr volunteered to implement this across
4082 * all other contexts, all requests for this should be forwarded to him ;)
4084 * @param int $courseid The id of the course to check
4085 * @return bool True if the user has switched roles within the course.
4087 function is_role_switched($courseid) {
4088 global $USER;
4089 $context = context_course::instance($courseid, MUST_EXIST);
4090 return (!empty($USER->access['rsw'][$context->path]));
4094 * Get any role that has an override on exact context
4096 * @param context $context The context to check
4097 * @return array An array of roles
4099 function get_roles_with_override_on_context(context $context) {
4100 global $DB;
4102 return $DB->get_records_sql("SELECT r.*
4103 FROM {role_capabilities} rc, {role} r
4104 WHERE rc.roleid = r.id AND rc.contextid = ?",
4105 array($context->id));
4109 * Get all capabilities for this role on this context (overrides)
4111 * @param stdClass $role
4112 * @param context $context
4113 * @return array
4115 function get_capabilities_from_role_on_context($role, context $context) {
4116 global $DB;
4118 return $DB->get_records_sql("SELECT *
4119 FROM {role_capabilities}
4120 WHERE contextid = ? AND roleid = ?",
4121 array($context->id, $role->id));
4125 * Find all user assignment of users for this role, on this context
4127 * @param stdClass $role
4128 * @param context $context
4129 * @return array
4131 function get_users_from_role_on_context($role, context $context) {
4132 global $DB;
4134 return $DB->get_records_sql("SELECT *
4135 FROM {role_assignments}
4136 WHERE contextid = ? AND roleid = ?",
4137 array($context->id, $role->id));
4141 * Simple function returning a boolean true if user has roles
4142 * in context or parent contexts, otherwise false.
4144 * @param int $userid
4145 * @param int $roleid
4146 * @param int $contextid empty means any context
4147 * @return bool
4149 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4150 global $DB;
4152 if ($contextid) {
4153 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4154 return false;
4156 $parents = $context->get_parent_context_ids(true);
4157 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4158 $params['userid'] = $userid;
4159 $params['roleid'] = $roleid;
4161 $sql = "SELECT COUNT(ra.id)
4162 FROM {role_assignments} ra
4163 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4165 $count = $DB->get_field_sql($sql, $params);
4166 return ($count > 0);
4168 } else {
4169 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4174 * Get localised role name or alias if exists and format the text.
4176 * @param stdClass $role role object
4177 * - optional 'coursealias' property should be included for performance reasons if course context used
4178 * - description property is not required here
4179 * @param context|bool $context empty means system context
4180 * @param int $rolenamedisplay type of role name
4181 * @return string localised role name or course role name alias
4183 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4184 global $DB;
4186 if ($rolenamedisplay == ROLENAME_SHORT) {
4187 return $role->shortname;
4190 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4191 $coursecontext = null;
4194 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4195 $role = clone($role); // Do not modify parameters.
4196 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4197 $role->coursealias = $r->name;
4198 } else {
4199 $role->coursealias = null;
4203 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4204 if ($coursecontext) {
4205 return $role->coursealias;
4206 } else {
4207 return null;
4211 if (trim($role->name) !== '') {
4212 // For filtering always use context where was the thing defined - system for roles here.
4213 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4215 } else {
4216 // Empty role->name means we want to see localised role name based on shortname,
4217 // only default roles are supposed to be localised.
4218 switch ($role->shortname) {
4219 case 'manager': $original = get_string('manager', 'role'); break;
4220 case 'coursecreator': $original = get_string('coursecreators'); break;
4221 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4222 case 'teacher': $original = get_string('noneditingteacher'); break;
4223 case 'student': $original = get_string('defaultcoursestudent'); break;
4224 case 'guest': $original = get_string('guest'); break;
4225 case 'user': $original = get_string('authenticateduser'); break;
4226 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4227 // We should not get here, the role UI should require the name for custom roles!
4228 default: $original = $role->shortname; break;
4232 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4233 return $original;
4236 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4237 return "$original ($role->shortname)";
4240 if ($rolenamedisplay == ROLENAME_ALIAS) {
4241 if ($coursecontext and trim($role->coursealias) !== '') {
4242 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4243 } else {
4244 return $original;
4248 if ($rolenamedisplay == ROLENAME_BOTH) {
4249 if ($coursecontext and trim($role->coursealias) !== '') {
4250 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4251 } else {
4252 return $original;
4256 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4260 * Returns localised role description if available.
4261 * If the name is empty it tries to find the default role name using
4262 * hardcoded list of default role names or other methods in the future.
4264 * @param stdClass $role
4265 * @return string localised role name
4267 function role_get_description(stdClass $role) {
4268 if (!html_is_blank($role->description)) {
4269 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4272 switch ($role->shortname) {
4273 case 'manager': return get_string('managerdescription', 'role');
4274 case 'coursecreator': return get_string('coursecreatorsdescription');
4275 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4276 case 'teacher': return get_string('noneditingteacherdescription');
4277 case 'student': return get_string('defaultcoursestudentdescription');
4278 case 'guest': return get_string('guestdescription');
4279 case 'user': return get_string('authenticateduserdescription');
4280 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4281 default: return '';
4286 * Get all the localised role names for a context.
4288 * In new installs default roles have empty names, this function
4289 * add localised role names using current language pack.
4291 * @param context $context the context, null means system context
4292 * @param array of role objects with a ->localname field containing the context-specific role name.
4293 * @param int $rolenamedisplay
4294 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4295 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4297 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4298 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4302 * Prepare list of roles for display, apply aliases and localise default role names.
4304 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4305 * @param context $context the context, null means system context
4306 * @param int $rolenamedisplay
4307 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4308 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4310 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4311 global $DB;
4313 if (empty($roleoptions)) {
4314 return array();
4317 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4318 $coursecontext = null;
4321 // We usually need all role columns...
4322 $first = reset($roleoptions);
4323 if ($returnmenu === null) {
4324 $returnmenu = !is_object($first);
4327 if (!is_object($first) or !property_exists($first, 'shortname')) {
4328 $allroles = get_all_roles($context);
4329 foreach ($roleoptions as $rid => $unused) {
4330 $roleoptions[$rid] = $allroles[$rid];
4334 // Inject coursealias if necessary.
4335 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4336 $first = reset($roleoptions);
4337 if (!property_exists($first, 'coursealias')) {
4338 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4339 foreach ($aliasnames as $alias) {
4340 if (isset($roleoptions[$alias->roleid])) {
4341 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4347 // Add localname property.
4348 foreach ($roleoptions as $rid => $role) {
4349 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4352 if (!$returnmenu) {
4353 return $roleoptions;
4356 $menu = array();
4357 foreach ($roleoptions as $rid => $role) {
4358 $menu[$rid] = $role->localname;
4361 return $menu;
4365 * Aids in detecting if a new line is required when reading a new capability
4367 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4368 * when we read in a new capability.
4369 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4370 * but when we are in grade, all reports/import/export capabilities should be together
4372 * @param string $cap component string a
4373 * @param string $comp component string b
4374 * @param int $contextlevel
4375 * @return bool whether 2 component are in different "sections"
4377 function component_level_changed($cap, $comp, $contextlevel) {
4379 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4380 $compsa = explode('/', $cap->component);
4381 $compsb = explode('/', $comp);
4383 // list of system reports
4384 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4385 return false;
4388 // we are in gradebook, still
4389 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4390 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4391 return false;
4394 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4395 return false;
4399 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4403 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4404 * and return an array of roleids in order.
4406 * @param array $allroles array of roles, as returned by get_all_roles();
4407 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4409 function fix_role_sortorder($allroles) {
4410 global $DB;
4412 $rolesort = array();
4413 $i = 0;
4414 foreach ($allroles as $role) {
4415 $rolesort[$i] = $role->id;
4416 if ($role->sortorder != $i) {
4417 $r = new stdClass();
4418 $r->id = $role->id;
4419 $r->sortorder = $i;
4420 $DB->update_record('role', $r);
4421 $allroles[$role->id]->sortorder = $i;
4423 $i++;
4425 return $rolesort;
4429 * Switch the sort order of two roles (used in admin/roles/manage.php).
4431 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4432 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4433 * @return boolean success or failure
4435 function switch_roles($first, $second) {
4436 global $DB;
4437 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4438 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4439 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4440 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4441 return $result;
4445 * Duplicates all the base definitions of a role
4447 * @param stdClass $sourcerole role to copy from
4448 * @param int $targetrole id of role to copy to
4450 function role_cap_duplicate($sourcerole, $targetrole) {
4451 global $DB;
4453 $systemcontext = context_system::instance();
4454 $caps = $DB->get_records_sql("SELECT *
4455 FROM {role_capabilities}
4456 WHERE roleid = ? AND contextid = ?",
4457 array($sourcerole->id, $systemcontext->id));
4458 // adding capabilities
4459 foreach ($caps as $cap) {
4460 unset($cap->id);
4461 $cap->roleid = $targetrole;
4462 $DB->insert_record('role_capabilities', $cap);
4465 // Reset any cache of this role, including MUC.
4466 accesslib_clear_role_cache($targetrole);
4470 * Returns two lists, this can be used to find out if user has capability.
4471 * Having any needed role and no forbidden role in this context means
4472 * user has this capability in this context.
4473 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4475 * @param stdClass $context
4476 * @param string $capability
4477 * @return array($neededroles, $forbiddenroles)
4479 function get_roles_with_cap_in_context($context, $capability) {
4480 global $DB;
4482 $ctxids = trim($context->path, '/'); // kill leading slash
4483 $ctxids = str_replace('/', ',', $ctxids);
4485 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4486 FROM {role_capabilities} rc
4487 JOIN {context} ctx ON ctx.id = rc.contextid
4488 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4489 ORDER BY rc.roleid ASC, ctx.depth DESC";
4490 $params = array('cap'=>$capability);
4492 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4493 // no cap definitions --> no capability
4494 return array(array(), array());
4497 $forbidden = array();
4498 $needed = array();
4499 foreach($capdefs as $def) {
4500 if (isset($forbidden[$def->roleid])) {
4501 continue;
4503 if ($def->permission == CAP_PROHIBIT) {
4504 $forbidden[$def->roleid] = $def->roleid;
4505 unset($needed[$def->roleid]);
4506 continue;
4508 if (!isset($needed[$def->roleid])) {
4509 if ($def->permission == CAP_ALLOW) {
4510 $needed[$def->roleid] = true;
4511 } else if ($def->permission == CAP_PREVENT) {
4512 $needed[$def->roleid] = false;
4516 unset($capdefs);
4518 // remove all those roles not allowing
4519 foreach($needed as $key=>$value) {
4520 if (!$value) {
4521 unset($needed[$key]);
4522 } else {
4523 $needed[$key] = $key;
4527 return array($needed, $forbidden);
4531 * Returns an array of role IDs that have ALL of the the supplied capabilities
4532 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4534 * @param stdClass $context
4535 * @param array $capabilities An array of capabilities
4536 * @return array of roles with all of the required capabilities
4538 function get_roles_with_caps_in_context($context, $capabilities) {
4539 $neededarr = array();
4540 $forbiddenarr = array();
4541 foreach($capabilities as $caprequired) {
4542 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4545 $rolesthatcanrate = array();
4546 if (!empty($neededarr)) {
4547 foreach ($neededarr as $needed) {
4548 if (empty($rolesthatcanrate)) {
4549 $rolesthatcanrate = $needed;
4550 } else {
4551 //only want roles that have all caps
4552 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4556 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4557 foreach ($forbiddenarr as $forbidden) {
4558 //remove any roles that are forbidden any of the caps
4559 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4562 return $rolesthatcanrate;
4566 * Returns an array of role names that have ALL of the the supplied capabilities
4567 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4569 * @param stdClass $context
4570 * @param array $capabilities An array of capabilities
4571 * @return array of roles with all of the required capabilities
4573 function get_role_names_with_caps_in_context($context, $capabilities) {
4574 global $DB;
4576 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4577 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4579 $roles = array();
4580 foreach ($rolesthatcanrate as $r) {
4581 $roles[$r] = $allroles[$r];
4584 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4588 * This function verifies the prohibit comes from this context
4589 * and there are no more prohibits in parent contexts.
4591 * @param int $roleid
4592 * @param context $context
4593 * @param string $capability name
4594 * @return bool
4596 function prohibit_is_removable($roleid, context $context, $capability) {
4597 global $DB;
4599 $ctxids = trim($context->path, '/'); // kill leading slash
4600 $ctxids = str_replace('/', ',', $ctxids);
4602 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4604 $sql = "SELECT ctx.id
4605 FROM {role_capabilities} rc
4606 JOIN {context} ctx ON ctx.id = rc.contextid
4607 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4608 ORDER BY ctx.depth DESC";
4610 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4611 // no prohibits == nothing to remove
4612 return true;
4615 if (count($prohibits) > 1) {
4616 // more prohibits can not be removed
4617 return false;
4620 return !empty($prohibits[$context->id]);
4624 * More user friendly role permission changing,
4625 * it should produce as few overrides as possible.
4627 * @param int $roleid
4628 * @param stdClass $context
4629 * @param string $capname capability name
4630 * @param int $permission
4631 * @return void
4633 function role_change_permission($roleid, $context, $capname, $permission) {
4634 global $DB;
4636 if ($permission == CAP_INHERIT) {
4637 unassign_capability($capname, $roleid, $context->id);
4638 return;
4641 $ctxids = trim($context->path, '/'); // kill leading slash
4642 $ctxids = str_replace('/', ',', $ctxids);
4644 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4646 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4647 FROM {role_capabilities} rc
4648 JOIN {context} ctx ON ctx.id = rc.contextid
4649 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4650 ORDER BY ctx.depth DESC";
4652 if ($existing = $DB->get_records_sql($sql, $params)) {
4653 foreach($existing as $e) {
4654 if ($e->permission == CAP_PROHIBIT) {
4655 // prohibit can not be overridden, no point in changing anything
4656 return;
4659 $lowest = array_shift($existing);
4660 if ($lowest->permission == $permission) {
4661 // permission already set in this context or parent - nothing to do
4662 return;
4664 if ($existing) {
4665 $parent = array_shift($existing);
4666 if ($parent->permission == $permission) {
4667 // permission already set in parent context or parent - just unset in this context
4668 // we do this because we want as few overrides as possible for performance reasons
4669 unassign_capability($capname, $roleid, $context->id);
4670 return;
4674 } else {
4675 if ($permission == CAP_PREVENT) {
4676 // nothing means role does not have permission
4677 return;
4681 // assign the needed capability
4682 assign_capability($capname, $permission, $roleid, $context->id, true);
4687 * Basic moodle context abstraction class.
4689 * Google confirms that no other important framework is using "context" class,
4690 * we could use something else like mcontext or moodle_context, but we need to type
4691 * this very often which would be annoying and it would take too much space...
4693 * This class is derived from stdClass for backwards compatibility with
4694 * odl $context record that was returned from DML $DB->get_record()
4696 * @package core_access
4697 * @category access
4698 * @copyright Petr Skoda {@link http://skodak.org}
4699 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4700 * @since Moodle 2.2
4702 * @property-read int $id context id
4703 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4704 * @property-read int $instanceid id of related instance in each context
4705 * @property-read string $path path to context, starts with system context
4706 * @property-read int $depth
4708 abstract class context extends stdClass implements IteratorAggregate {
4711 * The context id
4712 * Can be accessed publicly through $context->id
4713 * @var int
4715 protected $_id;
4718 * The context level
4719 * Can be accessed publicly through $context->contextlevel
4720 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4722 protected $_contextlevel;
4725 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4726 * Can be accessed publicly through $context->instanceid
4727 * @var int
4729 protected $_instanceid;
4732 * The path to the context always starting from the system context
4733 * Can be accessed publicly through $context->path
4734 * @var string
4736 protected $_path;
4739 * The depth of the context in relation to parent contexts
4740 * Can be accessed publicly through $context->depth
4741 * @var int
4743 protected $_depth;
4746 * Whether this context is locked or not.
4748 * Can be accessed publicly through $context->locked.
4750 * @var int
4752 protected $_locked;
4755 * @var array Context caching info
4757 private static $cache_contextsbyid = array();
4760 * @var array Context caching info
4762 private static $cache_contexts = array();
4765 * Context count
4766 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4767 * @var int
4769 protected static $cache_count = 0;
4772 * @var array Context caching info
4774 protected static $cache_preloaded = array();
4777 * @var context_system The system context once initialised
4779 protected static $systemcontext = null;
4782 * Resets the cache to remove all data.
4783 * @static
4785 protected static function reset_caches() {
4786 self::$cache_contextsbyid = array();
4787 self::$cache_contexts = array();
4788 self::$cache_count = 0;
4789 self::$cache_preloaded = array();
4791 self::$systemcontext = null;
4795 * Adds a context to the cache. If the cache is full, discards a batch of
4796 * older entries.
4798 * @static
4799 * @param context $context New context to add
4800 * @return void
4802 protected static function cache_add(context $context) {
4803 if (isset(self::$cache_contextsbyid[$context->id])) {
4804 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4805 return;
4808 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4809 $i = 0;
4810 foreach(self::$cache_contextsbyid as $ctx) {
4811 $i++;
4812 if ($i <= 100) {
4813 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4814 continue;
4816 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4817 // we remove oldest third of the contexts to make room for more contexts
4818 break;
4820 unset(self::$cache_contextsbyid[$ctx->id]);
4821 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4822 self::$cache_count--;
4826 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4827 self::$cache_contextsbyid[$context->id] = $context;
4828 self::$cache_count++;
4832 * Removes a context from the cache.
4834 * @static
4835 * @param context $context Context object to remove
4836 * @return void
4838 protected static function cache_remove(context $context) {
4839 if (!isset(self::$cache_contextsbyid[$context->id])) {
4840 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4841 return;
4843 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4844 unset(self::$cache_contextsbyid[$context->id]);
4846 self::$cache_count--;
4848 if (self::$cache_count < 0) {
4849 self::$cache_count = 0;
4854 * Gets a context from the cache.
4856 * @static
4857 * @param int $contextlevel Context level
4858 * @param int $instance Instance ID
4859 * @return context|bool Context or false if not in cache
4861 protected static function cache_get($contextlevel, $instance) {
4862 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4863 return self::$cache_contexts[$contextlevel][$instance];
4865 return false;
4869 * Gets a context from the cache based on its id.
4871 * @static
4872 * @param int $id Context ID
4873 * @return context|bool Context or false if not in cache
4875 protected static function cache_get_by_id($id) {
4876 if (isset(self::$cache_contextsbyid[$id])) {
4877 return self::$cache_contextsbyid[$id];
4879 return false;
4883 * Preloads context information from db record and strips the cached info.
4885 * @static
4886 * @param stdClass $rec
4887 * @return void (modifies $rec)
4889 protected static function preload_from_record(stdClass $rec) {
4890 $notenoughdata = false;
4891 $notenoughdata = $notenoughdata || empty($rec->ctxid);
4892 $notenoughdata = $notenoughdata || empty($rec->ctxlevel);
4893 $notenoughdata = $notenoughdata || !isset($rec->ctxinstance);
4894 $notenoughdata = $notenoughdata || empty($rec->ctxpath);
4895 $notenoughdata = $notenoughdata || empty($rec->ctxdepth);
4896 $notenoughdata = $notenoughdata || !isset($rec->ctxlocked);
4897 if ($notenoughdata) {
4898 // The record does not have enough data, passed here repeatedly or context does not exist yet.
4899 if (isset($rec->ctxid) && !isset($rec->ctxlocked)) {
4900 debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER);
4902 return;
4905 $record = (object) [
4906 'id' => $rec->ctxid,
4907 'contextlevel' => $rec->ctxlevel,
4908 'instanceid' => $rec->ctxinstance,
4909 'path' => $rec->ctxpath,
4910 'depth' => $rec->ctxdepth,
4911 'locked' => $rec->ctxlocked,
4914 unset($rec->ctxid);
4915 unset($rec->ctxlevel);
4916 unset($rec->ctxinstance);
4917 unset($rec->ctxpath);
4918 unset($rec->ctxdepth);
4919 unset($rec->ctxlocked);
4921 return context::create_instance_from_record($record);
4925 // ====== magic methods =======
4928 * Magic setter method, we do not want anybody to modify properties from the outside
4929 * @param string $name
4930 * @param mixed $value
4932 public function __set($name, $value) {
4933 debugging('Can not change context instance properties!');
4937 * Magic method getter, redirects to read only values.
4938 * @param string $name
4939 * @return mixed
4941 public function __get($name) {
4942 switch ($name) {
4943 case 'id':
4944 return $this->_id;
4945 case 'contextlevel':
4946 return $this->_contextlevel;
4947 case 'instanceid':
4948 return $this->_instanceid;
4949 case 'path':
4950 return $this->_path;
4951 case 'depth':
4952 return $this->_depth;
4953 case 'locked':
4954 return $this->is_locked();
4956 default:
4957 debugging('Invalid context property accessed! '.$name);
4958 return null;
4963 * Full support for isset on our magic read only properties.
4964 * @param string $name
4965 * @return bool
4967 public function __isset($name) {
4968 switch ($name) {
4969 case 'id':
4970 return isset($this->_id);
4971 case 'contextlevel':
4972 return isset($this->_contextlevel);
4973 case 'instanceid':
4974 return isset($this->_instanceid);
4975 case 'path':
4976 return isset($this->_path);
4977 case 'depth':
4978 return isset($this->_depth);
4979 case 'locked':
4980 // Locked is always set.
4981 return true;
4982 default:
4983 return false;
4988 * All properties are read only, sorry.
4989 * @param string $name
4991 public function __unset($name) {
4992 debugging('Can not unset context instance properties!');
4995 // ====== implementing method from interface IteratorAggregate ======
4998 * Create an iterator because magic vars can't be seen by 'foreach'.
5000 * Now we can convert context object to array using convert_to_array(),
5001 * and feed it properly to json_encode().
5003 public function getIterator() {
5004 $ret = array(
5005 'id' => $this->id,
5006 'contextlevel' => $this->contextlevel,
5007 'instanceid' => $this->instanceid,
5008 'path' => $this->path,
5009 'depth' => $this->depth,
5010 'locked' => $this->locked,
5012 return new ArrayIterator($ret);
5015 // ====== general context methods ======
5018 * Constructor is protected so that devs are forced to
5019 * use context_xxx::instance() or context::instance_by_id().
5021 * @param stdClass $record
5023 protected function __construct(stdClass $record) {
5024 $this->_id = (int)$record->id;
5025 $this->_contextlevel = (int)$record->contextlevel;
5026 $this->_instanceid = $record->instanceid;
5027 $this->_path = $record->path;
5028 $this->_depth = $record->depth;
5030 if (isset($record->locked)) {
5031 $this->_locked = $record->locked;
5032 } else if (!during_initial_install() && !moodle_needs_upgrading()) {
5033 debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER);
5038 * This function is also used to work around 'protected' keyword problems in context_helper.
5039 * @static
5040 * @param stdClass $record
5041 * @return context instance
5043 protected static function create_instance_from_record(stdClass $record) {
5044 $classname = context_helper::get_class_for_level($record->contextlevel);
5046 if ($context = context::cache_get_by_id($record->id)) {
5047 return $context;
5050 $context = new $classname($record);
5051 context::cache_add($context);
5053 return $context;
5057 * Copy prepared new contexts from temp table to context table,
5058 * we do this in db specific way for perf reasons only.
5059 * @static
5061 protected static function merge_context_temp_table() {
5062 global $DB;
5064 /* MDL-11347:
5065 * - mysql does not allow to use FROM in UPDATE statements
5066 * - using two tables after UPDATE works in mysql, but might give unexpected
5067 * results in pg 8 (depends on configuration)
5068 * - using table alias in UPDATE does not work in pg < 8.2
5070 * Different code for each database - mostly for performance reasons
5073 $dbfamily = $DB->get_dbfamily();
5074 if ($dbfamily == 'mysql') {
5075 $updatesql = "UPDATE {context} ct, {context_temp} temp
5076 SET ct.path = temp.path,
5077 ct.depth = temp.depth,
5078 ct.locked = temp.locked
5079 WHERE ct.id = temp.id";
5080 } else if ($dbfamily == 'oracle') {
5081 $updatesql = "UPDATE {context} ct
5082 SET (ct.path, ct.depth, ct.locked) =
5083 (SELECT temp.path, temp.depth, temp.locked
5084 FROM {context_temp} temp
5085 WHERE temp.id=ct.id)
5086 WHERE EXISTS (SELECT 'x'
5087 FROM {context_temp} temp
5088 WHERE temp.id = ct.id)";
5089 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5090 $updatesql = "UPDATE {context}
5091 SET path = temp.path,
5092 depth = temp.depth,
5093 locked = temp.locked
5094 FROM {context_temp} temp
5095 WHERE temp.id={context}.id";
5096 } else {
5097 // sqlite and others
5098 $updatesql = "UPDATE {context}
5099 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5100 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id),
5101 locked = (SELECT locked FROM {context_temp} WHERE id = {context}.id)
5102 WHERE id IN (SELECT id FROM {context_temp})";
5105 $DB->execute($updatesql);
5109 * Get a context instance as an object, from a given context id.
5111 * @static
5112 * @param int $id context id
5113 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5114 * MUST_EXIST means throw exception if no record found
5115 * @return context|bool the context object or false if not found
5117 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5118 global $DB;
5120 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5121 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5122 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5125 if ($id == SYSCONTEXTID) {
5126 return context_system::instance(0, $strictness);
5129 if (is_array($id) or is_object($id) or empty($id)) {
5130 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5133 if ($context = context::cache_get_by_id($id)) {
5134 return $context;
5137 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5138 return context::create_instance_from_record($record);
5141 return false;
5145 * Update context info after moving context in the tree structure.
5147 * @param context $newparent
5148 * @return void
5150 public function update_moved(context $newparent) {
5151 global $DB;
5153 $frompath = $this->_path;
5154 $newpath = $newparent->path . '/' . $this->_id;
5156 $trans = $DB->start_delegated_transaction();
5158 $setdepth = '';
5159 if (($newparent->depth +1) != $this->_depth) {
5160 $diff = $newparent->depth - $this->_depth + 1;
5161 $setdepth = ", depth = depth + $diff";
5163 $sql = "UPDATE {context}
5164 SET path = ?
5165 $setdepth
5166 WHERE id = ?";
5167 $params = array($newpath, $this->_id);
5168 $DB->execute($sql, $params);
5170 $this->_path = $newpath;
5171 $this->_depth = $newparent->depth + 1;
5173 $sql = "UPDATE {context}
5174 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5175 $setdepth
5176 WHERE path LIKE ?";
5177 $params = array($newpath, "{$frompath}/%");
5178 $DB->execute($sql, $params);
5180 $this->mark_dirty();
5182 context::reset_caches();
5184 $trans->allow_commit();
5188 * Set whether this context has been locked or not.
5190 * @param bool $locked
5191 * @return $this
5193 public function set_locked(bool $locked) {
5194 global $DB;
5196 if ($this->_locked == $locked) {
5197 return $this;
5200 $this->_locked = $locked;
5201 $DB->set_field('context', 'locked', (int) $locked, ['id' => $this->id]);
5202 $this->mark_dirty();
5203 self::reset_caches();
5205 return $this;
5209 * Remove all context path info and optionally rebuild it.
5211 * @param bool $rebuild
5212 * @return void
5214 public function reset_paths($rebuild = true) {
5215 global $DB;
5217 if ($this->_path) {
5218 $this->mark_dirty();
5220 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5221 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5222 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5223 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5224 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5225 $this->_depth = 0;
5226 $this->_path = null;
5229 if ($rebuild) {
5230 context_helper::build_all_paths(false);
5233 context::reset_caches();
5237 * Delete all data linked to content, do not delete the context record itself
5239 public function delete_content() {
5240 global $CFG, $DB;
5242 blocks_delete_all_for_context($this->_id);
5243 filter_delete_all_for_context($this->_id);
5245 require_once($CFG->dirroot . '/comment/lib.php');
5246 comment::delete_comments(array('contextid'=>$this->_id));
5248 require_once($CFG->dirroot.'/rating/lib.php');
5249 $delopt = new stdclass();
5250 $delopt->contextid = $this->_id;
5251 $rm = new rating_manager();
5252 $rm->delete_ratings($delopt);
5254 // delete all files attached to this context
5255 $fs = get_file_storage();
5256 $fs->delete_area_files($this->_id);
5258 // Delete all repository instances attached to this context.
5259 require_once($CFG->dirroot . '/repository/lib.php');
5260 repository::delete_all_for_context($this->_id);
5262 // delete all advanced grading data attached to this context
5263 require_once($CFG->dirroot.'/grade/grading/lib.php');
5264 grading_manager::delete_all_for_context($this->_id);
5266 // now delete stuff from role related tables, role_unassign_all
5267 // and unenrol should be called earlier to do proper cleanup
5268 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5269 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5270 $this->delete_capabilities();
5274 * Unassign all capabilities from a context.
5276 public function delete_capabilities() {
5277 global $DB;
5279 $ids = $DB->get_fieldset_select('role_capabilities', 'DISTINCT roleid', 'contextid = ?', array($this->_id));
5280 if ($ids) {
5281 $DB->delete_records('role_capabilities', array('contextid' => $this->_id));
5283 // Reset any cache of these roles, including MUC.
5284 accesslib_clear_role_cache($ids);
5289 * Delete the context content and the context record itself
5291 public function delete() {
5292 global $DB;
5294 if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5295 throw new coding_exception('Cannot delete system context');
5298 // double check the context still exists
5299 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5300 context::cache_remove($this);
5301 return;
5304 $this->delete_content();
5305 $DB->delete_records('context', array('id'=>$this->_id));
5306 // purge static context cache if entry present
5307 context::cache_remove($this);
5310 // ====== context level related methods ======
5313 * Utility method for context creation
5315 * @static
5316 * @param int $contextlevel
5317 * @param int $instanceid
5318 * @param string $parentpath
5319 * @return stdClass context record
5321 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5322 global $DB;
5324 $record = new stdClass();
5325 $record->contextlevel = $contextlevel;
5326 $record->instanceid = $instanceid;
5327 $record->depth = 0;
5328 $record->path = null; //not known before insert
5329 $record->locked = 0;
5331 $record->id = $DB->insert_record('context', $record);
5333 // now add path if known - it can be added later
5334 if (!is_null($parentpath)) {
5335 $record->path = $parentpath.'/'.$record->id;
5336 $record->depth = substr_count($record->path, '/');
5337 $DB->update_record('context', $record);
5340 return $record;
5344 * Returns human readable context identifier.
5346 * @param boolean $withprefix whether to prefix the name of the context with the
5347 * type of context, e.g. User, Course, Forum, etc.
5348 * @param boolean $short whether to use the short name of the thing. Only applies
5349 * to course contexts
5350 * @return string the human readable context name.
5352 public function get_context_name($withprefix = true, $short = false) {
5353 // must be implemented in all context levels
5354 throw new coding_exception('can not get name of abstract context');
5358 * Whether the current context is locked.
5360 * @return bool
5362 public function is_locked() {
5363 if ($this->_locked) {
5364 return true;
5367 if ($parent = $this->get_parent_context()) {
5368 return $parent->is_locked();
5371 return false;
5375 * Returns the most relevant URL for this context.
5377 * @return moodle_url
5379 public abstract function get_url();
5382 * Returns array of relevant context capability records.
5384 * @return array
5386 public abstract function get_capabilities();
5389 * Recursive function which, given a context, find all its children context ids.
5391 * For course category contexts it will return immediate children and all subcategory contexts.
5392 * It will NOT recurse into courses or subcategories categories.
5393 * If you want to do that, call it on the returned courses/categories.
5395 * When called for a course context, it will return the modules and blocks
5396 * displayed in the course page and blocks displayed on the module pages.
5398 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5399 * contexts ;-)
5401 * @return array Array of child records
5403 public function get_child_contexts() {
5404 global $DB;
5406 if (empty($this->_path) or empty($this->_depth)) {
5407 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5408 return array();
5411 $sql = "SELECT ctx.*
5412 FROM {context} ctx
5413 WHERE ctx.path LIKE ?";
5414 $params = array($this->_path.'/%');
5415 $records = $DB->get_records_sql($sql, $params);
5417 $result = array();
5418 foreach ($records as $record) {
5419 $result[$record->id] = context::create_instance_from_record($record);
5422 return $result;
5426 * Returns parent contexts of this context in reversed order, i.e. parent first,
5427 * then grand parent, etc.
5429 * @param bool $includeself true means include self too
5430 * @return array of context instances
5432 public function get_parent_contexts($includeself = false) {
5433 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5434 return array();
5437 $result = array();
5438 foreach ($contextids as $contextid) {
5439 $parent = context::instance_by_id($contextid, MUST_EXIST);
5440 $result[$parent->id] = $parent;
5443 return $result;
5447 * Returns parent context ids of this context in reversed order, i.e. parent first,
5448 * then grand parent, etc.
5450 * @param bool $includeself true means include self too
5451 * @return array of context ids
5453 public function get_parent_context_ids($includeself = false) {
5454 if (empty($this->_path)) {
5455 return array();
5458 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5459 $parentcontexts = explode('/', $parentcontexts);
5460 if (!$includeself) {
5461 array_pop($parentcontexts); // and remove its own id
5464 return array_reverse($parentcontexts);
5468 * Returns parent context paths of this context.
5470 * @param bool $includeself true means include self too
5471 * @return array of context paths
5473 public function get_parent_context_paths($includeself = false) {
5474 if (empty($this->_path)) {
5475 return array();
5478 $contextids = explode('/', $this->_path);
5480 $path = '';
5481 $paths = array();
5482 foreach ($contextids as $contextid) {
5483 if ($contextid) {
5484 $path .= '/' . $contextid;
5485 $paths[$contextid] = $path;
5489 if (!$includeself) {
5490 unset($paths[$this->_id]);
5493 return $paths;
5497 * Returns parent context
5499 * @return context
5501 public function get_parent_context() {
5502 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5503 return false;
5506 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5507 $parentcontexts = explode('/', $parentcontexts);
5508 array_pop($parentcontexts); // self
5509 $contextid = array_pop($parentcontexts); // immediate parent
5511 return context::instance_by_id($contextid, MUST_EXIST);
5515 * Is this context part of any course? If yes return course context.
5517 * @param bool $strict true means throw exception if not found, false means return false if not found
5518 * @return context_course context of the enclosing course, null if not found or exception
5520 public function get_course_context($strict = true) {
5521 if ($strict) {
5522 throw new coding_exception('Context does not belong to any course.');
5523 } else {
5524 return false;
5529 * Returns sql necessary for purging of stale context instances.
5531 * @static
5532 * @return string cleanup SQL
5534 protected static function get_cleanup_sql() {
5535 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5539 * Rebuild context paths and depths at context level.
5541 * @static
5542 * @param bool $force
5543 * @return void
5545 protected static function build_paths($force) {
5546 throw new coding_exception('build_paths() method must be implemented in all context levels');
5550 * Create missing context instances at given level
5552 * @static
5553 * @return void
5555 protected static function create_level_instances() {
5556 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5560 * Reset all cached permissions and definitions if the necessary.
5561 * @return void
5563 public function reload_if_dirty() {
5564 global $ACCESSLIB_PRIVATE, $USER;
5566 // Load dirty contexts list if needed
5567 if (CLI_SCRIPT) {
5568 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5569 // we do not load dirty flags in CLI and cron
5570 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5572 } else {
5573 if (!isset($USER->access['time'])) {
5574 // Nothing has been loaded yet, so we do not need to check dirty flags now.
5575 return;
5578 // From skodak: No idea why -2 is there, server cluster time difference maybe...
5579 $changedsince = $USER->access['time'] - 2;
5581 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5582 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $changedsince);
5585 if (!isset($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
5586 $ACCESSLIB_PRIVATE->dirtyusers[$USER->id] = get_cache_flag('accesslib/dirtyusers', $USER->id, $changedsince);
5590 $dirty = false;
5592 if (!empty($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
5593 $dirty = true;
5594 } else if (!empty($ACCESSLIB_PRIVATE->dirtycontexts)) {
5595 $paths = $this->get_parent_context_paths(true);
5597 foreach ($paths as $path) {
5598 if (isset($ACCESSLIB_PRIVATE->dirtycontexts[$path])) {
5599 $dirty = true;
5600 break;
5605 if ($dirty) {
5606 // Reload all capabilities of USER and others - preserving loginas, roleswitches, etc.
5607 // Then cleanup any marks of dirtyness... at least from our short term memory!
5608 reload_all_capabilities();
5613 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5615 public function mark_dirty() {
5616 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5618 if (during_initial_install()) {
5619 return;
5622 // only if it is a non-empty string
5623 if (is_string($this->_path) && $this->_path !== '') {
5624 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5625 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5626 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5627 } else {
5628 if (CLI_SCRIPT) {
5629 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5630 } else {
5631 if (isset($USER->access['time'])) {
5632 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5633 } else {
5634 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5636 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5645 * Context maintenance and helper methods.
5647 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5648 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5649 * level implementation from the rest of code, the code completion returns what developers need.
5651 * Thank you Tim Hunt for helping me with this nasty trick.
5653 * @package core_access
5654 * @category access
5655 * @copyright Petr Skoda {@link http://skodak.org}
5656 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5657 * @since Moodle 2.2
5659 class context_helper extends context {
5662 * @var array An array mapping context levels to classes
5664 private static $alllevels;
5667 * Instance does not make sense here, only static use
5669 protected function __construct() {
5673 * Reset internal context levels array.
5675 public static function reset_levels() {
5676 self::$alllevels = null;
5680 * Initialise context levels, call before using self::$alllevels.
5682 private static function init_levels() {
5683 global $CFG;
5685 if (isset(self::$alllevels)) {
5686 return;
5688 self::$alllevels = array(
5689 CONTEXT_SYSTEM => 'context_system',
5690 CONTEXT_USER => 'context_user',
5691 CONTEXT_COURSECAT => 'context_coursecat',
5692 CONTEXT_COURSE => 'context_course',
5693 CONTEXT_MODULE => 'context_module',
5694 CONTEXT_BLOCK => 'context_block',
5697 if (empty($CFG->custom_context_classes)) {
5698 return;
5701 $levels = $CFG->custom_context_classes;
5702 if (!is_array($levels)) {
5703 $levels = @unserialize($levels);
5705 if (!is_array($levels)) {
5706 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
5707 return;
5710 // Unsupported custom levels, use with care!!!
5711 foreach ($levels as $level => $classname) {
5712 self::$alllevels[$level] = $classname;
5714 ksort(self::$alllevels);
5718 * Returns a class name of the context level class
5720 * @static
5721 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5722 * @return string class name of the context class
5724 public static function get_class_for_level($contextlevel) {
5725 self::init_levels();
5726 if (isset(self::$alllevels[$contextlevel])) {
5727 return self::$alllevels[$contextlevel];
5728 } else {
5729 throw new coding_exception('Invalid context level specified');
5734 * Returns a list of all context levels
5736 * @static
5737 * @return array int=>string (level=>level class name)
5739 public static function get_all_levels() {
5740 self::init_levels();
5741 return self::$alllevels;
5745 * Remove stale contexts that belonged to deleted instances.
5746 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5748 * @static
5749 * @return void
5751 public static function cleanup_instances() {
5752 global $DB;
5753 self::init_levels();
5755 $sqls = array();
5756 foreach (self::$alllevels as $level=>$classname) {
5757 $sqls[] = $classname::get_cleanup_sql();
5760 $sql = implode(" UNION ", $sqls);
5762 // it is probably better to use transactions, it might be faster too
5763 $transaction = $DB->start_delegated_transaction();
5765 $rs = $DB->get_recordset_sql($sql);
5766 foreach ($rs as $record) {
5767 $context = context::create_instance_from_record($record);
5768 $context->delete();
5770 $rs->close();
5772 $transaction->allow_commit();
5776 * Create all context instances at the given level and above.
5778 * @static
5779 * @param int $contextlevel null means all levels
5780 * @param bool $buildpaths
5781 * @return void
5783 public static function create_instances($contextlevel = null, $buildpaths = true) {
5784 self::init_levels();
5785 foreach (self::$alllevels as $level=>$classname) {
5786 if ($contextlevel and $level > $contextlevel) {
5787 // skip potential sub-contexts
5788 continue;
5790 $classname::create_level_instances();
5791 if ($buildpaths) {
5792 $classname::build_paths(false);
5798 * Rebuild paths and depths in all context levels.
5800 * @static
5801 * @param bool $force false means add missing only
5802 * @return void
5804 public static function build_all_paths($force = false) {
5805 self::init_levels();
5806 foreach (self::$alllevels as $classname) {
5807 $classname::build_paths($force);
5810 // reset static course cache - it might have incorrect cached data
5811 accesslib_clear_all_caches(true);
5815 * Resets the cache to remove all data.
5816 * @static
5818 public static function reset_caches() {
5819 context::reset_caches();
5823 * Returns all fields necessary for context preloading from user $rec.
5825 * This helps with performance when dealing with hundreds of contexts.
5827 * @static
5828 * @param string $tablealias context table alias in the query
5829 * @return array (table.column=>alias, ...)
5831 public static function get_preload_record_columns($tablealias) {
5832 return [
5833 "$tablealias.id" => "ctxid",
5834 "$tablealias.path" => "ctxpath",
5835 "$tablealias.depth" => "ctxdepth",
5836 "$tablealias.contextlevel" => "ctxlevel",
5837 "$tablealias.instanceid" => "ctxinstance",
5838 "$tablealias.locked" => "ctxlocked",
5843 * Returns all fields necessary for context preloading from user $rec.
5845 * This helps with performance when dealing with hundreds of contexts.
5847 * @static
5848 * @param string $tablealias context table alias in the query
5849 * @return string
5851 public static function get_preload_record_columns_sql($tablealias) {
5852 return "$tablealias.id AS ctxid, " .
5853 "$tablealias.path AS ctxpath, " .
5854 "$tablealias.depth AS ctxdepth, " .
5855 "$tablealias.contextlevel AS ctxlevel, " .
5856 "$tablealias.instanceid AS ctxinstance, " .
5857 "$tablealias.locked AS ctxlocked";
5861 * Preloads context information from db record and strips the cached info.
5863 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5865 * @static
5866 * @param stdClass $rec
5867 * @return void (modifies $rec)
5869 public static function preload_from_record(stdClass $rec) {
5870 context::preload_from_record($rec);
5874 * Preload all contexts instances from course.
5876 * To be used if you expect multiple queries for course activities...
5878 * @static
5879 * @param int $courseid
5881 public static function preload_course($courseid) {
5882 // Users can call this multiple times without doing any harm
5883 if (isset(context::$cache_preloaded[$courseid])) {
5884 return;
5886 $coursecontext = context_course::instance($courseid);
5887 $coursecontext->get_child_contexts();
5889 context::$cache_preloaded[$courseid] = true;
5893 * Delete context instance
5895 * @static
5896 * @param int $contextlevel
5897 * @param int $instanceid
5898 * @return void
5900 public static function delete_instance($contextlevel, $instanceid) {
5901 global $DB;
5903 // double check the context still exists
5904 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5905 $context = context::create_instance_from_record($record);
5906 $context->delete();
5907 } else {
5908 // we should try to purge the cache anyway
5913 * Returns the name of specified context level
5915 * @static
5916 * @param int $contextlevel
5917 * @return string name of the context level
5919 public static function get_level_name($contextlevel) {
5920 $classname = context_helper::get_class_for_level($contextlevel);
5921 return $classname::get_level_name();
5925 * not used
5927 public function get_url() {
5931 * not used
5933 public function get_capabilities() {
5939 * System context class
5941 * @package core_access
5942 * @category access
5943 * @copyright Petr Skoda {@link http://skodak.org}
5944 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5945 * @since Moodle 2.2
5947 class context_system extends context {
5949 * Please use context_system::instance() if you need the instance of context.
5951 * @param stdClass $record
5953 protected function __construct(stdClass $record) {
5954 parent::__construct($record);
5955 if ($record->contextlevel != CONTEXT_SYSTEM) {
5956 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5961 * Returns human readable context level name.
5963 * @static
5964 * @return string the human readable context level name.
5966 public static function get_level_name() {
5967 return get_string('coresystem');
5971 * Returns human readable context identifier.
5973 * @param boolean $withprefix does not apply to system context
5974 * @param boolean $short does not apply to system context
5975 * @return string the human readable context name.
5977 public function get_context_name($withprefix = true, $short = false) {
5978 return self::get_level_name();
5982 * Returns the most relevant URL for this context.
5984 * @return moodle_url
5986 public function get_url() {
5987 return new moodle_url('/');
5991 * Returns array of relevant context capability records.
5993 * @return array
5995 public function get_capabilities() {
5996 global $DB;
5998 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6000 $params = array();
6001 $sql = "SELECT *
6002 FROM {capabilities}";
6004 return $DB->get_records_sql($sql.' '.$sort, $params);
6008 * Create missing context instances at system context
6009 * @static
6011 protected static function create_level_instances() {
6012 // nothing to do here, the system context is created automatically in installer
6013 self::instance(0);
6017 * Returns system context instance.
6019 * @static
6020 * @param int $instanceid should be 0
6021 * @param int $strictness
6022 * @param bool $cache
6023 * @return context_system context instance
6025 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
6026 global $DB;
6028 if ($instanceid != 0) {
6029 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
6032 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
6033 if (!isset(context::$systemcontext)) {
6034 $record = new stdClass();
6035 $record->id = SYSCONTEXTID;
6036 $record->contextlevel = CONTEXT_SYSTEM;
6037 $record->instanceid = 0;
6038 $record->path = '/'.SYSCONTEXTID;
6039 $record->depth = 1;
6040 $record->locked = 0;
6041 context::$systemcontext = new context_system($record);
6043 return context::$systemcontext;
6046 try {
6047 // We ignore the strictness completely because system context must exist except during install.
6048 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6049 } catch (dml_exception $e) {
6050 //table or record does not exist
6051 if (!during_initial_install()) {
6052 // do not mess with system context after install, it simply must exist
6053 throw $e;
6055 $record = null;
6058 if (!$record) {
6059 $record = new stdClass();
6060 $record->contextlevel = CONTEXT_SYSTEM;
6061 $record->instanceid = 0;
6062 $record->depth = 1;
6063 $record->path = null; // Not known before insert.
6064 $record->locked = 0;
6066 try {
6067 if ($DB->count_records('context')) {
6068 // contexts already exist, this is very weird, system must be first!!!
6069 return null;
6071 if (defined('SYSCONTEXTID')) {
6072 // this would happen only in unittest on sites that went through weird 1.7 upgrade
6073 $record->id = SYSCONTEXTID;
6074 $DB->import_record('context', $record);
6075 $DB->get_manager()->reset_sequence('context');
6076 } else {
6077 $record->id = $DB->insert_record('context', $record);
6079 } catch (dml_exception $e) {
6080 // can not create context - table does not exist yet, sorry
6081 return null;
6085 if ($record->instanceid != 0) {
6086 // this is very weird, somebody must be messing with context table
6087 debugging('Invalid system context detected');
6090 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6091 // fix path if necessary, initial install or path reset
6092 $record->depth = 1;
6093 $record->path = '/'.$record->id;
6094 $DB->update_record('context', $record);
6097 if (empty($record->locked)) {
6098 $record->locked = 0;
6101 if (!defined('SYSCONTEXTID')) {
6102 define('SYSCONTEXTID', $record->id);
6105 context::$systemcontext = new context_system($record);
6106 return context::$systemcontext;
6110 * Returns all site contexts except the system context, DO NOT call on production servers!!
6112 * Contexts are not cached.
6114 * @return array
6116 public function get_child_contexts() {
6117 global $DB;
6119 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6121 // Just get all the contexts except for CONTEXT_SYSTEM level
6122 // and hope we don't OOM in the process - don't cache
6123 $sql = "SELECT c.*
6124 FROM {context} c
6125 WHERE contextlevel > ".CONTEXT_SYSTEM;
6126 $records = $DB->get_records_sql($sql);
6128 $result = array();
6129 foreach ($records as $record) {
6130 $result[$record->id] = context::create_instance_from_record($record);
6133 return $result;
6137 * Returns sql necessary for purging of stale context instances.
6139 * @static
6140 * @return string cleanup SQL
6142 protected static function get_cleanup_sql() {
6143 $sql = "
6144 SELECT c.*
6145 FROM {context} c
6146 WHERE 1=2
6149 return $sql;
6153 * Rebuild context paths and depths at system context level.
6155 * @static
6156 * @param bool $force
6158 protected static function build_paths($force) {
6159 global $DB;
6161 /* note: ignore $force here, we always do full test of system context */
6163 // exactly one record must exist
6164 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6166 if ($record->instanceid != 0) {
6167 debugging('Invalid system context detected');
6170 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6171 debugging('Invalid SYSCONTEXTID detected');
6174 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6175 // fix path if necessary, initial install or path reset
6176 $record->depth = 1;
6177 $record->path = '/'.$record->id;
6178 $DB->update_record('context', $record);
6183 * Set whether this context has been locked or not.
6185 * @param bool $locked
6186 * @return $this
6188 public function set_locked(bool $locked) {
6189 throw new \coding_exception('It is not possible to lock the system context');
6191 return $this;
6197 * User context class
6199 * @package core_access
6200 * @category access
6201 * @copyright Petr Skoda {@link http://skodak.org}
6202 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6203 * @since Moodle 2.2
6205 class context_user extends context {
6207 * Please use context_user::instance($userid) if you need the instance of context.
6208 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6210 * @param stdClass $record
6212 protected function __construct(stdClass $record) {
6213 parent::__construct($record);
6214 if ($record->contextlevel != CONTEXT_USER) {
6215 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6220 * Returns human readable context level name.
6222 * @static
6223 * @return string the human readable context level name.
6225 public static function get_level_name() {
6226 return get_string('user');
6230 * Returns human readable context identifier.
6232 * @param boolean $withprefix whether to prefix the name of the context with User
6233 * @param boolean $short does not apply to user context
6234 * @return string the human readable context name.
6236 public function get_context_name($withprefix = true, $short = false) {
6237 global $DB;
6239 $name = '';
6240 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6241 if ($withprefix){
6242 $name = get_string('user').': ';
6244 $name .= fullname($user);
6246 return $name;
6250 * Returns the most relevant URL for this context.
6252 * @return moodle_url
6254 public function get_url() {
6255 global $COURSE;
6257 if ($COURSE->id == SITEID) {
6258 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6259 } else {
6260 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6262 return $url;
6266 * Returns array of relevant context capability records.
6268 * @return array
6270 public function get_capabilities() {
6271 global $DB;
6273 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6275 $extracaps = array('moodle/grade:viewall');
6276 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6277 $sql = "SELECT *
6278 FROM {capabilities}
6279 WHERE contextlevel = ".CONTEXT_USER."
6280 OR name $extra";
6282 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6286 * Returns user context instance.
6288 * @static
6289 * @param int $userid id from {user} table
6290 * @param int $strictness
6291 * @return context_user context instance
6293 public static function instance($userid, $strictness = MUST_EXIST) {
6294 global $DB;
6296 if ($context = context::cache_get(CONTEXT_USER, $userid)) {
6297 return $context;
6300 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER, 'instanceid' => $userid))) {
6301 if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6302 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6306 if ($record) {
6307 $context = new context_user($record);
6308 context::cache_add($context);
6309 return $context;
6312 return false;
6316 * Create missing context instances at user context level
6317 * @static
6319 protected static function create_level_instances() {
6320 global $DB;
6322 $sql = "SELECT ".CONTEXT_USER.", u.id
6323 FROM {user} u
6324 WHERE u.deleted = 0
6325 AND NOT EXISTS (SELECT 'x'
6326 FROM {context} cx
6327 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6328 $contextdata = $DB->get_recordset_sql($sql);
6329 foreach ($contextdata as $context) {
6330 context::insert_context_record(CONTEXT_USER, $context->id, null);
6332 $contextdata->close();
6336 * Returns sql necessary for purging of stale context instances.
6338 * @static
6339 * @return string cleanup SQL
6341 protected static function get_cleanup_sql() {
6342 $sql = "
6343 SELECT c.*
6344 FROM {context} c
6345 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6346 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6349 return $sql;
6353 * Rebuild context paths and depths at user context level.
6355 * @static
6356 * @param bool $force
6358 protected static function build_paths($force) {
6359 global $DB;
6361 // First update normal users.
6362 $path = $DB->sql_concat('?', 'id');
6363 $pathstart = '/' . SYSCONTEXTID . '/';
6364 $params = array($pathstart);
6366 if ($force) {
6367 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6368 $params[] = $pathstart;
6369 } else {
6370 $where = "depth = 0 OR path IS NULL";
6373 $sql = "UPDATE {context}
6374 SET depth = 2,
6375 path = {$path}
6376 WHERE contextlevel = " . CONTEXT_USER . "
6377 AND ($where)";
6378 $DB->execute($sql, $params);
6384 * Course category context class
6386 * @package core_access
6387 * @category access
6388 * @copyright Petr Skoda {@link http://skodak.org}
6389 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6390 * @since Moodle 2.2
6392 class context_coursecat extends context {
6394 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6395 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6397 * @param stdClass $record
6399 protected function __construct(stdClass $record) {
6400 parent::__construct($record);
6401 if ($record->contextlevel != CONTEXT_COURSECAT) {
6402 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6407 * Returns human readable context level name.
6409 * @static
6410 * @return string the human readable context level name.
6412 public static function get_level_name() {
6413 return get_string('category');
6417 * Returns human readable context identifier.
6419 * @param boolean $withprefix whether to prefix the name of the context with Category
6420 * @param boolean $short does not apply to course categories
6421 * @return string the human readable context name.
6423 public function get_context_name($withprefix = true, $short = false) {
6424 global $DB;
6426 $name = '';
6427 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6428 if ($withprefix){
6429 $name = get_string('category').': ';
6431 $name .= format_string($category->name, true, array('context' => $this));
6433 return $name;
6437 * Returns the most relevant URL for this context.
6439 * @return moodle_url
6441 public function get_url() {
6442 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6446 * Returns array of relevant context capability records.
6448 * @return array
6450 public function get_capabilities() {
6451 global $DB;
6453 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6455 $params = array();
6456 $sql = "SELECT *
6457 FROM {capabilities}
6458 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6460 return $DB->get_records_sql($sql.' '.$sort, $params);
6464 * Returns course category context instance.
6466 * @static
6467 * @param int $categoryid id from {course_categories} table
6468 * @param int $strictness
6469 * @return context_coursecat context instance
6471 public static function instance($categoryid, $strictness = MUST_EXIST) {
6472 global $DB;
6474 if ($context = context::cache_get(CONTEXT_COURSECAT, $categoryid)) {
6475 return $context;
6478 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT, 'instanceid' => $categoryid))) {
6479 if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6480 if ($category->parent) {
6481 $parentcontext = context_coursecat::instance($category->parent);
6482 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6483 } else {
6484 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6489 if ($record) {
6490 $context = new context_coursecat($record);
6491 context::cache_add($context);
6492 return $context;
6495 return false;
6499 * Returns immediate child contexts of category and all subcategories,
6500 * children of subcategories and courses are not returned.
6502 * @return array
6504 public function get_child_contexts() {
6505 global $DB;
6507 if (empty($this->_path) or empty($this->_depth)) {
6508 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6509 return array();
6512 $sql = "SELECT ctx.*
6513 FROM {context} ctx
6514 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6515 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6516 $records = $DB->get_records_sql($sql, $params);
6518 $result = array();
6519 foreach ($records as $record) {
6520 $result[$record->id] = context::create_instance_from_record($record);
6523 return $result;
6527 * Create missing context instances at course category context level
6528 * @static
6530 protected static function create_level_instances() {
6531 global $DB;
6533 $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6534 FROM {course_categories} cc
6535 WHERE NOT EXISTS (SELECT 'x'
6536 FROM {context} cx
6537 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6538 $contextdata = $DB->get_recordset_sql($sql);
6539 foreach ($contextdata as $context) {
6540 context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6542 $contextdata->close();
6546 * Returns sql necessary for purging of stale context instances.
6548 * @static
6549 * @return string cleanup SQL
6551 protected static function get_cleanup_sql() {
6552 $sql = "
6553 SELECT c.*
6554 FROM {context} c
6555 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6556 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6559 return $sql;
6563 * Rebuild context paths and depths at course category context level.
6565 * @static
6566 * @param bool $force
6568 protected static function build_paths($force) {
6569 global $DB;
6571 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6572 if ($force) {
6573 $ctxemptyclause = $emptyclause = '';
6574 } else {
6575 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6576 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6579 $base = '/'.SYSCONTEXTID;
6581 // Normal top level categories
6582 $sql = "UPDATE {context}
6583 SET depth=2,
6584 path=".$DB->sql_concat("'$base/'", 'id')."
6585 WHERE contextlevel=".CONTEXT_COURSECAT."
6586 AND EXISTS (SELECT 'x'
6587 FROM {course_categories} cc
6588 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6589 $emptyclause";
6590 $DB->execute($sql);
6592 // Deeper categories - one query per depthlevel
6593 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6594 for ($n=2; $n<=$maxdepth; $n++) {
6595 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
6596 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
6597 FROM {context} ctx
6598 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6599 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6600 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6601 $ctxemptyclause";
6602 $trans = $DB->start_delegated_transaction();
6603 $DB->delete_records('context_temp');
6604 $DB->execute($sql);
6605 context::merge_context_temp_table();
6606 $DB->delete_records('context_temp');
6607 $trans->allow_commit();
6616 * Course context class
6618 * @package core_access
6619 * @category access
6620 * @copyright Petr Skoda {@link http://skodak.org}
6621 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6622 * @since Moodle 2.2
6624 class context_course extends context {
6626 * Please use context_course::instance($courseid) if you need the instance of context.
6627 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6629 * @param stdClass $record
6631 protected function __construct(stdClass $record) {
6632 parent::__construct($record);
6633 if ($record->contextlevel != CONTEXT_COURSE) {
6634 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6639 * Returns human readable context level name.
6641 * @static
6642 * @return string the human readable context level name.
6644 public static function get_level_name() {
6645 return get_string('course');
6649 * Returns human readable context identifier.
6651 * @param boolean $withprefix whether to prefix the name of the context with Course
6652 * @param boolean $short whether to use the short name of the thing.
6653 * @return string the human readable context name.
6655 public function get_context_name($withprefix = true, $short = false) {
6656 global $DB;
6658 $name = '';
6659 if ($this->_instanceid == SITEID) {
6660 $name = get_string('frontpage', 'admin');
6661 } else {
6662 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6663 if ($withprefix){
6664 $name = get_string('course').': ';
6666 if ($short){
6667 $name .= format_string($course->shortname, true, array('context' => $this));
6668 } else {
6669 $name .= format_string(get_course_display_name_for_list($course));
6673 return $name;
6677 * Returns the most relevant URL for this context.
6679 * @return moodle_url
6681 public function get_url() {
6682 if ($this->_instanceid != SITEID) {
6683 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6686 return new moodle_url('/');
6690 * Returns array of relevant context capability records.
6692 * @return array
6694 public function get_capabilities() {
6695 global $DB;
6697 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6699 $params = array();
6700 $sql = "SELECT *
6701 FROM {capabilities}
6702 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6704 return $DB->get_records_sql($sql.' '.$sort, $params);
6708 * Is this context part of any course? If yes return course context.
6710 * @param bool $strict true means throw exception if not found, false means return false if not found
6711 * @return context_course context of the enclosing course, null if not found or exception
6713 public function get_course_context($strict = true) {
6714 return $this;
6718 * Returns course context instance.
6720 * @static
6721 * @param int $courseid id from {course} table
6722 * @param int $strictness
6723 * @return context_course context instance
6725 public static function instance($courseid, $strictness = MUST_EXIST) {
6726 global $DB;
6728 if ($context = context::cache_get(CONTEXT_COURSE, $courseid)) {
6729 return $context;
6732 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $courseid))) {
6733 if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
6734 if ($course->category) {
6735 $parentcontext = context_coursecat::instance($course->category);
6736 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6737 } else {
6738 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6743 if ($record) {
6744 $context = new context_course($record);
6745 context::cache_add($context);
6746 return $context;
6749 return false;
6753 * Create missing context instances at course context level
6754 * @static
6756 protected static function create_level_instances() {
6757 global $DB;
6759 $sql = "SELECT ".CONTEXT_COURSE.", c.id
6760 FROM {course} c
6761 WHERE NOT EXISTS (SELECT 'x'
6762 FROM {context} cx
6763 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6764 $contextdata = $DB->get_recordset_sql($sql);
6765 foreach ($contextdata as $context) {
6766 context::insert_context_record(CONTEXT_COURSE, $context->id, null);
6768 $contextdata->close();
6772 * Returns sql necessary for purging of stale context instances.
6774 * @static
6775 * @return string cleanup SQL
6777 protected static function get_cleanup_sql() {
6778 $sql = "
6779 SELECT c.*
6780 FROM {context} c
6781 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6782 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6785 return $sql;
6789 * Rebuild context paths and depths at course context level.
6791 * @static
6792 * @param bool $force
6794 protected static function build_paths($force) {
6795 global $DB;
6797 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6798 if ($force) {
6799 $ctxemptyclause = $emptyclause = '';
6800 } else {
6801 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6802 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6805 $base = '/'.SYSCONTEXTID;
6807 // Standard frontpage
6808 $sql = "UPDATE {context}
6809 SET depth = 2,
6810 path = ".$DB->sql_concat("'$base/'", 'id')."
6811 WHERE contextlevel = ".CONTEXT_COURSE."
6812 AND EXISTS (SELECT 'x'
6813 FROM {course} c
6814 WHERE c.id = {context}.instanceid AND c.category = 0)
6815 $emptyclause";
6816 $DB->execute($sql);
6818 // standard courses
6819 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
6820 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
6821 FROM {context} ctx
6822 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6823 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6824 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6825 $ctxemptyclause";
6826 $trans = $DB->start_delegated_transaction();
6827 $DB->delete_records('context_temp');
6828 $DB->execute($sql);
6829 context::merge_context_temp_table();
6830 $DB->delete_records('context_temp');
6831 $trans->allow_commit();
6838 * Course module context class
6840 * @package core_access
6841 * @category access
6842 * @copyright Petr Skoda {@link http://skodak.org}
6843 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6844 * @since Moodle 2.2
6846 class context_module extends context {
6848 * Please use context_module::instance($cmid) if you need the instance of context.
6849 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6851 * @param stdClass $record
6853 protected function __construct(stdClass $record) {
6854 parent::__construct($record);
6855 if ($record->contextlevel != CONTEXT_MODULE) {
6856 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6861 * Returns human readable context level name.
6863 * @static
6864 * @return string the human readable context level name.
6866 public static function get_level_name() {
6867 return get_string('activitymodule');
6871 * Returns human readable context identifier.
6873 * @param boolean $withprefix whether to prefix the name of the context with the
6874 * module name, e.g. Forum, Glossary, etc.
6875 * @param boolean $short does not apply to module context
6876 * @return string the human readable context name.
6878 public function get_context_name($withprefix = true, $short = false) {
6879 global $DB;
6881 $name = '';
6882 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6883 FROM {course_modules} cm
6884 JOIN {modules} md ON md.id = cm.module
6885 WHERE cm.id = ?", array($this->_instanceid))) {
6886 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6887 if ($withprefix){
6888 $name = get_string('modulename', $cm->modname).': ';
6890 $name .= format_string($mod->name, true, array('context' => $this));
6893 return $name;
6897 * Returns the most relevant URL for this context.
6899 * @return moodle_url
6901 public function get_url() {
6902 global $DB;
6904 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6905 FROM {course_modules} cm
6906 JOIN {modules} md ON md.id = cm.module
6907 WHERE cm.id = ?", array($this->_instanceid))) {
6908 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6911 return new moodle_url('/');
6915 * Returns array of relevant context capability records.
6917 * @return array
6919 public function get_capabilities() {
6920 global $DB, $CFG;
6922 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6924 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6925 $module = $DB->get_record('modules', array('id'=>$cm->module));
6927 $subcaps = array();
6928 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6929 if (file_exists($subpluginsfile)) {
6930 $subplugins = array(); // should be redefined in the file
6931 include($subpluginsfile);
6932 if (!empty($subplugins)) {
6933 foreach (array_keys($subplugins) as $subplugintype) {
6934 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
6935 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6941 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6942 $extracaps = array();
6943 if (file_exists($modfile)) {
6944 include_once($modfile);
6945 $modfunction = $module->name.'_get_extra_capabilities';
6946 if (function_exists($modfunction)) {
6947 $extracaps = $modfunction();
6951 $extracaps = array_merge($subcaps, $extracaps);
6952 $extra = '';
6953 list($extra, $params) = $DB->get_in_or_equal(
6954 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
6955 if (!empty($extra)) {
6956 $extra = "OR name $extra";
6959 // Fetch the list of modules, and remove this one.
6960 $components = \core_component::get_component_list();
6961 $componentnames = $components['mod'];
6962 unset($componentnames["mod_{$module->name}"]);
6963 $componentnames = array_keys($componentnames);
6965 // Exclude all other modules.
6966 list($notcompsql, $notcompparams) = $DB->get_in_or_equal($componentnames, SQL_PARAMS_NAMED, 'notcomp', false);
6967 $params = array_merge($params, $notcompparams);
6970 // Exclude other component submodules.
6971 $i = 0;
6972 $ignorecomponents = [];
6973 foreach ($componentnames as $mod) {
6974 if ($subplugins = \core_component::get_subplugins($mod)) {
6975 foreach (array_keys($subplugins) as $subplugintype) {
6976 $paramname = "notlike{$i}";
6977 $ignorecomponents[] = $DB->sql_like('component', ":{$paramname}", true, true, true);
6978 $params[$paramname] = "{$subplugintype}_%";
6979 $i++;
6983 $notlikesql = "(" . implode(' AND ', $ignorecomponents) . ")";
6985 $sql = "SELECT *
6986 FROM {capabilities}
6987 WHERE (contextlevel = ".CONTEXT_MODULE."
6988 AND component {$notcompsql}
6989 AND {$notlikesql})
6990 $extra";
6992 return $DB->get_records_sql($sql.' '.$sort, $params);
6996 * Is this context part of any course? If yes return course context.
6998 * @param bool $strict true means throw exception if not found, false means return false if not found
6999 * @return context_course context of the enclosing course, null if not found or exception
7001 public function get_course_context($strict = true) {
7002 return $this->get_parent_context();
7006 * Returns module context instance.
7008 * @static
7009 * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
7010 * @param int $strictness
7011 * @return context_module context instance
7013 public static function instance($cmid, $strictness = MUST_EXIST) {
7014 global $DB;
7016 if ($context = context::cache_get(CONTEXT_MODULE, $cmid)) {
7017 return $context;
7020 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE, 'instanceid' => $cmid))) {
7021 if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
7022 $parentcontext = context_course::instance($cm->course);
7023 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
7027 if ($record) {
7028 $context = new context_module($record);
7029 context::cache_add($context);
7030 return $context;
7033 return false;
7037 * Create missing context instances at module context level
7038 * @static
7040 protected static function create_level_instances() {
7041 global $DB;
7043 $sql = "SELECT ".CONTEXT_MODULE.", cm.id
7044 FROM {course_modules} cm
7045 WHERE NOT EXISTS (SELECT 'x'
7046 FROM {context} cx
7047 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
7048 $contextdata = $DB->get_recordset_sql($sql);
7049 foreach ($contextdata as $context) {
7050 context::insert_context_record(CONTEXT_MODULE, $context->id, null);
7052 $contextdata->close();
7056 * Returns sql necessary for purging of stale context instances.
7058 * @static
7059 * @return string cleanup SQL
7061 protected static function get_cleanup_sql() {
7062 $sql = "
7063 SELECT c.*
7064 FROM {context} c
7065 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
7066 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
7069 return $sql;
7073 * Rebuild context paths and depths at module context level.
7075 * @static
7076 * @param bool $force
7078 protected static function build_paths($force) {
7079 global $DB;
7081 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
7082 if ($force) {
7083 $ctxemptyclause = '';
7084 } else {
7085 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7088 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7089 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7090 FROM {context} ctx
7091 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
7092 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
7093 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7094 $ctxemptyclause";
7095 $trans = $DB->start_delegated_transaction();
7096 $DB->delete_records('context_temp');
7097 $DB->execute($sql);
7098 context::merge_context_temp_table();
7099 $DB->delete_records('context_temp');
7100 $trans->allow_commit();
7107 * Block context class
7109 * @package core_access
7110 * @category access
7111 * @copyright Petr Skoda {@link http://skodak.org}
7112 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7113 * @since Moodle 2.2
7115 class context_block extends context {
7117 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
7118 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7120 * @param stdClass $record
7122 protected function __construct(stdClass $record) {
7123 parent::__construct($record);
7124 if ($record->contextlevel != CONTEXT_BLOCK) {
7125 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
7130 * Returns human readable context level name.
7132 * @static
7133 * @return string the human readable context level name.
7135 public static function get_level_name() {
7136 return get_string('block');
7140 * Returns human readable context identifier.
7142 * @param boolean $withprefix whether to prefix the name of the context with Block
7143 * @param boolean $short does not apply to block context
7144 * @return string the human readable context name.
7146 public function get_context_name($withprefix = true, $short = false) {
7147 global $DB, $CFG;
7149 $name = '';
7150 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
7151 global $CFG;
7152 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7153 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7154 $blockname = "block_$blockinstance->blockname";
7155 if ($blockobject = new $blockname()) {
7156 if ($withprefix){
7157 $name = get_string('block').': ';
7159 $name .= $blockobject->title;
7163 return $name;
7167 * Returns the most relevant URL for this context.
7169 * @return moodle_url
7171 public function get_url() {
7172 $parentcontexts = $this->get_parent_context();
7173 return $parentcontexts->get_url();
7177 * Returns array of relevant context capability records.
7179 * @return array
7181 public function get_capabilities() {
7182 global $DB;
7184 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7186 $params = array();
7187 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
7189 $extra = '';
7190 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7191 if ($extracaps) {
7192 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7193 $extra = "OR name $extra";
7196 $sql = "SELECT *
7197 FROM {capabilities}
7198 WHERE (contextlevel = ".CONTEXT_BLOCK."
7199 AND component = :component)
7200 $extra";
7201 $params['component'] = 'block_' . $bi->blockname;
7203 return $DB->get_records_sql($sql.' '.$sort, $params);
7207 * Is this context part of any course? If yes return course context.
7209 * @param bool $strict true means throw exception if not found, false means return false if not found
7210 * @return context_course context of the enclosing course, null if not found or exception
7212 public function get_course_context($strict = true) {
7213 $parentcontext = $this->get_parent_context();
7214 return $parentcontext->get_course_context($strict);
7218 * Returns block context instance.
7220 * @static
7221 * @param int $blockinstanceid id from {block_instances} table.
7222 * @param int $strictness
7223 * @return context_block context instance
7225 public static function instance($blockinstanceid, $strictness = MUST_EXIST) {
7226 global $DB;
7228 if ($context = context::cache_get(CONTEXT_BLOCK, $blockinstanceid)) {
7229 return $context;
7232 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $blockinstanceid))) {
7233 if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
7234 $parentcontext = context::instance_by_id($bi->parentcontextid);
7235 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7239 if ($record) {
7240 $context = new context_block($record);
7241 context::cache_add($context);
7242 return $context;
7245 return false;
7249 * Block do not have child contexts...
7250 * @return array
7252 public function get_child_contexts() {
7253 return array();
7257 * Create missing context instances at block context level
7258 * @static
7260 protected static function create_level_instances() {
7261 global $DB;
7263 $sql = "SELECT ".CONTEXT_BLOCK.", bi.id
7264 FROM {block_instances} bi
7265 WHERE NOT EXISTS (SELECT 'x'
7266 FROM {context} cx
7267 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7268 $contextdata = $DB->get_recordset_sql($sql);
7269 foreach ($contextdata as $context) {
7270 context::insert_context_record(CONTEXT_BLOCK, $context->id, null);
7272 $contextdata->close();
7276 * Returns sql necessary for purging of stale context instances.
7278 * @static
7279 * @return string cleanup SQL
7281 protected static function get_cleanup_sql() {
7282 $sql = "
7283 SELECT c.*
7284 FROM {context} c
7285 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7286 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7289 return $sql;
7293 * Rebuild context paths and depths at block context level.
7295 * @static
7296 * @param bool $force
7298 protected static function build_paths($force) {
7299 global $DB;
7301 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7302 if ($force) {
7303 $ctxemptyclause = '';
7304 } else {
7305 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7308 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7309 $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7310 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7311 FROM {context} ctx
7312 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7313 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7314 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7315 $ctxemptyclause";
7316 $trans = $DB->start_delegated_transaction();
7317 $DB->delete_records('context_temp');
7318 $DB->execute($sql);
7319 context::merge_context_temp_table();
7320 $DB->delete_records('context_temp');
7321 $trans->allow_commit();
7327 // ============== DEPRECATED FUNCTIONS ==========================================
7328 // Old context related functions were deprecated in 2.0, it is recommended
7329 // to use context classes in new code. Old function can be used when
7330 // creating patches that are supposed to be backported to older stable branches.
7331 // These deprecated functions will not be removed in near future,
7332 // before removing devs will be warned with a debugging message first,
7333 // then we will add error message and only after that we can remove the functions
7334 // completely.
7337 * Runs get_records select on context table and returns the result
7338 * Does get_records_select on the context table, and returns the results ordered
7339 * by contextlevel, and then the natural sort order within each level.
7340 * for the purpose of $select, you need to know that the context table has been
7341 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7343 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7344 * @param array $params any parameters required by $select.
7345 * @return array the requested context records.
7347 function get_sorted_contexts($select, $params = array()) {
7349 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7351 global $DB;
7352 if ($select) {
7353 $select = 'WHERE ' . $select;
7355 return $DB->get_records_sql("
7356 SELECT ctx.*
7357 FROM {context} ctx
7358 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7359 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7360 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7361 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7362 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7363 $select
7364 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7365 ", $params);
7369 * Given context and array of users, returns array of users whose enrolment status is suspended,
7370 * or enrolment has expired or has not started. Also removes those users from the given array
7372 * @param context $context context in which suspended users should be extracted.
7373 * @param array $users list of users.
7374 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7375 * @return array list of suspended users.
7377 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7378 global $DB;
7380 // Get active enrolled users.
7381 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7382 $activeusers = $DB->get_records_sql($sql, $params);
7384 // Move suspended users to a separate array & remove from the initial one.
7385 $susers = array();
7386 if (sizeof($activeusers)) {
7387 foreach ($users as $userid => $user) {
7388 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7389 $susers[$userid] = $user;
7390 unset($users[$userid]);
7394 return $susers;
7398 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7399 * or enrolment has expired or not started.
7401 * @param context $context context in which user enrolment is checked.
7402 * @param bool $usecache Enable or disable (default) the request cache
7403 * @return array list of suspended user id's.
7405 function get_suspended_userids(context $context, $usecache = false) {
7406 global $DB;
7408 if ($usecache) {
7409 $cache = cache::make('core', 'suspended_userids');
7410 $susers = $cache->get($context->id);
7411 if ($susers !== false) {
7412 return $susers;
7416 $coursecontext = $context->get_course_context();
7417 $susers = array();
7419 // Front page users are always enrolled, so suspended list is empty.
7420 if ($coursecontext->instanceid != SITEID) {
7421 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7422 $susers = $DB->get_fieldset_sql($sql, $params);
7423 $susers = array_combine($susers, $susers);
7426 // Cache results for the remainder of this request.
7427 if ($usecache) {
7428 $cache->set($context->id, $susers);
7431 return $susers;
7435 * Gets sql for finding users with capability in the given context
7437 * @param context $context
7438 * @param string|array $capability Capability name or array of names.
7439 * If an array is provided then this is the equivalent of a logical 'OR',
7440 * i.e. the user needs to have one of these capabilities.
7441 * @return array($sql, $params)
7443 function get_with_capability_sql(context $context, $capability) {
7444 static $i = 0;
7445 $i++;
7446 $prefix = 'cu' . $i . '_';
7448 $capjoin = get_with_capability_join($context, $capability, $prefix . 'u.id');
7450 $sql = "SELECT DISTINCT {$prefix}u.id
7451 FROM {user} {$prefix}u
7452 $capjoin->joins
7453 WHERE {$prefix}u.deleted = 0 AND $capjoin->wheres";
7455 return array($sql, $capjoin->params);
7459 * Gets sql joins for finding users with capability in the given context
7461 * @param context $context Context for the join
7462 * @param string|array $capability Capability name or array of names.
7463 * If an array is provided then this is the equivalent of a logical 'OR',
7464 * i.e. the user needs to have one of these capabilities.
7465 * @param string $useridcolumn e.g. 'u.id'
7466 * @return \core\dml\sql_join Contains joins, wheres, params
7468 function get_with_capability_join(context $context, $capability, $useridcolumn) {
7469 global $DB, $CFG;
7471 // Use unique prefix just in case somebody makes some SQL magic with the result.
7472 static $i = 0;
7473 $i++;
7474 $prefix = 'eu' . $i . '_';
7476 // First find the course context.
7477 $coursecontext = $context->get_course_context();
7479 $isfrontpage = ($coursecontext->instanceid == SITEID);
7481 $joins = array();
7482 $wheres = array();
7483 $params = array();
7485 list($contextids, $contextpaths) = get_context_info_list($context);
7487 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
7489 list($incaps, $capsparams) = $DB->get_in_or_equal($capability, SQL_PARAMS_NAMED, 'cap');
7491 $defs = array();
7492 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
7493 FROM {role_capabilities} rc
7494 JOIN {context} ctx on rc.contextid = ctx.id
7495 WHERE rc.contextid $incontexts AND rc.capability $incaps";
7496 $rcs = $DB->get_records_sql($sql, array_merge($cparams, $capsparams));
7497 foreach ($rcs as $rc) {
7498 $defs[$rc->path][$rc->roleid] = $rc->permission;
7501 $access = array();
7502 if (!empty($defs)) {
7503 foreach ($contextpaths as $path) {
7504 if (empty($defs[$path])) {
7505 continue;
7507 foreach ($defs[$path] as $roleid => $perm) {
7508 if ($perm == CAP_PROHIBIT) {
7509 $access[$roleid] = CAP_PROHIBIT;
7510 continue;
7512 if (!isset($access[$roleid])) {
7513 $access[$roleid] = (int) $perm;
7519 unset($defs);
7521 // Make lists of roles that are needed and prohibited.
7522 $needed = array(); // One of these is enough.
7523 $prohibited = array(); // Must not have any of these.
7524 foreach ($access as $roleid => $perm) {
7525 if ($perm == CAP_PROHIBIT) {
7526 unset($needed[$roleid]);
7527 $prohibited[$roleid] = true;
7528 } else {
7529 if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
7530 $needed[$roleid] = true;
7535 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
7536 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
7538 $nobody = false;
7540 if ($isfrontpage) {
7541 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
7542 $nobody = true;
7543 } else {
7544 if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
7545 // Everybody not having prohibit has the capability.
7546 $needed = array();
7547 } else {
7548 if (empty($needed)) {
7549 $nobody = true;
7553 } else {
7554 if (!empty($prohibited[$defaultuserroleid])) {
7555 $nobody = true;
7556 } else {
7557 if (!empty($needed[$defaultuserroleid])) {
7558 // Everybody not having prohibit has the capability.
7559 $needed = array();
7560 } else {
7561 if (empty($needed)) {
7562 $nobody = true;
7568 if ($nobody) {
7569 // Nobody can match so return some SQL that does not return any results.
7570 $wheres[] = "1 = 2";
7572 } else {
7574 if ($needed) {
7575 $ctxids = implode(',', $contextids);
7576 $roleids = implode(',', array_keys($needed));
7577 $joins[] = "JOIN {role_assignments} {$prefix}ra3
7578 ON ({$prefix}ra3.userid = $useridcolumn
7579 AND {$prefix}ra3.roleid IN ($roleids)
7580 AND {$prefix}ra3.contextid IN ($ctxids))";
7583 if ($prohibited) {
7584 $ctxids = implode(',', $contextids);
7585 $roleids = implode(',', array_keys($prohibited));
7586 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4
7587 ON ({$prefix}ra4.userid = $useridcolumn
7588 AND {$prefix}ra4.roleid IN ($roleids)
7589 AND {$prefix}ra4.contextid IN ($ctxids))";
7590 $wheres[] = "{$prefix}ra4.id IS NULL";
7595 $wheres[] = "$useridcolumn <> :{$prefix}guestid";
7596 $params["{$prefix}guestid"] = $CFG->siteguest;
7598 $joins = implode("\n", $joins);
7599 $wheres = "(" . implode(" AND ", $wheres) . ")";
7601 return new \core\dml\sql_join($joins, $wheres, $params);