MDL-60425 blog: Remove empty line
[moodle.git] / lib / accesslib.php
blob27ec530542be6a2cf8ceed170d2844843e76e2e5
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 // somehow make sure the user is not deleted and actually exists
482 if ($userid != 0) {
483 if ($userid == $USER->id and isset($USER->deleted)) {
484 // this prevents one query per page, it is a bit of cheating,
485 // but hopefully session is terminated properly once user is deleted
486 if ($USER->deleted) {
487 return false;
489 } else {
490 if (!context_user::instance($userid, IGNORE_MISSING)) {
491 // no user context == invalid userid
492 return false;
497 // context path/depth must be valid
498 if (empty($context->path) or $context->depth == 0) {
499 // this should not happen often, each upgrade tries to rebuild the context paths
500 debugging('Context id '.$context->id.' does not have valid path, please use context_helper::build_all_paths()');
501 if (is_siteadmin($userid)) {
502 return true;
503 } else {
504 return false;
508 // Find out if user is admin - it is not possible to override the doanything in any way
509 // and it is not possible to switch to admin role either.
510 if ($doanything) {
511 if (is_siteadmin($userid)) {
512 if ($userid != $USER->id) {
513 return true;
515 // make sure switchrole is not used in this context
516 if (empty($USER->access['rsw'])) {
517 return true;
519 $parts = explode('/', trim($context->path, '/'));
520 $path = '';
521 $switched = false;
522 foreach ($parts as $part) {
523 $path .= '/' . $part;
524 if (!empty($USER->access['rsw'][$path])) {
525 $switched = true;
526 break;
529 if (!$switched) {
530 return true;
532 //ok, admin switched role in this context, let's use normal access control rules
536 // Careful check for staleness...
537 $context->reload_if_dirty();
539 if ($USER->id == $userid) {
540 if (!isset($USER->access)) {
541 load_all_capabilities();
543 $access =& $USER->access;
545 } else {
546 // make sure user accessdata is really loaded
547 get_user_accessdata($userid, true);
548 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
551 return has_capability_in_accessdata($capability, $context, $access);
555 * Check if the user has any one of several capabilities from a list.
557 * This is just a utility method that calls has_capability in a loop. Try to put
558 * the capabilities that most users are likely to have first in the list for best
559 * performance.
561 * @category access
562 * @see has_capability()
564 * @param array $capabilities an array of capability names.
565 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
566 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
567 * @param boolean $doanything If false, ignore effect of admin role assignment
568 * @return boolean true if the user has any of these capabilities. Otherwise false.
570 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
571 foreach ($capabilities as $capability) {
572 if (has_capability($capability, $context, $user, $doanything)) {
573 return true;
576 return false;
580 * Check if the user has all the capabilities in a list.
582 * This is just a utility method that calls has_capability in a loop. Try to put
583 * the capabilities that fewest users are likely to have first in the list for best
584 * performance.
586 * @category access
587 * @see has_capability()
589 * @param array $capabilities an array of capability names.
590 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
591 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
592 * @param boolean $doanything If false, ignore effect of admin role assignment
593 * @return boolean true if the user has all of these capabilities. Otherwise false.
595 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
596 foreach ($capabilities as $capability) {
597 if (!has_capability($capability, $context, $user, $doanything)) {
598 return false;
601 return true;
605 * Is course creator going to have capability in a new course?
607 * This is intended to be used in enrolment plugins before or during course creation,
608 * do not use after the course is fully created.
610 * @category access
612 * @param string $capability the name of the capability to check.
613 * @param context $context course or category context where is course going to be created
614 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
615 * @return boolean true if the user will have this capability.
617 * @throws coding_exception if different type of context submitted
619 function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) {
620 global $CFG;
622 if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) {
623 throw new coding_exception('Only course or course category context expected');
626 if (has_capability($capability, $context, $user)) {
627 // User already has the capability, it could be only removed if CAP_PROHIBIT
628 // was involved here, but we ignore that.
629 return true;
632 if (!has_capability('moodle/course:create', $context, $user)) {
633 return false;
636 if (!enrol_is_enabled('manual')) {
637 return false;
640 if (empty($CFG->creatornewroleid)) {
641 return false;
644 if ($context->contextlevel == CONTEXT_COURSE) {
645 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
646 return false;
648 } else {
649 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
650 return false;
654 // Most likely they will be enrolled after the course creation is finished,
655 // does the new role have the required capability?
656 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
657 return isset($neededroles[$CFG->creatornewroleid]);
661 * Check if the user is an admin at the site level.
663 * Please note that use of proper capabilities is always encouraged,
664 * this function is supposed to be used from core or for temporary hacks.
666 * @category access
668 * @param int|stdClass $user_or_id user id or user object
669 * @return bool true if user is one of the administrators, false otherwise
671 function is_siteadmin($user_or_id = null) {
672 global $CFG, $USER;
674 if ($user_or_id === null) {
675 $user_or_id = $USER;
678 if (empty($user_or_id)) {
679 return false;
681 if (!empty($user_or_id->id)) {
682 $userid = $user_or_id->id;
683 } else {
684 $userid = $user_or_id;
687 // Because this script is called many times (150+ for course page) with
688 // the same parameters, it is worth doing minor optimisations. This static
689 // cache stores the value for a single userid, saving about 2ms from course
690 // page load time without using significant memory. As the static cache
691 // also includes the value it depends on, this cannot break unit tests.
692 static $knownid, $knownresult, $knownsiteadmins;
693 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
694 return $knownresult;
696 $knownid = $userid;
697 $knownsiteadmins = $CFG->siteadmins;
699 $siteadmins = explode(',', $CFG->siteadmins);
700 $knownresult = in_array($userid, $siteadmins);
701 return $knownresult;
705 * Returns true if user has at least one role assign
706 * of 'coursecontact' role (is potentially listed in some course descriptions).
708 * @param int $userid
709 * @return bool
711 function has_coursecontact_role($userid) {
712 global $DB, $CFG;
714 if (empty($CFG->coursecontact)) {
715 return false;
717 $sql = "SELECT 1
718 FROM {role_assignments}
719 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
720 return $DB->record_exists_sql($sql, array('userid'=>$userid));
724 * Does the user have a capability to do something?
726 * Walk the accessdata array and return true/false.
727 * Deals with prohibits, role switching, aggregating
728 * capabilities, etc.
730 * The main feature of here is being FAST and with no
731 * side effects.
733 * Notes:
735 * Switch Role merges with default role
736 * ------------------------------------
737 * If you are a teacher in course X, you have at least
738 * teacher-in-X + defaultloggedinuser-sitewide. So in the
739 * course you'll have techer+defaultloggedinuser.
740 * We try to mimic that in switchrole.
742 * Permission evaluation
743 * ---------------------
744 * Originally there was an extremely complicated way
745 * to determine the user access that dealt with
746 * "locality" or role assignments and role overrides.
747 * Now we simply evaluate access for each role separately
748 * and then verify if user has at least one role with allow
749 * and at the same time no role with prohibit.
751 * @access private
752 * @param string $capability
753 * @param context $context
754 * @param array $accessdata
755 * @return bool
757 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
758 global $CFG;
760 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
761 $path = $context->path;
762 $paths = array($path);
763 while($path = rtrim($path, '0123456789')) {
764 $path = rtrim($path, '/');
765 if ($path === '') {
766 break;
768 $paths[] = $path;
771 $roles = array();
772 $switchedrole = false;
774 // Find out if role switched
775 if (!empty($accessdata['rsw'])) {
776 // From the bottom up...
777 foreach ($paths as $path) {
778 if (isset($accessdata['rsw'][$path])) {
779 // Found a switchrole assignment - check for that role _plus_ the default user role
780 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
781 $switchedrole = true;
782 break;
787 if (!$switchedrole) {
788 // get all users roles in this context and above
789 foreach ($paths as $path) {
790 if (isset($accessdata['ra'][$path])) {
791 foreach ($accessdata['ra'][$path] as $roleid) {
792 $roles[$roleid] = null;
798 // Now find out what access is given to each role, going bottom-->up direction
799 $rdefs = get_role_definitions(array_keys($roles));
800 $allowed = false;
802 foreach ($roles as $roleid => $ignored) {
803 foreach ($paths as $path) {
804 if (isset($rdefs[$roleid][$path][$capability])) {
805 $perm = (int)$rdefs[$roleid][$path][$capability];
806 if ($perm === CAP_PROHIBIT) {
807 // any CAP_PROHIBIT found means no permission for the user
808 return false;
810 if (is_null($roles[$roleid])) {
811 $roles[$roleid] = $perm;
815 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
816 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
819 return $allowed;
823 * A convenience function that tests has_capability, and displays an error if
824 * the user does not have that capability.
826 * NOTE before Moodle 2.0, this function attempted to make an appropriate
827 * require_login call before checking the capability. This is no longer the case.
828 * You must call require_login (or one of its variants) if you want to check the
829 * user is logged in, before you call this function.
831 * @see has_capability()
833 * @param string $capability the name of the capability to check. For example mod/forum:view
834 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
835 * @param int $userid A user id. By default (null) checks the permissions of the current user.
836 * @param bool $doanything If false, ignore effect of admin role assignment
837 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
838 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
839 * @return void terminates with an error if the user does not have the given capability.
841 function require_capability($capability, context $context, $userid = null, $doanything = true,
842 $errormessage = 'nopermissions', $stringfile = '') {
843 if (!has_capability($capability, $context, $userid, $doanything)) {
844 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
849 * Return a nested array showing all role assignments for the user.
850 * [ra] => [contextpath][roleid] = roleid
852 * @access private
853 * @param int $userid - the id of the user
854 * @return array access info array
856 function get_user_roles_sitewide_accessdata($userid) {
857 global $CFG, $DB;
859 $accessdata = get_empty_accessdata();
861 // start with the default role
862 if (!empty($CFG->defaultuserroleid)) {
863 $syscontext = context_system::instance();
864 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
867 // load the "default frontpage role"
868 if (!empty($CFG->defaultfrontpageroleid)) {
869 $frontpagecontext = context_course::instance(get_site()->id);
870 if ($frontpagecontext->path) {
871 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
875 // Preload every assigned role.
876 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
877 FROM {role_assignments} ra
878 JOIN {context} ctx ON ctx.id = ra.contextid
879 WHERE ra.userid = :userid";
881 $rs = $DB->get_recordset_sql($sql, array('userid' => $userid));
883 foreach ($rs as $ra) {
884 // RAs leafs are arrays to support multi-role assignments...
885 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
888 $rs->close();
890 return $accessdata;
894 * Returns empty accessdata structure.
896 * @access private
897 * @return array empt accessdata
899 function get_empty_accessdata() {
900 $accessdata = array(); // named list
901 $accessdata['ra'] = array();
902 $accessdata['time'] = time();
903 $accessdata['rsw'] = array();
905 return $accessdata;
909 * Get accessdata for a given user.
911 * @access private
912 * @param int $userid
913 * @param bool $preloadonly true means do not return access array
914 * @return array accessdata
916 function get_user_accessdata($userid, $preloadonly=false) {
917 global $CFG, $ACCESSLIB_PRIVATE, $USER;
919 if (isset($USER->access)) {
920 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->access;
923 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
924 if (empty($userid)) {
925 if (!empty($CFG->notloggedinroleid)) {
926 $accessdata = get_role_access($CFG->notloggedinroleid);
927 } else {
928 // weird
929 return get_empty_accessdata();
932 } else if (isguestuser($userid)) {
933 if ($guestrole = get_guest_role()) {
934 $accessdata = get_role_access($guestrole->id);
935 } else {
936 //weird
937 return get_empty_accessdata();
940 } else {
941 // Includes default role and frontpage role.
942 $accessdata = get_user_roles_sitewide_accessdata($userid);
945 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
948 if ($preloadonly) {
949 return;
950 } else {
951 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
956 * A convenience function to completely load all the capabilities
957 * for the current user. It is called from has_capability() and functions change permissions.
959 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
960 * @see check_enrolment_plugins()
962 * @access private
963 * @return void
965 function load_all_capabilities() {
966 global $USER;
968 // roles not installed yet - we are in the middle of installation
969 if (during_initial_install()) {
970 return;
973 if (!isset($USER->id)) {
974 // this should not happen
975 $USER->id = 0;
978 unset($USER->access);
979 $USER->access = get_user_accessdata($USER->id);
981 // Clear to force a refresh
982 unset($USER->mycourses);
984 // init/reset internal enrol caches - active course enrolments and temp access
985 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
989 * A convenience function to completely reload all the capabilities
990 * for the current user when roles have been updated in a relevant
991 * context -- but PRESERVING switchroles and loginas.
992 * This function resets all accesslib and context caches.
994 * That is - completely transparent to the user.
996 * Note: reloads $USER->access completely.
998 * @access private
999 * @return void
1001 function reload_all_capabilities() {
1002 global $USER, $DB, $ACCESSLIB_PRIVATE;
1004 // copy switchroles
1005 $sw = array();
1006 if (!empty($USER->access['rsw'])) {
1007 $sw = $USER->access['rsw'];
1010 accesslib_clear_all_caches(true);
1011 unset($USER->access);
1013 // Prevent dirty flags refetching on this page.
1014 $ACCESSLIB_PRIVATE->dirtycontexts = array();
1015 $ACCESSLIB_PRIVATE->dirtyusers = array($USER->id => false);
1017 load_all_capabilities();
1019 foreach ($sw as $path => $roleid) {
1020 if ($record = $DB->get_record('context', array('path'=>$path))) {
1021 $context = context::instance_by_id($record->id);
1022 if (has_capability('moodle/role:switchroles', $context)) {
1023 role_switch($roleid, $context);
1030 * Adds a temp role to current USER->access array.
1032 * Useful for the "temporary guest" access we grant to logged-in users.
1033 * This is useful for enrol plugins only.
1035 * @since Moodle 2.2
1036 * @param context_course $coursecontext
1037 * @param int $roleid
1038 * @return void
1040 function load_temp_course_role(context_course $coursecontext, $roleid) {
1041 global $USER, $SITE;
1043 if (empty($roleid)) {
1044 debugging('invalid role specified in load_temp_course_role()');
1045 return;
1048 if ($coursecontext->instanceid == $SITE->id) {
1049 debugging('Can not use temp roles on the frontpage');
1050 return;
1053 if (!isset($USER->access)) {
1054 load_all_capabilities();
1057 $coursecontext->reload_if_dirty();
1059 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1060 return;
1063 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1067 * Removes any extra guest roles from current USER->access array.
1068 * This is useful for enrol plugins only.
1070 * @since Moodle 2.2
1071 * @param context_course $coursecontext
1072 * @return void
1074 function remove_temp_course_roles(context_course $coursecontext) {
1075 global $DB, $USER, $SITE;
1077 if ($coursecontext->instanceid == $SITE->id) {
1078 debugging('Can not use temp roles on the frontpage');
1079 return;
1082 if (empty($USER->access['ra'][$coursecontext->path])) {
1083 //no roles here, weird
1084 return;
1087 $sql = "SELECT DISTINCT ra.roleid AS id
1088 FROM {role_assignments} ra
1089 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1090 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1092 $USER->access['ra'][$coursecontext->path] = array();
1093 foreach($ras as $r) {
1094 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1099 * Returns array of all role archetypes.
1101 * @return array
1103 function get_role_archetypes() {
1104 return array(
1105 'manager' => 'manager',
1106 'coursecreator' => 'coursecreator',
1107 'editingteacher' => 'editingteacher',
1108 'teacher' => 'teacher',
1109 'student' => 'student',
1110 'guest' => 'guest',
1111 'user' => 'user',
1112 'frontpage' => 'frontpage'
1117 * Assign the defaults found in this capability definition to roles that have
1118 * the corresponding legacy capabilities assigned to them.
1120 * @param string $capability
1121 * @param array $legacyperms an array in the format (example):
1122 * 'guest' => CAP_PREVENT,
1123 * 'student' => CAP_ALLOW,
1124 * 'teacher' => CAP_ALLOW,
1125 * 'editingteacher' => CAP_ALLOW,
1126 * 'coursecreator' => CAP_ALLOW,
1127 * 'manager' => CAP_ALLOW
1128 * @return boolean success or failure.
1130 function assign_legacy_capabilities($capability, $legacyperms) {
1132 $archetypes = get_role_archetypes();
1134 foreach ($legacyperms as $type => $perm) {
1136 $systemcontext = context_system::instance();
1137 if ($type === 'admin') {
1138 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1139 $type = 'manager';
1142 if (!array_key_exists($type, $archetypes)) {
1143 print_error('invalidlegacy', '', '', $type);
1146 if ($roles = get_archetype_roles($type)) {
1147 foreach ($roles as $role) {
1148 // Assign a site level capability.
1149 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1150 return false;
1155 return true;
1159 * Verify capability risks.
1161 * @param stdClass $capability a capability - a row from the capabilities table.
1162 * @return boolean whether this capability is safe - that is, whether people with the
1163 * safeoverrides capability should be allowed to change it.
1165 function is_safe_capability($capability) {
1166 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1170 * Get the local override (if any) for a given capability in a role in a context
1172 * @param int $roleid
1173 * @param int $contextid
1174 * @param string $capability
1175 * @return stdClass local capability override
1177 function get_local_override($roleid, $contextid, $capability) {
1178 global $DB;
1179 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1183 * Returns context instance plus related course and cm instances
1185 * @param int $contextid
1186 * @return array of ($context, $course, $cm)
1188 function get_context_info_array($contextid) {
1189 global $DB;
1191 $context = context::instance_by_id($contextid, MUST_EXIST);
1192 $course = null;
1193 $cm = null;
1195 if ($context->contextlevel == CONTEXT_COURSE) {
1196 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1198 } else if ($context->contextlevel == CONTEXT_MODULE) {
1199 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1200 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1202 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1203 $parent = $context->get_parent_context();
1205 if ($parent->contextlevel == CONTEXT_COURSE) {
1206 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1207 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1208 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1209 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1213 return array($context, $course, $cm);
1217 * Function that creates a role
1219 * @param string $name role name
1220 * @param string $shortname role short name
1221 * @param string $description role description
1222 * @param string $archetype
1223 * @return int id or dml_exception
1225 function create_role($name, $shortname, $description, $archetype = '') {
1226 global $DB;
1228 if (strpos($archetype, 'moodle/legacy:') !== false) {
1229 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1232 // verify role archetype actually exists
1233 $archetypes = get_role_archetypes();
1234 if (empty($archetypes[$archetype])) {
1235 $archetype = '';
1238 // Insert the role record.
1239 $role = new stdClass();
1240 $role->name = $name;
1241 $role->shortname = $shortname;
1242 $role->description = $description;
1243 $role->archetype = $archetype;
1245 //find free sortorder number
1246 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1247 if (empty($role->sortorder)) {
1248 $role->sortorder = 1;
1250 $id = $DB->insert_record('role', $role);
1252 return $id;
1256 * Function that deletes a role and cleanups up after it
1258 * @param int $roleid id of role to delete
1259 * @return bool always true
1261 function delete_role($roleid) {
1262 global $DB;
1264 // first unssign all users
1265 role_unassign_all(array('roleid'=>$roleid));
1267 // cleanup all references to this role, ignore errors
1268 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1269 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1270 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1271 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1272 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1273 $DB->delete_records('role_names', array('roleid'=>$roleid));
1274 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1276 // Get role record before it's deleted.
1277 $role = $DB->get_record('role', array('id'=>$roleid));
1279 // Finally delete the role itself.
1280 $DB->delete_records('role', array('id'=>$roleid));
1282 // Trigger event.
1283 $event = \core\event\role_deleted::create(
1284 array(
1285 'context' => context_system::instance(),
1286 'objectid' => $roleid,
1287 'other' =>
1288 array(
1289 'shortname' => $role->shortname,
1290 'description' => $role->description,
1291 'archetype' => $role->archetype
1295 $event->add_record_snapshot('role', $role);
1296 $event->trigger();
1298 // Reset any cache of this role, including MUC.
1299 accesslib_clear_role_cache($roleid);
1301 return true;
1305 * Function to write context specific overrides, or default capabilities.
1307 * @param string $capability string name
1308 * @param int $permission CAP_ constants
1309 * @param int $roleid role id
1310 * @param int|context $contextid context id
1311 * @param bool $overwrite
1312 * @return bool always true or exception
1314 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1315 global $USER, $DB;
1317 if ($contextid instanceof context) {
1318 $context = $contextid;
1319 } else {
1320 $context = context::instance_by_id($contextid);
1323 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1324 unassign_capability($capability, $roleid, $context->id);
1325 return true;
1328 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1330 if ($existing and !$overwrite) { // We want to keep whatever is there already
1331 return true;
1334 $cap = new stdClass();
1335 $cap->contextid = $context->id;
1336 $cap->roleid = $roleid;
1337 $cap->capability = $capability;
1338 $cap->permission = $permission;
1339 $cap->timemodified = time();
1340 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1342 if ($existing) {
1343 $cap->id = $existing->id;
1344 $DB->update_record('role_capabilities', $cap);
1345 } else {
1346 if ($DB->record_exists('context', array('id'=>$context->id))) {
1347 $DB->insert_record('role_capabilities', $cap);
1351 // Reset any cache of this role, including MUC.
1352 accesslib_clear_role_cache($roleid);
1354 return true;
1358 * Unassign a capability from a role.
1360 * @param string $capability the name of the capability
1361 * @param int $roleid the role id
1362 * @param int|context $contextid null means all contexts
1363 * @return boolean true or exception
1365 function unassign_capability($capability, $roleid, $contextid = null) {
1366 global $DB;
1368 if (!empty($contextid)) {
1369 if ($contextid instanceof context) {
1370 $context = $contextid;
1371 } else {
1372 $context = context::instance_by_id($contextid);
1374 // delete from context rel, if this is the last override in this context
1375 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1376 } else {
1377 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1380 // Reset any cache of this role, including MUC.
1381 accesslib_clear_role_cache($roleid);
1383 return true;
1387 * Get the roles that have a given capability assigned to it
1389 * This function does not resolve the actual permission of the capability.
1390 * It just checks for permissions and overrides.
1391 * Use get_roles_with_cap_in_context() if resolution is required.
1393 * @param string $capability capability name (string)
1394 * @param string $permission optional, the permission defined for this capability
1395 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1396 * @param stdClass $context null means any
1397 * @return array of role records
1399 function get_roles_with_capability($capability, $permission = null, $context = null) {
1400 global $DB;
1402 if ($context) {
1403 $contexts = $context->get_parent_context_ids(true);
1404 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1405 $contextsql = "AND rc.contextid $insql";
1406 } else {
1407 $params = array();
1408 $contextsql = '';
1411 if ($permission) {
1412 $permissionsql = " AND rc.permission = :permission";
1413 $params['permission'] = $permission;
1414 } else {
1415 $permissionsql = '';
1418 $sql = "SELECT r.*
1419 FROM {role} r
1420 WHERE r.id IN (SELECT rc.roleid
1421 FROM {role_capabilities} rc
1422 WHERE rc.capability = :capname
1423 $contextsql
1424 $permissionsql)";
1425 $params['capname'] = $capability;
1428 return $DB->get_records_sql($sql, $params);
1432 * This function makes a role-assignment (a role for a user in a particular context)
1434 * @param int $roleid the role of the id
1435 * @param int $userid userid
1436 * @param int|context $contextid id of the context
1437 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1438 * @param int $itemid id of enrolment/auth plugin
1439 * @param string $timemodified defaults to current time
1440 * @return int new/existing id of the assignment
1442 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1443 global $USER, $DB;
1445 // first of all detect if somebody is using old style parameters
1446 if ($contextid === 0 or is_numeric($component)) {
1447 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1450 // now validate all parameters
1451 if (empty($roleid)) {
1452 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1455 if (empty($userid)) {
1456 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1459 if ($itemid) {
1460 if (strpos($component, '_') === false) {
1461 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1463 } else {
1464 $itemid = 0;
1465 if ($component !== '' and strpos($component, '_') === false) {
1466 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1470 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1471 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1474 if ($contextid instanceof context) {
1475 $context = $contextid;
1476 } else {
1477 $context = context::instance_by_id($contextid, MUST_EXIST);
1480 if (!$timemodified) {
1481 $timemodified = time();
1484 // Check for existing entry
1485 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1487 if ($ras) {
1488 // role already assigned - this should not happen
1489 if (count($ras) > 1) {
1490 // very weird - remove all duplicates!
1491 $ra = array_shift($ras);
1492 foreach ($ras as $r) {
1493 $DB->delete_records('role_assignments', array('id'=>$r->id));
1495 } else {
1496 $ra = reset($ras);
1499 // actually there is no need to update, reset anything or trigger any event, so just return
1500 return $ra->id;
1503 // Create a new entry
1504 $ra = new stdClass();
1505 $ra->roleid = $roleid;
1506 $ra->contextid = $context->id;
1507 $ra->userid = $userid;
1508 $ra->component = $component;
1509 $ra->itemid = $itemid;
1510 $ra->timemodified = $timemodified;
1511 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1512 $ra->sortorder = 0;
1514 $ra->id = $DB->insert_record('role_assignments', $ra);
1516 // Role assignments have changed, so mark user as dirty.
1517 mark_user_dirty($userid);
1519 core_course_category::role_assignment_changed($roleid, $context);
1521 $event = \core\event\role_assigned::create(array(
1522 'context' => $context,
1523 'objectid' => $ra->roleid,
1524 'relateduserid' => $ra->userid,
1525 'other' => array(
1526 'id' => $ra->id,
1527 'component' => $ra->component,
1528 'itemid' => $ra->itemid
1531 $event->add_record_snapshot('role_assignments', $ra);
1532 $event->trigger();
1534 return $ra->id;
1538 * Removes one role assignment
1540 * @param int $roleid
1541 * @param int $userid
1542 * @param int $contextid
1543 * @param string $component
1544 * @param int $itemid
1545 * @return void
1547 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1548 // first make sure the params make sense
1549 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1550 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1553 if ($itemid) {
1554 if (strpos($component, '_') === false) {
1555 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1557 } else {
1558 $itemid = 0;
1559 if ($component !== '' and strpos($component, '_') === false) {
1560 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1564 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1568 * Removes multiple role assignments, parameters may contain:
1569 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1571 * @param array $params role assignment parameters
1572 * @param bool $subcontexts unassign in subcontexts too
1573 * @param bool $includemanual include manual role assignments too
1574 * @return void
1576 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1577 global $USER, $CFG, $DB;
1579 if (!$params) {
1580 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1583 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1584 foreach ($params as $key=>$value) {
1585 if (!in_array($key, $allowed)) {
1586 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1590 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1591 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1594 if ($includemanual) {
1595 if (!isset($params['component']) or $params['component'] === '') {
1596 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1600 if ($subcontexts) {
1601 if (empty($params['contextid'])) {
1602 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1606 $ras = $DB->get_records('role_assignments', $params);
1607 foreach($ras as $ra) {
1608 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1609 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1610 // Role assignments have changed, so mark user as dirty.
1611 mark_user_dirty($ra->userid);
1613 $event = \core\event\role_unassigned::create(array(
1614 'context' => $context,
1615 'objectid' => $ra->roleid,
1616 'relateduserid' => $ra->userid,
1617 'other' => array(
1618 'id' => $ra->id,
1619 'component' => $ra->component,
1620 'itemid' => $ra->itemid
1623 $event->add_record_snapshot('role_assignments', $ra);
1624 $event->trigger();
1625 core_course_category::role_assignment_changed($ra->roleid, $context);
1628 unset($ras);
1630 // process subcontexts
1631 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1632 if ($params['contextid'] instanceof context) {
1633 $context = $params['contextid'];
1634 } else {
1635 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1638 if ($context) {
1639 $contexts = $context->get_child_contexts();
1640 $mparams = $params;
1641 foreach($contexts as $context) {
1642 $mparams['contextid'] = $context->id;
1643 $ras = $DB->get_records('role_assignments', $mparams);
1644 foreach($ras as $ra) {
1645 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1646 // Role assignments have changed, so mark user as dirty.
1647 mark_user_dirty($ra->userid);
1649 $event = \core\event\role_unassigned::create(
1650 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1651 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1652 $event->add_record_snapshot('role_assignments', $ra);
1653 $event->trigger();
1654 core_course_category::role_assignment_changed($ra->roleid, $context);
1660 // do this once more for all manual role assignments
1661 if ($includemanual) {
1662 $params['component'] = '';
1663 role_unassign_all($params, $subcontexts, false);
1668 * Mark a user as dirty (with timestamp) so as to force reloading of the user session.
1670 * @param int $userid
1671 * @return void
1673 function mark_user_dirty($userid) {
1674 global $CFG, $ACCESSLIB_PRIVATE;
1676 if (during_initial_install()) {
1677 return;
1680 // Throw exception if invalid userid is provided.
1681 if (empty($userid)) {
1682 throw new coding_exception('Invalid user parameter supplied for mark_user_dirty() function!');
1685 // Set dirty flag in database, set dirty field locally, and clear local accessdata cache.
1686 set_cache_flag('accesslib/dirtyusers', $userid, 1, time() + $CFG->sessiontimeout);
1687 $ACCESSLIB_PRIVATE->dirtyusers[$userid] = 1;
1688 unset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
1692 * Determines if a user is currently logged in
1694 * @category access
1696 * @return bool
1698 function isloggedin() {
1699 global $USER;
1701 return (!empty($USER->id));
1705 * Determines if a user is logged in as real guest user with username 'guest'.
1707 * @category access
1709 * @param int|object $user mixed user object or id, $USER if not specified
1710 * @return bool true if user is the real guest user, false if not logged in or other user
1712 function isguestuser($user = null) {
1713 global $USER, $DB, $CFG;
1715 // make sure we have the user id cached in config table, because we are going to use it a lot
1716 if (empty($CFG->siteguest)) {
1717 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1718 // guest does not exist yet, weird
1719 return false;
1721 set_config('siteguest', $guestid);
1723 if ($user === null) {
1724 $user = $USER;
1727 if ($user === null) {
1728 // happens when setting the $USER
1729 return false;
1731 } else if (is_numeric($user)) {
1732 return ($CFG->siteguest == $user);
1734 } else if (is_object($user)) {
1735 if (empty($user->id)) {
1736 return false; // not logged in means is not be guest
1737 } else {
1738 return ($CFG->siteguest == $user->id);
1741 } else {
1742 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1747 * Does user have a (temporary or real) guest access to course?
1749 * @category access
1751 * @param context $context
1752 * @param stdClass|int $user
1753 * @return bool
1755 function is_guest(context $context, $user = null) {
1756 global $USER;
1758 // first find the course context
1759 $coursecontext = $context->get_course_context();
1761 // make sure there is a real user specified
1762 if ($user === null) {
1763 $userid = isset($USER->id) ? $USER->id : 0;
1764 } else {
1765 $userid = is_object($user) ? $user->id : $user;
1768 if (isguestuser($userid)) {
1769 // can not inspect or be enrolled
1770 return true;
1773 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1774 // viewing users appear out of nowhere, they are neither guests nor participants
1775 return false;
1778 // consider only real active enrolments here
1779 if (is_enrolled($coursecontext, $user, '', true)) {
1780 return false;
1783 return true;
1787 * Returns true if the user has moodle/course:view capability in the course,
1788 * this is intended for admins, managers (aka small admins), inspectors, etc.
1790 * @category access
1792 * @param context $context
1793 * @param int|stdClass $user if null $USER is used
1794 * @param string $withcapability extra capability name
1795 * @return bool
1797 function is_viewing(context $context, $user = null, $withcapability = '') {
1798 // first find the course context
1799 $coursecontext = $context->get_course_context();
1801 if (isguestuser($user)) {
1802 // can not inspect
1803 return false;
1806 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1807 // admins are allowed to inspect courses
1808 return false;
1811 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1812 // site admins always have the capability, but the enrolment above blocks
1813 return false;
1816 return true;
1820 * Returns true if the user is able to access the course.
1822 * This function is in no way, shape, or form a substitute for require_login.
1823 * It should only be used in circumstances where it is not possible to call require_login
1824 * such as the navigation.
1826 * This function checks many of the methods of access to a course such as the view
1827 * capability, enrollments, and guest access. It also makes use of the cache
1828 * generated by require_login for guest access.
1830 * The flags within the $USER object that are used here should NEVER be used outside
1831 * of this function can_access_course and require_login. Doing so WILL break future
1832 * versions.
1834 * @param stdClass $course record
1835 * @param stdClass|int|null $user user record or id, current user if null
1836 * @param string $withcapability Check for this capability as well.
1837 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1838 * @return boolean Returns true if the user is able to access the course
1840 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
1841 global $DB, $USER;
1843 // this function originally accepted $coursecontext parameter
1844 if ($course instanceof context) {
1845 if ($course instanceof context_course) {
1846 debugging('deprecated context parameter, please use $course record');
1847 $coursecontext = $course;
1848 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
1849 } else {
1850 debugging('Invalid context parameter, please use $course record');
1851 return false;
1853 } else {
1854 $coursecontext = context_course::instance($course->id);
1857 if (!isset($USER->id)) {
1858 // should never happen
1859 $USER->id = 0;
1860 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
1863 // make sure there is a user specified
1864 if ($user === null) {
1865 $userid = $USER->id;
1866 } else {
1867 $userid = is_object($user) ? $user->id : $user;
1869 unset($user);
1871 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
1872 return false;
1875 if ($userid == $USER->id) {
1876 if (!empty($USER->access['rsw'][$coursecontext->path])) {
1877 // the fact that somebody switched role means they can access the course no matter to what role they switched
1878 return true;
1882 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
1883 return false;
1886 if (is_viewing($coursecontext, $userid)) {
1887 return true;
1890 if ($userid != $USER->id) {
1891 // for performance reasons we do not verify temporary guest access for other users, sorry...
1892 return is_enrolled($coursecontext, $userid, '', $onlyactive);
1895 // === from here we deal only with $USER ===
1897 $coursecontext->reload_if_dirty();
1899 if (isset($USER->enrol['enrolled'][$course->id])) {
1900 if ($USER->enrol['enrolled'][$course->id] > time()) {
1901 return true;
1904 if (isset($USER->enrol['tempguest'][$course->id])) {
1905 if ($USER->enrol['tempguest'][$course->id] > time()) {
1906 return true;
1910 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
1911 return true;
1914 // if not enrolled try to gain temporary guest access
1915 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
1916 $enrols = enrol_get_plugins(true);
1917 foreach($instances as $instance) {
1918 if (!isset($enrols[$instance->enrol])) {
1919 continue;
1921 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
1922 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
1923 if ($until !== false and $until > time()) {
1924 $USER->enrol['tempguest'][$course->id] = $until;
1925 return true;
1928 if (isset($USER->enrol['tempguest'][$course->id])) {
1929 unset($USER->enrol['tempguest'][$course->id]);
1930 remove_temp_course_roles($coursecontext);
1933 return false;
1937 * Loads the capability definitions for the component (from file).
1939 * Loads the capability definitions for the component (from file). If no
1940 * capabilities are defined for the component, we simply return an empty array.
1942 * @access private
1943 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
1944 * @return array array of capabilities
1946 function load_capability_def($component) {
1947 $defpath = core_component::get_component_directory($component).'/db/access.php';
1949 $capabilities = array();
1950 if (file_exists($defpath)) {
1951 require($defpath);
1952 if (!empty(${$component.'_capabilities'})) {
1953 // BC capability array name
1954 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
1955 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
1956 $capabilities = ${$component.'_capabilities'};
1960 return $capabilities;
1964 * Gets the capabilities that have been cached in the database for this component.
1966 * @access private
1967 * @param string $component - examples: 'moodle', 'mod_forum'
1968 * @return array array of capabilities
1970 function get_cached_capabilities($component = 'moodle') {
1971 global $DB;
1972 $caps = get_all_capabilities();
1973 $componentcaps = array();
1974 foreach ($caps as $cap) {
1975 if ($cap['component'] == $component) {
1976 $componentcaps[] = (object) $cap;
1979 return $componentcaps;
1983 * Returns default capabilities for given role archetype.
1985 * @param string $archetype role archetype
1986 * @return array
1988 function get_default_capabilities($archetype) {
1989 global $DB;
1991 if (!$archetype) {
1992 return array();
1995 $alldefs = array();
1996 $defaults = array();
1997 $components = array();
1998 $allcaps = get_all_capabilities();
2000 foreach ($allcaps as $cap) {
2001 if (!in_array($cap['component'], $components)) {
2002 $components[] = $cap['component'];
2003 $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
2006 foreach($alldefs as $name=>$def) {
2007 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2008 if (isset($def['archetypes'])) {
2009 if (isset($def['archetypes'][$archetype])) {
2010 $defaults[$name] = $def['archetypes'][$archetype];
2012 // 'legacy' is for backward compatibility with 1.9 access.php
2013 } else {
2014 if (isset($def['legacy'][$archetype])) {
2015 $defaults[$name] = $def['legacy'][$archetype];
2020 return $defaults;
2024 * Return default roles that can be assigned, overridden or switched
2025 * by give role archetype.
2027 * @param string $type assign|override|switch|view
2028 * @param string $archetype
2029 * @return array of role ids
2031 function get_default_role_archetype_allows($type, $archetype) {
2032 global $DB;
2034 if (empty($archetype)) {
2035 return array();
2038 $roles = $DB->get_records('role');
2039 $archetypemap = array();
2040 foreach ($roles as $role) {
2041 if ($role->archetype) {
2042 $archetypemap[$role->archetype][$role->id] = $role->id;
2046 $defaults = array(
2047 'assign' => array(
2048 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2049 'coursecreator' => array(),
2050 'editingteacher' => array('teacher', 'student'),
2051 'teacher' => array(),
2052 'student' => array(),
2053 'guest' => array(),
2054 'user' => array(),
2055 'frontpage' => array(),
2057 'override' => array(
2058 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2059 'coursecreator' => array(),
2060 'editingteacher' => array('teacher', 'student', 'guest'),
2061 'teacher' => array(),
2062 'student' => array(),
2063 'guest' => array(),
2064 'user' => array(),
2065 'frontpage' => array(),
2067 'switch' => array(
2068 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2069 'coursecreator' => array(),
2070 'editingteacher' => array('teacher', 'student', 'guest'),
2071 'teacher' => array('student', 'guest'),
2072 'student' => array(),
2073 'guest' => array(),
2074 'user' => array(),
2075 'frontpage' => array(),
2077 'view' => array(
2078 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2079 'coursecreator' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2080 'editingteacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2081 'teacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2082 'student' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2083 'guest' => array(),
2084 'user' => array(),
2085 'frontpage' => array(),
2089 if (!isset($defaults[$type][$archetype])) {
2090 debugging("Unknown type '$type'' or archetype '$archetype''");
2091 return array();
2094 $return = array();
2095 foreach ($defaults[$type][$archetype] as $at) {
2096 if (isset($archetypemap[$at])) {
2097 foreach ($archetypemap[$at] as $roleid) {
2098 $return[$roleid] = $roleid;
2103 return $return;
2107 * Reset role capabilities to default according to selected role archetype.
2108 * If no archetype selected, removes all capabilities.
2110 * This applies to capabilities that are assigned to the role (that you could
2111 * edit in the 'define roles' interface), and not to any capability overrides
2112 * in different locations.
2114 * @param int $roleid ID of role to reset capabilities for
2116 function reset_role_capabilities($roleid) {
2117 global $DB;
2119 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2120 $defaultcaps = get_default_capabilities($role->archetype);
2122 $systemcontext = context_system::instance();
2124 $DB->delete_records('role_capabilities',
2125 array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2127 foreach($defaultcaps as $cap=>$permission) {
2128 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2131 // Reset any cache of this role, including MUC.
2132 accesslib_clear_role_cache($roleid);
2136 * Updates the capabilities table with the component capability definitions.
2137 * If no parameters are given, the function updates the core moodle
2138 * capabilities.
2140 * Note that the absence of the db/access.php capabilities definition file
2141 * will cause any stored capabilities for the component to be removed from
2142 * the database.
2144 * @access private
2145 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2146 * @return boolean true if success, exception in case of any problems
2148 function update_capabilities($component = 'moodle') {
2149 global $DB, $OUTPUT;
2151 $storedcaps = array();
2153 $filecaps = load_capability_def($component);
2154 foreach($filecaps as $capname=>$unused) {
2155 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2156 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2160 // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2161 // So ensure our updating is based on fresh data.
2162 cache::make('core', 'capabilities')->delete('core_capabilities');
2164 $cachedcaps = get_cached_capabilities($component);
2165 if ($cachedcaps) {
2166 foreach ($cachedcaps as $cachedcap) {
2167 array_push($storedcaps, $cachedcap->name);
2168 // update risk bitmasks and context levels in existing capabilities if needed
2169 if (array_key_exists($cachedcap->name, $filecaps)) {
2170 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2171 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2173 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2174 $updatecap = new stdClass();
2175 $updatecap->id = $cachedcap->id;
2176 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2177 $DB->update_record('capabilities', $updatecap);
2179 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2180 $updatecap = new stdClass();
2181 $updatecap->id = $cachedcap->id;
2182 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2183 $DB->update_record('capabilities', $updatecap);
2186 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2187 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2189 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2190 $updatecap = new stdClass();
2191 $updatecap->id = $cachedcap->id;
2192 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2193 $DB->update_record('capabilities', $updatecap);
2199 // Flush the cached again, as we have changed DB.
2200 cache::make('core', 'capabilities')->delete('core_capabilities');
2202 // Are there new capabilities in the file definition?
2203 $newcaps = array();
2205 foreach ($filecaps as $filecap => $def) {
2206 if (!$storedcaps ||
2207 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2208 if (!array_key_exists('riskbitmask', $def)) {
2209 $def['riskbitmask'] = 0; // no risk if not specified
2211 $newcaps[$filecap] = $def;
2214 // Add new capabilities to the stored definition.
2215 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2216 foreach ($newcaps as $capname => $capdef) {
2217 $capability = new stdClass();
2218 $capability->name = $capname;
2219 $capability->captype = $capdef['captype'];
2220 $capability->contextlevel = $capdef['contextlevel'];
2221 $capability->component = $component;
2222 $capability->riskbitmask = $capdef['riskbitmask'];
2224 $DB->insert_record('capabilities', $capability, false);
2226 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2227 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2228 foreach ($rolecapabilities as $rolecapability){
2229 //assign_capability will update rather than insert if capability exists
2230 if (!assign_capability($capname, $rolecapability->permission,
2231 $rolecapability->roleid, $rolecapability->contextid, true)){
2232 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2236 // we ignore archetype key if we have cloned permissions
2237 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2238 assign_legacy_capabilities($capname, $capdef['archetypes']);
2239 // 'legacy' is for backward compatibility with 1.9 access.php
2240 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2241 assign_legacy_capabilities($capname, $capdef['legacy']);
2244 // Are there any capabilities that have been removed from the file
2245 // definition that we need to delete from the stored capabilities and
2246 // role assignments?
2247 capabilities_cleanup($component, $filecaps);
2249 // reset static caches
2250 accesslib_reset_role_cache();
2252 // Flush the cached again, as we have changed DB.
2253 cache::make('core', 'capabilities')->delete('core_capabilities');
2255 return true;
2259 * Deletes cached capabilities that are no longer needed by the component.
2260 * Also unassigns these capabilities from any roles that have them.
2261 * NOTE: this function is called from lib/db/upgrade.php
2263 * @access private
2264 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2265 * @param array $newcapdef array of the new capability definitions that will be
2266 * compared with the cached capabilities
2267 * @return int number of deprecated capabilities that have been removed
2269 function capabilities_cleanup($component, $newcapdef = null) {
2270 global $DB;
2272 $removedcount = 0;
2274 if ($cachedcaps = get_cached_capabilities($component)) {
2275 foreach ($cachedcaps as $cachedcap) {
2276 if (empty($newcapdef) ||
2277 array_key_exists($cachedcap->name, $newcapdef) === false) {
2279 // Remove from capabilities cache.
2280 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2281 $removedcount++;
2282 // Delete from roles.
2283 if ($roles = get_roles_with_capability($cachedcap->name)) {
2284 foreach($roles as $role) {
2285 if (!unassign_capability($cachedcap->name, $role->id)) {
2286 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2290 } // End if.
2293 if ($removedcount) {
2294 cache::make('core', 'capabilities')->delete('core_capabilities');
2296 return $removedcount;
2300 * Returns an array of all the known types of risk
2301 * The array keys can be used, for example as CSS class names, or in calls to
2302 * print_risk_icon. The values are the corresponding RISK_ constants.
2304 * @return array all the known types of risk.
2306 function get_all_risks() {
2307 return array(
2308 'riskmanagetrust' => RISK_MANAGETRUST,
2309 'riskconfig' => RISK_CONFIG,
2310 'riskxss' => RISK_XSS,
2311 'riskpersonal' => RISK_PERSONAL,
2312 'riskspam' => RISK_SPAM,
2313 'riskdataloss' => RISK_DATALOSS,
2318 * Return a link to moodle docs for a given capability name
2320 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2321 * @return string the human-readable capability name as a link to Moodle Docs.
2323 function get_capability_docs_link($capability) {
2324 $url = get_docs_url('Capabilities/' . $capability->name);
2325 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2329 * This function pulls out all the resolved capabilities (overrides and
2330 * defaults) of a role used in capability overrides in contexts at a given
2331 * context.
2333 * @param int $roleid
2334 * @param context $context
2335 * @param string $cap capability, optional, defaults to ''
2336 * @return array Array of capabilities
2338 function role_context_capabilities($roleid, context $context, $cap = '') {
2339 global $DB;
2341 $contexts = $context->get_parent_context_ids(true);
2342 $contexts = '('.implode(',', $contexts).')';
2344 $params = array($roleid);
2346 if ($cap) {
2347 $search = " AND rc.capability = ? ";
2348 $params[] = $cap;
2349 } else {
2350 $search = '';
2353 $sql = "SELECT rc.*
2354 FROM {role_capabilities} rc, {context} c
2355 WHERE rc.contextid in $contexts
2356 AND rc.roleid = ?
2357 AND rc.contextid = c.id $search
2358 ORDER BY c.contextlevel DESC, rc.capability DESC";
2360 $capabilities = array();
2362 if ($records = $DB->get_records_sql($sql, $params)) {
2363 // We are traversing via reverse order.
2364 foreach ($records as $record) {
2365 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2366 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2367 $capabilities[$record->capability] = $record->permission;
2371 return $capabilities;
2375 * Constructs array with contextids as first parameter and context paths,
2376 * in both cases bottom top including self.
2378 * @access private
2379 * @param context $context
2380 * @return array
2382 function get_context_info_list(context $context) {
2383 $contextids = explode('/', ltrim($context->path, '/'));
2384 $contextpaths = array();
2385 $contextids2 = $contextids;
2386 while ($contextids2) {
2387 $contextpaths[] = '/' . implode('/', $contextids2);
2388 array_pop($contextids2);
2390 return array($contextids, $contextpaths);
2394 * Check if context is the front page context or a context inside it
2396 * Returns true if this context is the front page context, or a context inside it,
2397 * otherwise false.
2399 * @param context $context a context object.
2400 * @return bool
2402 function is_inside_frontpage(context $context) {
2403 $frontpagecontext = context_course::instance(SITEID);
2404 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2408 * Returns capability information (cached)
2410 * @param string $capabilityname
2411 * @return stdClass or null if capability not found
2413 function get_capability_info($capabilityname) {
2414 $caps = get_all_capabilities();
2416 if (!isset($caps[$capabilityname])) {
2417 return null;
2420 return (object) $caps[$capabilityname];
2424 * Returns all capabilitiy records, preferably from MUC and not database.
2426 * @return array All capability records indexed by capability name
2428 function get_all_capabilities() {
2429 global $DB;
2430 $cache = cache::make('core', 'capabilities');
2431 if (!$allcaps = $cache->get('core_capabilities')) {
2432 $rs = $DB->get_recordset('capabilities');
2433 $allcaps = array();
2434 foreach ($rs as $capability) {
2435 $capability->riskbitmask = (int) $capability->riskbitmask;
2436 $allcaps[$capability->name] = (array) $capability;
2438 $rs->close();
2439 $cache->set('core_capabilities', $allcaps);
2441 return $allcaps;
2445 * Returns the human-readable, translated version of the capability.
2446 * Basically a big switch statement.
2448 * @param string $capabilityname e.g. mod/choice:readresponses
2449 * @return string
2451 function get_capability_string($capabilityname) {
2453 // Typical capability name is 'plugintype/pluginname:capabilityname'
2454 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2456 if ($type === 'moodle') {
2457 $component = 'core_role';
2458 } else if ($type === 'quizreport') {
2459 //ugly hack!!
2460 $component = 'quiz_'.$name;
2461 } else {
2462 $component = $type.'_'.$name;
2465 $stringname = $name.':'.$capname;
2467 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2468 return get_string($stringname, $component);
2471 $dir = core_component::get_component_directory($component);
2472 if (!file_exists($dir)) {
2473 // plugin broken or does not exist, do not bother with printing of debug message
2474 return $capabilityname.' ???';
2477 // something is wrong in plugin, better print debug
2478 return get_string($stringname, $component);
2482 * This gets the mod/block/course/core etc strings.
2484 * @param string $component
2485 * @param int $contextlevel
2486 * @return string|bool String is success, false if failed
2488 function get_component_string($component, $contextlevel) {
2490 if ($component === 'moodle' or $component === 'core') {
2491 switch ($contextlevel) {
2492 // TODO MDL-46123: this should probably use context level names instead
2493 case CONTEXT_SYSTEM: return get_string('coresystem');
2494 case CONTEXT_USER: return get_string('users');
2495 case CONTEXT_COURSECAT: return get_string('categories');
2496 case CONTEXT_COURSE: return get_string('course');
2497 case CONTEXT_MODULE: return get_string('activities');
2498 case CONTEXT_BLOCK: return get_string('block');
2499 default: print_error('unknowncontext');
2503 list($type, $name) = core_component::normalize_component($component);
2504 $dir = core_component::get_plugin_directory($type, $name);
2505 if (!file_exists($dir)) {
2506 // plugin not installed, bad luck, there is no way to find the name
2507 return $component.' ???';
2510 switch ($type) {
2511 // TODO MDL-46123: this is really hacky and should be improved.
2512 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2513 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2514 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2515 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2516 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2517 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2518 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2519 case 'mod':
2520 if (get_string_manager()->string_exists('pluginname', $component)) {
2521 return get_string('activity').': '.get_string('pluginname', $component);
2522 } else {
2523 return get_string('activity').': '.get_string('modulename', $component);
2525 default: return get_string('pluginname', $component);
2530 * Gets the list of roles assigned to this context and up (parents)
2531 * from the aggregation of:
2532 * a) the list of roles that are visible on user profile page and participants page (profileroles setting) and;
2533 * b) if applicable, those roles that are assigned in the context.
2535 * @param context $context
2536 * @return array
2538 function get_profile_roles(context $context) {
2539 global $CFG, $DB;
2540 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2541 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2542 if (has_capability('moodle/role:assign', $context)) {
2543 $rolesinscope = array_keys(get_all_roles($context));
2544 } else {
2545 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2548 if (empty($rolesinscope)) {
2549 return [];
2552 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2553 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2554 $params = array_merge($params, $cparams);
2556 if ($coursecontext = $context->get_course_context(false)) {
2557 $params['coursecontext'] = $coursecontext->id;
2558 } else {
2559 $params['coursecontext'] = 0;
2562 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2563 FROM {role_assignments} ra, {role} r
2564 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2565 WHERE r.id = ra.roleid
2566 AND ra.contextid $contextlist
2567 AND r.id $rallowed
2568 ORDER BY r.sortorder ASC";
2570 return $DB->get_records_sql($sql, $params);
2574 * Gets the list of roles assigned to this context and up (parents)
2576 * @param context $context
2577 * @param boolean $includeparents, false means without parents.
2578 * @return array
2580 function get_roles_used_in_context(context $context, $includeparents = true) {
2581 global $DB;
2583 if ($includeparents === true) {
2584 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2585 } else {
2586 list($contextlist, $params) = $DB->get_in_or_equal($context->id, SQL_PARAMS_NAMED, 'cl');
2589 if ($coursecontext = $context->get_course_context(false)) {
2590 $params['coursecontext'] = $coursecontext->id;
2591 } else {
2592 $params['coursecontext'] = 0;
2595 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2596 FROM {role_assignments} ra, {role} r
2597 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2598 WHERE r.id = ra.roleid
2599 AND ra.contextid $contextlist
2600 ORDER BY r.sortorder ASC";
2602 return $DB->get_records_sql($sql, $params);
2606 * This function is used to print roles column in user profile page.
2607 * It is using the CFG->profileroles to limit the list to only interesting roles.
2608 * (The permission tab has full details of user role assignments.)
2610 * @param int $userid
2611 * @param int $courseid
2612 * @return string
2614 function get_user_roles_in_course($userid, $courseid) {
2615 global $CFG, $DB;
2616 if ($courseid == SITEID) {
2617 $context = context_system::instance();
2618 } else {
2619 $context = context_course::instance($courseid);
2621 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2622 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2623 if (has_capability('moodle/role:assign', $context)) {
2624 $rolesinscope = array_keys(get_all_roles($context));
2625 } else {
2626 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2628 if (empty($rolesinscope)) {
2629 return '';
2632 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2633 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2634 $params = array_merge($params, $cparams);
2636 if ($coursecontext = $context->get_course_context(false)) {
2637 $params['coursecontext'] = $coursecontext->id;
2638 } else {
2639 $params['coursecontext'] = 0;
2642 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2643 FROM {role_assignments} ra, {role} r
2644 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2645 WHERE r.id = ra.roleid
2646 AND ra.contextid $contextlist
2647 AND r.id $rallowed
2648 AND ra.userid = :userid
2649 ORDER BY r.sortorder ASC";
2650 $params['userid'] = $userid;
2652 $rolestring = '';
2654 if ($roles = $DB->get_records_sql($sql, $params)) {
2655 $viewableroles = get_viewable_roles($context, $userid);
2657 $rolenames = array();
2658 foreach ($roles as $roleid => $unused) {
2659 if (isset($viewableroles[$roleid])) {
2660 $url = new moodle_url('/user/index.php', ['contextid' => $context->id, 'roleid' => $roleid]);
2661 $rolenames[] = '<a href="' . $url . '">' . $viewableroles[$roleid] . '</a>';
2664 $rolestring = implode(',', $rolenames);
2667 return $rolestring;
2671 * Checks if a user can assign users to a particular role in this context
2673 * @param context $context
2674 * @param int $targetroleid - the id of the role you want to assign users to
2675 * @return boolean
2677 function user_can_assign(context $context, $targetroleid) {
2678 global $DB;
2680 // First check to see if the user is a site administrator.
2681 if (is_siteadmin()) {
2682 return true;
2685 // Check if user has override capability.
2686 // If not return false.
2687 if (!has_capability('moodle/role:assign', $context)) {
2688 return false;
2690 // pull out all active roles of this user from this context(or above)
2691 if ($userroles = get_user_roles($context)) {
2692 foreach ($userroles as $userrole) {
2693 // if any in the role_allow_override table, then it's ok
2694 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2695 return true;
2700 return false;
2704 * Returns all site roles in correct sort order.
2706 * Note: this method does not localise role names or descriptions,
2707 * use role_get_names() if you need role names.
2709 * @param context $context optional context for course role name aliases
2710 * @return array of role records with optional coursealias property
2712 function get_all_roles(context $context = null) {
2713 global $DB;
2715 if (!$context or !$coursecontext = $context->get_course_context(false)) {
2716 $coursecontext = null;
2719 if ($coursecontext) {
2720 $sql = "SELECT r.*, rn.name AS coursealias
2721 FROM {role} r
2722 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2723 ORDER BY r.sortorder ASC";
2724 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
2726 } else {
2727 return $DB->get_records('role', array(), 'sortorder ASC');
2732 * Returns roles of a specified archetype
2734 * @param string $archetype
2735 * @return array of full role records
2737 function get_archetype_roles($archetype) {
2738 global $DB;
2739 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2743 * Gets all the user roles assigned in this context, or higher contexts for a list of users.
2745 * If you try using the combination $userids = [], $checkparentcontexts = true then this is likely
2746 * to cause an out-of-memory error on large Moodle sites, so this combination is deprecated and
2747 * outputs a warning, even though it is the default.
2749 * @param context $context
2750 * @param array $userids. An empty list means fetch all role assignments for the context.
2751 * @param bool $checkparentcontexts defaults to true
2752 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2753 * @return array
2755 function get_users_roles(context $context, $userids = [], $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2756 global $DB;
2758 if (!$userids && $checkparentcontexts) {
2759 debugging('Please do not call get_users_roles() with $checkparentcontexts = true ' .
2760 'and $userids array not set. This combination causes large Moodle sites ' .
2761 'with lots of site-wide role assignemnts to run out of memory.', DEBUG_DEVELOPER);
2764 if ($checkparentcontexts) {
2765 $contextids = $context->get_parent_context_ids();
2766 } else {
2767 $contextids = array();
2769 $contextids[] = $context->id;
2771 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
2773 // If userids was passed as an empty array, we fetch all role assignments for the course.
2774 if (empty($userids)) {
2775 $useridlist = ' IS NOT NULL ';
2776 $uparams = [];
2777 } else {
2778 list($useridlist, $uparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'uids');
2781 $sql = "SELECT ra.*, r.name, r.shortname, ra.userid
2782 FROM {role_assignments} ra, {role} r, {context} c
2783 WHERE ra.userid $useridlist
2784 AND ra.roleid = r.id
2785 AND ra.contextid = c.id
2786 AND ra.contextid $contextids
2787 ORDER BY $order";
2789 $all = $DB->get_records_sql($sql , array_merge($params, $uparams));
2791 // Return results grouped by userid.
2792 $result = [];
2793 foreach ($all as $id => $record) {
2794 if (!isset($result[$record->userid])) {
2795 $result[$record->userid] = [];
2797 $result[$record->userid][$record->id] = $record;
2800 // Make sure all requested users are included in the result, even if they had no role assignments.
2801 foreach ($userids as $id) {
2802 if (!isset($result[$id])) {
2803 $result[$id] = [];
2807 return $result;
2812 * Gets all the user roles assigned in this context, or higher contexts
2813 * this is mainly used when checking if a user can assign a role, or overriding a role
2814 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2815 * allow_override tables
2817 * @param context $context
2818 * @param int $userid
2819 * @param bool $checkparentcontexts defaults to true
2820 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2821 * @return array
2823 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2824 global $USER, $DB;
2826 if (empty($userid)) {
2827 if (empty($USER->id)) {
2828 return array();
2830 $userid = $USER->id;
2833 if ($checkparentcontexts) {
2834 $contextids = $context->get_parent_context_ids();
2835 } else {
2836 $contextids = array();
2838 $contextids[] = $context->id;
2840 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2842 array_unshift($params, $userid);
2844 $sql = "SELECT ra.*, r.name, r.shortname
2845 FROM {role_assignments} ra, {role} r, {context} c
2846 WHERE ra.userid = ?
2847 AND ra.roleid = r.id
2848 AND ra.contextid = c.id
2849 AND ra.contextid $contextids
2850 ORDER BY $order";
2852 return $DB->get_records_sql($sql ,$params);
2856 * Like get_user_roles, but adds in the authenticated user role, and the front
2857 * page roles, if applicable.
2859 * @param context $context the context.
2860 * @param int $userid optional. Defaults to $USER->id
2861 * @return array of objects with fields ->userid, ->contextid and ->roleid.
2863 function get_user_roles_with_special(context $context, $userid = 0) {
2864 global $CFG, $USER;
2866 if (empty($userid)) {
2867 if (empty($USER->id)) {
2868 return array();
2870 $userid = $USER->id;
2873 $ras = get_user_roles($context, $userid);
2875 // Add front-page role if relevant.
2876 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2877 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
2878 is_inside_frontpage($context);
2879 if ($defaultfrontpageroleid && $isfrontpage) {
2880 $frontpagecontext = context_course::instance(SITEID);
2881 $ra = new stdClass();
2882 $ra->userid = $userid;
2883 $ra->contextid = $frontpagecontext->id;
2884 $ra->roleid = $defaultfrontpageroleid;
2885 $ras[] = $ra;
2888 // Add authenticated user role if relevant.
2889 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2890 if ($defaultuserroleid && !isguestuser($userid)) {
2891 $systemcontext = context_system::instance();
2892 $ra = new stdClass();
2893 $ra->userid = $userid;
2894 $ra->contextid = $systemcontext->id;
2895 $ra->roleid = $defaultuserroleid;
2896 $ras[] = $ra;
2899 return $ras;
2903 * Creates a record in the role_allow_override table
2905 * @param int $fromroleid source roleid
2906 * @param int $targetroleid target roleid
2907 * @return void
2909 function core_role_set_override_allowed($fromroleid, $targetroleid) {
2910 global $DB;
2912 $record = new stdClass();
2913 $record->roleid = $fromroleid;
2914 $record->allowoverride = $targetroleid;
2915 $DB->insert_record('role_allow_override', $record);
2919 * Creates a record in the role_allow_assign table
2921 * @param int $fromroleid source roleid
2922 * @param int $targetroleid target roleid
2923 * @return void
2925 function core_role_set_assign_allowed($fromroleid, $targetroleid) {
2926 global $DB;
2928 $record = new stdClass();
2929 $record->roleid = $fromroleid;
2930 $record->allowassign = $targetroleid;
2931 $DB->insert_record('role_allow_assign', $record);
2935 * Creates a record in the role_allow_switch table
2937 * @param int $fromroleid source roleid
2938 * @param int $targetroleid target roleid
2939 * @return void
2941 function core_role_set_switch_allowed($fromroleid, $targetroleid) {
2942 global $DB;
2944 $record = new stdClass();
2945 $record->roleid = $fromroleid;
2946 $record->allowswitch = $targetroleid;
2947 $DB->insert_record('role_allow_switch', $record);
2951 * Creates a record in the role_allow_view table
2953 * @param int $fromroleid source roleid
2954 * @param int $targetroleid target roleid
2955 * @return void
2957 function core_role_set_view_allowed($fromroleid, $targetroleid) {
2958 global $DB;
2960 $record = new stdClass();
2961 $record->roleid = $fromroleid;
2962 $record->allowview = $targetroleid;
2963 $DB->insert_record('role_allow_view', $record);
2967 * Gets a list of roles that this user can assign in this context
2969 * @param context $context the context.
2970 * @param int $rolenamedisplay the type of role name to display. One of the
2971 * ROLENAME_X constants. Default ROLENAME_ALIAS.
2972 * @param bool $withusercounts if true, count the number of users with each role.
2973 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
2974 * @return array if $withusercounts is false, then an array $roleid => $rolename.
2975 * if $withusercounts is true, returns a list of three arrays,
2976 * $rolenames, $rolecounts, and $nameswithcounts.
2978 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
2979 global $USER, $DB;
2981 // make sure there is a real user specified
2982 if ($user === null) {
2983 $userid = isset($USER->id) ? $USER->id : 0;
2984 } else {
2985 $userid = is_object($user) ? $user->id : $user;
2988 if (!has_capability('moodle/role:assign', $context, $userid)) {
2989 if ($withusercounts) {
2990 return array(array(), array(), array());
2991 } else {
2992 return array();
2996 $params = array();
2997 $extrafields = '';
2999 if ($withusercounts) {
3000 $extrafields = ', (SELECT count(u.id)
3001 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3002 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3003 ) AS usercount';
3004 $params['conid'] = $context->id;
3007 if (is_siteadmin($userid)) {
3008 // show all roles allowed in this context to admins
3009 $assignrestriction = "";
3010 } else {
3011 $parents = $context->get_parent_context_ids(true);
3012 $contexts = implode(',' , $parents);
3013 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3014 FROM {role_allow_assign} raa
3015 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3016 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3017 ) ar ON ar.id = r.id";
3018 $params['userid'] = $userid;
3020 $params['contextlevel'] = $context->contextlevel;
3022 if ($coursecontext = $context->get_course_context(false)) {
3023 $params['coursecontext'] = $coursecontext->id;
3024 } else {
3025 $params['coursecontext'] = 0; // no course aliases
3026 $coursecontext = null;
3028 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3029 FROM {role} r
3030 $assignrestriction
3031 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3032 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3033 ORDER BY r.sortorder ASC";
3034 $roles = $DB->get_records_sql($sql, $params);
3036 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3038 if (!$withusercounts) {
3039 return $rolenames;
3042 $rolecounts = array();
3043 $nameswithcounts = array();
3044 foreach ($roles as $role) {
3045 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3046 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3048 return array($rolenames, $rolecounts, $nameswithcounts);
3052 * Gets a list of roles that this user can switch to in a context
3054 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3055 * This function just process the contents of the role_allow_switch table. You also need to
3056 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3058 * @param context $context a context.
3059 * @return array an array $roleid => $rolename.
3061 function get_switchable_roles(context $context) {
3062 global $USER, $DB;
3064 // You can't switch roles without this capability.
3065 if (!has_capability('moodle/role:switchroles', $context)) {
3066 return [];
3069 $params = array();
3070 $extrajoins = '';
3071 $extrawhere = '';
3072 if (!is_siteadmin()) {
3073 // Admins are allowed to switch to any role with.
3074 // Others are subject to the additional constraint that the switch-to role must be allowed by
3075 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3076 $parents = $context->get_parent_context_ids(true);
3077 $contexts = implode(',' , $parents);
3079 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3080 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3081 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3082 $params['userid'] = $USER->id;
3085 if ($coursecontext = $context->get_course_context(false)) {
3086 $params['coursecontext'] = $coursecontext->id;
3087 } else {
3088 $params['coursecontext'] = 0; // no course aliases
3089 $coursecontext = null;
3092 $query = "
3093 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3094 FROM (SELECT DISTINCT rc.roleid
3095 FROM {role_capabilities} rc
3096 $extrajoins
3097 $extrawhere) idlist
3098 JOIN {role} r ON r.id = idlist.roleid
3099 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3100 ORDER BY r.sortorder";
3101 $roles = $DB->get_records_sql($query, $params);
3103 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3107 * Gets a list of roles that this user can view in a context
3109 * @param context $context a context.
3110 * @param int $userid id of user.
3111 * @return array an array $roleid => $rolename.
3113 function get_viewable_roles(context $context, $userid = null) {
3114 global $USER, $DB;
3116 if ($userid == null) {
3117 $userid = $USER->id;
3120 $params = array();
3121 $extrajoins = '';
3122 $extrawhere = '';
3123 if (!is_siteadmin()) {
3124 // Admins are allowed to view any role.
3125 // Others are subject to the additional constraint that the view role must be allowed by
3126 // 'role_allow_view' for some role they have assigned in this context or any parent.
3127 $contexts = $context->get_parent_context_ids(true);
3128 list($insql, $inparams) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED);
3130 $extrajoins = "JOIN {role_allow_view} ras ON ras.allowview = r.id
3131 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3132 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid $insql";
3134 $params += $inparams;
3135 $params['userid'] = $userid;
3138 if ($coursecontext = $context->get_course_context(false)) {
3139 $params['coursecontext'] = $coursecontext->id;
3140 } else {
3141 $params['coursecontext'] = 0; // No course aliases.
3142 $coursecontext = null;
3145 $query = "
3146 SELECT r.id, r.name, r.shortname, rn.name AS coursealias, r.sortorder
3147 FROM {role} r
3148 $extrajoins
3149 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3150 $extrawhere
3151 GROUP BY r.id, r.name, r.shortname, rn.name, r.sortorder
3152 ORDER BY r.sortorder";
3153 $roles = $DB->get_records_sql($query, $params);
3155 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3159 * Gets a list of roles that this user can override in this context.
3161 * @param context $context the context.
3162 * @param int $rolenamedisplay the type of role name to display. One of the
3163 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3164 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3165 * @return array if $withcounts is false, then an array $roleid => $rolename.
3166 * if $withusercounts is true, returns a list of three arrays,
3167 * $rolenames, $rolecounts, and $nameswithcounts.
3169 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3170 global $USER, $DB;
3172 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3173 if ($withcounts) {
3174 return array(array(), array(), array());
3175 } else {
3176 return array();
3180 $parents = $context->get_parent_context_ids(true);
3181 $contexts = implode(',' , $parents);
3183 $params = array();
3184 $extrafields = '';
3186 $params['userid'] = $USER->id;
3187 if ($withcounts) {
3188 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3189 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3190 $params['conid'] = $context->id;
3193 if ($coursecontext = $context->get_course_context(false)) {
3194 $params['coursecontext'] = $coursecontext->id;
3195 } else {
3196 $params['coursecontext'] = 0; // no course aliases
3197 $coursecontext = null;
3200 if (is_siteadmin()) {
3201 // show all roles to admins
3202 $roles = $DB->get_records_sql("
3203 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3204 FROM {role} ro
3205 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3206 ORDER BY ro.sortorder ASC", $params);
3208 } else {
3209 $roles = $DB->get_records_sql("
3210 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3211 FROM {role} ro
3212 JOIN (SELECT DISTINCT r.id
3213 FROM {role} r
3214 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3215 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3216 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3217 ) inline_view ON ro.id = inline_view.id
3218 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3219 ORDER BY ro.sortorder ASC", $params);
3222 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3224 if (!$withcounts) {
3225 return $rolenames;
3228 $rolecounts = array();
3229 $nameswithcounts = array();
3230 foreach ($roles as $role) {
3231 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3232 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3234 return array($rolenames, $rolecounts, $nameswithcounts);
3238 * Create a role menu suitable for default role selection in enrol plugins.
3240 * @package core_enrol
3242 * @param context $context
3243 * @param int $addroleid current or default role - always added to list
3244 * @return array roleid=>localised role name
3246 function get_default_enrol_roles(context $context, $addroleid = null) {
3247 global $DB;
3249 $params = array('contextlevel'=>CONTEXT_COURSE);
3251 if ($coursecontext = $context->get_course_context(false)) {
3252 $params['coursecontext'] = $coursecontext->id;
3253 } else {
3254 $params['coursecontext'] = 0; // no course names
3255 $coursecontext = null;
3258 if ($addroleid) {
3259 $addrole = "OR r.id = :addroleid";
3260 $params['addroleid'] = $addroleid;
3261 } else {
3262 $addrole = "";
3265 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3266 FROM {role} r
3267 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3268 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3269 WHERE rcl.id IS NOT NULL $addrole
3270 ORDER BY sortorder DESC";
3272 $roles = $DB->get_records_sql($sql, $params);
3274 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3278 * Return context levels where this role is assignable.
3280 * @param integer $roleid the id of a role.
3281 * @return array list of the context levels at which this role may be assigned.
3283 function get_role_contextlevels($roleid) {
3284 global $DB;
3285 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3286 'contextlevel', 'id,contextlevel');
3290 * Return roles suitable for assignment at the specified context level.
3292 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3294 * @param integer $contextlevel a contextlevel.
3295 * @return array list of role ids that are assignable at this context level.
3297 function get_roles_for_contextlevels($contextlevel) {
3298 global $DB;
3299 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3300 '', 'id,roleid');
3304 * Returns default context levels where roles can be assigned.
3306 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3307 * from the array returned by get_role_archetypes();
3308 * @return array list of the context levels at which this type of role may be assigned by default.
3310 function get_default_contextlevels($rolearchetype) {
3311 static $defaults = array(
3312 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3313 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3314 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3315 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3316 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3317 'guest' => array(),
3318 'user' => array(),
3319 'frontpage' => array());
3321 if (isset($defaults[$rolearchetype])) {
3322 return $defaults[$rolearchetype];
3323 } else {
3324 return array();
3329 * Set the context levels at which a particular role can be assigned.
3330 * Throws exceptions in case of error.
3332 * @param integer $roleid the id of a role.
3333 * @param array $contextlevels the context levels at which this role should be assignable,
3334 * duplicate levels are removed.
3335 * @return void
3337 function set_role_contextlevels($roleid, array $contextlevels) {
3338 global $DB;
3339 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3340 $rcl = new stdClass();
3341 $rcl->roleid = $roleid;
3342 $contextlevels = array_unique($contextlevels);
3343 foreach ($contextlevels as $level) {
3344 $rcl->contextlevel = $level;
3345 $DB->insert_record('role_context_levels', $rcl, false, true);
3350 * Who has this capability in this context?
3352 * This can be a very expensive call - use sparingly and keep
3353 * the results if you are going to need them again soon.
3355 * Note if $fields is empty this function attempts to get u.*
3356 * which can get rather large - and has a serious perf impact
3357 * on some DBs.
3359 * @param context $context
3360 * @param string|array $capability - capability name(s)
3361 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3362 * @param string $sort - the sort order. Default is lastaccess time.
3363 * @param mixed $limitfrom - number of records to skip (offset)
3364 * @param mixed $limitnum - number of records to fetch
3365 * @param string|array $groups - single group or array of groups - only return
3366 * users who are in one of these group(s).
3367 * @param string|array $exceptions - list of users to exclude, comma separated or array
3368 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3369 * @param bool $view_ignored - use get_enrolled_sql() instead
3370 * @param bool $useviewallgroups if $groups is set the return users who
3371 * have capability both $capability and moodle/site:accessallgroups
3372 * in this context, as well as users who have $capability and who are
3373 * in $groups.
3374 * @return array of user records
3376 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3377 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3378 global $CFG, $DB;
3380 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3381 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3383 $ctxids = trim($context->path, '/');
3384 $ctxids = str_replace('/', ',', $ctxids);
3386 // Context is the frontpage
3387 $iscoursepage = false; // coursepage other than fp
3388 $isfrontpage = false;
3389 if ($context->contextlevel == CONTEXT_COURSE) {
3390 if ($context->instanceid == SITEID) {
3391 $isfrontpage = true;
3392 } else {
3393 $iscoursepage = true;
3396 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3398 $caps = (array)$capability;
3400 // construct list of context paths bottom-->top
3401 list($contextids, $paths) = get_context_info_list($context);
3403 // we need to find out all roles that have these capabilities either in definition or in overrides
3404 $defs = array();
3405 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3406 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3407 $params = array_merge($params, $params2);
3408 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3409 FROM {role_capabilities} rc
3410 JOIN {context} ctx on rc.contextid = ctx.id
3411 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3413 $rcs = $DB->get_records_sql($sql, $params);
3414 foreach ($rcs as $rc) {
3415 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3418 // go through the permissions bottom-->top direction to evaluate the current permission,
3419 // first one wins (prohibit is an exception that always wins)
3420 $access = array();
3421 foreach ($caps as $cap) {
3422 foreach ($paths as $path) {
3423 if (empty($defs[$cap][$path])) {
3424 continue;
3426 foreach($defs[$cap][$path] as $roleid => $perm) {
3427 if ($perm == CAP_PROHIBIT) {
3428 $access[$cap][$roleid] = CAP_PROHIBIT;
3429 continue;
3431 if (!isset($access[$cap][$roleid])) {
3432 $access[$cap][$roleid] = (int)$perm;
3438 // make lists of roles that are needed and prohibited in this context
3439 $needed = array(); // one of these is enough
3440 $prohibited = array(); // must not have any of these
3441 foreach ($caps as $cap) {
3442 if (empty($access[$cap])) {
3443 continue;
3445 foreach ($access[$cap] as $roleid => $perm) {
3446 if ($perm == CAP_PROHIBIT) {
3447 unset($needed[$cap][$roleid]);
3448 $prohibited[$cap][$roleid] = true;
3449 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3450 $needed[$cap][$roleid] = true;
3453 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3454 // easy, nobody has the permission
3455 unset($needed[$cap]);
3456 unset($prohibited[$cap]);
3457 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3458 // everybody is disqualified on the frontpage
3459 unset($needed[$cap]);
3460 unset($prohibited[$cap]);
3462 if (empty($prohibited[$cap])) {
3463 unset($prohibited[$cap]);
3467 if (empty($needed)) {
3468 // there can not be anybody if no roles match this request
3469 return array();
3472 if (empty($prohibited)) {
3473 // we can compact the needed roles
3474 $n = array();
3475 foreach ($needed as $cap) {
3476 foreach ($cap as $roleid=>$unused) {
3477 $n[$roleid] = true;
3480 $needed = array('any'=>$n);
3481 unset($n);
3484 // ***** Set up default fields ******
3485 if (empty($fields)) {
3486 if ($iscoursepage) {
3487 $fields = 'u.*, ul.timeaccess AS lastaccess';
3488 } else {
3489 $fields = 'u.*';
3491 } else {
3492 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3493 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3497 // Set up default sort
3498 if (empty($sort)) { // default to course lastaccess or just lastaccess
3499 if ($iscoursepage) {
3500 $sort = 'ul.timeaccess';
3501 } else {
3502 $sort = 'u.lastaccess';
3506 // Prepare query clauses
3507 $wherecond = array();
3508 $params = array();
3509 $joins = array();
3511 // User lastaccess JOIN
3512 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3513 // user_lastaccess is not required MDL-13810
3514 } else {
3515 if ($iscoursepage) {
3516 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3517 } else {
3518 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3522 // We never return deleted users or guest account.
3523 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3524 $params['guestid'] = $CFG->siteguest;
3526 // Groups
3527 if ($groups) {
3528 $groups = (array)$groups;
3529 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3530 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3531 $params = array_merge($params, $grpparams);
3533 if ($useviewallgroups) {
3534 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3535 if (!empty($viewallgroupsusers)) {
3536 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3537 } else {
3538 $wherecond[] = "($grouptest)";
3540 } else {
3541 $wherecond[] = "($grouptest)";
3545 // User exceptions
3546 if (!empty($exceptions)) {
3547 $exceptions = (array)$exceptions;
3548 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3549 $params = array_merge($params, $exparams);
3550 $wherecond[] = "u.id $exsql";
3553 // now add the needed and prohibited roles conditions as joins
3554 if (!empty($needed['any'])) {
3555 // simple case - there are no prohibits involved
3556 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3557 // everybody
3558 } else {
3559 $joins[] = "JOIN (SELECT DISTINCT userid
3560 FROM {role_assignments}
3561 WHERE contextid IN ($ctxids)
3562 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3563 ) ra ON ra.userid = u.id";
3565 } else {
3566 $unions = array();
3567 $everybody = false;
3568 foreach ($needed as $cap=>$unused) {
3569 if (empty($prohibited[$cap])) {
3570 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3571 $everybody = true;
3572 break;
3573 } else {
3574 $unions[] = "SELECT userid
3575 FROM {role_assignments}
3576 WHERE contextid IN ($ctxids)
3577 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3579 } else {
3580 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3581 // nobody can have this cap because it is prevented in default roles
3582 continue;
3584 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3585 // everybody except the prohibitted - hiding does not matter
3586 $unions[] = "SELECT id AS userid
3587 FROM {user}
3588 WHERE id NOT IN (SELECT userid
3589 FROM {role_assignments}
3590 WHERE contextid IN ($ctxids)
3591 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3593 } else {
3594 $unions[] = "SELECT userid
3595 FROM {role_assignments}
3596 WHERE contextid IN ($ctxids) AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3597 AND userid NOT IN (
3598 SELECT userid
3599 FROM {role_assignments}
3600 WHERE contextid IN ($ctxids)
3601 AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . ")
3606 if (!$everybody) {
3607 if ($unions) {
3608 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3609 } else {
3610 // only prohibits found - nobody can be matched
3611 $wherecond[] = "1 = 2";
3616 // Collect WHERE conditions and needed joins
3617 $where = implode(' AND ', $wherecond);
3618 if ($where !== '') {
3619 $where = 'WHERE ' . $where;
3621 $joins = implode("\n", $joins);
3623 // Ok, let's get the users!
3624 $sql = "SELECT $fields
3625 FROM {user} u
3626 $joins
3627 $where
3628 ORDER BY $sort";
3630 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3634 * Re-sort a users array based on a sorting policy
3636 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3637 * based on a sorting policy. This is to support the odd practice of
3638 * sorting teachers by 'authority', where authority was "lowest id of the role
3639 * assignment".
3641 * Will execute 1 database query. Only suitable for small numbers of users, as it
3642 * uses an u.id IN() clause.
3644 * Notes about the sorting criteria.
3646 * As a default, we cannot rely on role.sortorder because then
3647 * admins/coursecreators will always win. That is why the sane
3648 * rule "is locality matters most", with sortorder as 2nd
3649 * consideration.
3651 * If you want role.sortorder, use the 'sortorder' policy, and
3652 * name explicitly what roles you want to cover. It's probably
3653 * a good idea to see what roles have the capabilities you want
3654 * (array_diff() them against roiles that have 'can-do-anything'
3655 * to weed out admin-ish roles. Or fetch a list of roles from
3656 * variables like $CFG->coursecontact .
3658 * @param array $users Users array, keyed on userid
3659 * @param context $context
3660 * @param array $roles ids of the roles to include, optional
3661 * @param string $sortpolicy defaults to locality, more about
3662 * @return array sorted copy of the array
3664 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3665 global $DB;
3667 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3668 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3669 if (empty($roles)) {
3670 $roleswhere = '';
3671 } else {
3672 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3675 $sql = "SELECT ra.userid
3676 FROM {role_assignments} ra
3677 JOIN {role} r
3678 ON ra.roleid=r.id
3679 JOIN {context} ctx
3680 ON ra.contextid=ctx.id
3681 WHERE $userswhere
3682 $contextwhere
3683 $roleswhere";
3685 // Default 'locality' policy -- read PHPDoc notes
3686 // about sort policies...
3687 $orderby = 'ORDER BY '
3688 .'ctx.depth DESC, ' /* locality wins */
3689 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3690 .'ra.id'; /* role assignment order tie-breaker */
3691 if ($sortpolicy === 'sortorder') {
3692 $orderby = 'ORDER BY '
3693 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3694 .'ra.id'; /* role assignment order tie-breaker */
3697 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3698 $sortedusers = array();
3699 $seen = array();
3701 foreach ($sortedids as $id) {
3702 // Avoid duplicates
3703 if (isset($seen[$id])) {
3704 continue;
3706 $seen[$id] = true;
3708 // assign
3709 $sortedusers[$id] = $users[$id];
3711 return $sortedusers;
3715 * Gets all the users assigned this role in this context or higher
3717 * Note that moodle is based on capabilities and it is usually better
3718 * to check permissions than to check role ids as the capabilities
3719 * system is more flexible. If you really need, you can to use this
3720 * function but consider has_capability() as a possible substitute.
3722 * All $sort fields are added into $fields if not present there yet.
3724 * If $roleid is an array or is empty (all roles) you need to set $fields
3725 * (and $sort by extension) params according to it, as the first field
3726 * returned by the database should be unique (ra.id is the best candidate).
3728 * @param int $roleid (can also be an array of ints!)
3729 * @param context $context
3730 * @param bool $parent if true, get list of users assigned in higher context too
3731 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3732 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3733 * null => use default sort from users_order_by_sql.
3734 * @param bool $all true means all, false means limit to enrolled users
3735 * @param string $group defaults to ''
3736 * @param mixed $limitfrom defaults to ''
3737 * @param mixed $limitnum defaults to ''
3738 * @param string $extrawheretest defaults to ''
3739 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3740 * @return array
3742 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3743 $sort = null, $all = true, $group = '',
3744 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3745 global $DB;
3747 if (empty($fields)) {
3748 $allnames = get_all_user_name_fields(true, 'u');
3749 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
3750 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3751 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3752 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3753 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3756 // Prevent wrong function uses.
3757 if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
3758 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
3759 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
3761 if (!empty($roleid)) {
3762 // Solving partially the issue when specifying multiple roles.
3763 $users = array();
3764 foreach ($roleid as $id) {
3765 // Ignoring duplicated keys keeping the first user appearance.
3766 $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
3767 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
3769 return $users;
3773 $parentcontexts = '';
3774 if ($parent) {
3775 $parentcontexts = substr($context->path, 1); // kill leading slash
3776 $parentcontexts = str_replace('/', ',', $parentcontexts);
3777 if ($parentcontexts !== '') {
3778 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3782 if ($roleid) {
3783 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
3784 $roleselect = "AND ra.roleid $rids";
3785 } else {
3786 $params = array();
3787 $roleselect = '';
3790 if ($coursecontext = $context->get_course_context(false)) {
3791 $params['coursecontext'] = $coursecontext->id;
3792 } else {
3793 $params['coursecontext'] = 0;
3796 if ($group) {
3797 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3798 $groupselect = " AND gm.groupid = :groupid ";
3799 $params['groupid'] = $group;
3800 } else {
3801 $groupjoin = '';
3802 $groupselect = '';
3805 $params['contextid'] = $context->id;
3807 if ($extrawheretest) {
3808 $extrawheretest = ' AND ' . $extrawheretest;
3811 if ($whereorsortparams) {
3812 $params = array_merge($params, $whereorsortparams);
3815 if (!$sort) {
3816 list($sort, $sortparams) = users_order_by_sql('u');
3817 $params = array_merge($params, $sortparams);
3820 // Adding the fields from $sort that are not present in $fields.
3821 $sortarray = preg_split('/,\s*/', $sort);
3822 $fieldsarray = preg_split('/,\s*/', $fields);
3824 // Discarding aliases from the fields.
3825 $fieldnames = array();
3826 foreach ($fieldsarray as $key => $field) {
3827 list($fieldnames[$key]) = explode(' ', $field);
3830 $addedfields = array();
3831 foreach ($sortarray as $sortfield) {
3832 // Throw away any additional arguments to the sort (e.g. ASC/DESC).
3833 list($sortfield) = explode(' ', $sortfield);
3834 list($tableprefix) = explode('.', $sortfield);
3835 $fieldpresent = false;
3836 foreach ($fieldnames as $fieldname) {
3837 if ($fieldname === $sortfield || $fieldname === $tableprefix.'.*') {
3838 $fieldpresent = true;
3839 break;
3843 if (!$fieldpresent) {
3844 $fieldsarray[] = $sortfield;
3845 $addedfields[] = $sortfield;
3849 $fields = implode(', ', $fieldsarray);
3850 if (!empty($addedfields)) {
3851 $addedfields = implode(', ', $addedfields);
3852 debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
3855 if ($all === null) {
3856 // Previously null was used to indicate that parameter was not used.
3857 $all = true;
3859 if (!$all and $coursecontext) {
3860 // Do not use get_enrolled_sql() here for performance reasons.
3861 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
3862 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
3863 $params['ecourseid'] = $coursecontext->instanceid;
3864 } else {
3865 $ejoin = "";
3868 $sql = "SELECT DISTINCT $fields, ra.roleid
3869 FROM {role_assignments} ra
3870 JOIN {user} u ON u.id = ra.userid
3871 JOIN {role} r ON ra.roleid = r.id
3872 $ejoin
3873 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3874 $groupjoin
3875 WHERE (ra.contextid = :contextid $parentcontexts)
3876 $roleselect
3877 $groupselect
3878 $extrawheretest
3879 ORDER BY $sort"; // join now so that we can just use fullname() later
3881 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3885 * Counts all the users assigned this role in this context or higher
3887 * @param int|array $roleid either int or an array of ints
3888 * @param context $context
3889 * @param bool $parent if true, get list of users assigned in higher context too
3890 * @return int Returns the result count
3892 function count_role_users($roleid, context $context, $parent = false) {
3893 global $DB;
3895 if ($parent) {
3896 if ($contexts = $context->get_parent_context_ids()) {
3897 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3898 } else {
3899 $parentcontexts = '';
3901 } else {
3902 $parentcontexts = '';
3905 if ($roleid) {
3906 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3907 $roleselect = "AND r.roleid $rids";
3908 } else {
3909 $params = array();
3910 $roleselect = '';
3913 array_unshift($params, $context->id);
3915 $sql = "SELECT COUNT(DISTINCT u.id)
3916 FROM {role_assignments} r
3917 JOIN {user} u ON u.id = r.userid
3918 WHERE (r.contextid = ? $parentcontexts)
3919 $roleselect
3920 AND u.deleted = 0";
3922 return $DB->count_records_sql($sql, $params);
3926 * This function gets the list of courses that this user has a particular capability in.
3928 * It is now reasonably efficient, but bear in mind that if there are users who have the capability
3929 * everywhere, it may return an array of all courses.
3931 * @param string $capability Capability in question
3932 * @param int $userid User ID or null for current user
3933 * @param bool $doanything True if 'doanything' is permitted (default)
3934 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3935 * otherwise use a comma-separated list of the fields you require, not including id.
3936 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
3937 * @param string $orderby If set, use a comma-separated list of fields from course
3938 * table with sql modifiers (DESC) if needed
3939 * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
3940 * @return array|bool Array of courses, if none found false is returned.
3942 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '',
3943 $limit = 0) {
3944 global $DB, $USER;
3946 // Default to current user.
3947 if (!$userid) {
3948 $userid = $USER->id;
3951 if ($doanything && is_siteadmin($userid)) {
3952 // If the user is a site admin and $doanything is enabled then there is no need to restrict
3953 // the list of courses.
3954 $contextlimitsql = '';
3955 $contextlimitparams = [];
3956 } else {
3957 // Gets SQL to limit contexts ('x' table) to those where the user has this capability.
3958 list ($contextlimitsql, $contextlimitparams) = \core\access\get_user_capability_course_helper::get_sql(
3959 $userid, $capability);
3960 if (!$contextlimitsql) {
3961 // If the does not have this capability in any context, return false without querying.
3962 return false;
3965 $contextlimitsql = 'WHERE' . $contextlimitsql;
3968 // Convert fields list and ordering
3969 $fieldlist = '';
3970 if ($fieldsexceptid) {
3971 $fields = array_map('trim', explode(',', $fieldsexceptid));
3972 foreach($fields as $field) {
3973 // Context fields have a different alias.
3974 if (strpos($field, 'ctx') === 0) {
3975 switch($field) {
3976 case 'ctxlevel' :
3977 $realfield = 'contextlevel';
3978 break;
3979 case 'ctxinstance' :
3980 $realfield = 'instanceid';
3981 break;
3982 default:
3983 $realfield = substr($field, 3);
3984 break;
3986 $fieldlist .= ',x.' . $realfield . ' AS ' . $field;
3987 } else {
3988 $fieldlist .= ',c.'.$field;
3992 if ($orderby) {
3993 $fields = explode(',', $orderby);
3994 $orderby = '';
3995 foreach($fields as $field) {
3996 if ($orderby) {
3997 $orderby .= ',';
3999 $orderby .= 'c.'.$field;
4001 $orderby = 'ORDER BY '.$orderby;
4004 $courses = array();
4005 $rs = $DB->get_recordset_sql("
4006 SELECT c.id $fieldlist
4007 FROM {course} c
4008 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
4009 $contextlimitsql
4010 $orderby", array_merge([CONTEXT_COURSE], $contextlimitparams));
4011 foreach ($rs as $course) {
4012 $courses[] = $course;
4013 $limit--;
4014 if ($limit == 0) {
4015 break;
4018 $rs->close();
4019 return empty($courses) ? false : $courses;
4023 * Switches the current user to another role for the current session and only
4024 * in the given context.
4026 * The caller *must* check
4027 * - that this op is allowed
4028 * - that the requested role can be switched to in this context (use get_switchable_roles)
4029 * - that the requested role is NOT $CFG->defaultuserroleid
4031 * To "unswitch" pass 0 as the roleid.
4033 * This function *will* modify $USER->access - beware
4035 * @param integer $roleid the role to switch to.
4036 * @param context $context the context in which to perform the switch.
4037 * @return bool success or failure.
4039 function role_switch($roleid, context $context) {
4040 global $USER;
4042 // Add the ghost RA to $USER->access as $USER->access['rsw'][$path] = $roleid.
4043 // To un-switch just unset($USER->access['rsw'][$path]).
4045 // Note: it is not possible to switch to roles that do not have course:view
4047 if (!isset($USER->access)) {
4048 load_all_capabilities();
4051 // Add the switch RA
4052 if ($roleid == 0) {
4053 unset($USER->access['rsw'][$context->path]);
4054 return true;
4057 $USER->access['rsw'][$context->path] = $roleid;
4059 return true;
4063 * Checks if the user has switched roles within the given course.
4065 * Note: You can only switch roles within the course, hence it takes a course id
4066 * rather than a context. On that note Petr volunteered to implement this across
4067 * all other contexts, all requests for this should be forwarded to him ;)
4069 * @param int $courseid The id of the course to check
4070 * @return bool True if the user has switched roles within the course.
4072 function is_role_switched($courseid) {
4073 global $USER;
4074 $context = context_course::instance($courseid, MUST_EXIST);
4075 return (!empty($USER->access['rsw'][$context->path]));
4079 * Get any role that has an override on exact context
4081 * @param context $context The context to check
4082 * @return array An array of roles
4084 function get_roles_with_override_on_context(context $context) {
4085 global $DB;
4087 return $DB->get_records_sql("SELECT r.*
4088 FROM {role_capabilities} rc, {role} r
4089 WHERE rc.roleid = r.id AND rc.contextid = ?",
4090 array($context->id));
4094 * Get all capabilities for this role on this context (overrides)
4096 * @param stdClass $role
4097 * @param context $context
4098 * @return array
4100 function get_capabilities_from_role_on_context($role, context $context) {
4101 global $DB;
4103 return $DB->get_records_sql("SELECT *
4104 FROM {role_capabilities}
4105 WHERE contextid = ? AND roleid = ?",
4106 array($context->id, $role->id));
4110 * Find all user assignment of users for this role, on this context
4112 * @param stdClass $role
4113 * @param context $context
4114 * @return array
4116 function get_users_from_role_on_context($role, context $context) {
4117 global $DB;
4119 return $DB->get_records_sql("SELECT *
4120 FROM {role_assignments}
4121 WHERE contextid = ? AND roleid = ?",
4122 array($context->id, $role->id));
4126 * Simple function returning a boolean true if user has roles
4127 * in context or parent contexts, otherwise false.
4129 * @param int $userid
4130 * @param int $roleid
4131 * @param int $contextid empty means any context
4132 * @return bool
4134 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4135 global $DB;
4137 if ($contextid) {
4138 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4139 return false;
4141 $parents = $context->get_parent_context_ids(true);
4142 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4143 $params['userid'] = $userid;
4144 $params['roleid'] = $roleid;
4146 $sql = "SELECT COUNT(ra.id)
4147 FROM {role_assignments} ra
4148 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4150 $count = $DB->get_field_sql($sql, $params);
4151 return ($count > 0);
4153 } else {
4154 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4159 * Get localised role name or alias if exists and format the text.
4161 * @param stdClass $role role object
4162 * - optional 'coursealias' property should be included for performance reasons if course context used
4163 * - description property is not required here
4164 * @param context|bool $context empty means system context
4165 * @param int $rolenamedisplay type of role name
4166 * @return string localised role name or course role name alias
4168 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4169 global $DB;
4171 if ($rolenamedisplay == ROLENAME_SHORT) {
4172 return $role->shortname;
4175 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4176 $coursecontext = null;
4179 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4180 $role = clone($role); // Do not modify parameters.
4181 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4182 $role->coursealias = $r->name;
4183 } else {
4184 $role->coursealias = null;
4188 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4189 if ($coursecontext) {
4190 return $role->coursealias;
4191 } else {
4192 return null;
4196 if (trim($role->name) !== '') {
4197 // For filtering always use context where was the thing defined - system for roles here.
4198 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4200 } else {
4201 // Empty role->name means we want to see localised role name based on shortname,
4202 // only default roles are supposed to be localised.
4203 switch ($role->shortname) {
4204 case 'manager': $original = get_string('manager', 'role'); break;
4205 case 'coursecreator': $original = get_string('coursecreators'); break;
4206 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4207 case 'teacher': $original = get_string('noneditingteacher'); break;
4208 case 'student': $original = get_string('defaultcoursestudent'); break;
4209 case 'guest': $original = get_string('guest'); break;
4210 case 'user': $original = get_string('authenticateduser'); break;
4211 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4212 // We should not get here, the role UI should require the name for custom roles!
4213 default: $original = $role->shortname; break;
4217 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4218 return $original;
4221 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4222 return "$original ($role->shortname)";
4225 if ($rolenamedisplay == ROLENAME_ALIAS) {
4226 if ($coursecontext and trim($role->coursealias) !== '') {
4227 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4228 } else {
4229 return $original;
4233 if ($rolenamedisplay == ROLENAME_BOTH) {
4234 if ($coursecontext and trim($role->coursealias) !== '') {
4235 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4236 } else {
4237 return $original;
4241 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4245 * Returns localised role description if available.
4246 * If the name is empty it tries to find the default role name using
4247 * hardcoded list of default role names or other methods in the future.
4249 * @param stdClass $role
4250 * @return string localised role name
4252 function role_get_description(stdClass $role) {
4253 if (!html_is_blank($role->description)) {
4254 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4257 switch ($role->shortname) {
4258 case 'manager': return get_string('managerdescription', 'role');
4259 case 'coursecreator': return get_string('coursecreatorsdescription');
4260 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4261 case 'teacher': return get_string('noneditingteacherdescription');
4262 case 'student': return get_string('defaultcoursestudentdescription');
4263 case 'guest': return get_string('guestdescription');
4264 case 'user': return get_string('authenticateduserdescription');
4265 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4266 default: return '';
4271 * Get all the localised role names for a context.
4273 * In new installs default roles have empty names, this function
4274 * add localised role names using current language pack.
4276 * @param context $context the context, null means system context
4277 * @param array of role objects with a ->localname field containing the context-specific role name.
4278 * @param int $rolenamedisplay
4279 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4280 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4282 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4283 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4287 * Prepare list of roles for display, apply aliases and localise default role names.
4289 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4290 * @param context $context the context, null means system context
4291 * @param int $rolenamedisplay
4292 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4293 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4295 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4296 global $DB;
4298 if (empty($roleoptions)) {
4299 return array();
4302 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4303 $coursecontext = null;
4306 // We usually need all role columns...
4307 $first = reset($roleoptions);
4308 if ($returnmenu === null) {
4309 $returnmenu = !is_object($first);
4312 if (!is_object($first) or !property_exists($first, 'shortname')) {
4313 $allroles = get_all_roles($context);
4314 foreach ($roleoptions as $rid => $unused) {
4315 $roleoptions[$rid] = $allroles[$rid];
4319 // Inject coursealias if necessary.
4320 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4321 $first = reset($roleoptions);
4322 if (!property_exists($first, 'coursealias')) {
4323 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4324 foreach ($aliasnames as $alias) {
4325 if (isset($roleoptions[$alias->roleid])) {
4326 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4332 // Add localname property.
4333 foreach ($roleoptions as $rid => $role) {
4334 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4337 if (!$returnmenu) {
4338 return $roleoptions;
4341 $menu = array();
4342 foreach ($roleoptions as $rid => $role) {
4343 $menu[$rid] = $role->localname;
4346 return $menu;
4350 * Aids in detecting if a new line is required when reading a new capability
4352 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4353 * when we read in a new capability.
4354 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4355 * but when we are in grade, all reports/import/export capabilities should be together
4357 * @param string $cap component string a
4358 * @param string $comp component string b
4359 * @param int $contextlevel
4360 * @return bool whether 2 component are in different "sections"
4362 function component_level_changed($cap, $comp, $contextlevel) {
4364 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4365 $compsa = explode('/', $cap->component);
4366 $compsb = explode('/', $comp);
4368 // list of system reports
4369 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4370 return false;
4373 // we are in gradebook, still
4374 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4375 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4376 return false;
4379 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4380 return false;
4384 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4388 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4389 * and return an array of roleids in order.
4391 * @param array $allroles array of roles, as returned by get_all_roles();
4392 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4394 function fix_role_sortorder($allroles) {
4395 global $DB;
4397 $rolesort = array();
4398 $i = 0;
4399 foreach ($allroles as $role) {
4400 $rolesort[$i] = $role->id;
4401 if ($role->sortorder != $i) {
4402 $r = new stdClass();
4403 $r->id = $role->id;
4404 $r->sortorder = $i;
4405 $DB->update_record('role', $r);
4406 $allroles[$role->id]->sortorder = $i;
4408 $i++;
4410 return $rolesort;
4414 * Switch the sort order of two roles (used in admin/roles/manage.php).
4416 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4417 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4418 * @return boolean success or failure
4420 function switch_roles($first, $second) {
4421 global $DB;
4422 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4423 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4424 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4425 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4426 return $result;
4430 * Duplicates all the base definitions of a role
4432 * @param stdClass $sourcerole role to copy from
4433 * @param int $targetrole id of role to copy to
4435 function role_cap_duplicate($sourcerole, $targetrole) {
4436 global $DB;
4438 $systemcontext = context_system::instance();
4439 $caps = $DB->get_records_sql("SELECT *
4440 FROM {role_capabilities}
4441 WHERE roleid = ? AND contextid = ?",
4442 array($sourcerole->id, $systemcontext->id));
4443 // adding capabilities
4444 foreach ($caps as $cap) {
4445 unset($cap->id);
4446 $cap->roleid = $targetrole;
4447 $DB->insert_record('role_capabilities', $cap);
4450 // Reset any cache of this role, including MUC.
4451 accesslib_clear_role_cache($targetrole);
4455 * Returns two lists, this can be used to find out if user has capability.
4456 * Having any needed role and no forbidden role in this context means
4457 * user has this capability in this context.
4458 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4460 * @param stdClass $context
4461 * @param string $capability
4462 * @return array($neededroles, $forbiddenroles)
4464 function get_roles_with_cap_in_context($context, $capability) {
4465 global $DB;
4467 $ctxids = trim($context->path, '/'); // kill leading slash
4468 $ctxids = str_replace('/', ',', $ctxids);
4470 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4471 FROM {role_capabilities} rc
4472 JOIN {context} ctx ON ctx.id = rc.contextid
4473 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4474 ORDER BY rc.roleid ASC, ctx.depth DESC";
4475 $params = array('cap'=>$capability);
4477 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4478 // no cap definitions --> no capability
4479 return array(array(), array());
4482 $forbidden = array();
4483 $needed = array();
4484 foreach($capdefs as $def) {
4485 if (isset($forbidden[$def->roleid])) {
4486 continue;
4488 if ($def->permission == CAP_PROHIBIT) {
4489 $forbidden[$def->roleid] = $def->roleid;
4490 unset($needed[$def->roleid]);
4491 continue;
4493 if (!isset($needed[$def->roleid])) {
4494 if ($def->permission == CAP_ALLOW) {
4495 $needed[$def->roleid] = true;
4496 } else if ($def->permission == CAP_PREVENT) {
4497 $needed[$def->roleid] = false;
4501 unset($capdefs);
4503 // remove all those roles not allowing
4504 foreach($needed as $key=>$value) {
4505 if (!$value) {
4506 unset($needed[$key]);
4507 } else {
4508 $needed[$key] = $key;
4512 return array($needed, $forbidden);
4516 * Returns an array of role IDs that have ALL of the the supplied capabilities
4517 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4519 * @param stdClass $context
4520 * @param array $capabilities An array of capabilities
4521 * @return array of roles with all of the required capabilities
4523 function get_roles_with_caps_in_context($context, $capabilities) {
4524 $neededarr = array();
4525 $forbiddenarr = array();
4526 foreach($capabilities as $caprequired) {
4527 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4530 $rolesthatcanrate = array();
4531 if (!empty($neededarr)) {
4532 foreach ($neededarr as $needed) {
4533 if (empty($rolesthatcanrate)) {
4534 $rolesthatcanrate = $needed;
4535 } else {
4536 //only want roles that have all caps
4537 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4541 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4542 foreach ($forbiddenarr as $forbidden) {
4543 //remove any roles that are forbidden any of the caps
4544 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4547 return $rolesthatcanrate;
4551 * Returns an array of role names that have ALL of the the supplied capabilities
4552 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4554 * @param stdClass $context
4555 * @param array $capabilities An array of capabilities
4556 * @return array of roles with all of the required capabilities
4558 function get_role_names_with_caps_in_context($context, $capabilities) {
4559 global $DB;
4561 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4562 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4564 $roles = array();
4565 foreach ($rolesthatcanrate as $r) {
4566 $roles[$r] = $allroles[$r];
4569 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4573 * This function verifies the prohibit comes from this context
4574 * and there are no more prohibits in parent contexts.
4576 * @param int $roleid
4577 * @param context $context
4578 * @param string $capability name
4579 * @return bool
4581 function prohibit_is_removable($roleid, context $context, $capability) {
4582 global $DB;
4584 $ctxids = trim($context->path, '/'); // kill leading slash
4585 $ctxids = str_replace('/', ',', $ctxids);
4587 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4589 $sql = "SELECT ctx.id
4590 FROM {role_capabilities} rc
4591 JOIN {context} ctx ON ctx.id = rc.contextid
4592 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4593 ORDER BY ctx.depth DESC";
4595 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4596 // no prohibits == nothing to remove
4597 return true;
4600 if (count($prohibits) > 1) {
4601 // more prohibits can not be removed
4602 return false;
4605 return !empty($prohibits[$context->id]);
4609 * More user friendly role permission changing,
4610 * it should produce as few overrides as possible.
4612 * @param int $roleid
4613 * @param stdClass $context
4614 * @param string $capname capability name
4615 * @param int $permission
4616 * @return void
4618 function role_change_permission($roleid, $context, $capname, $permission) {
4619 global $DB;
4621 if ($permission == CAP_INHERIT) {
4622 unassign_capability($capname, $roleid, $context->id);
4623 return;
4626 $ctxids = trim($context->path, '/'); // kill leading slash
4627 $ctxids = str_replace('/', ',', $ctxids);
4629 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4631 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4632 FROM {role_capabilities} rc
4633 JOIN {context} ctx ON ctx.id = rc.contextid
4634 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4635 ORDER BY ctx.depth DESC";
4637 if ($existing = $DB->get_records_sql($sql, $params)) {
4638 foreach($existing as $e) {
4639 if ($e->permission == CAP_PROHIBIT) {
4640 // prohibit can not be overridden, no point in changing anything
4641 return;
4644 $lowest = array_shift($existing);
4645 if ($lowest->permission == $permission) {
4646 // permission already set in this context or parent - nothing to do
4647 return;
4649 if ($existing) {
4650 $parent = array_shift($existing);
4651 if ($parent->permission == $permission) {
4652 // permission already set in parent context or parent - just unset in this context
4653 // we do this because we want as few overrides as possible for performance reasons
4654 unassign_capability($capname, $roleid, $context->id);
4655 return;
4659 } else {
4660 if ($permission == CAP_PREVENT) {
4661 // nothing means role does not have permission
4662 return;
4666 // assign the needed capability
4667 assign_capability($capname, $permission, $roleid, $context->id, true);
4672 * Basic moodle context abstraction class.
4674 * Google confirms that no other important framework is using "context" class,
4675 * we could use something else like mcontext or moodle_context, but we need to type
4676 * this very often which would be annoying and it would take too much space...
4678 * This class is derived from stdClass for backwards compatibility with
4679 * odl $context record that was returned from DML $DB->get_record()
4681 * @package core_access
4682 * @category access
4683 * @copyright Petr Skoda {@link http://skodak.org}
4684 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4685 * @since Moodle 2.2
4687 * @property-read int $id context id
4688 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4689 * @property-read int $instanceid id of related instance in each context
4690 * @property-read string $path path to context, starts with system context
4691 * @property-read int $depth
4693 abstract class context extends stdClass implements IteratorAggregate {
4696 * The context id
4697 * Can be accessed publicly through $context->id
4698 * @var int
4700 protected $_id;
4703 * The context level
4704 * Can be accessed publicly through $context->contextlevel
4705 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4707 protected $_contextlevel;
4710 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4711 * Can be accessed publicly through $context->instanceid
4712 * @var int
4714 protected $_instanceid;
4717 * The path to the context always starting from the system context
4718 * Can be accessed publicly through $context->path
4719 * @var string
4721 protected $_path;
4724 * The depth of the context in relation to parent contexts
4725 * Can be accessed publicly through $context->depth
4726 * @var int
4728 protected $_depth;
4731 * @var array Context caching info
4733 private static $cache_contextsbyid = array();
4736 * @var array Context caching info
4738 private static $cache_contexts = array();
4741 * Context count
4742 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4743 * @var int
4745 protected static $cache_count = 0;
4748 * @var array Context caching info
4750 protected static $cache_preloaded = array();
4753 * @var context_system The system context once initialised
4755 protected static $systemcontext = null;
4758 * Resets the cache to remove all data.
4759 * @static
4761 protected static function reset_caches() {
4762 self::$cache_contextsbyid = array();
4763 self::$cache_contexts = array();
4764 self::$cache_count = 0;
4765 self::$cache_preloaded = array();
4767 self::$systemcontext = null;
4771 * Adds a context to the cache. If the cache is full, discards a batch of
4772 * older entries.
4774 * @static
4775 * @param context $context New context to add
4776 * @return void
4778 protected static function cache_add(context $context) {
4779 if (isset(self::$cache_contextsbyid[$context->id])) {
4780 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4781 return;
4784 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4785 $i = 0;
4786 foreach(self::$cache_contextsbyid as $ctx) {
4787 $i++;
4788 if ($i <= 100) {
4789 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4790 continue;
4792 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4793 // we remove oldest third of the contexts to make room for more contexts
4794 break;
4796 unset(self::$cache_contextsbyid[$ctx->id]);
4797 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4798 self::$cache_count--;
4802 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4803 self::$cache_contextsbyid[$context->id] = $context;
4804 self::$cache_count++;
4808 * Removes a context from the cache.
4810 * @static
4811 * @param context $context Context object to remove
4812 * @return void
4814 protected static function cache_remove(context $context) {
4815 if (!isset(self::$cache_contextsbyid[$context->id])) {
4816 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4817 return;
4819 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4820 unset(self::$cache_contextsbyid[$context->id]);
4822 self::$cache_count--;
4824 if (self::$cache_count < 0) {
4825 self::$cache_count = 0;
4830 * Gets a context from the cache.
4832 * @static
4833 * @param int $contextlevel Context level
4834 * @param int $instance Instance ID
4835 * @return context|bool Context or false if not in cache
4837 protected static function cache_get($contextlevel, $instance) {
4838 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4839 return self::$cache_contexts[$contextlevel][$instance];
4841 return false;
4845 * Gets a context from the cache based on its id.
4847 * @static
4848 * @param int $id Context ID
4849 * @return context|bool Context or false if not in cache
4851 protected static function cache_get_by_id($id) {
4852 if (isset(self::$cache_contextsbyid[$id])) {
4853 return self::$cache_contextsbyid[$id];
4855 return false;
4859 * Preloads context information from db record and strips the cached info.
4861 * @static
4862 * @param stdClass $rec
4863 * @return void (modifies $rec)
4865 protected static function preload_from_record(stdClass $rec) {
4866 if (empty($rec->ctxid) or empty($rec->ctxlevel) or !isset($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
4867 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4868 return;
4871 // note: in PHP5 the objects are passed by reference, no need to return $rec
4872 $record = new stdClass();
4873 $record->id = $rec->ctxid; unset($rec->ctxid);
4874 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
4875 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
4876 $record->path = $rec->ctxpath; unset($rec->ctxpath);
4877 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
4879 return context::create_instance_from_record($record);
4883 // ====== magic methods =======
4886 * Magic setter method, we do not want anybody to modify properties from the outside
4887 * @param string $name
4888 * @param mixed $value
4890 public function __set($name, $value) {
4891 debugging('Can not change context instance properties!');
4895 * Magic method getter, redirects to read only values.
4896 * @param string $name
4897 * @return mixed
4899 public function __get($name) {
4900 switch ($name) {
4901 case 'id': return $this->_id;
4902 case 'contextlevel': return $this->_contextlevel;
4903 case 'instanceid': return $this->_instanceid;
4904 case 'path': return $this->_path;
4905 case 'depth': return $this->_depth;
4907 default:
4908 debugging('Invalid context property accessed! '.$name);
4909 return null;
4914 * Full support for isset on our magic read only properties.
4915 * @param string $name
4916 * @return bool
4918 public function __isset($name) {
4919 switch ($name) {
4920 case 'id': return isset($this->_id);
4921 case 'contextlevel': return isset($this->_contextlevel);
4922 case 'instanceid': return isset($this->_instanceid);
4923 case 'path': return isset($this->_path);
4924 case 'depth': return isset($this->_depth);
4926 default: return false;
4932 * ALl properties are read only, sorry.
4933 * @param string $name
4935 public function __unset($name) {
4936 debugging('Can not unset context instance properties!');
4939 // ====== implementing method from interface IteratorAggregate ======
4942 * Create an iterator because magic vars can't be seen by 'foreach'.
4944 * Now we can convert context object to array using convert_to_array(),
4945 * and feed it properly to json_encode().
4947 public function getIterator() {
4948 $ret = array(
4949 'id' => $this->id,
4950 'contextlevel' => $this->contextlevel,
4951 'instanceid' => $this->instanceid,
4952 'path' => $this->path,
4953 'depth' => $this->depth
4955 return new ArrayIterator($ret);
4958 // ====== general context methods ======
4961 * Constructor is protected so that devs are forced to
4962 * use context_xxx::instance() or context::instance_by_id().
4964 * @param stdClass $record
4966 protected function __construct(stdClass $record) {
4967 $this->_id = (int)$record->id;
4968 $this->_contextlevel = (int)$record->contextlevel;
4969 $this->_instanceid = $record->instanceid;
4970 $this->_path = $record->path;
4971 $this->_depth = $record->depth;
4975 * This function is also used to work around 'protected' keyword problems in context_helper.
4976 * @static
4977 * @param stdClass $record
4978 * @return context instance
4980 protected static function create_instance_from_record(stdClass $record) {
4981 $classname = context_helper::get_class_for_level($record->contextlevel);
4983 if ($context = context::cache_get_by_id($record->id)) {
4984 return $context;
4987 $context = new $classname($record);
4988 context::cache_add($context);
4990 return $context;
4994 * Copy prepared new contexts from temp table to context table,
4995 * we do this in db specific way for perf reasons only.
4996 * @static
4998 protected static function merge_context_temp_table() {
4999 global $DB;
5001 /* MDL-11347:
5002 * - mysql does not allow to use FROM in UPDATE statements
5003 * - using two tables after UPDATE works in mysql, but might give unexpected
5004 * results in pg 8 (depends on configuration)
5005 * - using table alias in UPDATE does not work in pg < 8.2
5007 * Different code for each database - mostly for performance reasons
5010 $dbfamily = $DB->get_dbfamily();
5011 if ($dbfamily == 'mysql') {
5012 $updatesql = "UPDATE {context} ct, {context_temp} temp
5013 SET ct.path = temp.path,
5014 ct.depth = temp.depth
5015 WHERE ct.id = temp.id";
5016 } else if ($dbfamily == 'oracle') {
5017 $updatesql = "UPDATE {context} ct
5018 SET (ct.path, ct.depth) =
5019 (SELECT temp.path, temp.depth
5020 FROM {context_temp} temp
5021 WHERE temp.id=ct.id)
5022 WHERE EXISTS (SELECT 'x'
5023 FROM {context_temp} temp
5024 WHERE temp.id = ct.id)";
5025 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5026 $updatesql = "UPDATE {context}
5027 SET path = temp.path,
5028 depth = temp.depth
5029 FROM {context_temp} temp
5030 WHERE temp.id={context}.id";
5031 } else {
5032 // sqlite and others
5033 $updatesql = "UPDATE {context}
5034 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5035 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5036 WHERE id IN (SELECT id FROM {context_temp})";
5039 $DB->execute($updatesql);
5043 * Get a context instance as an object, from a given context id.
5045 * @static
5046 * @param int $id context id
5047 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5048 * MUST_EXIST means throw exception if no record found
5049 * @return context|bool the context object or false if not found
5051 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5052 global $DB;
5054 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5055 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5056 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5059 if ($id == SYSCONTEXTID) {
5060 return context_system::instance(0, $strictness);
5063 if (is_array($id) or is_object($id) or empty($id)) {
5064 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5067 if ($context = context::cache_get_by_id($id)) {
5068 return $context;
5071 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5072 return context::create_instance_from_record($record);
5075 return false;
5079 * Update context info after moving context in the tree structure.
5081 * @param context $newparent
5082 * @return void
5084 public function update_moved(context $newparent) {
5085 global $DB;
5087 $frompath = $this->_path;
5088 $newpath = $newparent->path . '/' . $this->_id;
5090 $trans = $DB->start_delegated_transaction();
5092 $setdepth = '';
5093 if (($newparent->depth +1) != $this->_depth) {
5094 $diff = $newparent->depth - $this->_depth + 1;
5095 $setdepth = ", depth = depth + $diff";
5097 $sql = "UPDATE {context}
5098 SET path = ?
5099 $setdepth
5100 WHERE id = ?";
5101 $params = array($newpath, $this->_id);
5102 $DB->execute($sql, $params);
5104 $this->_path = $newpath;
5105 $this->_depth = $newparent->depth + 1;
5107 $sql = "UPDATE {context}
5108 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5109 $setdepth
5110 WHERE path LIKE ?";
5111 $params = array($newpath, "{$frompath}/%");
5112 $DB->execute($sql, $params);
5114 $this->mark_dirty();
5116 context::reset_caches();
5118 $trans->allow_commit();
5122 * Remove all context path info and optionally rebuild it.
5124 * @param bool $rebuild
5125 * @return void
5127 public function reset_paths($rebuild = true) {
5128 global $DB;
5130 if ($this->_path) {
5131 $this->mark_dirty();
5133 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5134 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5135 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5136 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5137 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5138 $this->_depth = 0;
5139 $this->_path = null;
5142 if ($rebuild) {
5143 context_helper::build_all_paths(false);
5146 context::reset_caches();
5150 * Delete all data linked to content, do not delete the context record itself
5152 public function delete_content() {
5153 global $CFG, $DB;
5155 blocks_delete_all_for_context($this->_id);
5156 filter_delete_all_for_context($this->_id);
5158 require_once($CFG->dirroot . '/comment/lib.php');
5159 comment::delete_comments(array('contextid'=>$this->_id));
5161 require_once($CFG->dirroot.'/rating/lib.php');
5162 $delopt = new stdclass();
5163 $delopt->contextid = $this->_id;
5164 $rm = new rating_manager();
5165 $rm->delete_ratings($delopt);
5167 // delete all files attached to this context
5168 $fs = get_file_storage();
5169 $fs->delete_area_files($this->_id);
5171 // Delete all repository instances attached to this context.
5172 require_once($CFG->dirroot . '/repository/lib.php');
5173 repository::delete_all_for_context($this->_id);
5175 // delete all advanced grading data attached to this context
5176 require_once($CFG->dirroot.'/grade/grading/lib.php');
5177 grading_manager::delete_all_for_context($this->_id);
5179 // now delete stuff from role related tables, role_unassign_all
5180 // and unenrol should be called earlier to do proper cleanup
5181 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5182 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5183 $this->delete_capabilities();
5187 * Unassign all capabilities from a context.
5189 public function delete_capabilities() {
5190 global $DB;
5192 $ids = $DB->get_fieldset_select('role_capabilities', 'DISTINCT roleid', 'contextid = ?', array($this->_id));
5193 if ($ids) {
5194 $DB->delete_records('role_capabilities', array('contextid' => $this->_id));
5196 // Reset any cache of these roles, including MUC.
5197 accesslib_clear_role_cache($ids);
5202 * Delete the context content and the context record itself
5204 public function delete() {
5205 global $DB;
5207 if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5208 throw new coding_exception('Cannot delete system context');
5211 // double check the context still exists
5212 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5213 context::cache_remove($this);
5214 return;
5217 $this->delete_content();
5218 $DB->delete_records('context', array('id'=>$this->_id));
5219 // purge static context cache if entry present
5220 context::cache_remove($this);
5223 // ====== context level related methods ======
5226 * Utility method for context creation
5228 * @static
5229 * @param int $contextlevel
5230 * @param int $instanceid
5231 * @param string $parentpath
5232 * @return stdClass context record
5234 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5235 global $DB;
5237 $record = new stdClass();
5238 $record->contextlevel = $contextlevel;
5239 $record->instanceid = $instanceid;
5240 $record->depth = 0;
5241 $record->path = null; //not known before insert
5243 $record->id = $DB->insert_record('context', $record);
5245 // now add path if known - it can be added later
5246 if (!is_null($parentpath)) {
5247 $record->path = $parentpath.'/'.$record->id;
5248 $record->depth = substr_count($record->path, '/');
5249 $DB->update_record('context', $record);
5252 return $record;
5256 * Returns human readable context identifier.
5258 * @param boolean $withprefix whether to prefix the name of the context with the
5259 * type of context, e.g. User, Course, Forum, etc.
5260 * @param boolean $short whether to use the short name of the thing. Only applies
5261 * to course contexts
5262 * @return string the human readable context name.
5264 public function get_context_name($withprefix = true, $short = false) {
5265 // must be implemented in all context levels
5266 throw new coding_exception('can not get name of abstract context');
5270 * Returns the most relevant URL for this context.
5272 * @return moodle_url
5274 public abstract function get_url();
5277 * Returns array of relevant context capability records.
5279 * @return array
5281 public abstract function get_capabilities();
5284 * Recursive function which, given a context, find all its children context ids.
5286 * For course category contexts it will return immediate children and all subcategory contexts.
5287 * It will NOT recurse into courses or subcategories categories.
5288 * If you want to do that, call it on the returned courses/categories.
5290 * When called for a course context, it will return the modules and blocks
5291 * displayed in the course page and blocks displayed on the module pages.
5293 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5294 * contexts ;-)
5296 * @return array Array of child records
5298 public function get_child_contexts() {
5299 global $DB;
5301 if (empty($this->_path) or empty($this->_depth)) {
5302 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5303 return array();
5306 $sql = "SELECT ctx.*
5307 FROM {context} ctx
5308 WHERE ctx.path LIKE ?";
5309 $params = array($this->_path.'/%');
5310 $records = $DB->get_records_sql($sql, $params);
5312 $result = array();
5313 foreach ($records as $record) {
5314 $result[$record->id] = context::create_instance_from_record($record);
5317 return $result;
5321 * Returns parent contexts of this context in reversed order, i.e. parent first,
5322 * then grand parent, etc.
5324 * @param bool $includeself true means include self too
5325 * @return array of context instances
5327 public function get_parent_contexts($includeself = false) {
5328 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5329 return array();
5332 $result = array();
5333 foreach ($contextids as $contextid) {
5334 $parent = context::instance_by_id($contextid, MUST_EXIST);
5335 $result[$parent->id] = $parent;
5338 return $result;
5342 * Returns parent context ids of this context in reversed order, i.e. parent first,
5343 * then grand parent, etc.
5345 * @param bool $includeself true means include self too
5346 * @return array of context ids
5348 public function get_parent_context_ids($includeself = false) {
5349 if (empty($this->_path)) {
5350 return array();
5353 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5354 $parentcontexts = explode('/', $parentcontexts);
5355 if (!$includeself) {
5356 array_pop($parentcontexts); // and remove its own id
5359 return array_reverse($parentcontexts);
5363 * Returns parent context paths of this context.
5365 * @param bool $includeself true means include self too
5366 * @return array of context paths
5368 public function get_parent_context_paths($includeself = false) {
5369 if (empty($this->_path)) {
5370 return array();
5373 $contextids = explode('/', $this->_path);
5375 $path = '';
5376 $paths = array();
5377 foreach ($contextids as $contextid) {
5378 if ($contextid) {
5379 $path .= '/' . $contextid;
5380 $paths[$contextid] = $path;
5384 if (!$includeself) {
5385 unset($paths[$this->_id]);
5388 return $paths;
5392 * Returns parent context
5394 * @return context
5396 public function get_parent_context() {
5397 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5398 return false;
5401 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5402 $parentcontexts = explode('/', $parentcontexts);
5403 array_pop($parentcontexts); // self
5404 $contextid = array_pop($parentcontexts); // immediate parent
5406 return context::instance_by_id($contextid, MUST_EXIST);
5410 * Is this context part of any course? If yes return course context.
5412 * @param bool $strict true means throw exception if not found, false means return false if not found
5413 * @return context_course context of the enclosing course, null if not found or exception
5415 public function get_course_context($strict = true) {
5416 if ($strict) {
5417 throw new coding_exception('Context does not belong to any course.');
5418 } else {
5419 return false;
5424 * Returns sql necessary for purging of stale context instances.
5426 * @static
5427 * @return string cleanup SQL
5429 protected static function get_cleanup_sql() {
5430 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5434 * Rebuild context paths and depths at context level.
5436 * @static
5437 * @param bool $force
5438 * @return void
5440 protected static function build_paths($force) {
5441 throw new coding_exception('build_paths() method must be implemented in all context levels');
5445 * Create missing context instances at given level
5447 * @static
5448 * @return void
5450 protected static function create_level_instances() {
5451 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5455 * Reset all cached permissions and definitions if the necessary.
5456 * @return void
5458 public function reload_if_dirty() {
5459 global $ACCESSLIB_PRIVATE, $USER;
5461 // Load dirty contexts list if needed
5462 if (CLI_SCRIPT) {
5463 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5464 // we do not load dirty flags in CLI and cron
5465 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5467 } else {
5468 if (!isset($USER->access['time'])) {
5469 // Nothing has been loaded yet, so we do not need to check dirty flags now.
5470 return;
5473 // From skodak: No idea why -2 is there, server cluster time difference maybe...
5474 $changedsince = $USER->access['time'] - 2;
5476 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5477 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $changedsince);
5480 if (!isset($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
5481 $ACCESSLIB_PRIVATE->dirtyusers[$USER->id] = get_cache_flag('accesslib/dirtyusers', $USER->id, $changedsince);
5485 $dirty = false;
5487 if (!empty($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
5488 $dirty = true;
5489 } else if (!empty($ACCESSLIB_PRIVATE->dirtycontexts)) {
5490 $paths = $this->get_parent_context_paths(true);
5492 foreach ($paths as $path) {
5493 if (isset($ACCESSLIB_PRIVATE->dirtycontexts[$path])) {
5494 $dirty = true;
5495 break;
5500 if ($dirty) {
5501 // Reload all capabilities of USER and others - preserving loginas, roleswitches, etc.
5502 // Then cleanup any marks of dirtyness... at least from our short term memory!
5503 reload_all_capabilities();
5508 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5510 public function mark_dirty() {
5511 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5513 if (during_initial_install()) {
5514 return;
5517 // only if it is a non-empty string
5518 if (is_string($this->_path) && $this->_path !== '') {
5519 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5520 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5521 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5522 } else {
5523 if (CLI_SCRIPT) {
5524 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5525 } else {
5526 if (isset($USER->access['time'])) {
5527 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5528 } else {
5529 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5531 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5540 * Context maintenance and helper methods.
5542 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5543 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5544 * level implementation from the rest of code, the code completion returns what developers need.
5546 * Thank you Tim Hunt for helping me with this nasty trick.
5548 * @package core_access
5549 * @category access
5550 * @copyright Petr Skoda {@link http://skodak.org}
5551 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5552 * @since Moodle 2.2
5554 class context_helper extends context {
5557 * @var array An array mapping context levels to classes
5559 private static $alllevels;
5562 * Instance does not make sense here, only static use
5564 protected function __construct() {
5568 * Reset internal context levels array.
5570 public static function reset_levels() {
5571 self::$alllevels = null;
5575 * Initialise context levels, call before using self::$alllevels.
5577 private static function init_levels() {
5578 global $CFG;
5580 if (isset(self::$alllevels)) {
5581 return;
5583 self::$alllevels = array(
5584 CONTEXT_SYSTEM => 'context_system',
5585 CONTEXT_USER => 'context_user',
5586 CONTEXT_COURSECAT => 'context_coursecat',
5587 CONTEXT_COURSE => 'context_course',
5588 CONTEXT_MODULE => 'context_module',
5589 CONTEXT_BLOCK => 'context_block',
5592 if (empty($CFG->custom_context_classes)) {
5593 return;
5596 $levels = $CFG->custom_context_classes;
5597 if (!is_array($levels)) {
5598 $levels = @unserialize($levels);
5600 if (!is_array($levels)) {
5601 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
5602 return;
5605 // Unsupported custom levels, use with care!!!
5606 foreach ($levels as $level => $classname) {
5607 self::$alllevels[$level] = $classname;
5609 ksort(self::$alllevels);
5613 * Returns a class name of the context level class
5615 * @static
5616 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5617 * @return string class name of the context class
5619 public static function get_class_for_level($contextlevel) {
5620 self::init_levels();
5621 if (isset(self::$alllevels[$contextlevel])) {
5622 return self::$alllevels[$contextlevel];
5623 } else {
5624 throw new coding_exception('Invalid context level specified');
5629 * Returns a list of all context levels
5631 * @static
5632 * @return array int=>string (level=>level class name)
5634 public static function get_all_levels() {
5635 self::init_levels();
5636 return self::$alllevels;
5640 * Remove stale contexts that belonged to deleted instances.
5641 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5643 * @static
5644 * @return void
5646 public static function cleanup_instances() {
5647 global $DB;
5648 self::init_levels();
5650 $sqls = array();
5651 foreach (self::$alllevels as $level=>$classname) {
5652 $sqls[] = $classname::get_cleanup_sql();
5655 $sql = implode(" UNION ", $sqls);
5657 // it is probably better to use transactions, it might be faster too
5658 $transaction = $DB->start_delegated_transaction();
5660 $rs = $DB->get_recordset_sql($sql);
5661 foreach ($rs as $record) {
5662 $context = context::create_instance_from_record($record);
5663 $context->delete();
5665 $rs->close();
5667 $transaction->allow_commit();
5671 * Create all context instances at the given level and above.
5673 * @static
5674 * @param int $contextlevel null means all levels
5675 * @param bool $buildpaths
5676 * @return void
5678 public static function create_instances($contextlevel = null, $buildpaths = true) {
5679 self::init_levels();
5680 foreach (self::$alllevels as $level=>$classname) {
5681 if ($contextlevel and $level > $contextlevel) {
5682 // skip potential sub-contexts
5683 continue;
5685 $classname::create_level_instances();
5686 if ($buildpaths) {
5687 $classname::build_paths(false);
5693 * Rebuild paths and depths in all context levels.
5695 * @static
5696 * @param bool $force false means add missing only
5697 * @return void
5699 public static function build_all_paths($force = false) {
5700 self::init_levels();
5701 foreach (self::$alllevels as $classname) {
5702 $classname::build_paths($force);
5705 // reset static course cache - it might have incorrect cached data
5706 accesslib_clear_all_caches(true);
5710 * Resets the cache to remove all data.
5711 * @static
5713 public static function reset_caches() {
5714 context::reset_caches();
5718 * Returns all fields necessary for context preloading from user $rec.
5720 * This helps with performance when dealing with hundreds of contexts.
5722 * @static
5723 * @param string $tablealias context table alias in the query
5724 * @return array (table.column=>alias, ...)
5726 public static function get_preload_record_columns($tablealias) {
5727 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5731 * Returns all fields necessary for context preloading from user $rec.
5733 * This helps with performance when dealing with hundreds of contexts.
5735 * @static
5736 * @param string $tablealias context table alias in the query
5737 * @return string
5739 public static function get_preload_record_columns_sql($tablealias) {
5740 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5744 * Preloads context information from db record and strips the cached info.
5746 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5748 * @static
5749 * @param stdClass $rec
5750 * @return void (modifies $rec)
5752 public static function preload_from_record(stdClass $rec) {
5753 context::preload_from_record($rec);
5757 * Preload all contexts instances from course.
5759 * To be used if you expect multiple queries for course activities...
5761 * @static
5762 * @param int $courseid
5764 public static function preload_course($courseid) {
5765 // Users can call this multiple times without doing any harm
5766 if (isset(context::$cache_preloaded[$courseid])) {
5767 return;
5769 $coursecontext = context_course::instance($courseid);
5770 $coursecontext->get_child_contexts();
5772 context::$cache_preloaded[$courseid] = true;
5776 * Delete context instance
5778 * @static
5779 * @param int $contextlevel
5780 * @param int $instanceid
5781 * @return void
5783 public static function delete_instance($contextlevel, $instanceid) {
5784 global $DB;
5786 // double check the context still exists
5787 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5788 $context = context::create_instance_from_record($record);
5789 $context->delete();
5790 } else {
5791 // we should try to purge the cache anyway
5796 * Returns the name of specified context level
5798 * @static
5799 * @param int $contextlevel
5800 * @return string name of the context level
5802 public static function get_level_name($contextlevel) {
5803 $classname = context_helper::get_class_for_level($contextlevel);
5804 return $classname::get_level_name();
5808 * not used
5810 public function get_url() {
5814 * not used
5816 public function get_capabilities() {
5822 * System context class
5824 * @package core_access
5825 * @category access
5826 * @copyright Petr Skoda {@link http://skodak.org}
5827 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5828 * @since Moodle 2.2
5830 class context_system extends context {
5832 * Please use context_system::instance() if you need the instance of context.
5834 * @param stdClass $record
5836 protected function __construct(stdClass $record) {
5837 parent::__construct($record);
5838 if ($record->contextlevel != CONTEXT_SYSTEM) {
5839 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5844 * Returns human readable context level name.
5846 * @static
5847 * @return string the human readable context level name.
5849 public static function get_level_name() {
5850 return get_string('coresystem');
5854 * Returns human readable context identifier.
5856 * @param boolean $withprefix does not apply to system context
5857 * @param boolean $short does not apply to system context
5858 * @return string the human readable context name.
5860 public function get_context_name($withprefix = true, $short = false) {
5861 return self::get_level_name();
5865 * Returns the most relevant URL for this context.
5867 * @return moodle_url
5869 public function get_url() {
5870 return new moodle_url('/');
5874 * Returns array of relevant context capability records.
5876 * @return array
5878 public function get_capabilities() {
5879 global $DB;
5881 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5883 $params = array();
5884 $sql = "SELECT *
5885 FROM {capabilities}";
5887 return $DB->get_records_sql($sql.' '.$sort, $params);
5891 * Create missing context instances at system context
5892 * @static
5894 protected static function create_level_instances() {
5895 // nothing to do here, the system context is created automatically in installer
5896 self::instance(0);
5900 * Returns system context instance.
5902 * @static
5903 * @param int $instanceid should be 0
5904 * @param int $strictness
5905 * @param bool $cache
5906 * @return context_system context instance
5908 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
5909 global $DB;
5911 if ($instanceid != 0) {
5912 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5915 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5916 if (!isset(context::$systemcontext)) {
5917 $record = new stdClass();
5918 $record->id = SYSCONTEXTID;
5919 $record->contextlevel = CONTEXT_SYSTEM;
5920 $record->instanceid = 0;
5921 $record->path = '/'.SYSCONTEXTID;
5922 $record->depth = 1;
5923 context::$systemcontext = new context_system($record);
5925 return context::$systemcontext;
5929 try {
5930 // We ignore the strictness completely because system context must exist except during install.
5931 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5932 } catch (dml_exception $e) {
5933 //table or record does not exist
5934 if (!during_initial_install()) {
5935 // do not mess with system context after install, it simply must exist
5936 throw $e;
5938 $record = null;
5941 if (!$record) {
5942 $record = new stdClass();
5943 $record->contextlevel = CONTEXT_SYSTEM;
5944 $record->instanceid = 0;
5945 $record->depth = 1;
5946 $record->path = null; //not known before insert
5948 try {
5949 if ($DB->count_records('context')) {
5950 // contexts already exist, this is very weird, system must be first!!!
5951 return null;
5953 if (defined('SYSCONTEXTID')) {
5954 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5955 $record->id = SYSCONTEXTID;
5956 $DB->import_record('context', $record);
5957 $DB->get_manager()->reset_sequence('context');
5958 } else {
5959 $record->id = $DB->insert_record('context', $record);
5961 } catch (dml_exception $e) {
5962 // can not create context - table does not exist yet, sorry
5963 return null;
5967 if ($record->instanceid != 0) {
5968 // this is very weird, somebody must be messing with context table
5969 debugging('Invalid system context detected');
5972 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5973 // fix path if necessary, initial install or path reset
5974 $record->depth = 1;
5975 $record->path = '/'.$record->id;
5976 $DB->update_record('context', $record);
5979 if (!defined('SYSCONTEXTID')) {
5980 define('SYSCONTEXTID', $record->id);
5983 context::$systemcontext = new context_system($record);
5984 return context::$systemcontext;
5988 * Returns all site contexts except the system context, DO NOT call on production servers!!
5990 * Contexts are not cached.
5992 * @return array
5994 public function get_child_contexts() {
5995 global $DB;
5997 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
5999 // Just get all the contexts except for CONTEXT_SYSTEM level
6000 // and hope we don't OOM in the process - don't cache
6001 $sql = "SELECT c.*
6002 FROM {context} c
6003 WHERE contextlevel > ".CONTEXT_SYSTEM;
6004 $records = $DB->get_records_sql($sql);
6006 $result = array();
6007 foreach ($records as $record) {
6008 $result[$record->id] = context::create_instance_from_record($record);
6011 return $result;
6015 * Returns sql necessary for purging of stale context instances.
6017 * @static
6018 * @return string cleanup SQL
6020 protected static function get_cleanup_sql() {
6021 $sql = "
6022 SELECT c.*
6023 FROM {context} c
6024 WHERE 1=2
6027 return $sql;
6031 * Rebuild context paths and depths at system context level.
6033 * @static
6034 * @param bool $force
6036 protected static function build_paths($force) {
6037 global $DB;
6039 /* note: ignore $force here, we always do full test of system context */
6041 // exactly one record must exist
6042 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6044 if ($record->instanceid != 0) {
6045 debugging('Invalid system context detected');
6048 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6049 debugging('Invalid SYSCONTEXTID detected');
6052 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6053 // fix path if necessary, initial install or path reset
6054 $record->depth = 1;
6055 $record->path = '/'.$record->id;
6056 $DB->update_record('context', $record);
6063 * User context class
6065 * @package core_access
6066 * @category access
6067 * @copyright Petr Skoda {@link http://skodak.org}
6068 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6069 * @since Moodle 2.2
6071 class context_user extends context {
6073 * Please use context_user::instance($userid) if you need the instance of context.
6074 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6076 * @param stdClass $record
6078 protected function __construct(stdClass $record) {
6079 parent::__construct($record);
6080 if ($record->contextlevel != CONTEXT_USER) {
6081 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6086 * Returns human readable context level name.
6088 * @static
6089 * @return string the human readable context level name.
6091 public static function get_level_name() {
6092 return get_string('user');
6096 * Returns human readable context identifier.
6098 * @param boolean $withprefix whether to prefix the name of the context with User
6099 * @param boolean $short does not apply to user context
6100 * @return string the human readable context name.
6102 public function get_context_name($withprefix = true, $short = false) {
6103 global $DB;
6105 $name = '';
6106 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6107 if ($withprefix){
6108 $name = get_string('user').': ';
6110 $name .= fullname($user);
6112 return $name;
6116 * Returns the most relevant URL for this context.
6118 * @return moodle_url
6120 public function get_url() {
6121 global $COURSE;
6123 if ($COURSE->id == SITEID) {
6124 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6125 } else {
6126 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6128 return $url;
6132 * Returns array of relevant context capability records.
6134 * @return array
6136 public function get_capabilities() {
6137 global $DB;
6139 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6141 $extracaps = array('moodle/grade:viewall');
6142 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6143 $sql = "SELECT *
6144 FROM {capabilities}
6145 WHERE contextlevel = ".CONTEXT_USER."
6146 OR name $extra";
6148 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6152 * Returns user context instance.
6154 * @static
6155 * @param int $userid id from {user} table
6156 * @param int $strictness
6157 * @return context_user context instance
6159 public static function instance($userid, $strictness = MUST_EXIST) {
6160 global $DB;
6162 if ($context = context::cache_get(CONTEXT_USER, $userid)) {
6163 return $context;
6166 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER, 'instanceid' => $userid))) {
6167 if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6168 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6172 if ($record) {
6173 $context = new context_user($record);
6174 context::cache_add($context);
6175 return $context;
6178 return false;
6182 * Create missing context instances at user context level
6183 * @static
6185 protected static function create_level_instances() {
6186 global $DB;
6188 $sql = "SELECT ".CONTEXT_USER.", u.id
6189 FROM {user} u
6190 WHERE u.deleted = 0
6191 AND NOT EXISTS (SELECT 'x'
6192 FROM {context} cx
6193 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6194 $contextdata = $DB->get_recordset_sql($sql);
6195 foreach ($contextdata as $context) {
6196 context::insert_context_record(CONTEXT_USER, $context->id, null);
6198 $contextdata->close();
6202 * Returns sql necessary for purging of stale context instances.
6204 * @static
6205 * @return string cleanup SQL
6207 protected static function get_cleanup_sql() {
6208 $sql = "
6209 SELECT c.*
6210 FROM {context} c
6211 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6212 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6215 return $sql;
6219 * Rebuild context paths and depths at user context level.
6221 * @static
6222 * @param bool $force
6224 protected static function build_paths($force) {
6225 global $DB;
6227 // First update normal users.
6228 $path = $DB->sql_concat('?', 'id');
6229 $pathstart = '/' . SYSCONTEXTID . '/';
6230 $params = array($pathstart);
6232 if ($force) {
6233 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6234 $params[] = $pathstart;
6235 } else {
6236 $where = "depth = 0 OR path IS NULL";
6239 $sql = "UPDATE {context}
6240 SET depth = 2,
6241 path = {$path}
6242 WHERE contextlevel = " . CONTEXT_USER . "
6243 AND ($where)";
6244 $DB->execute($sql, $params);
6250 * Course category context class
6252 * @package core_access
6253 * @category access
6254 * @copyright Petr Skoda {@link http://skodak.org}
6255 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6256 * @since Moodle 2.2
6258 class context_coursecat extends context {
6260 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6261 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6263 * @param stdClass $record
6265 protected function __construct(stdClass $record) {
6266 parent::__construct($record);
6267 if ($record->contextlevel != CONTEXT_COURSECAT) {
6268 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6273 * Returns human readable context level name.
6275 * @static
6276 * @return string the human readable context level name.
6278 public static function get_level_name() {
6279 return get_string('category');
6283 * Returns human readable context identifier.
6285 * @param boolean $withprefix whether to prefix the name of the context with Category
6286 * @param boolean $short does not apply to course categories
6287 * @return string the human readable context name.
6289 public function get_context_name($withprefix = true, $short = false) {
6290 global $DB;
6292 $name = '';
6293 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6294 if ($withprefix){
6295 $name = get_string('category').': ';
6297 $name .= format_string($category->name, true, array('context' => $this));
6299 return $name;
6303 * Returns the most relevant URL for this context.
6305 * @return moodle_url
6307 public function get_url() {
6308 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6312 * Returns array of relevant context capability records.
6314 * @return array
6316 public function get_capabilities() {
6317 global $DB;
6319 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6321 $params = array();
6322 $sql = "SELECT *
6323 FROM {capabilities}
6324 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6326 return $DB->get_records_sql($sql.' '.$sort, $params);
6330 * Returns course category context instance.
6332 * @static
6333 * @param int $categoryid id from {course_categories} table
6334 * @param int $strictness
6335 * @return context_coursecat context instance
6337 public static function instance($categoryid, $strictness = MUST_EXIST) {
6338 global $DB;
6340 if ($context = context::cache_get(CONTEXT_COURSECAT, $categoryid)) {
6341 return $context;
6344 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT, 'instanceid' => $categoryid))) {
6345 if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6346 if ($category->parent) {
6347 $parentcontext = context_coursecat::instance($category->parent);
6348 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6349 } else {
6350 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6355 if ($record) {
6356 $context = new context_coursecat($record);
6357 context::cache_add($context);
6358 return $context;
6361 return false;
6365 * Returns immediate child contexts of category and all subcategories,
6366 * children of subcategories and courses are not returned.
6368 * @return array
6370 public function get_child_contexts() {
6371 global $DB;
6373 if (empty($this->_path) or empty($this->_depth)) {
6374 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6375 return array();
6378 $sql = "SELECT ctx.*
6379 FROM {context} ctx
6380 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6381 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6382 $records = $DB->get_records_sql($sql, $params);
6384 $result = array();
6385 foreach ($records as $record) {
6386 $result[$record->id] = context::create_instance_from_record($record);
6389 return $result;
6393 * Create missing context instances at course category context level
6394 * @static
6396 protected static function create_level_instances() {
6397 global $DB;
6399 $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6400 FROM {course_categories} cc
6401 WHERE NOT EXISTS (SELECT 'x'
6402 FROM {context} cx
6403 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6404 $contextdata = $DB->get_recordset_sql($sql);
6405 foreach ($contextdata as $context) {
6406 context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6408 $contextdata->close();
6412 * Returns sql necessary for purging of stale context instances.
6414 * @static
6415 * @return string cleanup SQL
6417 protected static function get_cleanup_sql() {
6418 $sql = "
6419 SELECT c.*
6420 FROM {context} c
6421 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6422 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6425 return $sql;
6429 * Rebuild context paths and depths at course category context level.
6431 * @static
6432 * @param bool $force
6434 protected static function build_paths($force) {
6435 global $DB;
6437 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6438 if ($force) {
6439 $ctxemptyclause = $emptyclause = '';
6440 } else {
6441 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6442 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6445 $base = '/'.SYSCONTEXTID;
6447 // Normal top level categories
6448 $sql = "UPDATE {context}
6449 SET depth=2,
6450 path=".$DB->sql_concat("'$base/'", 'id')."
6451 WHERE contextlevel=".CONTEXT_COURSECAT."
6452 AND EXISTS (SELECT 'x'
6453 FROM {course_categories} cc
6454 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6455 $emptyclause";
6456 $DB->execute($sql);
6458 // Deeper categories - one query per depthlevel
6459 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6460 for ($n=2; $n<=$maxdepth; $n++) {
6461 $sql = "INSERT INTO {context_temp} (id, path, depth)
6462 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6463 FROM {context} ctx
6464 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6465 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6466 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6467 $ctxemptyclause";
6468 $trans = $DB->start_delegated_transaction();
6469 $DB->delete_records('context_temp');
6470 $DB->execute($sql);
6471 context::merge_context_temp_table();
6472 $DB->delete_records('context_temp');
6473 $trans->allow_commit();
6482 * Course context class
6484 * @package core_access
6485 * @category access
6486 * @copyright Petr Skoda {@link http://skodak.org}
6487 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6488 * @since Moodle 2.2
6490 class context_course extends context {
6492 * Please use context_course::instance($courseid) if you need the instance of context.
6493 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6495 * @param stdClass $record
6497 protected function __construct(stdClass $record) {
6498 parent::__construct($record);
6499 if ($record->contextlevel != CONTEXT_COURSE) {
6500 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6505 * Returns human readable context level name.
6507 * @static
6508 * @return string the human readable context level name.
6510 public static function get_level_name() {
6511 return get_string('course');
6515 * Returns human readable context identifier.
6517 * @param boolean $withprefix whether to prefix the name of the context with Course
6518 * @param boolean $short whether to use the short name of the thing.
6519 * @return string the human readable context name.
6521 public function get_context_name($withprefix = true, $short = false) {
6522 global $DB;
6524 $name = '';
6525 if ($this->_instanceid == SITEID) {
6526 $name = get_string('frontpage', 'admin');
6527 } else {
6528 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6529 if ($withprefix){
6530 $name = get_string('course').': ';
6532 if ($short){
6533 $name .= format_string($course->shortname, true, array('context' => $this));
6534 } else {
6535 $name .= format_string(get_course_display_name_for_list($course));
6539 return $name;
6543 * Returns the most relevant URL for this context.
6545 * @return moodle_url
6547 public function get_url() {
6548 if ($this->_instanceid != SITEID) {
6549 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6552 return new moodle_url('/');
6556 * Returns array of relevant context capability records.
6558 * @return array
6560 public function get_capabilities() {
6561 global $DB;
6563 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6565 $params = array();
6566 $sql = "SELECT *
6567 FROM {capabilities}
6568 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6570 return $DB->get_records_sql($sql.' '.$sort, $params);
6574 * Is this context part of any course? If yes return course context.
6576 * @param bool $strict true means throw exception if not found, false means return false if not found
6577 * @return context_course context of the enclosing course, null if not found or exception
6579 public function get_course_context($strict = true) {
6580 return $this;
6584 * Returns course context instance.
6586 * @static
6587 * @param int $courseid id from {course} table
6588 * @param int $strictness
6589 * @return context_course context instance
6591 public static function instance($courseid, $strictness = MUST_EXIST) {
6592 global $DB;
6594 if ($context = context::cache_get(CONTEXT_COURSE, $courseid)) {
6595 return $context;
6598 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $courseid))) {
6599 if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
6600 if ($course->category) {
6601 $parentcontext = context_coursecat::instance($course->category);
6602 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6603 } else {
6604 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6609 if ($record) {
6610 $context = new context_course($record);
6611 context::cache_add($context);
6612 return $context;
6615 return false;
6619 * Create missing context instances at course context level
6620 * @static
6622 protected static function create_level_instances() {
6623 global $DB;
6625 $sql = "SELECT ".CONTEXT_COURSE.", c.id
6626 FROM {course} c
6627 WHERE NOT EXISTS (SELECT 'x'
6628 FROM {context} cx
6629 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6630 $contextdata = $DB->get_recordset_sql($sql);
6631 foreach ($contextdata as $context) {
6632 context::insert_context_record(CONTEXT_COURSE, $context->id, null);
6634 $contextdata->close();
6638 * Returns sql necessary for purging of stale context instances.
6640 * @static
6641 * @return string cleanup SQL
6643 protected static function get_cleanup_sql() {
6644 $sql = "
6645 SELECT c.*
6646 FROM {context} c
6647 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6648 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6651 return $sql;
6655 * Rebuild context paths and depths at course context level.
6657 * @static
6658 * @param bool $force
6660 protected static function build_paths($force) {
6661 global $DB;
6663 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6664 if ($force) {
6665 $ctxemptyclause = $emptyclause = '';
6666 } else {
6667 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6668 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6671 $base = '/'.SYSCONTEXTID;
6673 // Standard frontpage
6674 $sql = "UPDATE {context}
6675 SET depth = 2,
6676 path = ".$DB->sql_concat("'$base/'", 'id')."
6677 WHERE contextlevel = ".CONTEXT_COURSE."
6678 AND EXISTS (SELECT 'x'
6679 FROM {course} c
6680 WHERE c.id = {context}.instanceid AND c.category = 0)
6681 $emptyclause";
6682 $DB->execute($sql);
6684 // standard courses
6685 $sql = "INSERT INTO {context_temp} (id, path, depth)
6686 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6687 FROM {context} ctx
6688 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6689 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6690 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6691 $ctxemptyclause";
6692 $trans = $DB->start_delegated_transaction();
6693 $DB->delete_records('context_temp');
6694 $DB->execute($sql);
6695 context::merge_context_temp_table();
6696 $DB->delete_records('context_temp');
6697 $trans->allow_commit();
6704 * Course module context class
6706 * @package core_access
6707 * @category access
6708 * @copyright Petr Skoda {@link http://skodak.org}
6709 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6710 * @since Moodle 2.2
6712 class context_module extends context {
6714 * Please use context_module::instance($cmid) if you need the instance of context.
6715 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6717 * @param stdClass $record
6719 protected function __construct(stdClass $record) {
6720 parent::__construct($record);
6721 if ($record->contextlevel != CONTEXT_MODULE) {
6722 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6727 * Returns human readable context level name.
6729 * @static
6730 * @return string the human readable context level name.
6732 public static function get_level_name() {
6733 return get_string('activitymodule');
6737 * Returns human readable context identifier.
6739 * @param boolean $withprefix whether to prefix the name of the context with the
6740 * module name, e.g. Forum, Glossary, etc.
6741 * @param boolean $short does not apply to module context
6742 * @return string the human readable context name.
6744 public function get_context_name($withprefix = true, $short = false) {
6745 global $DB;
6747 $name = '';
6748 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6749 FROM {course_modules} cm
6750 JOIN {modules} md ON md.id = cm.module
6751 WHERE cm.id = ?", array($this->_instanceid))) {
6752 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6753 if ($withprefix){
6754 $name = get_string('modulename', $cm->modname).': ';
6756 $name .= format_string($mod->name, true, array('context' => $this));
6759 return $name;
6763 * Returns the most relevant URL for this context.
6765 * @return moodle_url
6767 public function get_url() {
6768 global $DB;
6770 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6771 FROM {course_modules} cm
6772 JOIN {modules} md ON md.id = cm.module
6773 WHERE cm.id = ?", array($this->_instanceid))) {
6774 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6777 return new moodle_url('/');
6781 * Returns array of relevant context capability records.
6783 * @return array
6785 public function get_capabilities() {
6786 global $DB, $CFG;
6788 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6790 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6791 $module = $DB->get_record('modules', array('id'=>$cm->module));
6793 $subcaps = array();
6794 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6795 if (file_exists($subpluginsfile)) {
6796 $subplugins = array(); // should be redefined in the file
6797 include($subpluginsfile);
6798 if (!empty($subplugins)) {
6799 foreach (array_keys($subplugins) as $subplugintype) {
6800 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
6801 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6807 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6808 $extracaps = array();
6809 if (file_exists($modfile)) {
6810 include_once($modfile);
6811 $modfunction = $module->name.'_get_extra_capabilities';
6812 if (function_exists($modfunction)) {
6813 $extracaps = $modfunction();
6817 $extracaps = array_merge($subcaps, $extracaps);
6818 $extra = '';
6819 list($extra, $params) = $DB->get_in_or_equal(
6820 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
6821 if (!empty($extra)) {
6822 $extra = "OR name $extra";
6824 $sql = "SELECT *
6825 FROM {capabilities}
6826 WHERE (contextlevel = ".CONTEXT_MODULE."
6827 AND (component = :component OR component = 'moodle'))
6828 $extra";
6829 $params['component'] = "mod_$module->name";
6831 return $DB->get_records_sql($sql.' '.$sort, $params);
6835 * Is this context part of any course? If yes return course context.
6837 * @param bool $strict true means throw exception if not found, false means return false if not found
6838 * @return context_course context of the enclosing course, null if not found or exception
6840 public function get_course_context($strict = true) {
6841 return $this->get_parent_context();
6845 * Returns module context instance.
6847 * @static
6848 * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
6849 * @param int $strictness
6850 * @return context_module context instance
6852 public static function instance($cmid, $strictness = MUST_EXIST) {
6853 global $DB;
6855 if ($context = context::cache_get(CONTEXT_MODULE, $cmid)) {
6856 return $context;
6859 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE, 'instanceid' => $cmid))) {
6860 if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
6861 $parentcontext = context_course::instance($cm->course);
6862 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
6866 if ($record) {
6867 $context = new context_module($record);
6868 context::cache_add($context);
6869 return $context;
6872 return false;
6876 * Create missing context instances at module context level
6877 * @static
6879 protected static function create_level_instances() {
6880 global $DB;
6882 $sql = "SELECT ".CONTEXT_MODULE.", cm.id
6883 FROM {course_modules} cm
6884 WHERE NOT EXISTS (SELECT 'x'
6885 FROM {context} cx
6886 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
6887 $contextdata = $DB->get_recordset_sql($sql);
6888 foreach ($contextdata as $context) {
6889 context::insert_context_record(CONTEXT_MODULE, $context->id, null);
6891 $contextdata->close();
6895 * Returns sql necessary for purging of stale context instances.
6897 * @static
6898 * @return string cleanup SQL
6900 protected static function get_cleanup_sql() {
6901 $sql = "
6902 SELECT c.*
6903 FROM {context} c
6904 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6905 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
6908 return $sql;
6912 * Rebuild context paths and depths at module context level.
6914 * @static
6915 * @param bool $force
6917 protected static function build_paths($force) {
6918 global $DB;
6920 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
6921 if ($force) {
6922 $ctxemptyclause = '';
6923 } else {
6924 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6927 $sql = "INSERT INTO {context_temp} (id, path, depth)
6928 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6929 FROM {context} ctx
6930 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
6931 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
6932 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6933 $ctxemptyclause";
6934 $trans = $DB->start_delegated_transaction();
6935 $DB->delete_records('context_temp');
6936 $DB->execute($sql);
6937 context::merge_context_temp_table();
6938 $DB->delete_records('context_temp');
6939 $trans->allow_commit();
6946 * Block context class
6948 * @package core_access
6949 * @category access
6950 * @copyright Petr Skoda {@link http://skodak.org}
6951 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6952 * @since Moodle 2.2
6954 class context_block extends context {
6956 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6957 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6959 * @param stdClass $record
6961 protected function __construct(stdClass $record) {
6962 parent::__construct($record);
6963 if ($record->contextlevel != CONTEXT_BLOCK) {
6964 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6969 * Returns human readable context level name.
6971 * @static
6972 * @return string the human readable context level name.
6974 public static function get_level_name() {
6975 return get_string('block');
6979 * Returns human readable context identifier.
6981 * @param boolean $withprefix whether to prefix the name of the context with Block
6982 * @param boolean $short does not apply to block context
6983 * @return string the human readable context name.
6985 public function get_context_name($withprefix = true, $short = false) {
6986 global $DB, $CFG;
6988 $name = '';
6989 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
6990 global $CFG;
6991 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
6992 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
6993 $blockname = "block_$blockinstance->blockname";
6994 if ($blockobject = new $blockname()) {
6995 if ($withprefix){
6996 $name = get_string('block').': ';
6998 $name .= $blockobject->title;
7002 return $name;
7006 * Returns the most relevant URL for this context.
7008 * @return moodle_url
7010 public function get_url() {
7011 $parentcontexts = $this->get_parent_context();
7012 return $parentcontexts->get_url();
7016 * Returns array of relevant context capability records.
7018 * @return array
7020 public function get_capabilities() {
7021 global $DB;
7023 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7025 $params = array();
7026 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
7028 $extra = '';
7029 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7030 if ($extracaps) {
7031 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7032 $extra = "OR name $extra";
7035 $sql = "SELECT *
7036 FROM {capabilities}
7037 WHERE (contextlevel = ".CONTEXT_BLOCK."
7038 AND component = :component)
7039 $extra";
7040 $params['component'] = 'block_' . $bi->blockname;
7042 return $DB->get_records_sql($sql.' '.$sort, $params);
7046 * Is this context part of any course? If yes return course context.
7048 * @param bool $strict true means throw exception if not found, false means return false if not found
7049 * @return context_course context of the enclosing course, null if not found or exception
7051 public function get_course_context($strict = true) {
7052 $parentcontext = $this->get_parent_context();
7053 return $parentcontext->get_course_context($strict);
7057 * Returns block context instance.
7059 * @static
7060 * @param int $blockinstanceid id from {block_instances} table.
7061 * @param int $strictness
7062 * @return context_block context instance
7064 public static function instance($blockinstanceid, $strictness = MUST_EXIST) {
7065 global $DB;
7067 if ($context = context::cache_get(CONTEXT_BLOCK, $blockinstanceid)) {
7068 return $context;
7071 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $blockinstanceid))) {
7072 if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
7073 $parentcontext = context::instance_by_id($bi->parentcontextid);
7074 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7078 if ($record) {
7079 $context = new context_block($record);
7080 context::cache_add($context);
7081 return $context;
7084 return false;
7088 * Block do not have child contexts...
7089 * @return array
7091 public function get_child_contexts() {
7092 return array();
7096 * Create missing context instances at block context level
7097 * @static
7099 protected static function create_level_instances() {
7100 global $DB;
7102 $sql = "SELECT ".CONTEXT_BLOCK.", bi.id
7103 FROM {block_instances} bi
7104 WHERE NOT EXISTS (SELECT 'x'
7105 FROM {context} cx
7106 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7107 $contextdata = $DB->get_recordset_sql($sql);
7108 foreach ($contextdata as $context) {
7109 context::insert_context_record(CONTEXT_BLOCK, $context->id, null);
7111 $contextdata->close();
7115 * Returns sql necessary for purging of stale context instances.
7117 * @static
7118 * @return string cleanup SQL
7120 protected static function get_cleanup_sql() {
7121 $sql = "
7122 SELECT c.*
7123 FROM {context} c
7124 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7125 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7128 return $sql;
7132 * Rebuild context paths and depths at block context level.
7134 * @static
7135 * @param bool $force
7137 protected static function build_paths($force) {
7138 global $DB;
7140 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7141 if ($force) {
7142 $ctxemptyclause = '';
7143 } else {
7144 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7147 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7148 $sql = "INSERT INTO {context_temp} (id, path, depth)
7149 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7150 FROM {context} ctx
7151 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7152 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7153 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7154 $ctxemptyclause";
7155 $trans = $DB->start_delegated_transaction();
7156 $DB->delete_records('context_temp');
7157 $DB->execute($sql);
7158 context::merge_context_temp_table();
7159 $DB->delete_records('context_temp');
7160 $trans->allow_commit();
7166 // ============== DEPRECATED FUNCTIONS ==========================================
7167 // Old context related functions were deprecated in 2.0, it is recommended
7168 // to use context classes in new code. Old function can be used when
7169 // creating patches that are supposed to be backported to older stable branches.
7170 // These deprecated functions will not be removed in near future,
7171 // before removing devs will be warned with a debugging message first,
7172 // then we will add error message and only after that we can remove the functions
7173 // completely.
7176 * Runs get_records select on context table and returns the result
7177 * Does get_records_select on the context table, and returns the results ordered
7178 * by contextlevel, and then the natural sort order within each level.
7179 * for the purpose of $select, you need to know that the context table has been
7180 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7182 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7183 * @param array $params any parameters required by $select.
7184 * @return array the requested context records.
7186 function get_sorted_contexts($select, $params = array()) {
7188 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7190 global $DB;
7191 if ($select) {
7192 $select = 'WHERE ' . $select;
7194 return $DB->get_records_sql("
7195 SELECT ctx.*
7196 FROM {context} ctx
7197 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7198 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7199 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7200 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7201 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7202 $select
7203 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7204 ", $params);
7208 * Given context and array of users, returns array of users whose enrolment status is suspended,
7209 * or enrolment has expired or has not started. Also removes those users from the given array
7211 * @param context $context context in which suspended users should be extracted.
7212 * @param array $users list of users.
7213 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7214 * @return array list of suspended users.
7216 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7217 global $DB;
7219 // Get active enrolled users.
7220 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7221 $activeusers = $DB->get_records_sql($sql, $params);
7223 // Move suspended users to a separate array & remove from the initial one.
7224 $susers = array();
7225 if (sizeof($activeusers)) {
7226 foreach ($users as $userid => $user) {
7227 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7228 $susers[$userid] = $user;
7229 unset($users[$userid]);
7233 return $susers;
7237 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7238 * or enrolment has expired or not started.
7240 * @param context $context context in which user enrolment is checked.
7241 * @param bool $usecache Enable or disable (default) the request cache
7242 * @return array list of suspended user id's.
7244 function get_suspended_userids(context $context, $usecache = false) {
7245 global $DB;
7247 if ($usecache) {
7248 $cache = cache::make('core', 'suspended_userids');
7249 $susers = $cache->get($context->id);
7250 if ($susers !== false) {
7251 return $susers;
7255 $coursecontext = $context->get_course_context();
7256 $susers = array();
7258 // Front page users are always enrolled, so suspended list is empty.
7259 if ($coursecontext->instanceid != SITEID) {
7260 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7261 $susers = $DB->get_fieldset_sql($sql, $params);
7262 $susers = array_combine($susers, $susers);
7265 // Cache results for the remainder of this request.
7266 if ($usecache) {
7267 $cache->set($context->id, $susers);
7270 return $susers;
7274 * Gets sql for finding users with capability in the given context
7276 * @param context $context
7277 * @param string|array $capability Capability name or array of names.
7278 * If an array is provided then this is the equivalent of a logical 'OR',
7279 * i.e. the user needs to have one of these capabilities.
7280 * @return array($sql, $params)
7282 function get_with_capability_sql(context $context, $capability) {
7283 static $i = 0;
7284 $i++;
7285 $prefix = 'cu' . $i . '_';
7287 $capjoin = get_with_capability_join($context, $capability, $prefix . 'u.id');
7289 $sql = "SELECT DISTINCT {$prefix}u.id
7290 FROM {user} {$prefix}u
7291 $capjoin->joins
7292 WHERE {$prefix}u.deleted = 0 AND $capjoin->wheres";
7294 return array($sql, $capjoin->params);
7298 * Gets sql joins for finding users with capability in the given context
7300 * @param context $context Context for the join
7301 * @param string|array $capability Capability name or array of names.
7302 * If an array is provided then this is the equivalent of a logical 'OR',
7303 * i.e. the user needs to have one of these capabilities.
7304 * @param string $useridcolumn e.g. 'u.id'
7305 * @return \core\dml\sql_join Contains joins, wheres, params
7307 function get_with_capability_join(context $context, $capability, $useridcolumn) {
7308 global $DB, $CFG;
7310 // Use unique prefix just in case somebody makes some SQL magic with the result.
7311 static $i = 0;
7312 $i++;
7313 $prefix = 'eu' . $i . '_';
7315 // First find the course context.
7316 $coursecontext = $context->get_course_context();
7318 $isfrontpage = ($coursecontext->instanceid == SITEID);
7320 $joins = array();
7321 $wheres = array();
7322 $params = array();
7324 list($contextids, $contextpaths) = get_context_info_list($context);
7326 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
7328 list($incaps, $capsparams) = $DB->get_in_or_equal($capability, SQL_PARAMS_NAMED, 'cap');
7330 $defs = array();
7331 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
7332 FROM {role_capabilities} rc
7333 JOIN {context} ctx on rc.contextid = ctx.id
7334 WHERE rc.contextid $incontexts AND rc.capability $incaps";
7335 $rcs = $DB->get_records_sql($sql, array_merge($cparams, $capsparams));
7336 foreach ($rcs as $rc) {
7337 $defs[$rc->path][$rc->roleid] = $rc->permission;
7340 $access = array();
7341 if (!empty($defs)) {
7342 foreach ($contextpaths as $path) {
7343 if (empty($defs[$path])) {
7344 continue;
7346 foreach ($defs[$path] as $roleid => $perm) {
7347 if ($perm == CAP_PROHIBIT) {
7348 $access[$roleid] = CAP_PROHIBIT;
7349 continue;
7351 if (!isset($access[$roleid])) {
7352 $access[$roleid] = (int) $perm;
7358 unset($defs);
7360 // Make lists of roles that are needed and prohibited.
7361 $needed = array(); // One of these is enough.
7362 $prohibited = array(); // Must not have any of these.
7363 foreach ($access as $roleid => $perm) {
7364 if ($perm == CAP_PROHIBIT) {
7365 unset($needed[$roleid]);
7366 $prohibited[$roleid] = true;
7367 } else {
7368 if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
7369 $needed[$roleid] = true;
7374 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
7375 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
7377 $nobody = false;
7379 if ($isfrontpage) {
7380 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
7381 $nobody = true;
7382 } else {
7383 if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
7384 // Everybody not having prohibit has the capability.
7385 $needed = array();
7386 } else {
7387 if (empty($needed)) {
7388 $nobody = true;
7392 } else {
7393 if (!empty($prohibited[$defaultuserroleid])) {
7394 $nobody = true;
7395 } else {
7396 if (!empty($needed[$defaultuserroleid])) {
7397 // Everybody not having prohibit has the capability.
7398 $needed = array();
7399 } else {
7400 if (empty($needed)) {
7401 $nobody = true;
7407 if ($nobody) {
7408 // Nobody can match so return some SQL that does not return any results.
7409 $wheres[] = "1 = 2";
7411 } else {
7413 if ($needed) {
7414 $ctxids = implode(',', $contextids);
7415 $roleids = implode(',', array_keys($needed));
7416 $joins[] = "JOIN {role_assignments} {$prefix}ra3
7417 ON ({$prefix}ra3.userid = $useridcolumn
7418 AND {$prefix}ra3.roleid IN ($roleids)
7419 AND {$prefix}ra3.contextid IN ($ctxids))";
7422 if ($prohibited) {
7423 $ctxids = implode(',', $contextids);
7424 $roleids = implode(',', array_keys($prohibited));
7425 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4
7426 ON ({$prefix}ra4.userid = $useridcolumn
7427 AND {$prefix}ra4.roleid IN ($roleids)
7428 AND {$prefix}ra4.contextid IN ($ctxids))";
7429 $wheres[] = "{$prefix}ra4.id IS NULL";
7434 $wheres[] = "$useridcolumn <> :{$prefix}guestid";
7435 $params["{$prefix}guestid"] = $CFG->siteguest;
7437 $joins = implode("\n", $joins);
7438 $wheres = "(" . implode(" AND ", $wheres) . ")";
7440 return new \core\dml\sql_join($joins, $wheres, $params);