MDL-62781 question/privacy: fix tests with CodeRunner is installed
[moodle.git] / lib / accesslib.php
blob536504cf847fb63b44ff6be9cc7d29f5e0bad569
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
66 * <b>accessdata</b>
68 * Access control data is held in the "accessdata" array
69 * which - for the logged-in user, will be in $USER->access
71 * For other users can be generated and passed around (but may also be cached
72 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser).
74 * $accessdata is a multidimensional array, holding
75 * role assignments (RAs), role-capabilities-perm sets
76 * (role defs) and a list of courses we have loaded
77 * data for.
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->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
188 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
190 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
191 * accesslib's private caches. You need to do this before setting up test data,
192 * and also at the end of the tests.
194 * @access private
195 * @return void
197 function accesslib_clear_all_caches_for_unit_testing() {
198 global $USER;
199 if (!PHPUNIT_TEST) {
200 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
203 accesslib_clear_all_caches(true);
205 unset($USER->access);
209 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
211 * This reset does not touch global $USER.
213 * @access private
214 * @param bool $resetcontexts
215 * @return void
217 function accesslib_clear_all_caches($resetcontexts) {
218 global $ACCESSLIB_PRIVATE;
220 $ACCESSLIB_PRIVATE->dirtycontexts = null;
221 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
222 $ACCESSLIB_PRIVATE->cacheroledefs = array();
224 $cache = cache::make('core', 'roledefs');
225 $cache->purge();
227 if ($resetcontexts) {
228 context_helper::reset_caches();
233 * Clears accesslib's private cache of a specific role or roles. ONLY BE USED FROM THIS LIBRARY FILE!
235 * This reset does not touch global $USER.
237 * @access private
238 * @param int|array $roles
239 * @return void
241 function accesslib_clear_role_cache($roles) {
242 global $ACCESSLIB_PRIVATE;
244 if (!is_array($roles)) {
245 $roles = [$roles];
248 foreach ($roles as $role) {
249 if (isset($ACCESSLIB_PRIVATE->cacheroledefs[$role])) {
250 unset($ACCESSLIB_PRIVATE->cacheroledefs[$role]);
254 $cache = cache::make('core', 'roledefs');
255 $cache->delete_many($roles);
259 * Role is assigned at system context.
261 * @access private
262 * @param int $roleid
263 * @return array
265 function get_role_access($roleid) {
266 $accessdata = get_empty_accessdata();
267 $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
268 return $accessdata;
272 * Fetch raw "site wide" role definitions.
273 * Even MUC static acceleration cache appears a bit slow for this.
274 * Important as can be hit hundreds of times per page.
276 * @param array $roleids List of role ids to fetch definitions for.
277 * @return array Complete definition for each requested role.
279 function get_role_definitions(array $roleids) {
280 global $ACCESSLIB_PRIVATE;
282 if (empty($roleids)) {
283 return array();
286 // Grab all keys we have not yet got in our static cache.
287 if ($uncached = array_diff($roleids, array_keys($ACCESSLIB_PRIVATE->cacheroledefs))) {
288 $cache = cache::make('core', 'roledefs');
289 foreach ($cache->get_many($uncached) as $roleid => $cachedroledef) {
290 if (is_array($cachedroledef)) {
291 $ACCESSLIB_PRIVATE->cacheroledefs[$roleid] = $cachedroledef;
295 // Check we have the remaining keys from the MUC.
296 if ($uncached = array_diff($roleids, array_keys($ACCESSLIB_PRIVATE->cacheroledefs))) {
297 $uncached = get_role_definitions_uncached($uncached);
298 $ACCESSLIB_PRIVATE->cacheroledefs += $uncached;
299 $cache->set_many($uncached);
303 // Return just the roles we need.
304 return array_intersect_key($ACCESSLIB_PRIVATE->cacheroledefs, array_flip($roleids));
308 * Query raw "site wide" role definitions.
310 * @param array $roleids List of role ids to fetch definitions for.
311 * @return array Complete definition for each requested role.
313 function get_role_definitions_uncached(array $roleids) {
314 global $DB;
316 if (empty($roleids)) {
317 return array();
320 // Create a blank results array: even if a role has no capabilities,
321 // we need to ensure it is included in the results to show we have
322 // loaded all the capabilities that there are.
323 $rdefs = array();
324 foreach ($roleids as $roleid) {
325 $rdefs[$roleid] = array();
328 // Load all the capabilities for these roles in all contexts.
329 list($sql, $params) = $DB->get_in_or_equal($roleids);
330 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
331 FROM {role_capabilities} rc
332 JOIN {context} ctx ON rc.contextid = ctx.id
333 WHERE rc.roleid $sql";
334 $rs = $DB->get_recordset_sql($sql, $params);
336 // Store the capabilities into the expected data structure.
337 foreach ($rs as $rd) {
338 if (!isset($rdefs[$rd->roleid][$rd->path])) {
339 $rdefs[$rd->roleid][$rd->path] = array();
341 $rdefs[$rd->roleid][$rd->path][$rd->capability] = (int) $rd->permission;
344 $rs->close();
346 // Sometimes (e.g. get_user_capability_course_helper::get_capability_info_at_each_context)
347 // we process role definitinons in a way that requires we see parent contexts
348 // before child contexts. This sort ensures that works (and is faster than
349 // sorting in the SQL query).
350 foreach ($rdefs as $roleid => $rdef) {
351 ksort($rdefs[$roleid]);
354 return $rdefs;
358 * Get the default guest role, this is used for guest account,
359 * search engine spiders, etc.
361 * @return stdClass role record
363 function get_guest_role() {
364 global $CFG, $DB;
366 if (empty($CFG->guestroleid)) {
367 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
368 $guestrole = array_shift($roles); // Pick the first one
369 set_config('guestroleid', $guestrole->id);
370 return $guestrole;
371 } else {
372 debugging('Can not find any guest role!');
373 return false;
375 } else {
376 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
377 return $guestrole;
378 } else {
379 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
380 set_config('guestroleid', '');
381 return get_guest_role();
387 * Check whether a user has a particular capability in a given context.
389 * For example:
390 * $context = context_module::instance($cm->id);
391 * has_capability('mod/forum:replypost', $context)
393 * By default checks the capabilities of the current user, but you can pass a
394 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
396 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
397 * or capabilities with XSS, config or data loss risks.
399 * @category access
401 * @param string $capability the name of the capability to check. For example mod/forum:view
402 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
403 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
404 * @param boolean $doanything If false, ignores effect of admin role assignment
405 * @return boolean true if the user has this capability. Otherwise false.
407 function has_capability($capability, context $context, $user = null, $doanything = true) {
408 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
410 if (during_initial_install()) {
411 if ($SCRIPT === "/$CFG->admin/index.php"
412 or $SCRIPT === "/$CFG->admin/cli/install.php"
413 or $SCRIPT === "/$CFG->admin/cli/install_database.php"
414 or (defined('BEHAT_UTIL') and BEHAT_UTIL)
415 or (defined('PHPUNIT_UTIL') and PHPUNIT_UTIL)) {
416 // we are in an installer - roles can not work yet
417 return true;
418 } else {
419 return false;
423 if (strpos($capability, 'moodle/legacy:') === 0) {
424 throw new coding_exception('Legacy capabilities can not be used any more!');
427 if (!is_bool($doanything)) {
428 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
431 // capability must exist
432 if (!$capinfo = get_capability_info($capability)) {
433 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
434 return false;
437 if (!isset($USER->id)) {
438 // should never happen
439 $USER->id = 0;
440 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER);
443 // make sure there is a real user specified
444 if ($user === null) {
445 $userid = $USER->id;
446 } else {
447 $userid = is_object($user) ? $user->id : $user;
450 // make sure forcelogin cuts off not-logged-in users if enabled
451 if (!empty($CFG->forcelogin) and $userid == 0) {
452 return false;
455 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
456 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
457 if (isguestuser($userid) or $userid == 0) {
458 return false;
462 // somehow make sure the user is not deleted and actually exists
463 if ($userid != 0) {
464 if ($userid == $USER->id and isset($USER->deleted)) {
465 // this prevents one query per page, it is a bit of cheating,
466 // but hopefully session is terminated properly once user is deleted
467 if ($USER->deleted) {
468 return false;
470 } else {
471 if (!context_user::instance($userid, IGNORE_MISSING)) {
472 // no user context == invalid userid
473 return false;
478 // context path/depth must be valid
479 if (empty($context->path) or $context->depth == 0) {
480 // this should not happen often, each upgrade tries to rebuild the context paths
481 debugging('Context id '.$context->id.' does not have valid path, please use context_helper::build_all_paths()');
482 if (is_siteadmin($userid)) {
483 return true;
484 } else {
485 return false;
489 // Find out if user is admin - it is not possible to override the doanything in any way
490 // and it is not possible to switch to admin role either.
491 if ($doanything) {
492 if (is_siteadmin($userid)) {
493 if ($userid != $USER->id) {
494 return true;
496 // make sure switchrole is not used in this context
497 if (empty($USER->access['rsw'])) {
498 return true;
500 $parts = explode('/', trim($context->path, '/'));
501 $path = '';
502 $switched = false;
503 foreach ($parts as $part) {
504 $path .= '/' . $part;
505 if (!empty($USER->access['rsw'][$path])) {
506 $switched = true;
507 break;
510 if (!$switched) {
511 return true;
513 //ok, admin switched role in this context, let's use normal access control rules
517 // Careful check for staleness...
518 $context->reload_if_dirty();
520 if ($USER->id == $userid) {
521 if (!isset($USER->access)) {
522 load_all_capabilities();
524 $access =& $USER->access;
526 } else {
527 // make sure user accessdata is really loaded
528 get_user_accessdata($userid, true);
529 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
532 return has_capability_in_accessdata($capability, $context, $access);
536 * Check if the user has any one of several capabilities from a list.
538 * This is just a utility method that calls has_capability in a loop. Try to put
539 * the capabilities that most users are likely to have first in the list for best
540 * performance.
542 * @category access
543 * @see has_capability()
545 * @param array $capabilities an array of capability names.
546 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
547 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
548 * @param boolean $doanything If false, ignore effect of admin role assignment
549 * @return boolean true if the user has any of these capabilities. Otherwise false.
551 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
552 foreach ($capabilities as $capability) {
553 if (has_capability($capability, $context, $user, $doanything)) {
554 return true;
557 return false;
561 * Check if the user has all the capabilities in a list.
563 * This is just a utility method that calls has_capability in a loop. Try to put
564 * the capabilities that fewest users are likely to have first in the list for best
565 * performance.
567 * @category access
568 * @see has_capability()
570 * @param array $capabilities an array of capability names.
571 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
572 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
573 * @param boolean $doanything If false, ignore effect of admin role assignment
574 * @return boolean true if the user has all of these capabilities. Otherwise false.
576 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
577 foreach ($capabilities as $capability) {
578 if (!has_capability($capability, $context, $user, $doanything)) {
579 return false;
582 return true;
586 * Is course creator going to have capability in a new course?
588 * This is intended to be used in enrolment plugins before or during course creation,
589 * do not use after the course is fully created.
591 * @category access
593 * @param string $capability the name of the capability to check.
594 * @param context $context course or category context where is course going to be created
595 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
596 * @return boolean true if the user will have this capability.
598 * @throws coding_exception if different type of context submitted
600 function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) {
601 global $CFG;
603 if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) {
604 throw new coding_exception('Only course or course category context expected');
607 if (has_capability($capability, $context, $user)) {
608 // User already has the capability, it could be only removed if CAP_PROHIBIT
609 // was involved here, but we ignore that.
610 return true;
613 if (!has_capability('moodle/course:create', $context, $user)) {
614 return false;
617 if (!enrol_is_enabled('manual')) {
618 return false;
621 if (empty($CFG->creatornewroleid)) {
622 return false;
625 if ($context->contextlevel == CONTEXT_COURSE) {
626 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
627 return false;
629 } else {
630 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
631 return false;
635 // Most likely they will be enrolled after the course creation is finished,
636 // does the new role have the required capability?
637 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
638 return isset($neededroles[$CFG->creatornewroleid]);
642 * Check if the user is an admin at the site level.
644 * Please note that use of proper capabilities is always encouraged,
645 * this function is supposed to be used from core or for temporary hacks.
647 * @category access
649 * @param int|stdClass $user_or_id user id or user object
650 * @return bool true if user is one of the administrators, false otherwise
652 function is_siteadmin($user_or_id = null) {
653 global $CFG, $USER;
655 if ($user_or_id === null) {
656 $user_or_id = $USER;
659 if (empty($user_or_id)) {
660 return false;
662 if (!empty($user_or_id->id)) {
663 $userid = $user_or_id->id;
664 } else {
665 $userid = $user_or_id;
668 // Because this script is called many times (150+ for course page) with
669 // the same parameters, it is worth doing minor optimisations. This static
670 // cache stores the value for a single userid, saving about 2ms from course
671 // page load time without using significant memory. As the static cache
672 // also includes the value it depends on, this cannot break unit tests.
673 static $knownid, $knownresult, $knownsiteadmins;
674 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
675 return $knownresult;
677 $knownid = $userid;
678 $knownsiteadmins = $CFG->siteadmins;
680 $siteadmins = explode(',', $CFG->siteadmins);
681 $knownresult = in_array($userid, $siteadmins);
682 return $knownresult;
686 * Returns true if user has at least one role assign
687 * of 'coursecontact' role (is potentially listed in some course descriptions).
689 * @param int $userid
690 * @return bool
692 function has_coursecontact_role($userid) {
693 global $DB, $CFG;
695 if (empty($CFG->coursecontact)) {
696 return false;
698 $sql = "SELECT 1
699 FROM {role_assignments}
700 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
701 return $DB->record_exists_sql($sql, array('userid'=>$userid));
705 * Does the user have a capability to do something?
707 * Walk the accessdata array and return true/false.
708 * Deals with prohibits, role switching, aggregating
709 * capabilities, etc.
711 * The main feature of here is being FAST and with no
712 * side effects.
714 * Notes:
716 * Switch Role merges with default role
717 * ------------------------------------
718 * If you are a teacher in course X, you have at least
719 * teacher-in-X + defaultloggedinuser-sitewide. So in the
720 * course you'll have techer+defaultloggedinuser.
721 * We try to mimic that in switchrole.
723 * Permission evaluation
724 * ---------------------
725 * Originally there was an extremely complicated way
726 * to determine the user access that dealt with
727 * "locality" or role assignments and role overrides.
728 * Now we simply evaluate access for each role separately
729 * and then verify if user has at least one role with allow
730 * and at the same time no role with prohibit.
732 * @access private
733 * @param string $capability
734 * @param context $context
735 * @param array $accessdata
736 * @return bool
738 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
739 global $CFG;
741 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
742 $path = $context->path;
743 $paths = array($path);
744 while($path = rtrim($path, '0123456789')) {
745 $path = rtrim($path, '/');
746 if ($path === '') {
747 break;
749 $paths[] = $path;
752 $roles = array();
753 $switchedrole = false;
755 // Find out if role switched
756 if (!empty($accessdata['rsw'])) {
757 // From the bottom up...
758 foreach ($paths as $path) {
759 if (isset($accessdata['rsw'][$path])) {
760 // Found a switchrole assignment - check for that role _plus_ the default user role
761 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
762 $switchedrole = true;
763 break;
768 if (!$switchedrole) {
769 // get all users roles in this context and above
770 foreach ($paths as $path) {
771 if (isset($accessdata['ra'][$path])) {
772 foreach ($accessdata['ra'][$path] as $roleid) {
773 $roles[$roleid] = null;
779 // Now find out what access is given to each role, going bottom-->up direction
780 $rdefs = get_role_definitions(array_keys($roles));
781 $allowed = false;
783 foreach ($roles as $roleid => $ignored) {
784 foreach ($paths as $path) {
785 if (isset($rdefs[$roleid][$path][$capability])) {
786 $perm = (int)$rdefs[$roleid][$path][$capability];
787 if ($perm === CAP_PROHIBIT) {
788 // any CAP_PROHIBIT found means no permission for the user
789 return false;
791 if (is_null($roles[$roleid])) {
792 $roles[$roleid] = $perm;
796 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
797 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
800 return $allowed;
804 * A convenience function that tests has_capability, and displays an error if
805 * the user does not have that capability.
807 * NOTE before Moodle 2.0, this function attempted to make an appropriate
808 * require_login call before checking the capability. This is no longer the case.
809 * You must call require_login (or one of its variants) if you want to check the
810 * user is logged in, before you call this function.
812 * @see has_capability()
814 * @param string $capability the name of the capability to check. For example mod/forum:view
815 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
816 * @param int $userid A user id. By default (null) checks the permissions of the current user.
817 * @param bool $doanything If false, ignore effect of admin role assignment
818 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
819 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
820 * @return void terminates with an error if the user does not have the given capability.
822 function require_capability($capability, context $context, $userid = null, $doanything = true,
823 $errormessage = 'nopermissions', $stringfile = '') {
824 if (!has_capability($capability, $context, $userid, $doanything)) {
825 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
830 * Return a nested array showing all role assignments for the user.
831 * [ra] => [contextpath][roleid] = roleid
833 * @access private
834 * @param int $userid - the id of the user
835 * @return array access info array
837 function get_user_roles_sitewide_accessdata($userid) {
838 global $CFG, $DB;
840 $accessdata = get_empty_accessdata();
842 // start with the default role
843 if (!empty($CFG->defaultuserroleid)) {
844 $syscontext = context_system::instance();
845 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
848 // load the "default frontpage role"
849 if (!empty($CFG->defaultfrontpageroleid)) {
850 $frontpagecontext = context_course::instance(get_site()->id);
851 if ($frontpagecontext->path) {
852 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
856 // Preload every assigned role.
857 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
858 FROM {role_assignments} ra
859 JOIN {context} ctx ON ctx.id = ra.contextid
860 WHERE ra.userid = :userid";
862 $rs = $DB->get_recordset_sql($sql, array('userid' => $userid));
864 foreach ($rs as $ra) {
865 // RAs leafs are arrays to support multi-role assignments...
866 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
869 $rs->close();
871 return $accessdata;
875 * Returns empty accessdata structure.
877 * @access private
878 * @return array empt accessdata
880 function get_empty_accessdata() {
881 $accessdata = array(); // named list
882 $accessdata['ra'] = array();
883 $accessdata['time'] = time();
884 $accessdata['rsw'] = array();
886 return $accessdata;
890 * Get accessdata for a given user.
892 * @access private
893 * @param int $userid
894 * @param bool $preloadonly true means do not return access array
895 * @return array accessdata
897 function get_user_accessdata($userid, $preloadonly=false) {
898 global $CFG, $ACCESSLIB_PRIVATE, $USER;
900 if (isset($USER->access)) {
901 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->access;
904 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
905 if (empty($userid)) {
906 if (!empty($CFG->notloggedinroleid)) {
907 $accessdata = get_role_access($CFG->notloggedinroleid);
908 } else {
909 // weird
910 return get_empty_accessdata();
913 } else if (isguestuser($userid)) {
914 if ($guestrole = get_guest_role()) {
915 $accessdata = get_role_access($guestrole->id);
916 } else {
917 //weird
918 return get_empty_accessdata();
921 } else {
922 // Includes default role and frontpage role.
923 $accessdata = get_user_roles_sitewide_accessdata($userid);
926 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
929 if ($preloadonly) {
930 return;
931 } else {
932 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
937 * A convenience function to completely load all the capabilities
938 * for the current user. It is called from has_capability() and functions change permissions.
940 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
941 * @see check_enrolment_plugins()
943 * @access private
944 * @return void
946 function load_all_capabilities() {
947 global $USER;
949 // roles not installed yet - we are in the middle of installation
950 if (during_initial_install()) {
951 return;
954 if (!isset($USER->id)) {
955 // this should not happen
956 $USER->id = 0;
959 unset($USER->access);
960 $USER->access = get_user_accessdata($USER->id);
962 // Clear to force a refresh
963 unset($USER->mycourses);
965 // init/reset internal enrol caches - active course enrolments and temp access
966 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
970 * A convenience function to completely reload all the capabilities
971 * for the current user when roles have been updated in a relevant
972 * context -- but PRESERVING switchroles and loginas.
973 * This function resets all accesslib and context caches.
975 * That is - completely transparent to the user.
977 * Note: reloads $USER->access completely.
979 * @access private
980 * @return void
982 function reload_all_capabilities() {
983 global $USER, $DB, $ACCESSLIB_PRIVATE;
985 // copy switchroles
986 $sw = array();
987 if (!empty($USER->access['rsw'])) {
988 $sw = $USER->access['rsw'];
991 accesslib_clear_all_caches(true);
992 unset($USER->access);
993 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
995 load_all_capabilities();
997 foreach ($sw as $path => $roleid) {
998 if ($record = $DB->get_record('context', array('path'=>$path))) {
999 $context = context::instance_by_id($record->id);
1000 role_switch($roleid, $context);
1006 * Adds a temp role to current USER->access array.
1008 * Useful for the "temporary guest" access we grant to logged-in users.
1009 * This is useful for enrol plugins only.
1011 * @since Moodle 2.2
1012 * @param context_course $coursecontext
1013 * @param int $roleid
1014 * @return void
1016 function load_temp_course_role(context_course $coursecontext, $roleid) {
1017 global $USER, $SITE;
1019 if (empty($roleid)) {
1020 debugging('invalid role specified in load_temp_course_role()');
1021 return;
1024 if ($coursecontext->instanceid == $SITE->id) {
1025 debugging('Can not use temp roles on the frontpage');
1026 return;
1029 if (!isset($USER->access)) {
1030 load_all_capabilities();
1033 $coursecontext->reload_if_dirty();
1035 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1036 return;
1039 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1043 * Removes any extra guest roles from current USER->access array.
1044 * This is useful for enrol plugins only.
1046 * @since Moodle 2.2
1047 * @param context_course $coursecontext
1048 * @return void
1050 function remove_temp_course_roles(context_course $coursecontext) {
1051 global $DB, $USER, $SITE;
1053 if ($coursecontext->instanceid == $SITE->id) {
1054 debugging('Can not use temp roles on the frontpage');
1055 return;
1058 if (empty($USER->access['ra'][$coursecontext->path])) {
1059 //no roles here, weird
1060 return;
1063 $sql = "SELECT DISTINCT ra.roleid AS id
1064 FROM {role_assignments} ra
1065 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1066 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1068 $USER->access['ra'][$coursecontext->path] = array();
1069 foreach($ras as $r) {
1070 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1075 * Returns array of all role archetypes.
1077 * @return array
1079 function get_role_archetypes() {
1080 return array(
1081 'manager' => 'manager',
1082 'coursecreator' => 'coursecreator',
1083 'editingteacher' => 'editingteacher',
1084 'teacher' => 'teacher',
1085 'student' => 'student',
1086 'guest' => 'guest',
1087 'user' => 'user',
1088 'frontpage' => 'frontpage'
1093 * Assign the defaults found in this capability definition to roles that have
1094 * the corresponding legacy capabilities assigned to them.
1096 * @param string $capability
1097 * @param array $legacyperms an array in the format (example):
1098 * 'guest' => CAP_PREVENT,
1099 * 'student' => CAP_ALLOW,
1100 * 'teacher' => CAP_ALLOW,
1101 * 'editingteacher' => CAP_ALLOW,
1102 * 'coursecreator' => CAP_ALLOW,
1103 * 'manager' => CAP_ALLOW
1104 * @return boolean success or failure.
1106 function assign_legacy_capabilities($capability, $legacyperms) {
1108 $archetypes = get_role_archetypes();
1110 foreach ($legacyperms as $type => $perm) {
1112 $systemcontext = context_system::instance();
1113 if ($type === 'admin') {
1114 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1115 $type = 'manager';
1118 if (!array_key_exists($type, $archetypes)) {
1119 print_error('invalidlegacy', '', '', $type);
1122 if ($roles = get_archetype_roles($type)) {
1123 foreach ($roles as $role) {
1124 // Assign a site level capability.
1125 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1126 return false;
1131 return true;
1135 * Verify capability risks.
1137 * @param stdClass $capability a capability - a row from the capabilities table.
1138 * @return boolean whether this capability is safe - that is, whether people with the
1139 * safeoverrides capability should be allowed to change it.
1141 function is_safe_capability($capability) {
1142 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1146 * Get the local override (if any) for a given capability in a role in a context
1148 * @param int $roleid
1149 * @param int $contextid
1150 * @param string $capability
1151 * @return stdClass local capability override
1153 function get_local_override($roleid, $contextid, $capability) {
1154 global $DB;
1155 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1159 * Returns context instance plus related course and cm instances
1161 * @param int $contextid
1162 * @return array of ($context, $course, $cm)
1164 function get_context_info_array($contextid) {
1165 global $DB;
1167 $context = context::instance_by_id($contextid, MUST_EXIST);
1168 $course = null;
1169 $cm = null;
1171 if ($context->contextlevel == CONTEXT_COURSE) {
1172 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1174 } else if ($context->contextlevel == CONTEXT_MODULE) {
1175 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1176 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1178 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1179 $parent = $context->get_parent_context();
1181 if ($parent->contextlevel == CONTEXT_COURSE) {
1182 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1183 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1184 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1185 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1189 return array($context, $course, $cm);
1193 * Function that creates a role
1195 * @param string $name role name
1196 * @param string $shortname role short name
1197 * @param string $description role description
1198 * @param string $archetype
1199 * @return int id or dml_exception
1201 function create_role($name, $shortname, $description, $archetype = '') {
1202 global $DB;
1204 if (strpos($archetype, 'moodle/legacy:') !== false) {
1205 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1208 // verify role archetype actually exists
1209 $archetypes = get_role_archetypes();
1210 if (empty($archetypes[$archetype])) {
1211 $archetype = '';
1214 // Insert the role record.
1215 $role = new stdClass();
1216 $role->name = $name;
1217 $role->shortname = $shortname;
1218 $role->description = $description;
1219 $role->archetype = $archetype;
1221 //find free sortorder number
1222 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1223 if (empty($role->sortorder)) {
1224 $role->sortorder = 1;
1226 $id = $DB->insert_record('role', $role);
1228 return $id;
1232 * Function that deletes a role and cleanups up after it
1234 * @param int $roleid id of role to delete
1235 * @return bool always true
1237 function delete_role($roleid) {
1238 global $DB;
1240 // first unssign all users
1241 role_unassign_all(array('roleid'=>$roleid));
1243 // cleanup all references to this role, ignore errors
1244 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1245 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1246 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1247 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1248 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1249 $DB->delete_records('role_names', array('roleid'=>$roleid));
1250 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1252 // Get role record before it's deleted.
1253 $role = $DB->get_record('role', array('id'=>$roleid));
1255 // Finally delete the role itself.
1256 $DB->delete_records('role', array('id'=>$roleid));
1258 // Trigger event.
1259 $event = \core\event\role_deleted::create(
1260 array(
1261 'context' => context_system::instance(),
1262 'objectid' => $roleid,
1263 'other' =>
1264 array(
1265 'shortname' => $role->shortname,
1266 'description' => $role->description,
1267 'archetype' => $role->archetype
1271 $event->add_record_snapshot('role', $role);
1272 $event->trigger();
1274 // Reset any cache of this role, including MUC.
1275 accesslib_clear_role_cache($roleid);
1277 return true;
1281 * Function to write context specific overrides, or default capabilities.
1283 * NOTE: use $context->mark_dirty() after this
1285 * @param string $capability string name
1286 * @param int $permission CAP_ constants
1287 * @param int $roleid role id
1288 * @param int|context $contextid context id
1289 * @param bool $overwrite
1290 * @return bool always true or exception
1292 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1293 global $USER, $DB;
1295 if ($contextid instanceof context) {
1296 $context = $contextid;
1297 } else {
1298 $context = context::instance_by_id($contextid);
1301 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1302 unassign_capability($capability, $roleid, $context->id);
1303 return true;
1306 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1308 if ($existing and !$overwrite) { // We want to keep whatever is there already
1309 return true;
1312 $cap = new stdClass();
1313 $cap->contextid = $context->id;
1314 $cap->roleid = $roleid;
1315 $cap->capability = $capability;
1316 $cap->permission = $permission;
1317 $cap->timemodified = time();
1318 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1320 if ($existing) {
1321 $cap->id = $existing->id;
1322 $DB->update_record('role_capabilities', $cap);
1323 } else {
1324 if ($DB->record_exists('context', array('id'=>$context->id))) {
1325 $DB->insert_record('role_capabilities', $cap);
1329 // Reset any cache of this role, including MUC.
1330 accesslib_clear_role_cache($roleid);
1332 return true;
1336 * Unassign a capability from a role.
1338 * NOTE: use $context->mark_dirty() after this
1340 * @param string $capability the name of the capability
1341 * @param int $roleid the role id
1342 * @param int|context $contextid null means all contexts
1343 * @return boolean true or exception
1345 function unassign_capability($capability, $roleid, $contextid = null) {
1346 global $DB;
1348 if (!empty($contextid)) {
1349 if ($contextid instanceof context) {
1350 $context = $contextid;
1351 } else {
1352 $context = context::instance_by_id($contextid);
1354 // delete from context rel, if this is the last override in this context
1355 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1356 } else {
1357 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1360 // Reset any cache of this role, including MUC.
1361 accesslib_clear_role_cache($roleid);
1363 return true;
1367 * Get the roles that have a given capability assigned to it
1369 * This function does not resolve the actual permission of the capability.
1370 * It just checks for permissions and overrides.
1371 * Use get_roles_with_cap_in_context() if resolution is required.
1373 * @param string $capability capability name (string)
1374 * @param string $permission optional, the permission defined for this capability
1375 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1376 * @param stdClass $context null means any
1377 * @return array of role records
1379 function get_roles_with_capability($capability, $permission = null, $context = null) {
1380 global $DB;
1382 if ($context) {
1383 $contexts = $context->get_parent_context_ids(true);
1384 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1385 $contextsql = "AND rc.contextid $insql";
1386 } else {
1387 $params = array();
1388 $contextsql = '';
1391 if ($permission) {
1392 $permissionsql = " AND rc.permission = :permission";
1393 $params['permission'] = $permission;
1394 } else {
1395 $permissionsql = '';
1398 $sql = "SELECT r.*
1399 FROM {role} r
1400 WHERE r.id IN (SELECT rc.roleid
1401 FROM {role_capabilities} rc
1402 WHERE rc.capability = :capname
1403 $contextsql
1404 $permissionsql)";
1405 $params['capname'] = $capability;
1408 return $DB->get_records_sql($sql, $params);
1412 * This function makes a role-assignment (a role for a user in a particular context)
1414 * @param int $roleid the role of the id
1415 * @param int $userid userid
1416 * @param int|context $contextid id of the context
1417 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1418 * @param int $itemid id of enrolment/auth plugin
1419 * @param string $timemodified defaults to current time
1420 * @return int new/existing id of the assignment
1422 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1423 global $USER, $DB, $CFG;
1425 // first of all detect if somebody is using old style parameters
1426 if ($contextid === 0 or is_numeric($component)) {
1427 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1430 // now validate all parameters
1431 if (empty($roleid)) {
1432 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1435 if (empty($userid)) {
1436 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1439 if ($itemid) {
1440 if (strpos($component, '_') === false) {
1441 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1443 } else {
1444 $itemid = 0;
1445 if ($component !== '' and strpos($component, '_') === false) {
1446 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1450 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1451 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1454 if ($contextid instanceof context) {
1455 $context = $contextid;
1456 } else {
1457 $context = context::instance_by_id($contextid, MUST_EXIST);
1460 if (!$timemodified) {
1461 $timemodified = time();
1464 // Check for existing entry
1465 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1467 if ($ras) {
1468 // role already assigned - this should not happen
1469 if (count($ras) > 1) {
1470 // very weird - remove all duplicates!
1471 $ra = array_shift($ras);
1472 foreach ($ras as $r) {
1473 $DB->delete_records('role_assignments', array('id'=>$r->id));
1475 } else {
1476 $ra = reset($ras);
1479 // actually there is no need to update, reset anything or trigger any event, so just return
1480 return $ra->id;
1483 // Create a new entry
1484 $ra = new stdClass();
1485 $ra->roleid = $roleid;
1486 $ra->contextid = $context->id;
1487 $ra->userid = $userid;
1488 $ra->component = $component;
1489 $ra->itemid = $itemid;
1490 $ra->timemodified = $timemodified;
1491 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1492 $ra->sortorder = 0;
1494 $ra->id = $DB->insert_record('role_assignments', $ra);
1496 // mark context as dirty - again expensive, but needed
1497 $context->mark_dirty();
1499 if (!empty($USER->id) && $USER->id == $userid) {
1500 // If the user is the current user, then do full reload of capabilities too.
1501 reload_all_capabilities();
1504 require_once($CFG->libdir . '/coursecatlib.php');
1505 coursecat::role_assignment_changed($roleid, $context);
1507 $event = \core\event\role_assigned::create(array(
1508 'context' => $context,
1509 'objectid' => $ra->roleid,
1510 'relateduserid' => $ra->userid,
1511 'other' => array(
1512 'id' => $ra->id,
1513 'component' => $ra->component,
1514 'itemid' => $ra->itemid
1517 $event->add_record_snapshot('role_assignments', $ra);
1518 $event->trigger();
1520 return $ra->id;
1524 * Removes one role assignment
1526 * @param int $roleid
1527 * @param int $userid
1528 * @param int $contextid
1529 * @param string $component
1530 * @param int $itemid
1531 * @return void
1533 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1534 // first make sure the params make sense
1535 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1536 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1539 if ($itemid) {
1540 if (strpos($component, '_') === false) {
1541 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1543 } else {
1544 $itemid = 0;
1545 if ($component !== '' and strpos($component, '_') === false) {
1546 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1550 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1554 * Removes multiple role assignments, parameters may contain:
1555 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1557 * @param array $params role assignment parameters
1558 * @param bool $subcontexts unassign in subcontexts too
1559 * @param bool $includemanual include manual role assignments too
1560 * @return void
1562 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1563 global $USER, $CFG, $DB;
1564 require_once($CFG->libdir . '/coursecatlib.php');
1566 if (!$params) {
1567 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1570 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1571 foreach ($params as $key=>$value) {
1572 if (!in_array($key, $allowed)) {
1573 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1577 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1578 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1581 if ($includemanual) {
1582 if (!isset($params['component']) or $params['component'] === '') {
1583 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1587 if ($subcontexts) {
1588 if (empty($params['contextid'])) {
1589 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1593 $ras = $DB->get_records('role_assignments', $params);
1594 foreach($ras as $ra) {
1595 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1596 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1597 // this is a bit expensive but necessary
1598 $context->mark_dirty();
1599 // If the user is the current user, then do full reload of capabilities too.
1600 if (!empty($USER->id) && $USER->id == $ra->userid) {
1601 reload_all_capabilities();
1603 $event = \core\event\role_unassigned::create(array(
1604 'context' => $context,
1605 'objectid' => $ra->roleid,
1606 'relateduserid' => $ra->userid,
1607 'other' => array(
1608 'id' => $ra->id,
1609 'component' => $ra->component,
1610 'itemid' => $ra->itemid
1613 $event->add_record_snapshot('role_assignments', $ra);
1614 $event->trigger();
1615 coursecat::role_assignment_changed($ra->roleid, $context);
1618 unset($ras);
1620 // process subcontexts
1621 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1622 if ($params['contextid'] instanceof context) {
1623 $context = $params['contextid'];
1624 } else {
1625 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1628 if ($context) {
1629 $contexts = $context->get_child_contexts();
1630 $mparams = $params;
1631 foreach($contexts as $context) {
1632 $mparams['contextid'] = $context->id;
1633 $ras = $DB->get_records('role_assignments', $mparams);
1634 foreach($ras as $ra) {
1635 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1636 // this is a bit expensive but necessary
1637 $context->mark_dirty();
1638 // If the user is the current user, then do full reload of capabilities too.
1639 if (!empty($USER->id) && $USER->id == $ra->userid) {
1640 reload_all_capabilities();
1642 $event = \core\event\role_unassigned::create(
1643 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1644 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1645 $event->add_record_snapshot('role_assignments', $ra);
1646 $event->trigger();
1647 coursecat::role_assignment_changed($ra->roleid, $context);
1653 // do this once more for all manual role assignments
1654 if ($includemanual) {
1655 $params['component'] = '';
1656 role_unassign_all($params, $subcontexts, false);
1661 * Determines if a user is currently logged in
1663 * @category access
1665 * @return bool
1667 function isloggedin() {
1668 global $USER;
1670 return (!empty($USER->id));
1674 * Determines if a user is logged in as real guest user with username 'guest'.
1676 * @category access
1678 * @param int|object $user mixed user object or id, $USER if not specified
1679 * @return bool true if user is the real guest user, false if not logged in or other user
1681 function isguestuser($user = null) {
1682 global $USER, $DB, $CFG;
1684 // make sure we have the user id cached in config table, because we are going to use it a lot
1685 if (empty($CFG->siteguest)) {
1686 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1687 // guest does not exist yet, weird
1688 return false;
1690 set_config('siteguest', $guestid);
1692 if ($user === null) {
1693 $user = $USER;
1696 if ($user === null) {
1697 // happens when setting the $USER
1698 return false;
1700 } else if (is_numeric($user)) {
1701 return ($CFG->siteguest == $user);
1703 } else if (is_object($user)) {
1704 if (empty($user->id)) {
1705 return false; // not logged in means is not be guest
1706 } else {
1707 return ($CFG->siteguest == $user->id);
1710 } else {
1711 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1716 * Does user have a (temporary or real) guest access to course?
1718 * @category access
1720 * @param context $context
1721 * @param stdClass|int $user
1722 * @return bool
1724 function is_guest(context $context, $user = null) {
1725 global $USER;
1727 // first find the course context
1728 $coursecontext = $context->get_course_context();
1730 // make sure there is a real user specified
1731 if ($user === null) {
1732 $userid = isset($USER->id) ? $USER->id : 0;
1733 } else {
1734 $userid = is_object($user) ? $user->id : $user;
1737 if (isguestuser($userid)) {
1738 // can not inspect or be enrolled
1739 return true;
1742 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1743 // viewing users appear out of nowhere, they are neither guests nor participants
1744 return false;
1747 // consider only real active enrolments here
1748 if (is_enrolled($coursecontext, $user, '', true)) {
1749 return false;
1752 return true;
1756 * Returns true if the user has moodle/course:view capability in the course,
1757 * this is intended for admins, managers (aka small admins), inspectors, etc.
1759 * @category access
1761 * @param context $context
1762 * @param int|stdClass $user if null $USER is used
1763 * @param string $withcapability extra capability name
1764 * @return bool
1766 function is_viewing(context $context, $user = null, $withcapability = '') {
1767 // first find the course context
1768 $coursecontext = $context->get_course_context();
1770 if (isguestuser($user)) {
1771 // can not inspect
1772 return false;
1775 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1776 // admins are allowed to inspect courses
1777 return false;
1780 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1781 // site admins always have the capability, but the enrolment above blocks
1782 return false;
1785 return true;
1789 * Returns true if the user is able to access the course.
1791 * This function is in no way, shape, or form a substitute for require_login.
1792 * It should only be used in circumstances where it is not possible to call require_login
1793 * such as the navigation.
1795 * This function checks many of the methods of access to a course such as the view
1796 * capability, enrollments, and guest access. It also makes use of the cache
1797 * generated by require_login for guest access.
1799 * The flags within the $USER object that are used here should NEVER be used outside
1800 * of this function can_access_course and require_login. Doing so WILL break future
1801 * versions.
1803 * @param stdClass $course record
1804 * @param stdClass|int|null $user user record or id, current user if null
1805 * @param string $withcapability Check for this capability as well.
1806 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1807 * @return boolean Returns true if the user is able to access the course
1809 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
1810 global $DB, $USER;
1812 // this function originally accepted $coursecontext parameter
1813 if ($course instanceof context) {
1814 if ($course instanceof context_course) {
1815 debugging('deprecated context parameter, please use $course record');
1816 $coursecontext = $course;
1817 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
1818 } else {
1819 debugging('Invalid context parameter, please use $course record');
1820 return false;
1822 } else {
1823 $coursecontext = context_course::instance($course->id);
1826 if (!isset($USER->id)) {
1827 // should never happen
1828 $USER->id = 0;
1829 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
1832 // make sure there is a user specified
1833 if ($user === null) {
1834 $userid = $USER->id;
1835 } else {
1836 $userid = is_object($user) ? $user->id : $user;
1838 unset($user);
1840 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
1841 return false;
1844 if ($userid == $USER->id) {
1845 if (!empty($USER->access['rsw'][$coursecontext->path])) {
1846 // the fact that somebody switched role means they can access the course no matter to what role they switched
1847 return true;
1851 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
1852 return false;
1855 if (is_viewing($coursecontext, $userid)) {
1856 return true;
1859 if ($userid != $USER->id) {
1860 // for performance reasons we do not verify temporary guest access for other users, sorry...
1861 return is_enrolled($coursecontext, $userid, '', $onlyactive);
1864 // === from here we deal only with $USER ===
1866 $coursecontext->reload_if_dirty();
1868 if (isset($USER->enrol['enrolled'][$course->id])) {
1869 if ($USER->enrol['enrolled'][$course->id] > time()) {
1870 return true;
1873 if (isset($USER->enrol['tempguest'][$course->id])) {
1874 if ($USER->enrol['tempguest'][$course->id] > time()) {
1875 return true;
1879 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
1880 return true;
1883 // if not enrolled try to gain temporary guest access
1884 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
1885 $enrols = enrol_get_plugins(true);
1886 foreach($instances as $instance) {
1887 if (!isset($enrols[$instance->enrol])) {
1888 continue;
1890 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
1891 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
1892 if ($until !== false and $until > time()) {
1893 $USER->enrol['tempguest'][$course->id] = $until;
1894 return true;
1897 if (isset($USER->enrol['tempguest'][$course->id])) {
1898 unset($USER->enrol['tempguest'][$course->id]);
1899 remove_temp_course_roles($coursecontext);
1902 return false;
1906 * Loads the capability definitions for the component (from file).
1908 * Loads the capability definitions for the component (from file). If no
1909 * capabilities are defined for the component, we simply return an empty array.
1911 * @access private
1912 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
1913 * @return array array of capabilities
1915 function load_capability_def($component) {
1916 $defpath = core_component::get_component_directory($component).'/db/access.php';
1918 $capabilities = array();
1919 if (file_exists($defpath)) {
1920 require($defpath);
1921 if (!empty(${$component.'_capabilities'})) {
1922 // BC capability array name
1923 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
1924 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
1925 $capabilities = ${$component.'_capabilities'};
1929 return $capabilities;
1933 * Gets the capabilities that have been cached in the database for this component.
1935 * @access private
1936 * @param string $component - examples: 'moodle', 'mod_forum'
1937 * @return array array of capabilities
1939 function get_cached_capabilities($component = 'moodle') {
1940 global $DB;
1941 $caps = get_all_capabilities();
1942 $componentcaps = array();
1943 foreach ($caps as $cap) {
1944 if ($cap['component'] == $component) {
1945 $componentcaps[] = (object) $cap;
1948 return $componentcaps;
1952 * Returns default capabilities for given role archetype.
1954 * @param string $archetype role archetype
1955 * @return array
1957 function get_default_capabilities($archetype) {
1958 global $DB;
1960 if (!$archetype) {
1961 return array();
1964 $alldefs = array();
1965 $defaults = array();
1966 $components = array();
1967 $allcaps = get_all_capabilities();
1969 foreach ($allcaps as $cap) {
1970 if (!in_array($cap['component'], $components)) {
1971 $components[] = $cap['component'];
1972 $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
1975 foreach($alldefs as $name=>$def) {
1976 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
1977 if (isset($def['archetypes'])) {
1978 if (isset($def['archetypes'][$archetype])) {
1979 $defaults[$name] = $def['archetypes'][$archetype];
1981 // 'legacy' is for backward compatibility with 1.9 access.php
1982 } else {
1983 if (isset($def['legacy'][$archetype])) {
1984 $defaults[$name] = $def['legacy'][$archetype];
1989 return $defaults;
1993 * Return default roles that can be assigned, overridden or switched
1994 * by give role archetype.
1996 * @param string $type assign|override|switch|view
1997 * @param string $archetype
1998 * @return array of role ids
2000 function get_default_role_archetype_allows($type, $archetype) {
2001 global $DB;
2003 if (empty($archetype)) {
2004 return array();
2007 $roles = $DB->get_records('role');
2008 $archetypemap = array();
2009 foreach ($roles as $role) {
2010 if ($role->archetype) {
2011 $archetypemap[$role->archetype][$role->id] = $role->id;
2015 $defaults = array(
2016 'assign' => array(
2017 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2018 'coursecreator' => array(),
2019 'editingteacher' => array('teacher', 'student'),
2020 'teacher' => array(),
2021 'student' => array(),
2022 'guest' => array(),
2023 'user' => array(),
2024 'frontpage' => array(),
2026 'override' => array(
2027 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2028 'coursecreator' => array(),
2029 'editingteacher' => array('teacher', 'student', 'guest'),
2030 'teacher' => array(),
2031 'student' => array(),
2032 'guest' => array(),
2033 'user' => array(),
2034 'frontpage' => array(),
2036 'switch' => array(
2037 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2038 'coursecreator' => array(),
2039 'editingteacher' => array('teacher', 'student', 'guest'),
2040 'teacher' => array('student', 'guest'),
2041 'student' => array(),
2042 'guest' => array(),
2043 'user' => array(),
2044 'frontpage' => array(),
2046 'view' => array(
2047 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2048 'coursecreator' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2049 'editingteacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2050 'teacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2051 'student' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2052 'guest' => array(),
2053 'user' => array(),
2054 'frontpage' => array(),
2058 if (!isset($defaults[$type][$archetype])) {
2059 debugging("Unknown type '$type'' or archetype '$archetype''");
2060 return array();
2063 $return = array();
2064 foreach ($defaults[$type][$archetype] as $at) {
2065 if (isset($archetypemap[$at])) {
2066 foreach ($archetypemap[$at] as $roleid) {
2067 $return[$roleid] = $roleid;
2072 return $return;
2076 * Reset role capabilities to default according to selected role archetype.
2077 * If no archetype selected, removes all capabilities.
2079 * This applies to capabilities that are assigned to the role (that you could
2080 * edit in the 'define roles' interface), and not to any capability overrides
2081 * in different locations.
2083 * @param int $roleid ID of role to reset capabilities for
2085 function reset_role_capabilities($roleid) {
2086 global $DB;
2088 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2089 $defaultcaps = get_default_capabilities($role->archetype);
2091 $systemcontext = context_system::instance();
2093 $DB->delete_records('role_capabilities',
2094 array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2096 foreach($defaultcaps as $cap=>$permission) {
2097 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2100 // Reset any cache of this role, including MUC.
2101 accesslib_clear_role_cache($roleid);
2103 // Mark the system context dirty.
2104 context_system::instance()->mark_dirty();
2108 * Updates the capabilities table with the component capability definitions.
2109 * If no parameters are given, the function updates the core moodle
2110 * capabilities.
2112 * Note that the absence of the db/access.php capabilities definition file
2113 * will cause any stored capabilities for the component to be removed from
2114 * the database.
2116 * @access private
2117 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2118 * @return boolean true if success, exception in case of any problems
2120 function update_capabilities($component = 'moodle') {
2121 global $DB, $OUTPUT;
2123 $storedcaps = array();
2125 $filecaps = load_capability_def($component);
2126 foreach($filecaps as $capname=>$unused) {
2127 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2128 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2132 // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2133 // So ensure our updating is based on fresh data.
2134 cache::make('core', 'capabilities')->delete('core_capabilities');
2136 $cachedcaps = get_cached_capabilities($component);
2137 if ($cachedcaps) {
2138 foreach ($cachedcaps as $cachedcap) {
2139 array_push($storedcaps, $cachedcap->name);
2140 // update risk bitmasks and context levels in existing capabilities if needed
2141 if (array_key_exists($cachedcap->name, $filecaps)) {
2142 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2143 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2145 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2146 $updatecap = new stdClass();
2147 $updatecap->id = $cachedcap->id;
2148 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2149 $DB->update_record('capabilities', $updatecap);
2151 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2152 $updatecap = new stdClass();
2153 $updatecap->id = $cachedcap->id;
2154 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2155 $DB->update_record('capabilities', $updatecap);
2158 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2159 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2161 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2162 $updatecap = new stdClass();
2163 $updatecap->id = $cachedcap->id;
2164 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2165 $DB->update_record('capabilities', $updatecap);
2171 // Flush the cached again, as we have changed DB.
2172 cache::make('core', 'capabilities')->delete('core_capabilities');
2174 // Are there new capabilities in the file definition?
2175 $newcaps = array();
2177 foreach ($filecaps as $filecap => $def) {
2178 if (!$storedcaps ||
2179 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2180 if (!array_key_exists('riskbitmask', $def)) {
2181 $def['riskbitmask'] = 0; // no risk if not specified
2183 $newcaps[$filecap] = $def;
2186 // Add new capabilities to the stored definition.
2187 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2188 foreach ($newcaps as $capname => $capdef) {
2189 $capability = new stdClass();
2190 $capability->name = $capname;
2191 $capability->captype = $capdef['captype'];
2192 $capability->contextlevel = $capdef['contextlevel'];
2193 $capability->component = $component;
2194 $capability->riskbitmask = $capdef['riskbitmask'];
2196 $DB->insert_record('capabilities', $capability, false);
2198 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2199 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2200 foreach ($rolecapabilities as $rolecapability){
2201 //assign_capability will update rather than insert if capability exists
2202 if (!assign_capability($capname, $rolecapability->permission,
2203 $rolecapability->roleid, $rolecapability->contextid, true)){
2204 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2208 // we ignore archetype key if we have cloned permissions
2209 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2210 assign_legacy_capabilities($capname, $capdef['archetypes']);
2211 // 'legacy' is for backward compatibility with 1.9 access.php
2212 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2213 assign_legacy_capabilities($capname, $capdef['legacy']);
2216 // Are there any capabilities that have been removed from the file
2217 // definition that we need to delete from the stored capabilities and
2218 // role assignments?
2219 capabilities_cleanup($component, $filecaps);
2221 // reset static caches
2222 accesslib_clear_all_caches(false);
2224 // Flush the cached again, as we have changed DB.
2225 cache::make('core', 'capabilities')->delete('core_capabilities');
2227 return true;
2231 * Deletes cached capabilities that are no longer needed by the component.
2232 * Also unassigns these capabilities from any roles that have them.
2233 * NOTE: this function is called from lib/db/upgrade.php
2235 * @access private
2236 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2237 * @param array $newcapdef array of the new capability definitions that will be
2238 * compared with the cached capabilities
2239 * @return int number of deprecated capabilities that have been removed
2241 function capabilities_cleanup($component, $newcapdef = null) {
2242 global $DB;
2244 $removedcount = 0;
2246 if ($cachedcaps = get_cached_capabilities($component)) {
2247 foreach ($cachedcaps as $cachedcap) {
2248 if (empty($newcapdef) ||
2249 array_key_exists($cachedcap->name, $newcapdef) === false) {
2251 // Remove from capabilities cache.
2252 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2253 $removedcount++;
2254 // Delete from roles.
2255 if ($roles = get_roles_with_capability($cachedcap->name)) {
2256 foreach($roles as $role) {
2257 if (!unassign_capability($cachedcap->name, $role->id)) {
2258 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2262 } // End if.
2265 if ($removedcount) {
2266 cache::make('core', 'capabilities')->delete('core_capabilities');
2268 return $removedcount;
2272 * Returns an array of all the known types of risk
2273 * The array keys can be used, for example as CSS class names, or in calls to
2274 * print_risk_icon. The values are the corresponding RISK_ constants.
2276 * @return array all the known types of risk.
2278 function get_all_risks() {
2279 return array(
2280 'riskmanagetrust' => RISK_MANAGETRUST,
2281 'riskconfig' => RISK_CONFIG,
2282 'riskxss' => RISK_XSS,
2283 'riskpersonal' => RISK_PERSONAL,
2284 'riskspam' => RISK_SPAM,
2285 'riskdataloss' => RISK_DATALOSS,
2290 * Return a link to moodle docs for a given capability name
2292 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2293 * @return string the human-readable capability name as a link to Moodle Docs.
2295 function get_capability_docs_link($capability) {
2296 $url = get_docs_url('Capabilities/' . $capability->name);
2297 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2301 * This function pulls out all the resolved capabilities (overrides and
2302 * defaults) of a role used in capability overrides in contexts at a given
2303 * context.
2305 * @param int $roleid
2306 * @param context $context
2307 * @param string $cap capability, optional, defaults to ''
2308 * @return array Array of capabilities
2310 function role_context_capabilities($roleid, context $context, $cap = '') {
2311 global $DB;
2313 $contexts = $context->get_parent_context_ids(true);
2314 $contexts = '('.implode(',', $contexts).')';
2316 $params = array($roleid);
2318 if ($cap) {
2319 $search = " AND rc.capability = ? ";
2320 $params[] = $cap;
2321 } else {
2322 $search = '';
2325 $sql = "SELECT rc.*
2326 FROM {role_capabilities} rc, {context} c
2327 WHERE rc.contextid in $contexts
2328 AND rc.roleid = ?
2329 AND rc.contextid = c.id $search
2330 ORDER BY c.contextlevel DESC, rc.capability DESC";
2332 $capabilities = array();
2334 if ($records = $DB->get_records_sql($sql, $params)) {
2335 // We are traversing via reverse order.
2336 foreach ($records as $record) {
2337 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2338 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2339 $capabilities[$record->capability] = $record->permission;
2343 return $capabilities;
2347 * Constructs array with contextids as first parameter and context paths,
2348 * in both cases bottom top including self.
2350 * @access private
2351 * @param context $context
2352 * @return array
2354 function get_context_info_list(context $context) {
2355 $contextids = explode('/', ltrim($context->path, '/'));
2356 $contextpaths = array();
2357 $contextids2 = $contextids;
2358 while ($contextids2) {
2359 $contextpaths[] = '/' . implode('/', $contextids2);
2360 array_pop($contextids2);
2362 return array($contextids, $contextpaths);
2366 * Check if context is the front page context or a context inside it
2368 * Returns true if this context is the front page context, or a context inside it,
2369 * otherwise false.
2371 * @param context $context a context object.
2372 * @return bool
2374 function is_inside_frontpage(context $context) {
2375 $frontpagecontext = context_course::instance(SITEID);
2376 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2380 * Returns capability information (cached)
2382 * @param string $capabilityname
2383 * @return stdClass or null if capability not found
2385 function get_capability_info($capabilityname) {
2386 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2388 $caps = get_all_capabilities();
2390 if (!isset($caps[$capabilityname])) {
2391 return null;
2394 return (object) $caps[$capabilityname];
2398 * Returns all capabilitiy records, preferably from MUC and not database.
2400 * @return array All capability records indexed by capability name
2402 function get_all_capabilities() {
2403 global $DB;
2404 $cache = cache::make('core', 'capabilities');
2405 if (!$allcaps = $cache->get('core_capabilities')) {
2406 $rs = $DB->get_recordset('capabilities');
2407 $allcaps = array();
2408 foreach ($rs as $capability) {
2409 $capability->riskbitmask = (int) $capability->riskbitmask;
2410 $allcaps[$capability->name] = (array) $capability;
2412 $rs->close();
2413 $cache->set('core_capabilities', $allcaps);
2415 return $allcaps;
2419 * Returns the human-readable, translated version of the capability.
2420 * Basically a big switch statement.
2422 * @param string $capabilityname e.g. mod/choice:readresponses
2423 * @return string
2425 function get_capability_string($capabilityname) {
2427 // Typical capability name is 'plugintype/pluginname:capabilityname'
2428 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2430 if ($type === 'moodle') {
2431 $component = 'core_role';
2432 } else if ($type === 'quizreport') {
2433 //ugly hack!!
2434 $component = 'quiz_'.$name;
2435 } else {
2436 $component = $type.'_'.$name;
2439 $stringname = $name.':'.$capname;
2441 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2442 return get_string($stringname, $component);
2445 $dir = core_component::get_component_directory($component);
2446 if (!file_exists($dir)) {
2447 // plugin broken or does not exist, do not bother with printing of debug message
2448 return $capabilityname.' ???';
2451 // something is wrong in plugin, better print debug
2452 return get_string($stringname, $component);
2456 * This gets the mod/block/course/core etc strings.
2458 * @param string $component
2459 * @param int $contextlevel
2460 * @return string|bool String is success, false if failed
2462 function get_component_string($component, $contextlevel) {
2464 if ($component === 'moodle' or $component === 'core') {
2465 switch ($contextlevel) {
2466 // TODO MDL-46123: this should probably use context level names instead
2467 case CONTEXT_SYSTEM: return get_string('coresystem');
2468 case CONTEXT_USER: return get_string('users');
2469 case CONTEXT_COURSECAT: return get_string('categories');
2470 case CONTEXT_COURSE: return get_string('course');
2471 case CONTEXT_MODULE: return get_string('activities');
2472 case CONTEXT_BLOCK: return get_string('block');
2473 default: print_error('unknowncontext');
2477 list($type, $name) = core_component::normalize_component($component);
2478 $dir = core_component::get_plugin_directory($type, $name);
2479 if (!file_exists($dir)) {
2480 // plugin not installed, bad luck, there is no way to find the name
2481 return $component.' ???';
2484 switch ($type) {
2485 // TODO MDL-46123: this is really hacky and should be improved.
2486 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2487 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2488 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2489 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2490 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2491 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2492 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2493 case 'mod':
2494 if (get_string_manager()->string_exists('pluginname', $component)) {
2495 return get_string('activity').': '.get_string('pluginname', $component);
2496 } else {
2497 return get_string('activity').': '.get_string('modulename', $component);
2499 default: return get_string('pluginname', $component);
2504 * Gets the list of roles assigned to this context and up (parents)
2505 * from the aggregation of:
2506 * a) the list of roles that are visible on user profile page and participants page (profileroles setting) and;
2507 * b) if applicable, those roles that are assigned in the context.
2509 * @param context $context
2510 * @return array
2512 function get_profile_roles(context $context) {
2513 global $CFG, $DB;
2514 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2515 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2516 if (has_capability('moodle/role:assign', $context)) {
2517 $rolesinscope = array_keys(get_all_roles($context));
2518 } else {
2519 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2522 if (empty($rolesinscope)) {
2523 return [];
2526 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2527 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2528 $params = array_merge($params, $cparams);
2530 if ($coursecontext = $context->get_course_context(false)) {
2531 $params['coursecontext'] = $coursecontext->id;
2532 } else {
2533 $params['coursecontext'] = 0;
2536 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2537 FROM {role_assignments} ra, {role} r
2538 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2539 WHERE r.id = ra.roleid
2540 AND ra.contextid $contextlist
2541 AND r.id $rallowed
2542 ORDER BY r.sortorder ASC";
2544 return $DB->get_records_sql($sql, $params);
2548 * Gets the list of roles assigned to this context and up (parents)
2550 * @param context $context
2551 * @return array
2553 function get_roles_used_in_context(context $context) {
2554 global $DB;
2556 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2558 if ($coursecontext = $context->get_course_context(false)) {
2559 $params['coursecontext'] = $coursecontext->id;
2560 } else {
2561 $params['coursecontext'] = 0;
2564 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2565 FROM {role_assignments} ra, {role} r
2566 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2567 WHERE r.id = ra.roleid
2568 AND ra.contextid $contextlist
2569 ORDER BY r.sortorder ASC";
2571 return $DB->get_records_sql($sql, $params);
2575 * This function is used to print roles column in user profile page.
2576 * It is using the CFG->profileroles to limit the list to only interesting roles.
2577 * (The permission tab has full details of user role assignments.)
2579 * @param int $userid
2580 * @param int $courseid
2581 * @return string
2583 function get_user_roles_in_course($userid, $courseid) {
2584 global $CFG, $DB;
2585 if ($courseid == SITEID) {
2586 $context = context_system::instance();
2587 } else {
2588 $context = context_course::instance($courseid);
2590 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2591 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2592 if (has_capability('moodle/role:assign', $context)) {
2593 $rolesinscope = array_keys(get_all_roles($context));
2594 } else {
2595 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2597 if (empty($rolesinscope)) {
2598 return '';
2601 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2602 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2603 $params = array_merge($params, $cparams);
2605 if ($coursecontext = $context->get_course_context(false)) {
2606 $params['coursecontext'] = $coursecontext->id;
2607 } else {
2608 $params['coursecontext'] = 0;
2611 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2612 FROM {role_assignments} ra, {role} r
2613 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2614 WHERE r.id = ra.roleid
2615 AND ra.contextid $contextlist
2616 AND r.id $rallowed
2617 AND ra.userid = :userid
2618 ORDER BY r.sortorder ASC";
2619 $params['userid'] = $userid;
2621 $rolestring = '';
2623 if ($roles = $DB->get_records_sql($sql, $params)) {
2624 $viewableroles = get_viewable_roles($context, $userid);
2626 $rolenames = array();
2627 foreach ($roles as $roleid => $unused) {
2628 if (isset($viewableroles[$roleid])) {
2629 $url = new moodle_url('/user/index.php', ['contextid' => $context->id, 'roleid' => $roleid]);
2630 $rolenames[] = '<a href="' . $url . '">' . $viewableroles[$roleid] . '</a>';
2633 $rolestring = implode(',', $rolenames);
2636 return $rolestring;
2640 * Checks if a user can assign users to a particular role in this context
2642 * @param context $context
2643 * @param int $targetroleid - the id of the role you want to assign users to
2644 * @return boolean
2646 function user_can_assign(context $context, $targetroleid) {
2647 global $DB;
2649 // First check to see if the user is a site administrator.
2650 if (is_siteadmin()) {
2651 return true;
2654 // Check if user has override capability.
2655 // If not return false.
2656 if (!has_capability('moodle/role:assign', $context)) {
2657 return false;
2659 // pull out all active roles of this user from this context(or above)
2660 if ($userroles = get_user_roles($context)) {
2661 foreach ($userroles as $userrole) {
2662 // if any in the role_allow_override table, then it's ok
2663 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2664 return true;
2669 return false;
2673 * Returns all site roles in correct sort order.
2675 * Note: this method does not localise role names or descriptions,
2676 * use role_get_names() if you need role names.
2678 * @param context $context optional context for course role name aliases
2679 * @return array of role records with optional coursealias property
2681 function get_all_roles(context $context = null) {
2682 global $DB;
2684 if (!$context or !$coursecontext = $context->get_course_context(false)) {
2685 $coursecontext = null;
2688 if ($coursecontext) {
2689 $sql = "SELECT r.*, rn.name AS coursealias
2690 FROM {role} r
2691 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2692 ORDER BY r.sortorder ASC";
2693 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
2695 } else {
2696 return $DB->get_records('role', array(), 'sortorder ASC');
2701 * Returns roles of a specified archetype
2703 * @param string $archetype
2704 * @return array of full role records
2706 function get_archetype_roles($archetype) {
2707 global $DB;
2708 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2712 * Gets all the user roles assigned in this context, or higher contexts for a list of users.
2714 * If you try using the combination $userids = [], $checkparentcontexts = true then this is likely
2715 * to cause an out-of-memory error on large Moodle sites, so this combination is deprecated and
2716 * outputs a warning, even though it is the default.
2718 * @param context $context
2719 * @param array $userids. An empty list means fetch all role assignments for the context.
2720 * @param bool $checkparentcontexts defaults to true
2721 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2722 * @return array
2724 function get_users_roles(context $context, $userids = [], $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2725 global $DB;
2727 if (!$userids && $checkparentcontexts) {
2728 debugging('Please do not call get_users_roles() with $checkparentcontexts = true ' .
2729 'and $userids array not set. This combination causes large Moodle sites ' .
2730 'with lots of site-wide role assignemnts to run out of memory.', DEBUG_DEVELOPER);
2733 if ($checkparentcontexts) {
2734 $contextids = $context->get_parent_context_ids();
2735 } else {
2736 $contextids = array();
2738 $contextids[] = $context->id;
2740 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
2742 // If userids was passed as an empty array, we fetch all role assignments for the course.
2743 if (empty($userids)) {
2744 $useridlist = ' IS NOT NULL ';
2745 $uparams = [];
2746 } else {
2747 list($useridlist, $uparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'uids');
2750 $sql = "SELECT ra.*, r.name, r.shortname, ra.userid
2751 FROM {role_assignments} ra, {role} r, {context} c
2752 WHERE ra.userid $useridlist
2753 AND ra.roleid = r.id
2754 AND ra.contextid = c.id
2755 AND ra.contextid $contextids
2756 ORDER BY $order";
2758 $all = $DB->get_records_sql($sql , array_merge($params, $uparams));
2760 // Return results grouped by userid.
2761 $result = [];
2762 foreach ($all as $id => $record) {
2763 if (!isset($result[$record->userid])) {
2764 $result[$record->userid] = [];
2766 $result[$record->userid][$record->id] = $record;
2769 // Make sure all requested users are included in the result, even if they had no role assignments.
2770 foreach ($userids as $id) {
2771 if (!isset($result[$id])) {
2772 $result[$id] = [];
2776 return $result;
2781 * Gets all the user roles assigned in this context, or higher contexts
2782 * this is mainly used when checking if a user can assign a role, or overriding a role
2783 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2784 * allow_override tables
2786 * @param context $context
2787 * @param int $userid
2788 * @param bool $checkparentcontexts defaults to true
2789 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2790 * @return array
2792 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2793 global $USER, $DB;
2795 if (empty($userid)) {
2796 if (empty($USER->id)) {
2797 return array();
2799 $userid = $USER->id;
2802 if ($checkparentcontexts) {
2803 $contextids = $context->get_parent_context_ids();
2804 } else {
2805 $contextids = array();
2807 $contextids[] = $context->id;
2809 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2811 array_unshift($params, $userid);
2813 $sql = "SELECT ra.*, r.name, r.shortname
2814 FROM {role_assignments} ra, {role} r, {context} c
2815 WHERE ra.userid = ?
2816 AND ra.roleid = r.id
2817 AND ra.contextid = c.id
2818 AND ra.contextid $contextids
2819 ORDER BY $order";
2821 return $DB->get_records_sql($sql ,$params);
2825 * Like get_user_roles, but adds in the authenticated user role, and the front
2826 * page roles, if applicable.
2828 * @param context $context the context.
2829 * @param int $userid optional. Defaults to $USER->id
2830 * @return array of objects with fields ->userid, ->contextid and ->roleid.
2832 function get_user_roles_with_special(context $context, $userid = 0) {
2833 global $CFG, $USER;
2835 if (empty($userid)) {
2836 if (empty($USER->id)) {
2837 return array();
2839 $userid = $USER->id;
2842 $ras = get_user_roles($context, $userid);
2844 // Add front-page role if relevant.
2845 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2846 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
2847 is_inside_frontpage($context);
2848 if ($defaultfrontpageroleid && $isfrontpage) {
2849 $frontpagecontext = context_course::instance(SITEID);
2850 $ra = new stdClass();
2851 $ra->userid = $userid;
2852 $ra->contextid = $frontpagecontext->id;
2853 $ra->roleid = $defaultfrontpageroleid;
2854 $ras[] = $ra;
2857 // Add authenticated user role if relevant.
2858 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2859 if ($defaultuserroleid && !isguestuser($userid)) {
2860 $systemcontext = context_system::instance();
2861 $ra = new stdClass();
2862 $ra->userid = $userid;
2863 $ra->contextid = $systemcontext->id;
2864 $ra->roleid = $defaultuserroleid;
2865 $ras[] = $ra;
2868 return $ras;
2872 * Creates a record in the role_allow_override table
2874 * @param int $fromroleid source roleid
2875 * @param int $targetroleid target roleid
2876 * @return void
2878 function core_role_set_override_allowed($fromroleid, $targetroleid) {
2879 global $DB;
2881 $record = new stdClass();
2882 $record->roleid = $fromroleid;
2883 $record->allowoverride = $targetroleid;
2884 $DB->insert_record('role_allow_override', $record);
2888 * Creates a record in the role_allow_assign table
2890 * @param int $fromroleid source roleid
2891 * @param int $targetroleid target roleid
2892 * @return void
2894 function core_role_set_assign_allowed($fromroleid, $targetroleid) {
2895 global $DB;
2897 $record = new stdClass();
2898 $record->roleid = $fromroleid;
2899 $record->allowassign = $targetroleid;
2900 $DB->insert_record('role_allow_assign', $record);
2904 * Creates a record in the role_allow_switch table
2906 * @param int $fromroleid source roleid
2907 * @param int $targetroleid target roleid
2908 * @return void
2910 function core_role_set_switch_allowed($fromroleid, $targetroleid) {
2911 global $DB;
2913 $record = new stdClass();
2914 $record->roleid = $fromroleid;
2915 $record->allowswitch = $targetroleid;
2916 $DB->insert_record('role_allow_switch', $record);
2920 * Creates a record in the role_allow_view table
2922 * @param int $fromroleid source roleid
2923 * @param int $targetroleid target roleid
2924 * @return void
2926 function core_role_set_view_allowed($fromroleid, $targetroleid) {
2927 global $DB;
2929 $record = new stdClass();
2930 $record->roleid = $fromroleid;
2931 $record->allowview = $targetroleid;
2932 $DB->insert_record('role_allow_view', $record);
2936 * Gets a list of roles that this user can assign in this context
2938 * @param context $context the context.
2939 * @param int $rolenamedisplay the type of role name to display. One of the
2940 * ROLENAME_X constants. Default ROLENAME_ALIAS.
2941 * @param bool $withusercounts if true, count the number of users with each role.
2942 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
2943 * @return array if $withusercounts is false, then an array $roleid => $rolename.
2944 * if $withusercounts is true, returns a list of three arrays,
2945 * $rolenames, $rolecounts, and $nameswithcounts.
2947 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
2948 global $USER, $DB;
2950 // make sure there is a real user specified
2951 if ($user === null) {
2952 $userid = isset($USER->id) ? $USER->id : 0;
2953 } else {
2954 $userid = is_object($user) ? $user->id : $user;
2957 if (!has_capability('moodle/role:assign', $context, $userid)) {
2958 if ($withusercounts) {
2959 return array(array(), array(), array());
2960 } else {
2961 return array();
2965 $params = array();
2966 $extrafields = '';
2968 if ($withusercounts) {
2969 $extrafields = ', (SELECT count(u.id)
2970 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
2971 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
2972 ) AS usercount';
2973 $params['conid'] = $context->id;
2976 if (is_siteadmin($userid)) {
2977 // show all roles allowed in this context to admins
2978 $assignrestriction = "";
2979 } else {
2980 $parents = $context->get_parent_context_ids(true);
2981 $contexts = implode(',' , $parents);
2982 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
2983 FROM {role_allow_assign} raa
2984 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
2985 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
2986 ) ar ON ar.id = r.id";
2987 $params['userid'] = $userid;
2989 $params['contextlevel'] = $context->contextlevel;
2991 if ($coursecontext = $context->get_course_context(false)) {
2992 $params['coursecontext'] = $coursecontext->id;
2993 } else {
2994 $params['coursecontext'] = 0; // no course aliases
2995 $coursecontext = null;
2997 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
2998 FROM {role} r
2999 $assignrestriction
3000 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3001 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3002 ORDER BY r.sortorder ASC";
3003 $roles = $DB->get_records_sql($sql, $params);
3005 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3007 if (!$withusercounts) {
3008 return $rolenames;
3011 $rolecounts = array();
3012 $nameswithcounts = array();
3013 foreach ($roles as $role) {
3014 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3015 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3017 return array($rolenames, $rolecounts, $nameswithcounts);
3021 * Gets a list of roles that this user can switch to in a context
3023 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3024 * This function just process the contents of the role_allow_switch table. You also need to
3025 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3027 * @param context $context a context.
3028 * @return array an array $roleid => $rolename.
3030 function get_switchable_roles(context $context) {
3031 global $USER, $DB;
3033 // You can't switch roles without this capability.
3034 if (!has_capability('moodle/role:switchroles', $context)) {
3035 return [];
3038 $params = array();
3039 $extrajoins = '';
3040 $extrawhere = '';
3041 if (!is_siteadmin()) {
3042 // Admins are allowed to switch to any role with.
3043 // Others are subject to the additional constraint that the switch-to role must be allowed by
3044 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3045 $parents = $context->get_parent_context_ids(true);
3046 $contexts = implode(',' , $parents);
3048 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3049 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3050 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3051 $params['userid'] = $USER->id;
3054 if ($coursecontext = $context->get_course_context(false)) {
3055 $params['coursecontext'] = $coursecontext->id;
3056 } else {
3057 $params['coursecontext'] = 0; // no course aliases
3058 $coursecontext = null;
3061 $query = "
3062 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3063 FROM (SELECT DISTINCT rc.roleid
3064 FROM {role_capabilities} rc
3065 $extrajoins
3066 $extrawhere) idlist
3067 JOIN {role} r ON r.id = idlist.roleid
3068 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3069 ORDER BY r.sortorder";
3070 $roles = $DB->get_records_sql($query, $params);
3072 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3076 * Gets a list of roles that this user can view in a context
3078 * @param context $context a context.
3079 * @param int $userid id of user.
3080 * @return array an array $roleid => $rolename.
3082 function get_viewable_roles(context $context, $userid = null) {
3083 global $USER, $DB;
3085 if ($userid == null) {
3086 $userid = $USER->id;
3089 $params = array();
3090 $extrajoins = '';
3091 $extrawhere = '';
3092 if (!is_siteadmin()) {
3093 // Admins are allowed to view any role.
3094 // Others are subject to the additional constraint that the view role must be allowed by
3095 // 'role_allow_view' for some role they have assigned in this context or any parent.
3096 $contexts = $context->get_parent_context_ids(true);
3097 list($insql, $inparams) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED);
3099 $extrajoins = "JOIN {role_allow_view} ras ON ras.allowview = r.id
3100 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3101 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid $insql";
3103 $params += $inparams;
3104 $params['userid'] = $userid;
3107 if ($coursecontext = $context->get_course_context(false)) {
3108 $params['coursecontext'] = $coursecontext->id;
3109 } else {
3110 $params['coursecontext'] = 0; // No course aliases.
3111 $coursecontext = null;
3114 $query = "
3115 SELECT r.id, r.name, r.shortname, rn.name AS coursealias, r.sortorder
3116 FROM {role} r
3117 $extrajoins
3118 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3119 $extrawhere
3120 GROUP BY r.id, r.name, r.shortname, rn.name, r.sortorder
3121 ORDER BY r.sortorder";
3122 $roles = $DB->get_records_sql($query, $params);
3124 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3128 * Gets a list of roles that this user can override in this context.
3130 * @param context $context the context.
3131 * @param int $rolenamedisplay the type of role name to display. One of the
3132 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3133 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3134 * @return array if $withcounts is false, then an array $roleid => $rolename.
3135 * if $withusercounts is true, returns a list of three arrays,
3136 * $rolenames, $rolecounts, and $nameswithcounts.
3138 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3139 global $USER, $DB;
3141 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3142 if ($withcounts) {
3143 return array(array(), array(), array());
3144 } else {
3145 return array();
3149 $parents = $context->get_parent_context_ids(true);
3150 $contexts = implode(',' , $parents);
3152 $params = array();
3153 $extrafields = '';
3155 $params['userid'] = $USER->id;
3156 if ($withcounts) {
3157 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3158 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3159 $params['conid'] = $context->id;
3162 if ($coursecontext = $context->get_course_context(false)) {
3163 $params['coursecontext'] = $coursecontext->id;
3164 } else {
3165 $params['coursecontext'] = 0; // no course aliases
3166 $coursecontext = null;
3169 if (is_siteadmin()) {
3170 // show all roles to admins
3171 $roles = $DB->get_records_sql("
3172 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3173 FROM {role} ro
3174 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3175 ORDER BY ro.sortorder ASC", $params);
3177 } else {
3178 $roles = $DB->get_records_sql("
3179 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3180 FROM {role} ro
3181 JOIN (SELECT DISTINCT r.id
3182 FROM {role} r
3183 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3184 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3185 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3186 ) inline_view ON ro.id = inline_view.id
3187 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3188 ORDER BY ro.sortorder ASC", $params);
3191 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3193 if (!$withcounts) {
3194 return $rolenames;
3197 $rolecounts = array();
3198 $nameswithcounts = array();
3199 foreach ($roles as $role) {
3200 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3201 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3203 return array($rolenames, $rolecounts, $nameswithcounts);
3207 * Create a role menu suitable for default role selection in enrol plugins.
3209 * @package core_enrol
3211 * @param context $context
3212 * @param int $addroleid current or default role - always added to list
3213 * @return array roleid=>localised role name
3215 function get_default_enrol_roles(context $context, $addroleid = null) {
3216 global $DB;
3218 $params = array('contextlevel'=>CONTEXT_COURSE);
3220 if ($coursecontext = $context->get_course_context(false)) {
3221 $params['coursecontext'] = $coursecontext->id;
3222 } else {
3223 $params['coursecontext'] = 0; // no course names
3224 $coursecontext = null;
3227 if ($addroleid) {
3228 $addrole = "OR r.id = :addroleid";
3229 $params['addroleid'] = $addroleid;
3230 } else {
3231 $addrole = "";
3234 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3235 FROM {role} r
3236 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3237 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3238 WHERE rcl.id IS NOT NULL $addrole
3239 ORDER BY sortorder DESC";
3241 $roles = $DB->get_records_sql($sql, $params);
3243 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3247 * Return context levels where this role is assignable.
3249 * @param integer $roleid the id of a role.
3250 * @return array list of the context levels at which this role may be assigned.
3252 function get_role_contextlevels($roleid) {
3253 global $DB;
3254 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3255 'contextlevel', 'id,contextlevel');
3259 * Return roles suitable for assignment at the specified context level.
3261 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3263 * @param integer $contextlevel a contextlevel.
3264 * @return array list of role ids that are assignable at this context level.
3266 function get_roles_for_contextlevels($contextlevel) {
3267 global $DB;
3268 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3269 '', 'id,roleid');
3273 * Returns default context levels where roles can be assigned.
3275 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3276 * from the array returned by get_role_archetypes();
3277 * @return array list of the context levels at which this type of role may be assigned by default.
3279 function get_default_contextlevels($rolearchetype) {
3280 static $defaults = array(
3281 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3282 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3283 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3284 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3285 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3286 'guest' => array(),
3287 'user' => array(),
3288 'frontpage' => array());
3290 if (isset($defaults[$rolearchetype])) {
3291 return $defaults[$rolearchetype];
3292 } else {
3293 return array();
3298 * Set the context levels at which a particular role can be assigned.
3299 * Throws exceptions in case of error.
3301 * @param integer $roleid the id of a role.
3302 * @param array $contextlevels the context levels at which this role should be assignable,
3303 * duplicate levels are removed.
3304 * @return void
3306 function set_role_contextlevels($roleid, array $contextlevels) {
3307 global $DB;
3308 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3309 $rcl = new stdClass();
3310 $rcl->roleid = $roleid;
3311 $contextlevels = array_unique($contextlevels);
3312 foreach ($contextlevels as $level) {
3313 $rcl->contextlevel = $level;
3314 $DB->insert_record('role_context_levels', $rcl, false, true);
3319 * Who has this capability in this context?
3321 * This can be a very expensive call - use sparingly and keep
3322 * the results if you are going to need them again soon.
3324 * Note if $fields is empty this function attempts to get u.*
3325 * which can get rather large - and has a serious perf impact
3326 * on some DBs.
3328 * @param context $context
3329 * @param string|array $capability - capability name(s)
3330 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3331 * @param string $sort - the sort order. Default is lastaccess time.
3332 * @param mixed $limitfrom - number of records to skip (offset)
3333 * @param mixed $limitnum - number of records to fetch
3334 * @param string|array $groups - single group or array of groups - only return
3335 * users who are in one of these group(s).
3336 * @param string|array $exceptions - list of users to exclude, comma separated or array
3337 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3338 * @param bool $view_ignored - use get_enrolled_sql() instead
3339 * @param bool $useviewallgroups if $groups is set the return users who
3340 * have capability both $capability and moodle/site:accessallgroups
3341 * in this context, as well as users who have $capability and who are
3342 * in $groups.
3343 * @return array of user records
3345 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3346 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3347 global $CFG, $DB;
3349 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3350 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3352 $ctxids = trim($context->path, '/');
3353 $ctxids = str_replace('/', ',', $ctxids);
3355 // Context is the frontpage
3356 $iscoursepage = false; // coursepage other than fp
3357 $isfrontpage = false;
3358 if ($context->contextlevel == CONTEXT_COURSE) {
3359 if ($context->instanceid == SITEID) {
3360 $isfrontpage = true;
3361 } else {
3362 $iscoursepage = true;
3365 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3367 $caps = (array)$capability;
3369 // construct list of context paths bottom-->top
3370 list($contextids, $paths) = get_context_info_list($context);
3372 // we need to find out all roles that have these capabilities either in definition or in overrides
3373 $defs = array();
3374 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3375 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3376 $params = array_merge($params, $params2);
3377 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3378 FROM {role_capabilities} rc
3379 JOIN {context} ctx on rc.contextid = ctx.id
3380 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3382 $rcs = $DB->get_records_sql($sql, $params);
3383 foreach ($rcs as $rc) {
3384 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3387 // go through the permissions bottom-->top direction to evaluate the current permission,
3388 // first one wins (prohibit is an exception that always wins)
3389 $access = array();
3390 foreach ($caps as $cap) {
3391 foreach ($paths as $path) {
3392 if (empty($defs[$cap][$path])) {
3393 continue;
3395 foreach($defs[$cap][$path] as $roleid => $perm) {
3396 if ($perm == CAP_PROHIBIT) {
3397 $access[$cap][$roleid] = CAP_PROHIBIT;
3398 continue;
3400 if (!isset($access[$cap][$roleid])) {
3401 $access[$cap][$roleid] = (int)$perm;
3407 // make lists of roles that are needed and prohibited in this context
3408 $needed = array(); // one of these is enough
3409 $prohibited = array(); // must not have any of these
3410 foreach ($caps as $cap) {
3411 if (empty($access[$cap])) {
3412 continue;
3414 foreach ($access[$cap] as $roleid => $perm) {
3415 if ($perm == CAP_PROHIBIT) {
3416 unset($needed[$cap][$roleid]);
3417 $prohibited[$cap][$roleid] = true;
3418 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3419 $needed[$cap][$roleid] = true;
3422 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3423 // easy, nobody has the permission
3424 unset($needed[$cap]);
3425 unset($prohibited[$cap]);
3426 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3427 // everybody is disqualified on the frontpage
3428 unset($needed[$cap]);
3429 unset($prohibited[$cap]);
3431 if (empty($prohibited[$cap])) {
3432 unset($prohibited[$cap]);
3436 if (empty($needed)) {
3437 // there can not be anybody if no roles match this request
3438 return array();
3441 if (empty($prohibited)) {
3442 // we can compact the needed roles
3443 $n = array();
3444 foreach ($needed as $cap) {
3445 foreach ($cap as $roleid=>$unused) {
3446 $n[$roleid] = true;
3449 $needed = array('any'=>$n);
3450 unset($n);
3453 // ***** Set up default fields ******
3454 if (empty($fields)) {
3455 if ($iscoursepage) {
3456 $fields = 'u.*, ul.timeaccess AS lastaccess';
3457 } else {
3458 $fields = 'u.*';
3460 } else {
3461 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3462 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3466 // Set up default sort
3467 if (empty($sort)) { // default to course lastaccess or just lastaccess
3468 if ($iscoursepage) {
3469 $sort = 'ul.timeaccess';
3470 } else {
3471 $sort = 'u.lastaccess';
3475 // Prepare query clauses
3476 $wherecond = array();
3477 $params = array();
3478 $joins = array();
3480 // User lastaccess JOIN
3481 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3482 // user_lastaccess is not required MDL-13810
3483 } else {
3484 if ($iscoursepage) {
3485 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3486 } else {
3487 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3491 // We never return deleted users or guest account.
3492 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3493 $params['guestid'] = $CFG->siteguest;
3495 // Groups
3496 if ($groups) {
3497 $groups = (array)$groups;
3498 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3499 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3500 $params = array_merge($params, $grpparams);
3502 if ($useviewallgroups) {
3503 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3504 if (!empty($viewallgroupsusers)) {
3505 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3506 } else {
3507 $wherecond[] = "($grouptest)";
3509 } else {
3510 $wherecond[] = "($grouptest)";
3514 // User exceptions
3515 if (!empty($exceptions)) {
3516 $exceptions = (array)$exceptions;
3517 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3518 $params = array_merge($params, $exparams);
3519 $wherecond[] = "u.id $exsql";
3522 // now add the needed and prohibited roles conditions as joins
3523 if (!empty($needed['any'])) {
3524 // simple case - there are no prohibits involved
3525 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3526 // everybody
3527 } else {
3528 $joins[] = "JOIN (SELECT DISTINCT userid
3529 FROM {role_assignments}
3530 WHERE contextid IN ($ctxids)
3531 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3532 ) ra ON ra.userid = u.id";
3534 } else {
3535 $unions = array();
3536 $everybody = false;
3537 foreach ($needed as $cap=>$unused) {
3538 if (empty($prohibited[$cap])) {
3539 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3540 $everybody = true;
3541 break;
3542 } else {
3543 $unions[] = "SELECT userid
3544 FROM {role_assignments}
3545 WHERE contextid IN ($ctxids)
3546 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3548 } else {
3549 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3550 // nobody can have this cap because it is prevented in default roles
3551 continue;
3553 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3554 // everybody except the prohibitted - hiding does not matter
3555 $unions[] = "SELECT id AS userid
3556 FROM {user}
3557 WHERE id NOT IN (SELECT userid
3558 FROM {role_assignments}
3559 WHERE contextid IN ($ctxids)
3560 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3562 } else {
3563 $unions[] = "SELECT userid
3564 FROM {role_assignments}
3565 WHERE contextid IN ($ctxids) AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3566 AND userid NOT IN (
3567 SELECT userid
3568 FROM {role_assignments}
3569 WHERE contextid IN ($ctxids)
3570 AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . ")
3575 if (!$everybody) {
3576 if ($unions) {
3577 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3578 } else {
3579 // only prohibits found - nobody can be matched
3580 $wherecond[] = "1 = 2";
3585 // Collect WHERE conditions and needed joins
3586 $where = implode(' AND ', $wherecond);
3587 if ($where !== '') {
3588 $where = 'WHERE ' . $where;
3590 $joins = implode("\n", $joins);
3592 // Ok, let's get the users!
3593 $sql = "SELECT $fields
3594 FROM {user} u
3595 $joins
3596 $where
3597 ORDER BY $sort";
3599 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3603 * Re-sort a users array based on a sorting policy
3605 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3606 * based on a sorting policy. This is to support the odd practice of
3607 * sorting teachers by 'authority', where authority was "lowest id of the role
3608 * assignment".
3610 * Will execute 1 database query. Only suitable for small numbers of users, as it
3611 * uses an u.id IN() clause.
3613 * Notes about the sorting criteria.
3615 * As a default, we cannot rely on role.sortorder because then
3616 * admins/coursecreators will always win. That is why the sane
3617 * rule "is locality matters most", with sortorder as 2nd
3618 * consideration.
3620 * If you want role.sortorder, use the 'sortorder' policy, and
3621 * name explicitly what roles you want to cover. It's probably
3622 * a good idea to see what roles have the capabilities you want
3623 * (array_diff() them against roiles that have 'can-do-anything'
3624 * to weed out admin-ish roles. Or fetch a list of roles from
3625 * variables like $CFG->coursecontact .
3627 * @param array $users Users array, keyed on userid
3628 * @param context $context
3629 * @param array $roles ids of the roles to include, optional
3630 * @param string $sortpolicy defaults to locality, more about
3631 * @return array sorted copy of the array
3633 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3634 global $DB;
3636 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3637 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3638 if (empty($roles)) {
3639 $roleswhere = '';
3640 } else {
3641 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3644 $sql = "SELECT ra.userid
3645 FROM {role_assignments} ra
3646 JOIN {role} r
3647 ON ra.roleid=r.id
3648 JOIN {context} ctx
3649 ON ra.contextid=ctx.id
3650 WHERE $userswhere
3651 $contextwhere
3652 $roleswhere";
3654 // Default 'locality' policy -- read PHPDoc notes
3655 // about sort policies...
3656 $orderby = 'ORDER BY '
3657 .'ctx.depth DESC, ' /* locality wins */
3658 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3659 .'ra.id'; /* role assignment order tie-breaker */
3660 if ($sortpolicy === 'sortorder') {
3661 $orderby = 'ORDER BY '
3662 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3663 .'ra.id'; /* role assignment order tie-breaker */
3666 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3667 $sortedusers = array();
3668 $seen = array();
3670 foreach ($sortedids as $id) {
3671 // Avoid duplicates
3672 if (isset($seen[$id])) {
3673 continue;
3675 $seen[$id] = true;
3677 // assign
3678 $sortedusers[$id] = $users[$id];
3680 return $sortedusers;
3684 * Gets all the users assigned this role in this context or higher
3686 * Note that moodle is based on capabilities and it is usually better
3687 * to check permissions than to check role ids as the capabilities
3688 * system is more flexible. If you really need, you can to use this
3689 * function but consider has_capability() as a possible substitute.
3691 * All $sort fields are added into $fields if not present there yet.
3693 * If $roleid is an array or is empty (all roles) you need to set $fields
3694 * (and $sort by extension) params according to it, as the first field
3695 * returned by the database should be unique (ra.id is the best candidate).
3697 * @param int $roleid (can also be an array of ints!)
3698 * @param context $context
3699 * @param bool $parent if true, get list of users assigned in higher context too
3700 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3701 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3702 * null => use default sort from users_order_by_sql.
3703 * @param bool $all true means all, false means limit to enrolled users
3704 * @param string $group defaults to ''
3705 * @param mixed $limitfrom defaults to ''
3706 * @param mixed $limitnum defaults to ''
3707 * @param string $extrawheretest defaults to ''
3708 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3709 * @return array
3711 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3712 $sort = null, $all = true, $group = '',
3713 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3714 global $DB;
3716 if (empty($fields)) {
3717 $allnames = get_all_user_name_fields(true, 'u');
3718 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
3719 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3720 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3721 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3722 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3725 // Prevent wrong function uses.
3726 if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
3727 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
3728 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
3730 if (!empty($roleid)) {
3731 // Solving partially the issue when specifying multiple roles.
3732 $users = array();
3733 foreach ($roleid as $id) {
3734 // Ignoring duplicated keys keeping the first user appearance.
3735 $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
3736 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
3738 return $users;
3742 $parentcontexts = '';
3743 if ($parent) {
3744 $parentcontexts = substr($context->path, 1); // kill leading slash
3745 $parentcontexts = str_replace('/', ',', $parentcontexts);
3746 if ($parentcontexts !== '') {
3747 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3751 if ($roleid) {
3752 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
3753 $roleselect = "AND ra.roleid $rids";
3754 } else {
3755 $params = array();
3756 $roleselect = '';
3759 if ($coursecontext = $context->get_course_context(false)) {
3760 $params['coursecontext'] = $coursecontext->id;
3761 } else {
3762 $params['coursecontext'] = 0;
3765 if ($group) {
3766 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3767 $groupselect = " AND gm.groupid = :groupid ";
3768 $params['groupid'] = $group;
3769 } else {
3770 $groupjoin = '';
3771 $groupselect = '';
3774 $params['contextid'] = $context->id;
3776 if ($extrawheretest) {
3777 $extrawheretest = ' AND ' . $extrawheretest;
3780 if ($whereorsortparams) {
3781 $params = array_merge($params, $whereorsortparams);
3784 if (!$sort) {
3785 list($sort, $sortparams) = users_order_by_sql('u');
3786 $params = array_merge($params, $sortparams);
3789 // Adding the fields from $sort that are not present in $fields.
3790 $sortarray = preg_split('/,\s*/', $sort);
3791 $fieldsarray = preg_split('/,\s*/', $fields);
3793 // Discarding aliases from the fields.
3794 $fieldnames = array();
3795 foreach ($fieldsarray as $key => $field) {
3796 list($fieldnames[$key]) = explode(' ', $field);
3799 $addedfields = array();
3800 foreach ($sortarray as $sortfield) {
3801 // Throw away any additional arguments to the sort (e.g. ASC/DESC).
3802 list($sortfield) = explode(' ', $sortfield);
3803 list($tableprefix) = explode('.', $sortfield);
3804 $fieldpresent = false;
3805 foreach ($fieldnames as $fieldname) {
3806 if ($fieldname === $sortfield || $fieldname === $tableprefix.'.*') {
3807 $fieldpresent = true;
3808 break;
3812 if (!$fieldpresent) {
3813 $fieldsarray[] = $sortfield;
3814 $addedfields[] = $sortfield;
3818 $fields = implode(', ', $fieldsarray);
3819 if (!empty($addedfields)) {
3820 $addedfields = implode(', ', $addedfields);
3821 debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
3824 if ($all === null) {
3825 // Previously null was used to indicate that parameter was not used.
3826 $all = true;
3828 if (!$all and $coursecontext) {
3829 // Do not use get_enrolled_sql() here for performance reasons.
3830 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
3831 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
3832 $params['ecourseid'] = $coursecontext->instanceid;
3833 } else {
3834 $ejoin = "";
3837 $sql = "SELECT DISTINCT $fields, ra.roleid
3838 FROM {role_assignments} ra
3839 JOIN {user} u ON u.id = ra.userid
3840 JOIN {role} r ON ra.roleid = r.id
3841 $ejoin
3842 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3843 $groupjoin
3844 WHERE (ra.contextid = :contextid $parentcontexts)
3845 $roleselect
3846 $groupselect
3847 $extrawheretest
3848 ORDER BY $sort"; // join now so that we can just use fullname() later
3850 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3854 * Counts all the users assigned this role in this context or higher
3856 * @param int|array $roleid either int or an array of ints
3857 * @param context $context
3858 * @param bool $parent if true, get list of users assigned in higher context too
3859 * @return int Returns the result count
3861 function count_role_users($roleid, context $context, $parent = false) {
3862 global $DB;
3864 if ($parent) {
3865 if ($contexts = $context->get_parent_context_ids()) {
3866 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3867 } else {
3868 $parentcontexts = '';
3870 } else {
3871 $parentcontexts = '';
3874 if ($roleid) {
3875 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3876 $roleselect = "AND r.roleid $rids";
3877 } else {
3878 $params = array();
3879 $roleselect = '';
3882 array_unshift($params, $context->id);
3884 $sql = "SELECT COUNT(DISTINCT u.id)
3885 FROM {role_assignments} r
3886 JOIN {user} u ON u.id = r.userid
3887 WHERE (r.contextid = ? $parentcontexts)
3888 $roleselect
3889 AND u.deleted = 0";
3891 return $DB->count_records_sql($sql, $params);
3895 * This function gets the list of courses that this user has a particular capability in.
3897 * It is now reasonably efficient, but bear in mind that if there are users who have the capability
3898 * everywhere, it may return an array of all courses.
3900 * @param string $capability Capability in question
3901 * @param int $userid User ID or null for current user
3902 * @param bool $doanything True if 'doanything' is permitted (default)
3903 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3904 * otherwise use a comma-separated list of the fields you require, not including id.
3905 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
3906 * @param string $orderby If set, use a comma-separated list of fields from course
3907 * table with sql modifiers (DESC) if needed
3908 * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
3909 * @return array|bool Array of courses, if none found false is returned.
3911 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '',
3912 $limit = 0) {
3913 global $DB, $USER;
3915 // Default to current user.
3916 if (!$userid) {
3917 $userid = $USER->id;
3920 if ($doanything && is_siteadmin($userid)) {
3921 // If the user is a site admin and $doanything is enabled then there is no need to restrict
3922 // the list of courses.
3923 $contextlimitsql = '';
3924 $contextlimitparams = [];
3925 } else {
3926 // Gets SQL to limit contexts ('x' table) to those where the user has this capability.
3927 list ($contextlimitsql, $contextlimitparams) = \core\access\get_user_capability_course_helper::get_sql(
3928 $userid, $capability);
3929 if (!$contextlimitsql) {
3930 // If the does not have this capability in any context, return false without querying.
3931 return false;
3934 $contextlimitsql = 'WHERE' . $contextlimitsql;
3937 // Convert fields list and ordering
3938 $fieldlist = '';
3939 if ($fieldsexceptid) {
3940 $fields = array_map('trim', explode(',', $fieldsexceptid));
3941 foreach($fields as $field) {
3942 // Context fields have a different alias.
3943 if (strpos($field, 'ctx') === 0) {
3944 switch($field) {
3945 case 'ctxlevel' :
3946 $realfield = 'contextlevel';
3947 break;
3948 case 'ctxinstance' :
3949 $realfield = 'instanceid';
3950 break;
3951 default:
3952 $realfield = substr($field, 3);
3953 break;
3955 $fieldlist .= ',x.' . $realfield . ' AS ' . $field;
3956 } else {
3957 $fieldlist .= ',c.'.$field;
3961 if ($orderby) {
3962 $fields = explode(',', $orderby);
3963 $orderby = '';
3964 foreach($fields as $field) {
3965 if ($orderby) {
3966 $orderby .= ',';
3968 $orderby .= 'c.'.$field;
3970 $orderby = 'ORDER BY '.$orderby;
3973 $courses = array();
3974 $rs = $DB->get_recordset_sql("
3975 SELECT c.id $fieldlist
3976 FROM {course} c
3977 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
3978 $contextlimitsql
3979 $orderby", array_merge([CONTEXT_COURSE], $contextlimitparams));
3980 foreach ($rs as $course) {
3981 $courses[] = $course;
3982 $limit--;
3983 if ($limit == 0) {
3984 break;
3987 $rs->close();
3988 return empty($courses) ? false : $courses;
3992 * This function finds the roles assigned directly to this context only
3993 * i.e. no roles in parent contexts
3995 * @param context $context
3996 * @return array
3998 function get_roles_on_exact_context(context $context) {
3999 global $DB;
4001 return $DB->get_records_sql("SELECT r.*
4002 FROM {role_assignments} ra, {role} r
4003 WHERE ra.roleid = r.id AND ra.contextid = ?",
4004 array($context->id));
4008 * Switches the current user to another role for the current session and only
4009 * in the given context.
4011 * The caller *must* check
4012 * - that this op is allowed
4013 * - that the requested role can be switched to in this context (use get_switchable_roles)
4014 * - that the requested role is NOT $CFG->defaultuserroleid
4016 * To "unswitch" pass 0 as the roleid.
4018 * This function *will* modify $USER->access - beware
4020 * @param integer $roleid the role to switch to.
4021 * @param context $context the context in which to perform the switch.
4022 * @return bool success or failure.
4024 function role_switch($roleid, context $context) {
4025 global $USER;
4027 // Add the ghost RA to $USER->access as $USER->access['rsw'][$path] = $roleid.
4028 // To un-switch just unset($USER->access['rsw'][$path]).
4030 // Note: it is not possible to switch to roles that do not have course:view
4032 if (!isset($USER->access)) {
4033 load_all_capabilities();
4036 // Add the switch RA
4037 if ($roleid == 0) {
4038 unset($USER->access['rsw'][$context->path]);
4039 return true;
4042 $USER->access['rsw'][$context->path] = $roleid;
4044 return true;
4048 * Checks if the user has switched roles within the given course.
4050 * Note: You can only switch roles within the course, hence it takes a course id
4051 * rather than a context. On that note Petr volunteered to implement this across
4052 * all other contexts, all requests for this should be forwarded to him ;)
4054 * @param int $courseid The id of the course to check
4055 * @return bool True if the user has switched roles within the course.
4057 function is_role_switched($courseid) {
4058 global $USER;
4059 $context = context_course::instance($courseid, MUST_EXIST);
4060 return (!empty($USER->access['rsw'][$context->path]));
4064 * Get any role that has an override on exact context
4066 * @param context $context The context to check
4067 * @return array An array of roles
4069 function get_roles_with_override_on_context(context $context) {
4070 global $DB;
4072 return $DB->get_records_sql("SELECT r.*
4073 FROM {role_capabilities} rc, {role} r
4074 WHERE rc.roleid = r.id AND rc.contextid = ?",
4075 array($context->id));
4079 * Get all capabilities for this role on this context (overrides)
4081 * @param stdClass $role
4082 * @param context $context
4083 * @return array
4085 function get_capabilities_from_role_on_context($role, context $context) {
4086 global $DB;
4088 return $DB->get_records_sql("SELECT *
4089 FROM {role_capabilities}
4090 WHERE contextid = ? AND roleid = ?",
4091 array($context->id, $role->id));
4095 * Find out which roles has assignment on this context
4097 * @param context $context
4098 * @return array
4101 function get_roles_with_assignment_on_context(context $context) {
4102 global $DB;
4104 return $DB->get_records_sql("SELECT r.*
4105 FROM {role_assignments} ra, {role} r
4106 WHERE ra.roleid = r.id AND ra.contextid = ?",
4107 array($context->id));
4111 * Find all user assignment of users for this role, on this context
4113 * @param stdClass $role
4114 * @param context $context
4115 * @return array
4117 function get_users_from_role_on_context($role, context $context) {
4118 global $DB;
4120 return $DB->get_records_sql("SELECT *
4121 FROM {role_assignments}
4122 WHERE contextid = ? AND roleid = ?",
4123 array($context->id, $role->id));
4127 * Simple function returning a boolean true if user has roles
4128 * in context or parent contexts, otherwise false.
4130 * @param int $userid
4131 * @param int $roleid
4132 * @param int $contextid empty means any context
4133 * @return bool
4135 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4136 global $DB;
4138 if ($contextid) {
4139 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4140 return false;
4142 $parents = $context->get_parent_context_ids(true);
4143 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4144 $params['userid'] = $userid;
4145 $params['roleid'] = $roleid;
4147 $sql = "SELECT COUNT(ra.id)
4148 FROM {role_assignments} ra
4149 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4151 $count = $DB->get_field_sql($sql, $params);
4152 return ($count > 0);
4154 } else {
4155 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4160 * Get localised role name or alias if exists and format the text.
4162 * @param stdClass $role role object
4163 * - optional 'coursealias' property should be included for performance reasons if course context used
4164 * - description property is not required here
4165 * @param context|bool $context empty means system context
4166 * @param int $rolenamedisplay type of role name
4167 * @return string localised role name or course role name alias
4169 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4170 global $DB;
4172 if ($rolenamedisplay == ROLENAME_SHORT) {
4173 return $role->shortname;
4176 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4177 $coursecontext = null;
4180 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4181 $role = clone($role); // Do not modify parameters.
4182 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4183 $role->coursealias = $r->name;
4184 } else {
4185 $role->coursealias = null;
4189 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4190 if ($coursecontext) {
4191 return $role->coursealias;
4192 } else {
4193 return null;
4197 if (trim($role->name) !== '') {
4198 // For filtering always use context where was the thing defined - system for roles here.
4199 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4201 } else {
4202 // Empty role->name means we want to see localised role name based on shortname,
4203 // only default roles are supposed to be localised.
4204 switch ($role->shortname) {
4205 case 'manager': $original = get_string('manager', 'role'); break;
4206 case 'coursecreator': $original = get_string('coursecreators'); break;
4207 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4208 case 'teacher': $original = get_string('noneditingteacher'); break;
4209 case 'student': $original = get_string('defaultcoursestudent'); break;
4210 case 'guest': $original = get_string('guest'); break;
4211 case 'user': $original = get_string('authenticateduser'); break;
4212 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4213 // We should not get here, the role UI should require the name for custom roles!
4214 default: $original = $role->shortname; break;
4218 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4219 return $original;
4222 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4223 return "$original ($role->shortname)";
4226 if ($rolenamedisplay == ROLENAME_ALIAS) {
4227 if ($coursecontext and trim($role->coursealias) !== '') {
4228 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4229 } else {
4230 return $original;
4234 if ($rolenamedisplay == ROLENAME_BOTH) {
4235 if ($coursecontext and trim($role->coursealias) !== '') {
4236 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4237 } else {
4238 return $original;
4242 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4246 * Returns localised role description if available.
4247 * If the name is empty it tries to find the default role name using
4248 * hardcoded list of default role names or other methods in the future.
4250 * @param stdClass $role
4251 * @return string localised role name
4253 function role_get_description(stdClass $role) {
4254 if (!html_is_blank($role->description)) {
4255 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4258 switch ($role->shortname) {
4259 case 'manager': return get_string('managerdescription', 'role');
4260 case 'coursecreator': return get_string('coursecreatorsdescription');
4261 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4262 case 'teacher': return get_string('noneditingteacherdescription');
4263 case 'student': return get_string('defaultcoursestudentdescription');
4264 case 'guest': return get_string('guestdescription');
4265 case 'user': return get_string('authenticateduserdescription');
4266 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4267 default: return '';
4272 * Get all the localised role names for a context.
4274 * In new installs default roles have empty names, this function
4275 * add localised role names using current language pack.
4277 * @param context $context the context, null means system context
4278 * @param array of role objects with a ->localname field containing the context-specific role name.
4279 * @param int $rolenamedisplay
4280 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4281 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4283 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4284 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4288 * Prepare list of roles for display, apply aliases and localise default role names.
4290 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4291 * @param context $context the context, null means system context
4292 * @param int $rolenamedisplay
4293 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4294 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4296 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4297 global $DB;
4299 if (empty($roleoptions)) {
4300 return array();
4303 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4304 $coursecontext = null;
4307 // We usually need all role columns...
4308 $first = reset($roleoptions);
4309 if ($returnmenu === null) {
4310 $returnmenu = !is_object($first);
4313 if (!is_object($first) or !property_exists($first, 'shortname')) {
4314 $allroles = get_all_roles($context);
4315 foreach ($roleoptions as $rid => $unused) {
4316 $roleoptions[$rid] = $allroles[$rid];
4320 // Inject coursealias if necessary.
4321 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4322 $first = reset($roleoptions);
4323 if (!property_exists($first, 'coursealias')) {
4324 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4325 foreach ($aliasnames as $alias) {
4326 if (isset($roleoptions[$alias->roleid])) {
4327 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4333 // Add localname property.
4334 foreach ($roleoptions as $rid => $role) {
4335 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4338 if (!$returnmenu) {
4339 return $roleoptions;
4342 $menu = array();
4343 foreach ($roleoptions as $rid => $role) {
4344 $menu[$rid] = $role->localname;
4347 return $menu;
4351 * Aids in detecting if a new line is required when reading a new capability
4353 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4354 * when we read in a new capability.
4355 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4356 * but when we are in grade, all reports/import/export capabilities should be together
4358 * @param string $cap component string a
4359 * @param string $comp component string b
4360 * @param int $contextlevel
4361 * @return bool whether 2 component are in different "sections"
4363 function component_level_changed($cap, $comp, $contextlevel) {
4365 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4366 $compsa = explode('/', $cap->component);
4367 $compsb = explode('/', $comp);
4369 // list of system reports
4370 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4371 return false;
4374 // we are in gradebook, still
4375 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4376 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4377 return false;
4380 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4381 return false;
4385 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4389 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4390 * and return an array of roleids in order.
4392 * @param array $allroles array of roles, as returned by get_all_roles();
4393 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4395 function fix_role_sortorder($allroles) {
4396 global $DB;
4398 $rolesort = array();
4399 $i = 0;
4400 foreach ($allroles as $role) {
4401 $rolesort[$i] = $role->id;
4402 if ($role->sortorder != $i) {
4403 $r = new stdClass();
4404 $r->id = $role->id;
4405 $r->sortorder = $i;
4406 $DB->update_record('role', $r);
4407 $allroles[$role->id]->sortorder = $i;
4409 $i++;
4411 return $rolesort;
4415 * Switch the sort order of two roles (used in admin/roles/manage.php).
4417 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4418 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4419 * @return boolean success or failure
4421 function switch_roles($first, $second) {
4422 global $DB;
4423 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4424 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4425 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4426 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4427 return $result;
4431 * Duplicates all the base definitions of a role
4433 * @param stdClass $sourcerole role to copy from
4434 * @param int $targetrole id of role to copy to
4436 function role_cap_duplicate($sourcerole, $targetrole) {
4437 global $DB;
4439 $systemcontext = context_system::instance();
4440 $caps = $DB->get_records_sql("SELECT *
4441 FROM {role_capabilities}
4442 WHERE roleid = ? AND contextid = ?",
4443 array($sourcerole->id, $systemcontext->id));
4444 // adding capabilities
4445 foreach ($caps as $cap) {
4446 unset($cap->id);
4447 $cap->roleid = $targetrole;
4448 $DB->insert_record('role_capabilities', $cap);
4451 // Reset any cache of this role, including MUC.
4452 accesslib_clear_role_cache($targetrole);
4456 * Returns two lists, this can be used to find out if user has capability.
4457 * Having any needed role and no forbidden role in this context means
4458 * user has this capability in this context.
4459 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4461 * @param stdClass $context
4462 * @param string $capability
4463 * @return array($neededroles, $forbiddenroles)
4465 function get_roles_with_cap_in_context($context, $capability) {
4466 global $DB;
4468 $ctxids = trim($context->path, '/'); // kill leading slash
4469 $ctxids = str_replace('/', ',', $ctxids);
4471 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4472 FROM {role_capabilities} rc
4473 JOIN {context} ctx ON ctx.id = rc.contextid
4474 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4475 ORDER BY rc.roleid ASC, ctx.depth DESC";
4476 $params = array('cap'=>$capability);
4478 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4479 // no cap definitions --> no capability
4480 return array(array(), array());
4483 $forbidden = array();
4484 $needed = array();
4485 foreach($capdefs as $def) {
4486 if (isset($forbidden[$def->roleid])) {
4487 continue;
4489 if ($def->permission == CAP_PROHIBIT) {
4490 $forbidden[$def->roleid] = $def->roleid;
4491 unset($needed[$def->roleid]);
4492 continue;
4494 if (!isset($needed[$def->roleid])) {
4495 if ($def->permission == CAP_ALLOW) {
4496 $needed[$def->roleid] = true;
4497 } else if ($def->permission == CAP_PREVENT) {
4498 $needed[$def->roleid] = false;
4502 unset($capdefs);
4504 // remove all those roles not allowing
4505 foreach($needed as $key=>$value) {
4506 if (!$value) {
4507 unset($needed[$key]);
4508 } else {
4509 $needed[$key] = $key;
4513 return array($needed, $forbidden);
4517 * Returns an array of role IDs that have ALL of the the supplied capabilities
4518 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4520 * @param stdClass $context
4521 * @param array $capabilities An array of capabilities
4522 * @return array of roles with all of the required capabilities
4524 function get_roles_with_caps_in_context($context, $capabilities) {
4525 $neededarr = array();
4526 $forbiddenarr = array();
4527 foreach($capabilities as $caprequired) {
4528 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4531 $rolesthatcanrate = array();
4532 if (!empty($neededarr)) {
4533 foreach ($neededarr as $needed) {
4534 if (empty($rolesthatcanrate)) {
4535 $rolesthatcanrate = $needed;
4536 } else {
4537 //only want roles that have all caps
4538 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4542 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4543 foreach ($forbiddenarr as $forbidden) {
4544 //remove any roles that are forbidden any of the caps
4545 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4548 return $rolesthatcanrate;
4552 * Returns an array of role names that have ALL of the the supplied capabilities
4553 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4555 * @param stdClass $context
4556 * @param array $capabilities An array of capabilities
4557 * @return array of roles with all of the required capabilities
4559 function get_role_names_with_caps_in_context($context, $capabilities) {
4560 global $DB;
4562 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4563 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4565 $roles = array();
4566 foreach ($rolesthatcanrate as $r) {
4567 $roles[$r] = $allroles[$r];
4570 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4574 * This function verifies the prohibit comes from this context
4575 * and there are no more prohibits in parent contexts.
4577 * @param int $roleid
4578 * @param context $context
4579 * @param string $capability name
4580 * @return bool
4582 function prohibit_is_removable($roleid, context $context, $capability) {
4583 global $DB;
4585 $ctxids = trim($context->path, '/'); // kill leading slash
4586 $ctxids = str_replace('/', ',', $ctxids);
4588 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4590 $sql = "SELECT ctx.id
4591 FROM {role_capabilities} rc
4592 JOIN {context} ctx ON ctx.id = rc.contextid
4593 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4594 ORDER BY ctx.depth DESC";
4596 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4597 // no prohibits == nothing to remove
4598 return true;
4601 if (count($prohibits) > 1) {
4602 // more prohibits can not be removed
4603 return false;
4606 return !empty($prohibits[$context->id]);
4610 * More user friendly role permission changing,
4611 * it should produce as few overrides as possible.
4613 * @param int $roleid
4614 * @param stdClass $context
4615 * @param string $capname capability name
4616 * @param int $permission
4617 * @return void
4619 function role_change_permission($roleid, $context, $capname, $permission) {
4620 global $DB;
4622 if ($permission == CAP_INHERIT) {
4623 unassign_capability($capname, $roleid, $context->id);
4624 $context->mark_dirty();
4625 return;
4628 $ctxids = trim($context->path, '/'); // kill leading slash
4629 $ctxids = str_replace('/', ',', $ctxids);
4631 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4633 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4634 FROM {role_capabilities} rc
4635 JOIN {context} ctx ON ctx.id = rc.contextid
4636 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4637 ORDER BY ctx.depth DESC";
4639 if ($existing = $DB->get_records_sql($sql, $params)) {
4640 foreach($existing as $e) {
4641 if ($e->permission == CAP_PROHIBIT) {
4642 // prohibit can not be overridden, no point in changing anything
4643 return;
4646 $lowest = array_shift($existing);
4647 if ($lowest->permission == $permission) {
4648 // permission already set in this context or parent - nothing to do
4649 return;
4651 if ($existing) {
4652 $parent = array_shift($existing);
4653 if ($parent->permission == $permission) {
4654 // permission already set in parent context or parent - just unset in this context
4655 // we do this because we want as few overrides as possible for performance reasons
4656 unassign_capability($capname, $roleid, $context->id);
4657 $context->mark_dirty();
4658 return;
4662 } else {
4663 if ($permission == CAP_PREVENT) {
4664 // nothing means role does not have permission
4665 return;
4669 // assign the needed capability
4670 assign_capability($capname, $permission, $roleid, $context->id, true);
4672 // force cap reloading
4673 $context->mark_dirty();
4678 * Basic moodle context abstraction class.
4680 * Google confirms that no other important framework is using "context" class,
4681 * we could use something else like mcontext or moodle_context, but we need to type
4682 * this very often which would be annoying and it would take too much space...
4684 * This class is derived from stdClass for backwards compatibility with
4685 * odl $context record that was returned from DML $DB->get_record()
4687 * @package core_access
4688 * @category access
4689 * @copyright Petr Skoda {@link http://skodak.org}
4690 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4691 * @since Moodle 2.2
4693 * @property-read int $id context id
4694 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4695 * @property-read int $instanceid id of related instance in each context
4696 * @property-read string $path path to context, starts with system context
4697 * @property-read int $depth
4699 abstract class context extends stdClass implements IteratorAggregate {
4702 * The context id
4703 * Can be accessed publicly through $context->id
4704 * @var int
4706 protected $_id;
4709 * The context level
4710 * Can be accessed publicly through $context->contextlevel
4711 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4713 protected $_contextlevel;
4716 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4717 * Can be accessed publicly through $context->instanceid
4718 * @var int
4720 protected $_instanceid;
4723 * The path to the context always starting from the system context
4724 * Can be accessed publicly through $context->path
4725 * @var string
4727 protected $_path;
4730 * The depth of the context in relation to parent contexts
4731 * Can be accessed publicly through $context->depth
4732 * @var int
4734 protected $_depth;
4737 * @var array Context caching info
4739 private static $cache_contextsbyid = array();
4742 * @var array Context caching info
4744 private static $cache_contexts = array();
4747 * Context count
4748 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4749 * @var int
4751 protected static $cache_count = 0;
4754 * @var array Context caching info
4756 protected static $cache_preloaded = array();
4759 * @var context_system The system context once initialised
4761 protected static $systemcontext = null;
4764 * Resets the cache to remove all data.
4765 * @static
4767 protected static function reset_caches() {
4768 self::$cache_contextsbyid = array();
4769 self::$cache_contexts = array();
4770 self::$cache_count = 0;
4771 self::$cache_preloaded = array();
4773 self::$systemcontext = null;
4777 * Adds a context to the cache. If the cache is full, discards a batch of
4778 * older entries.
4780 * @static
4781 * @param context $context New context to add
4782 * @return void
4784 protected static function cache_add(context $context) {
4785 if (isset(self::$cache_contextsbyid[$context->id])) {
4786 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4787 return;
4790 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4791 $i = 0;
4792 foreach(self::$cache_contextsbyid as $ctx) {
4793 $i++;
4794 if ($i <= 100) {
4795 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4796 continue;
4798 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4799 // we remove oldest third of the contexts to make room for more contexts
4800 break;
4802 unset(self::$cache_contextsbyid[$ctx->id]);
4803 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4804 self::$cache_count--;
4808 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4809 self::$cache_contextsbyid[$context->id] = $context;
4810 self::$cache_count++;
4814 * Removes a context from the cache.
4816 * @static
4817 * @param context $context Context object to remove
4818 * @return void
4820 protected static function cache_remove(context $context) {
4821 if (!isset(self::$cache_contextsbyid[$context->id])) {
4822 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4823 return;
4825 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4826 unset(self::$cache_contextsbyid[$context->id]);
4828 self::$cache_count--;
4830 if (self::$cache_count < 0) {
4831 self::$cache_count = 0;
4836 * Gets a context from the cache.
4838 * @static
4839 * @param int $contextlevel Context level
4840 * @param int $instance Instance ID
4841 * @return context|bool Context or false if not in cache
4843 protected static function cache_get($contextlevel, $instance) {
4844 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4845 return self::$cache_contexts[$contextlevel][$instance];
4847 return false;
4851 * Gets a context from the cache based on its id.
4853 * @static
4854 * @param int $id Context ID
4855 * @return context|bool Context or false if not in cache
4857 protected static function cache_get_by_id($id) {
4858 if (isset(self::$cache_contextsbyid[$id])) {
4859 return self::$cache_contextsbyid[$id];
4861 return false;
4865 * Preloads context information from db record and strips the cached info.
4867 * @static
4868 * @param stdClass $rec
4869 * @return void (modifies $rec)
4871 protected static function preload_from_record(stdClass $rec) {
4872 if (empty($rec->ctxid) or empty($rec->ctxlevel) or !isset($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
4873 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4874 return;
4877 // note: in PHP5 the objects are passed by reference, no need to return $rec
4878 $record = new stdClass();
4879 $record->id = $rec->ctxid; unset($rec->ctxid);
4880 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
4881 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
4882 $record->path = $rec->ctxpath; unset($rec->ctxpath);
4883 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
4885 return context::create_instance_from_record($record);
4889 // ====== magic methods =======
4892 * Magic setter method, we do not want anybody to modify properties from the outside
4893 * @param string $name
4894 * @param mixed $value
4896 public function __set($name, $value) {
4897 debugging('Can not change context instance properties!');
4901 * Magic method getter, redirects to read only values.
4902 * @param string $name
4903 * @return mixed
4905 public function __get($name) {
4906 switch ($name) {
4907 case 'id': return $this->_id;
4908 case 'contextlevel': return $this->_contextlevel;
4909 case 'instanceid': return $this->_instanceid;
4910 case 'path': return $this->_path;
4911 case 'depth': return $this->_depth;
4913 default:
4914 debugging('Invalid context property accessed! '.$name);
4915 return null;
4920 * Full support for isset on our magic read only properties.
4921 * @param string $name
4922 * @return bool
4924 public function __isset($name) {
4925 switch ($name) {
4926 case 'id': return isset($this->_id);
4927 case 'contextlevel': return isset($this->_contextlevel);
4928 case 'instanceid': return isset($this->_instanceid);
4929 case 'path': return isset($this->_path);
4930 case 'depth': return isset($this->_depth);
4932 default: return false;
4938 * ALl properties are read only, sorry.
4939 * @param string $name
4941 public function __unset($name) {
4942 debugging('Can not unset context instance properties!');
4945 // ====== implementing method from interface IteratorAggregate ======
4948 * Create an iterator because magic vars can't be seen by 'foreach'.
4950 * Now we can convert context object to array using convert_to_array(),
4951 * and feed it properly to json_encode().
4953 public function getIterator() {
4954 $ret = array(
4955 'id' => $this->id,
4956 'contextlevel' => $this->contextlevel,
4957 'instanceid' => $this->instanceid,
4958 'path' => $this->path,
4959 'depth' => $this->depth
4961 return new ArrayIterator($ret);
4964 // ====== general context methods ======
4967 * Constructor is protected so that devs are forced to
4968 * use context_xxx::instance() or context::instance_by_id().
4970 * @param stdClass $record
4972 protected function __construct(stdClass $record) {
4973 $this->_id = (int)$record->id;
4974 $this->_contextlevel = (int)$record->contextlevel;
4975 $this->_instanceid = $record->instanceid;
4976 $this->_path = $record->path;
4977 $this->_depth = $record->depth;
4981 * This function is also used to work around 'protected' keyword problems in context_helper.
4982 * @static
4983 * @param stdClass $record
4984 * @return context instance
4986 protected static function create_instance_from_record(stdClass $record) {
4987 $classname = context_helper::get_class_for_level($record->contextlevel);
4989 if ($context = context::cache_get_by_id($record->id)) {
4990 return $context;
4993 $context = new $classname($record);
4994 context::cache_add($context);
4996 return $context;
5000 * Copy prepared new contexts from temp table to context table,
5001 * we do this in db specific way for perf reasons only.
5002 * @static
5004 protected static function merge_context_temp_table() {
5005 global $DB;
5007 /* MDL-11347:
5008 * - mysql does not allow to use FROM in UPDATE statements
5009 * - using two tables after UPDATE works in mysql, but might give unexpected
5010 * results in pg 8 (depends on configuration)
5011 * - using table alias in UPDATE does not work in pg < 8.2
5013 * Different code for each database - mostly for performance reasons
5016 $dbfamily = $DB->get_dbfamily();
5017 if ($dbfamily == 'mysql') {
5018 $updatesql = "UPDATE {context} ct, {context_temp} temp
5019 SET ct.path = temp.path,
5020 ct.depth = temp.depth
5021 WHERE ct.id = temp.id";
5022 } else if ($dbfamily == 'oracle') {
5023 $updatesql = "UPDATE {context} ct
5024 SET (ct.path, ct.depth) =
5025 (SELECT temp.path, temp.depth
5026 FROM {context_temp} temp
5027 WHERE temp.id=ct.id)
5028 WHERE EXISTS (SELECT 'x'
5029 FROM {context_temp} temp
5030 WHERE temp.id = ct.id)";
5031 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5032 $updatesql = "UPDATE {context}
5033 SET path = temp.path,
5034 depth = temp.depth
5035 FROM {context_temp} temp
5036 WHERE temp.id={context}.id";
5037 } else {
5038 // sqlite and others
5039 $updatesql = "UPDATE {context}
5040 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5041 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5042 WHERE id IN (SELECT id FROM {context_temp})";
5045 $DB->execute($updatesql);
5049 * Get a context instance as an object, from a given context id.
5051 * @static
5052 * @param int $id context id
5053 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5054 * MUST_EXIST means throw exception if no record found
5055 * @return context|bool the context object or false if not found
5057 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5058 global $DB;
5060 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5061 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5062 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5065 if ($id == SYSCONTEXTID) {
5066 return context_system::instance(0, $strictness);
5069 if (is_array($id) or is_object($id) or empty($id)) {
5070 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5073 if ($context = context::cache_get_by_id($id)) {
5074 return $context;
5077 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5078 return context::create_instance_from_record($record);
5081 return false;
5085 * Update context info after moving context in the tree structure.
5087 * @param context $newparent
5088 * @return void
5090 public function update_moved(context $newparent) {
5091 global $DB;
5093 $frompath = $this->_path;
5094 $newpath = $newparent->path . '/' . $this->_id;
5096 $trans = $DB->start_delegated_transaction();
5098 $this->mark_dirty();
5100 $setdepth = '';
5101 if (($newparent->depth +1) != $this->_depth) {
5102 $diff = $newparent->depth - $this->_depth + 1;
5103 $setdepth = ", depth = depth + $diff";
5105 $sql = "UPDATE {context}
5106 SET path = ?
5107 $setdepth
5108 WHERE id = ?";
5109 $params = array($newpath, $this->_id);
5110 $DB->execute($sql, $params);
5112 $this->_path = $newpath;
5113 $this->_depth = $newparent->depth + 1;
5115 $sql = "UPDATE {context}
5116 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5117 $setdepth
5118 WHERE path LIKE ?";
5119 $params = array($newpath, "{$frompath}/%");
5120 $DB->execute($sql, $params);
5122 $this->mark_dirty();
5124 context::reset_caches();
5126 $trans->allow_commit();
5130 * Remove all context path info and optionally rebuild it.
5132 * @param bool $rebuild
5133 * @return void
5135 public function reset_paths($rebuild = true) {
5136 global $DB;
5138 if ($this->_path) {
5139 $this->mark_dirty();
5141 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5142 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5143 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5144 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5145 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5146 $this->_depth = 0;
5147 $this->_path = null;
5150 if ($rebuild) {
5151 context_helper::build_all_paths(false);
5154 context::reset_caches();
5158 * Delete all data linked to content, do not delete the context record itself
5160 public function delete_content() {
5161 global $CFG, $DB;
5163 blocks_delete_all_for_context($this->_id);
5164 filter_delete_all_for_context($this->_id);
5166 require_once($CFG->dirroot . '/comment/lib.php');
5167 comment::delete_comments(array('contextid'=>$this->_id));
5169 require_once($CFG->dirroot.'/rating/lib.php');
5170 $delopt = new stdclass();
5171 $delopt->contextid = $this->_id;
5172 $rm = new rating_manager();
5173 $rm->delete_ratings($delopt);
5175 // delete all files attached to this context
5176 $fs = get_file_storage();
5177 $fs->delete_area_files($this->_id);
5179 // Delete all repository instances attached to this context.
5180 require_once($CFG->dirroot . '/repository/lib.php');
5181 repository::delete_all_for_context($this->_id);
5183 // delete all advanced grading data attached to this context
5184 require_once($CFG->dirroot.'/grade/grading/lib.php');
5185 grading_manager::delete_all_for_context($this->_id);
5187 $ids = $DB->get_fieldset_select('role_capabilities', 'DISTINCT roleid', 'contextid = ?', array($this->_id));
5189 // now delete stuff from role related tables, role_unassign_all
5190 // and unenrol should be called earlier to do proper cleanup
5191 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5192 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5193 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5195 if ($ids) {
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);
5222 // do not mark dirty contexts if parents unknown
5223 if (!is_null($this->_path) and $this->_depth > 0) {
5224 $this->mark_dirty();
5228 // ====== context level related methods ======
5231 * Utility method for context creation
5233 * @static
5234 * @param int $contextlevel
5235 * @param int $instanceid
5236 * @param string $parentpath
5237 * @return stdClass context record
5239 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5240 global $DB;
5242 $record = new stdClass();
5243 $record->contextlevel = $contextlevel;
5244 $record->instanceid = $instanceid;
5245 $record->depth = 0;
5246 $record->path = null; //not known before insert
5248 $record->id = $DB->insert_record('context', $record);
5250 // now add path if known - it can be added later
5251 if (!is_null($parentpath)) {
5252 $record->path = $parentpath.'/'.$record->id;
5253 $record->depth = substr_count($record->path, '/');
5254 $DB->update_record('context', $record);
5257 return $record;
5261 * Returns human readable context identifier.
5263 * @param boolean $withprefix whether to prefix the name of the context with the
5264 * type of context, e.g. User, Course, Forum, etc.
5265 * @param boolean $short whether to use the short name of the thing. Only applies
5266 * to course contexts
5267 * @return string the human readable context name.
5269 public function get_context_name($withprefix = true, $short = false) {
5270 // must be implemented in all context levels
5271 throw new coding_exception('can not get name of abstract context');
5275 * Returns the most relevant URL for this context.
5277 * @return moodle_url
5279 public abstract function get_url();
5282 * Returns array of relevant context capability records.
5284 * @return array
5286 public abstract function get_capabilities();
5289 * Recursive function which, given a context, find all its children context ids.
5291 * For course category contexts it will return immediate children and all subcategory contexts.
5292 * It will NOT recurse into courses or subcategories categories.
5293 * If you want to do that, call it on the returned courses/categories.
5295 * When called for a course context, it will return the modules and blocks
5296 * displayed in the course page and blocks displayed on the module pages.
5298 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5299 * contexts ;-)
5301 * @return array Array of child records
5303 public function get_child_contexts() {
5304 global $DB;
5306 if (empty($this->_path) or empty($this->_depth)) {
5307 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5308 return array();
5311 $sql = "SELECT ctx.*
5312 FROM {context} ctx
5313 WHERE ctx.path LIKE ?";
5314 $params = array($this->_path.'/%');
5315 $records = $DB->get_records_sql($sql, $params);
5317 $result = array();
5318 foreach ($records as $record) {
5319 $result[$record->id] = context::create_instance_from_record($record);
5322 return $result;
5326 * Returns parent contexts of this context in reversed order, i.e. parent first,
5327 * then grand parent, etc.
5329 * @param bool $includeself tre means include self too
5330 * @return array of context instances
5332 public function get_parent_contexts($includeself = false) {
5333 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5334 return array();
5337 $result = array();
5338 foreach ($contextids as $contextid) {
5339 $parent = context::instance_by_id($contextid, MUST_EXIST);
5340 $result[$parent->id] = $parent;
5343 return $result;
5347 * Returns parent contexts of this context in reversed order, i.e. parent first,
5348 * then grand parent, etc.
5350 * @param bool $includeself tre means include self too
5351 * @return array of context ids
5353 public function get_parent_context_ids($includeself = false) {
5354 if (empty($this->_path)) {
5355 return array();
5358 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5359 $parentcontexts = explode('/', $parentcontexts);
5360 if (!$includeself) {
5361 array_pop($parentcontexts); // and remove its own id
5364 return array_reverse($parentcontexts);
5368 * Returns parent context
5370 * @return context
5372 public function get_parent_context() {
5373 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5374 return false;
5377 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5378 $parentcontexts = explode('/', $parentcontexts);
5379 array_pop($parentcontexts); // self
5380 $contextid = array_pop($parentcontexts); // immediate parent
5382 return context::instance_by_id($contextid, MUST_EXIST);
5386 * Is this context part of any course? If yes return course context.
5388 * @param bool $strict true means throw exception if not found, false means return false if not found
5389 * @return context_course context of the enclosing course, null if not found or exception
5391 public function get_course_context($strict = true) {
5392 if ($strict) {
5393 throw new coding_exception('Context does not belong to any course.');
5394 } else {
5395 return false;
5400 * Returns sql necessary for purging of stale context instances.
5402 * @static
5403 * @return string cleanup SQL
5405 protected static function get_cleanup_sql() {
5406 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5410 * Rebuild context paths and depths at context level.
5412 * @static
5413 * @param bool $force
5414 * @return void
5416 protected static function build_paths($force) {
5417 throw new coding_exception('build_paths() method must be implemented in all context levels');
5421 * Create missing context instances at given level
5423 * @static
5424 * @return void
5426 protected static function create_level_instances() {
5427 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5431 * Reset all cached permissions and definitions if the necessary.
5432 * @return void
5434 public function reload_if_dirty() {
5435 global $ACCESSLIB_PRIVATE, $USER;
5437 // Load dirty contexts list if needed
5438 if (CLI_SCRIPT) {
5439 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5440 // we do not load dirty flags in CLI and cron
5441 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5443 } else {
5444 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5445 if (!isset($USER->access['time'])) {
5446 // nothing was loaded yet, we do not need to check dirty contexts now
5447 return;
5449 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5450 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5454 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5455 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5456 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5457 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5458 reload_all_capabilities();
5459 break;
5465 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5467 public function mark_dirty() {
5468 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5470 if (during_initial_install()) {
5471 return;
5474 // only if it is a non-empty string
5475 if (is_string($this->_path) && $this->_path !== '') {
5476 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5477 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5478 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5479 } else {
5480 if (CLI_SCRIPT) {
5481 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5482 } else {
5483 if (isset($USER->access['time'])) {
5484 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5485 } else {
5486 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5488 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5497 * Context maintenance and helper methods.
5499 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5500 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5501 * level implementation from the rest of code, the code completion returns what developers need.
5503 * Thank you Tim Hunt for helping me with this nasty trick.
5505 * @package core_access
5506 * @category access
5507 * @copyright Petr Skoda {@link http://skodak.org}
5508 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5509 * @since Moodle 2.2
5511 class context_helper extends context {
5514 * @var array An array mapping context levels to classes
5516 private static $alllevels;
5519 * Instance does not make sense here, only static use
5521 protected function __construct() {
5525 * Reset internal context levels array.
5527 public static function reset_levels() {
5528 self::$alllevels = null;
5532 * Initialise context levels, call before using self::$alllevels.
5534 private static function init_levels() {
5535 global $CFG;
5537 if (isset(self::$alllevels)) {
5538 return;
5540 self::$alllevels = array(
5541 CONTEXT_SYSTEM => 'context_system',
5542 CONTEXT_USER => 'context_user',
5543 CONTEXT_COURSECAT => 'context_coursecat',
5544 CONTEXT_COURSE => 'context_course',
5545 CONTEXT_MODULE => 'context_module',
5546 CONTEXT_BLOCK => 'context_block',
5549 if (empty($CFG->custom_context_classes)) {
5550 return;
5553 $levels = $CFG->custom_context_classes;
5554 if (!is_array($levels)) {
5555 $levels = @unserialize($levels);
5557 if (!is_array($levels)) {
5558 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
5559 return;
5562 // Unsupported custom levels, use with care!!!
5563 foreach ($levels as $level => $classname) {
5564 self::$alllevels[$level] = $classname;
5566 ksort(self::$alllevels);
5570 * Returns a class name of the context level class
5572 * @static
5573 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5574 * @return string class name of the context class
5576 public static function get_class_for_level($contextlevel) {
5577 self::init_levels();
5578 if (isset(self::$alllevels[$contextlevel])) {
5579 return self::$alllevels[$contextlevel];
5580 } else {
5581 throw new coding_exception('Invalid context level specified');
5586 * Returns a list of all context levels
5588 * @static
5589 * @return array int=>string (level=>level class name)
5591 public static function get_all_levels() {
5592 self::init_levels();
5593 return self::$alllevels;
5597 * Remove stale contexts that belonged to deleted instances.
5598 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5600 * @static
5601 * @return void
5603 public static function cleanup_instances() {
5604 global $DB;
5605 self::init_levels();
5607 $sqls = array();
5608 foreach (self::$alllevels as $level=>$classname) {
5609 $sqls[] = $classname::get_cleanup_sql();
5612 $sql = implode(" UNION ", $sqls);
5614 // it is probably better to use transactions, it might be faster too
5615 $transaction = $DB->start_delegated_transaction();
5617 $rs = $DB->get_recordset_sql($sql);
5618 foreach ($rs as $record) {
5619 $context = context::create_instance_from_record($record);
5620 $context->delete();
5622 $rs->close();
5624 $transaction->allow_commit();
5628 * Create all context instances at the given level and above.
5630 * @static
5631 * @param int $contextlevel null means all levels
5632 * @param bool $buildpaths
5633 * @return void
5635 public static function create_instances($contextlevel = null, $buildpaths = true) {
5636 self::init_levels();
5637 foreach (self::$alllevels as $level=>$classname) {
5638 if ($contextlevel and $level > $contextlevel) {
5639 // skip potential sub-contexts
5640 continue;
5642 $classname::create_level_instances();
5643 if ($buildpaths) {
5644 $classname::build_paths(false);
5650 * Rebuild paths and depths in all context levels.
5652 * @static
5653 * @param bool $force false means add missing only
5654 * @return void
5656 public static function build_all_paths($force = false) {
5657 self::init_levels();
5658 foreach (self::$alllevels as $classname) {
5659 $classname::build_paths($force);
5662 // reset static course cache - it might have incorrect cached data
5663 accesslib_clear_all_caches(true);
5667 * Resets the cache to remove all data.
5668 * @static
5670 public static function reset_caches() {
5671 context::reset_caches();
5675 * Returns all fields necessary for context preloading from user $rec.
5677 * This helps with performance when dealing with hundreds of contexts.
5679 * @static
5680 * @param string $tablealias context table alias in the query
5681 * @return array (table.column=>alias, ...)
5683 public static function get_preload_record_columns($tablealias) {
5684 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5688 * Returns all fields necessary for context preloading from user $rec.
5690 * This helps with performance when dealing with hundreds of contexts.
5692 * @static
5693 * @param string $tablealias context table alias in the query
5694 * @return string
5696 public static function get_preload_record_columns_sql($tablealias) {
5697 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5701 * Preloads context information from db record and strips the cached info.
5703 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5705 * @static
5706 * @param stdClass $rec
5707 * @return void (modifies $rec)
5709 public static function preload_from_record(stdClass $rec) {
5710 context::preload_from_record($rec);
5714 * Preload all contexts instances from course.
5716 * To be used if you expect multiple queries for course activities...
5718 * @static
5719 * @param int $courseid
5721 public static function preload_course($courseid) {
5722 // Users can call this multiple times without doing any harm
5723 if (isset(context::$cache_preloaded[$courseid])) {
5724 return;
5726 $coursecontext = context_course::instance($courseid);
5727 $coursecontext->get_child_contexts();
5729 context::$cache_preloaded[$courseid] = true;
5733 * Delete context instance
5735 * @static
5736 * @param int $contextlevel
5737 * @param int $instanceid
5738 * @return void
5740 public static function delete_instance($contextlevel, $instanceid) {
5741 global $DB;
5743 // double check the context still exists
5744 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5745 $context = context::create_instance_from_record($record);
5746 $context->delete();
5747 } else {
5748 // we should try to purge the cache anyway
5753 * Returns the name of specified context level
5755 * @static
5756 * @param int $contextlevel
5757 * @return string name of the context level
5759 public static function get_level_name($contextlevel) {
5760 $classname = context_helper::get_class_for_level($contextlevel);
5761 return $classname::get_level_name();
5765 * not used
5767 public function get_url() {
5771 * not used
5773 public function get_capabilities() {
5779 * System context class
5781 * @package core_access
5782 * @category access
5783 * @copyright Petr Skoda {@link http://skodak.org}
5784 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5785 * @since Moodle 2.2
5787 class context_system extends context {
5789 * Please use context_system::instance() if you need the instance of context.
5791 * @param stdClass $record
5793 protected function __construct(stdClass $record) {
5794 parent::__construct($record);
5795 if ($record->contextlevel != CONTEXT_SYSTEM) {
5796 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5801 * Returns human readable context level name.
5803 * @static
5804 * @return string the human readable context level name.
5806 public static function get_level_name() {
5807 return get_string('coresystem');
5811 * Returns human readable context identifier.
5813 * @param boolean $withprefix does not apply to system context
5814 * @param boolean $short does not apply to system context
5815 * @return string the human readable context name.
5817 public function get_context_name($withprefix = true, $short = false) {
5818 return self::get_level_name();
5822 * Returns the most relevant URL for this context.
5824 * @return moodle_url
5826 public function get_url() {
5827 return new moodle_url('/');
5831 * Returns array of relevant context capability records.
5833 * @return array
5835 public function get_capabilities() {
5836 global $DB;
5838 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5840 $params = array();
5841 $sql = "SELECT *
5842 FROM {capabilities}";
5844 return $DB->get_records_sql($sql.' '.$sort, $params);
5848 * Create missing context instances at system context
5849 * @static
5851 protected static function create_level_instances() {
5852 // nothing to do here, the system context is created automatically in installer
5853 self::instance(0);
5857 * Returns system context instance.
5859 * @static
5860 * @param int $instanceid should be 0
5861 * @param int $strictness
5862 * @param bool $cache
5863 * @return context_system context instance
5865 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
5866 global $DB;
5868 if ($instanceid != 0) {
5869 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5872 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5873 if (!isset(context::$systemcontext)) {
5874 $record = new stdClass();
5875 $record->id = SYSCONTEXTID;
5876 $record->contextlevel = CONTEXT_SYSTEM;
5877 $record->instanceid = 0;
5878 $record->path = '/'.SYSCONTEXTID;
5879 $record->depth = 1;
5880 context::$systemcontext = new context_system($record);
5882 return context::$systemcontext;
5886 try {
5887 // We ignore the strictness completely because system context must exist except during install.
5888 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5889 } catch (dml_exception $e) {
5890 //table or record does not exist
5891 if (!during_initial_install()) {
5892 // do not mess with system context after install, it simply must exist
5893 throw $e;
5895 $record = null;
5898 if (!$record) {
5899 $record = new stdClass();
5900 $record->contextlevel = CONTEXT_SYSTEM;
5901 $record->instanceid = 0;
5902 $record->depth = 1;
5903 $record->path = null; //not known before insert
5905 try {
5906 if ($DB->count_records('context')) {
5907 // contexts already exist, this is very weird, system must be first!!!
5908 return null;
5910 if (defined('SYSCONTEXTID')) {
5911 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5912 $record->id = SYSCONTEXTID;
5913 $DB->import_record('context', $record);
5914 $DB->get_manager()->reset_sequence('context');
5915 } else {
5916 $record->id = $DB->insert_record('context', $record);
5918 } catch (dml_exception $e) {
5919 // can not create context - table does not exist yet, sorry
5920 return null;
5924 if ($record->instanceid != 0) {
5925 // this is very weird, somebody must be messing with context table
5926 debugging('Invalid system context detected');
5929 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5930 // fix path if necessary, initial install or path reset
5931 $record->depth = 1;
5932 $record->path = '/'.$record->id;
5933 $DB->update_record('context', $record);
5936 if (!defined('SYSCONTEXTID')) {
5937 define('SYSCONTEXTID', $record->id);
5940 context::$systemcontext = new context_system($record);
5941 return context::$systemcontext;
5945 * Returns all site contexts except the system context, DO NOT call on production servers!!
5947 * Contexts are not cached.
5949 * @return array
5951 public function get_child_contexts() {
5952 global $DB;
5954 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
5956 // Just get all the contexts except for CONTEXT_SYSTEM level
5957 // and hope we don't OOM in the process - don't cache
5958 $sql = "SELECT c.*
5959 FROM {context} c
5960 WHERE contextlevel > ".CONTEXT_SYSTEM;
5961 $records = $DB->get_records_sql($sql);
5963 $result = array();
5964 foreach ($records as $record) {
5965 $result[$record->id] = context::create_instance_from_record($record);
5968 return $result;
5972 * Returns sql necessary for purging of stale context instances.
5974 * @static
5975 * @return string cleanup SQL
5977 protected static function get_cleanup_sql() {
5978 $sql = "
5979 SELECT c.*
5980 FROM {context} c
5981 WHERE 1=2
5984 return $sql;
5988 * Rebuild context paths and depths at system context level.
5990 * @static
5991 * @param bool $force
5993 protected static function build_paths($force) {
5994 global $DB;
5996 /* note: ignore $force here, we always do full test of system context */
5998 // exactly one record must exist
5999 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6001 if ($record->instanceid != 0) {
6002 debugging('Invalid system context detected');
6005 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6006 debugging('Invalid SYSCONTEXTID detected');
6009 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6010 // fix path if necessary, initial install or path reset
6011 $record->depth = 1;
6012 $record->path = '/'.$record->id;
6013 $DB->update_record('context', $record);
6020 * User context class
6022 * @package core_access
6023 * @category access
6024 * @copyright Petr Skoda {@link http://skodak.org}
6025 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6026 * @since Moodle 2.2
6028 class context_user extends context {
6030 * Please use context_user::instance($userid) if you need the instance of context.
6031 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6033 * @param stdClass $record
6035 protected function __construct(stdClass $record) {
6036 parent::__construct($record);
6037 if ($record->contextlevel != CONTEXT_USER) {
6038 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6043 * Returns human readable context level name.
6045 * @static
6046 * @return string the human readable context level name.
6048 public static function get_level_name() {
6049 return get_string('user');
6053 * Returns human readable context identifier.
6055 * @param boolean $withprefix whether to prefix the name of the context with User
6056 * @param boolean $short does not apply to user context
6057 * @return string the human readable context name.
6059 public function get_context_name($withprefix = true, $short = false) {
6060 global $DB;
6062 $name = '';
6063 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6064 if ($withprefix){
6065 $name = get_string('user').': ';
6067 $name .= fullname($user);
6069 return $name;
6073 * Returns the most relevant URL for this context.
6075 * @return moodle_url
6077 public function get_url() {
6078 global $COURSE;
6080 if ($COURSE->id == SITEID) {
6081 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6082 } else {
6083 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6085 return $url;
6089 * Returns array of relevant context capability records.
6091 * @return array
6093 public function get_capabilities() {
6094 global $DB;
6096 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6098 $extracaps = array('moodle/grade:viewall');
6099 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6100 $sql = "SELECT *
6101 FROM {capabilities}
6102 WHERE contextlevel = ".CONTEXT_USER."
6103 OR name $extra";
6105 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6109 * Returns user context instance.
6111 * @static
6112 * @param int $userid id from {user} table
6113 * @param int $strictness
6114 * @return context_user context instance
6116 public static function instance($userid, $strictness = MUST_EXIST) {
6117 global $DB;
6119 if ($context = context::cache_get(CONTEXT_USER, $userid)) {
6120 return $context;
6123 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER, 'instanceid' => $userid))) {
6124 if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6125 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6129 if ($record) {
6130 $context = new context_user($record);
6131 context::cache_add($context);
6132 return $context;
6135 return false;
6139 * Create missing context instances at user context level
6140 * @static
6142 protected static function create_level_instances() {
6143 global $DB;
6145 $sql = "SELECT ".CONTEXT_USER.", u.id
6146 FROM {user} u
6147 WHERE u.deleted = 0
6148 AND NOT EXISTS (SELECT 'x'
6149 FROM {context} cx
6150 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6151 $contextdata = $DB->get_recordset_sql($sql);
6152 foreach ($contextdata as $context) {
6153 context::insert_context_record(CONTEXT_USER, $context->id, null);
6155 $contextdata->close();
6159 * Returns sql necessary for purging of stale context instances.
6161 * @static
6162 * @return string cleanup SQL
6164 protected static function get_cleanup_sql() {
6165 $sql = "
6166 SELECT c.*
6167 FROM {context} c
6168 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6169 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6172 return $sql;
6176 * Rebuild context paths and depths at user context level.
6178 * @static
6179 * @param bool $force
6181 protected static function build_paths($force) {
6182 global $DB;
6184 // First update normal users.
6185 $path = $DB->sql_concat('?', 'id');
6186 $pathstart = '/' . SYSCONTEXTID . '/';
6187 $params = array($pathstart);
6189 if ($force) {
6190 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6191 $params[] = $pathstart;
6192 } else {
6193 $where = "depth = 0 OR path IS NULL";
6196 $sql = "UPDATE {context}
6197 SET depth = 2,
6198 path = {$path}
6199 WHERE contextlevel = " . CONTEXT_USER . "
6200 AND ($where)";
6201 $DB->execute($sql, $params);
6207 * Course category context class
6209 * @package core_access
6210 * @category access
6211 * @copyright Petr Skoda {@link http://skodak.org}
6212 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6213 * @since Moodle 2.2
6215 class context_coursecat extends context {
6217 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6218 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6220 * @param stdClass $record
6222 protected function __construct(stdClass $record) {
6223 parent::__construct($record);
6224 if ($record->contextlevel != CONTEXT_COURSECAT) {
6225 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6230 * Returns human readable context level name.
6232 * @static
6233 * @return string the human readable context level name.
6235 public static function get_level_name() {
6236 return get_string('category');
6240 * Returns human readable context identifier.
6242 * @param boolean $withprefix whether to prefix the name of the context with Category
6243 * @param boolean $short does not apply to course categories
6244 * @return string the human readable context name.
6246 public function get_context_name($withprefix = true, $short = false) {
6247 global $DB;
6249 $name = '';
6250 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6251 if ($withprefix){
6252 $name = get_string('category').': ';
6254 $name .= format_string($category->name, true, array('context' => $this));
6256 return $name;
6260 * Returns the most relevant URL for this context.
6262 * @return moodle_url
6264 public function get_url() {
6265 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6269 * Returns array of relevant context capability records.
6271 * @return array
6273 public function get_capabilities() {
6274 global $DB;
6276 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6278 $params = array();
6279 $sql = "SELECT *
6280 FROM {capabilities}
6281 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6283 return $DB->get_records_sql($sql.' '.$sort, $params);
6287 * Returns course category context instance.
6289 * @static
6290 * @param int $categoryid id from {course_categories} table
6291 * @param int $strictness
6292 * @return context_coursecat context instance
6294 public static function instance($categoryid, $strictness = MUST_EXIST) {
6295 global $DB;
6297 if ($context = context::cache_get(CONTEXT_COURSECAT, $categoryid)) {
6298 return $context;
6301 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT, 'instanceid' => $categoryid))) {
6302 if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6303 if ($category->parent) {
6304 $parentcontext = context_coursecat::instance($category->parent);
6305 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6306 } else {
6307 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6312 if ($record) {
6313 $context = new context_coursecat($record);
6314 context::cache_add($context);
6315 return $context;
6318 return false;
6322 * Returns immediate child contexts of category and all subcategories,
6323 * children of subcategories and courses are not returned.
6325 * @return array
6327 public function get_child_contexts() {
6328 global $DB;
6330 if (empty($this->_path) or empty($this->_depth)) {
6331 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6332 return array();
6335 $sql = "SELECT ctx.*
6336 FROM {context} ctx
6337 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6338 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6339 $records = $DB->get_records_sql($sql, $params);
6341 $result = array();
6342 foreach ($records as $record) {
6343 $result[$record->id] = context::create_instance_from_record($record);
6346 return $result;
6350 * Create missing context instances at course category context level
6351 * @static
6353 protected static function create_level_instances() {
6354 global $DB;
6356 $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6357 FROM {course_categories} cc
6358 WHERE NOT EXISTS (SELECT 'x'
6359 FROM {context} cx
6360 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6361 $contextdata = $DB->get_recordset_sql($sql);
6362 foreach ($contextdata as $context) {
6363 context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6365 $contextdata->close();
6369 * Returns sql necessary for purging of stale context instances.
6371 * @static
6372 * @return string cleanup SQL
6374 protected static function get_cleanup_sql() {
6375 $sql = "
6376 SELECT c.*
6377 FROM {context} c
6378 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6379 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6382 return $sql;
6386 * Rebuild context paths and depths at course category context level.
6388 * @static
6389 * @param bool $force
6391 protected static function build_paths($force) {
6392 global $DB;
6394 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6395 if ($force) {
6396 $ctxemptyclause = $emptyclause = '';
6397 } else {
6398 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6399 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6402 $base = '/'.SYSCONTEXTID;
6404 // Normal top level categories
6405 $sql = "UPDATE {context}
6406 SET depth=2,
6407 path=".$DB->sql_concat("'$base/'", 'id')."
6408 WHERE contextlevel=".CONTEXT_COURSECAT."
6409 AND EXISTS (SELECT 'x'
6410 FROM {course_categories} cc
6411 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6412 $emptyclause";
6413 $DB->execute($sql);
6415 // Deeper categories - one query per depthlevel
6416 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6417 for ($n=2; $n<=$maxdepth; $n++) {
6418 $sql = "INSERT INTO {context_temp} (id, path, depth)
6419 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6420 FROM {context} ctx
6421 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6422 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6423 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6424 $ctxemptyclause";
6425 $trans = $DB->start_delegated_transaction();
6426 $DB->delete_records('context_temp');
6427 $DB->execute($sql);
6428 context::merge_context_temp_table();
6429 $DB->delete_records('context_temp');
6430 $trans->allow_commit();
6439 * Course context class
6441 * @package core_access
6442 * @category access
6443 * @copyright Petr Skoda {@link http://skodak.org}
6444 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6445 * @since Moodle 2.2
6447 class context_course extends context {
6449 * Please use context_course::instance($courseid) if you need the instance of context.
6450 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6452 * @param stdClass $record
6454 protected function __construct(stdClass $record) {
6455 parent::__construct($record);
6456 if ($record->contextlevel != CONTEXT_COURSE) {
6457 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6462 * Returns human readable context level name.
6464 * @static
6465 * @return string the human readable context level name.
6467 public static function get_level_name() {
6468 return get_string('course');
6472 * Returns human readable context identifier.
6474 * @param boolean $withprefix whether to prefix the name of the context with Course
6475 * @param boolean $short whether to use the short name of the thing.
6476 * @return string the human readable context name.
6478 public function get_context_name($withprefix = true, $short = false) {
6479 global $DB;
6481 $name = '';
6482 if ($this->_instanceid == SITEID) {
6483 $name = get_string('frontpage', 'admin');
6484 } else {
6485 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6486 if ($withprefix){
6487 $name = get_string('course').': ';
6489 if ($short){
6490 $name .= format_string($course->shortname, true, array('context' => $this));
6491 } else {
6492 $name .= format_string(get_course_display_name_for_list($course));
6496 return $name;
6500 * Returns the most relevant URL for this context.
6502 * @return moodle_url
6504 public function get_url() {
6505 if ($this->_instanceid != SITEID) {
6506 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6509 return new moodle_url('/');
6513 * Returns array of relevant context capability records.
6515 * @return array
6517 public function get_capabilities() {
6518 global $DB;
6520 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6522 $params = array();
6523 $sql = "SELECT *
6524 FROM {capabilities}
6525 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6527 return $DB->get_records_sql($sql.' '.$sort, $params);
6531 * Is this context part of any course? If yes return course context.
6533 * @param bool $strict true means throw exception if not found, false means return false if not found
6534 * @return context_course context of the enclosing course, null if not found or exception
6536 public function get_course_context($strict = true) {
6537 return $this;
6541 * Returns course context instance.
6543 * @static
6544 * @param int $courseid id from {course} table
6545 * @param int $strictness
6546 * @return context_course context instance
6548 public static function instance($courseid, $strictness = MUST_EXIST) {
6549 global $DB;
6551 if ($context = context::cache_get(CONTEXT_COURSE, $courseid)) {
6552 return $context;
6555 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $courseid))) {
6556 if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
6557 if ($course->category) {
6558 $parentcontext = context_coursecat::instance($course->category);
6559 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6560 } else {
6561 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6566 if ($record) {
6567 $context = new context_course($record);
6568 context::cache_add($context);
6569 return $context;
6572 return false;
6576 * Create missing context instances at course context level
6577 * @static
6579 protected static function create_level_instances() {
6580 global $DB;
6582 $sql = "SELECT ".CONTEXT_COURSE.", c.id
6583 FROM {course} c
6584 WHERE NOT EXISTS (SELECT 'x'
6585 FROM {context} cx
6586 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6587 $contextdata = $DB->get_recordset_sql($sql);
6588 foreach ($contextdata as $context) {
6589 context::insert_context_record(CONTEXT_COURSE, $context->id, null);
6591 $contextdata->close();
6595 * Returns sql necessary for purging of stale context instances.
6597 * @static
6598 * @return string cleanup SQL
6600 protected static function get_cleanup_sql() {
6601 $sql = "
6602 SELECT c.*
6603 FROM {context} c
6604 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6605 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6608 return $sql;
6612 * Rebuild context paths and depths at course context level.
6614 * @static
6615 * @param bool $force
6617 protected static function build_paths($force) {
6618 global $DB;
6620 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6621 if ($force) {
6622 $ctxemptyclause = $emptyclause = '';
6623 } else {
6624 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6625 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6628 $base = '/'.SYSCONTEXTID;
6630 // Standard frontpage
6631 $sql = "UPDATE {context}
6632 SET depth = 2,
6633 path = ".$DB->sql_concat("'$base/'", 'id')."
6634 WHERE contextlevel = ".CONTEXT_COURSE."
6635 AND EXISTS (SELECT 'x'
6636 FROM {course} c
6637 WHERE c.id = {context}.instanceid AND c.category = 0)
6638 $emptyclause";
6639 $DB->execute($sql);
6641 // standard courses
6642 $sql = "INSERT INTO {context_temp} (id, path, depth)
6643 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6644 FROM {context} ctx
6645 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6646 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6647 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6648 $ctxemptyclause";
6649 $trans = $DB->start_delegated_transaction();
6650 $DB->delete_records('context_temp');
6651 $DB->execute($sql);
6652 context::merge_context_temp_table();
6653 $DB->delete_records('context_temp');
6654 $trans->allow_commit();
6661 * Course module context class
6663 * @package core_access
6664 * @category access
6665 * @copyright Petr Skoda {@link http://skodak.org}
6666 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6667 * @since Moodle 2.2
6669 class context_module extends context {
6671 * Please use context_module::instance($cmid) if you need the instance of context.
6672 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6674 * @param stdClass $record
6676 protected function __construct(stdClass $record) {
6677 parent::__construct($record);
6678 if ($record->contextlevel != CONTEXT_MODULE) {
6679 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6684 * Returns human readable context level name.
6686 * @static
6687 * @return string the human readable context level name.
6689 public static function get_level_name() {
6690 return get_string('activitymodule');
6694 * Returns human readable context identifier.
6696 * @param boolean $withprefix whether to prefix the name of the context with the
6697 * module name, e.g. Forum, Glossary, etc.
6698 * @param boolean $short does not apply to module context
6699 * @return string the human readable context name.
6701 public function get_context_name($withprefix = true, $short = false) {
6702 global $DB;
6704 $name = '';
6705 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6706 FROM {course_modules} cm
6707 JOIN {modules} md ON md.id = cm.module
6708 WHERE cm.id = ?", array($this->_instanceid))) {
6709 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6710 if ($withprefix){
6711 $name = get_string('modulename', $cm->modname).': ';
6713 $name .= format_string($mod->name, true, array('context' => $this));
6716 return $name;
6720 * Returns the most relevant URL for this context.
6722 * @return moodle_url
6724 public function get_url() {
6725 global $DB;
6727 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6728 FROM {course_modules} cm
6729 JOIN {modules} md ON md.id = cm.module
6730 WHERE cm.id = ?", array($this->_instanceid))) {
6731 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6734 return new moodle_url('/');
6738 * Returns array of relevant context capability records.
6740 * @return array
6742 public function get_capabilities() {
6743 global $DB, $CFG;
6745 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6747 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6748 $module = $DB->get_record('modules', array('id'=>$cm->module));
6750 $subcaps = array();
6751 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6752 if (file_exists($subpluginsfile)) {
6753 $subplugins = array(); // should be redefined in the file
6754 include($subpluginsfile);
6755 if (!empty($subplugins)) {
6756 foreach (array_keys($subplugins) as $subplugintype) {
6757 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
6758 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6764 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6765 $extracaps = array();
6766 if (file_exists($modfile)) {
6767 include_once($modfile);
6768 $modfunction = $module->name.'_get_extra_capabilities';
6769 if (function_exists($modfunction)) {
6770 $extracaps = $modfunction();
6774 $extracaps = array_merge($subcaps, $extracaps);
6775 $extra = '';
6776 list($extra, $params) = $DB->get_in_or_equal(
6777 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
6778 if (!empty($extra)) {
6779 $extra = "OR name $extra";
6781 $sql = "SELECT *
6782 FROM {capabilities}
6783 WHERE (contextlevel = ".CONTEXT_MODULE."
6784 AND (component = :component OR component = 'moodle'))
6785 $extra";
6786 $params['component'] = "mod_$module->name";
6788 return $DB->get_records_sql($sql.' '.$sort, $params);
6792 * Is this context part of any course? If yes return course context.
6794 * @param bool $strict true means throw exception if not found, false means return false if not found
6795 * @return context_course context of the enclosing course, null if not found or exception
6797 public function get_course_context($strict = true) {
6798 return $this->get_parent_context();
6802 * Returns module context instance.
6804 * @static
6805 * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
6806 * @param int $strictness
6807 * @return context_module context instance
6809 public static function instance($cmid, $strictness = MUST_EXIST) {
6810 global $DB;
6812 if ($context = context::cache_get(CONTEXT_MODULE, $cmid)) {
6813 return $context;
6816 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE, 'instanceid' => $cmid))) {
6817 if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
6818 $parentcontext = context_course::instance($cm->course);
6819 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
6823 if ($record) {
6824 $context = new context_module($record);
6825 context::cache_add($context);
6826 return $context;
6829 return false;
6833 * Create missing context instances at module context level
6834 * @static
6836 protected static function create_level_instances() {
6837 global $DB;
6839 $sql = "SELECT ".CONTEXT_MODULE.", cm.id
6840 FROM {course_modules} cm
6841 WHERE NOT EXISTS (SELECT 'x'
6842 FROM {context} cx
6843 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
6844 $contextdata = $DB->get_recordset_sql($sql);
6845 foreach ($contextdata as $context) {
6846 context::insert_context_record(CONTEXT_MODULE, $context->id, null);
6848 $contextdata->close();
6852 * Returns sql necessary for purging of stale context instances.
6854 * @static
6855 * @return string cleanup SQL
6857 protected static function get_cleanup_sql() {
6858 $sql = "
6859 SELECT c.*
6860 FROM {context} c
6861 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6862 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
6865 return $sql;
6869 * Rebuild context paths and depths at module context level.
6871 * @static
6872 * @param bool $force
6874 protected static function build_paths($force) {
6875 global $DB;
6877 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
6878 if ($force) {
6879 $ctxemptyclause = '';
6880 } else {
6881 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6884 $sql = "INSERT INTO {context_temp} (id, path, depth)
6885 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6886 FROM {context} ctx
6887 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
6888 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
6889 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6890 $ctxemptyclause";
6891 $trans = $DB->start_delegated_transaction();
6892 $DB->delete_records('context_temp');
6893 $DB->execute($sql);
6894 context::merge_context_temp_table();
6895 $DB->delete_records('context_temp');
6896 $trans->allow_commit();
6903 * Block context class
6905 * @package core_access
6906 * @category access
6907 * @copyright Petr Skoda {@link http://skodak.org}
6908 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6909 * @since Moodle 2.2
6911 class context_block extends context {
6913 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6914 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6916 * @param stdClass $record
6918 protected function __construct(stdClass $record) {
6919 parent::__construct($record);
6920 if ($record->contextlevel != CONTEXT_BLOCK) {
6921 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6926 * Returns human readable context level name.
6928 * @static
6929 * @return string the human readable context level name.
6931 public static function get_level_name() {
6932 return get_string('block');
6936 * Returns human readable context identifier.
6938 * @param boolean $withprefix whether to prefix the name of the context with Block
6939 * @param boolean $short does not apply to block context
6940 * @return string the human readable context name.
6942 public function get_context_name($withprefix = true, $short = false) {
6943 global $DB, $CFG;
6945 $name = '';
6946 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
6947 global $CFG;
6948 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
6949 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
6950 $blockname = "block_$blockinstance->blockname";
6951 if ($blockobject = new $blockname()) {
6952 if ($withprefix){
6953 $name = get_string('block').': ';
6955 $name .= $blockobject->title;
6959 return $name;
6963 * Returns the most relevant URL for this context.
6965 * @return moodle_url
6967 public function get_url() {
6968 $parentcontexts = $this->get_parent_context();
6969 return $parentcontexts->get_url();
6973 * Returns array of relevant context capability records.
6975 * @return array
6977 public function get_capabilities() {
6978 global $DB;
6980 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6982 $params = array();
6983 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
6985 $extra = '';
6986 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
6987 if ($extracaps) {
6988 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6989 $extra = "OR name $extra";
6992 $sql = "SELECT *
6993 FROM {capabilities}
6994 WHERE (contextlevel = ".CONTEXT_BLOCK."
6995 AND component = :component)
6996 $extra";
6997 $params['component'] = 'block_' . $bi->blockname;
6999 return $DB->get_records_sql($sql.' '.$sort, $params);
7003 * Is this context part of any course? If yes return course context.
7005 * @param bool $strict true means throw exception if not found, false means return false if not found
7006 * @return context_course context of the enclosing course, null if not found or exception
7008 public function get_course_context($strict = true) {
7009 $parentcontext = $this->get_parent_context();
7010 return $parentcontext->get_course_context($strict);
7014 * Returns block context instance.
7016 * @static
7017 * @param int $blockinstanceid id from {block_instances} table.
7018 * @param int $strictness
7019 * @return context_block context instance
7021 public static function instance($blockinstanceid, $strictness = MUST_EXIST) {
7022 global $DB;
7024 if ($context = context::cache_get(CONTEXT_BLOCK, $blockinstanceid)) {
7025 return $context;
7028 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $blockinstanceid))) {
7029 if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
7030 $parentcontext = context::instance_by_id($bi->parentcontextid);
7031 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7035 if ($record) {
7036 $context = new context_block($record);
7037 context::cache_add($context);
7038 return $context;
7041 return false;
7045 * Block do not have child contexts...
7046 * @return array
7048 public function get_child_contexts() {
7049 return array();
7053 * Create missing context instances at block context level
7054 * @static
7056 protected static function create_level_instances() {
7057 global $DB;
7059 $sql = "SELECT ".CONTEXT_BLOCK.", bi.id
7060 FROM {block_instances} bi
7061 WHERE NOT EXISTS (SELECT 'x'
7062 FROM {context} cx
7063 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7064 $contextdata = $DB->get_recordset_sql($sql);
7065 foreach ($contextdata as $context) {
7066 context::insert_context_record(CONTEXT_BLOCK, $context->id, null);
7068 $contextdata->close();
7072 * Returns sql necessary for purging of stale context instances.
7074 * @static
7075 * @return string cleanup SQL
7077 protected static function get_cleanup_sql() {
7078 $sql = "
7079 SELECT c.*
7080 FROM {context} c
7081 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7082 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7085 return $sql;
7089 * Rebuild context paths and depths at block context level.
7091 * @static
7092 * @param bool $force
7094 protected static function build_paths($force) {
7095 global $DB;
7097 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7098 if ($force) {
7099 $ctxemptyclause = '';
7100 } else {
7101 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7104 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7105 $sql = "INSERT INTO {context_temp} (id, path, depth)
7106 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7107 FROM {context} ctx
7108 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7109 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7110 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7111 $ctxemptyclause";
7112 $trans = $DB->start_delegated_transaction();
7113 $DB->delete_records('context_temp');
7114 $DB->execute($sql);
7115 context::merge_context_temp_table();
7116 $DB->delete_records('context_temp');
7117 $trans->allow_commit();
7123 // ============== DEPRECATED FUNCTIONS ==========================================
7124 // Old context related functions were deprecated in 2.0, it is recommended
7125 // to use context classes in new code. Old function can be used when
7126 // creating patches that are supposed to be backported to older stable branches.
7127 // These deprecated functions will not be removed in near future,
7128 // before removing devs will be warned with a debugging message first,
7129 // then we will add error message and only after that we can remove the functions
7130 // completely.
7133 * Runs get_records select on context table and returns the result
7134 * Does get_records_select on the context table, and returns the results ordered
7135 * by contextlevel, and then the natural sort order within each level.
7136 * for the purpose of $select, you need to know that the context table has been
7137 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7139 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7140 * @param array $params any parameters required by $select.
7141 * @return array the requested context records.
7143 function get_sorted_contexts($select, $params = array()) {
7145 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7147 global $DB;
7148 if ($select) {
7149 $select = 'WHERE ' . $select;
7151 return $DB->get_records_sql("
7152 SELECT ctx.*
7153 FROM {context} ctx
7154 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7155 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7156 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7157 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7158 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7159 $select
7160 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7161 ", $params);
7165 * Given context and array of users, returns array of users whose enrolment status is suspended,
7166 * or enrolment has expired or has not started. Also removes those users from the given array
7168 * @param context $context context in which suspended users should be extracted.
7169 * @param array $users list of users.
7170 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7171 * @return array list of suspended users.
7173 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7174 global $DB;
7176 // Get active enrolled users.
7177 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7178 $activeusers = $DB->get_records_sql($sql, $params);
7180 // Move suspended users to a separate array & remove from the initial one.
7181 $susers = array();
7182 if (sizeof($activeusers)) {
7183 foreach ($users as $userid => $user) {
7184 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7185 $susers[$userid] = $user;
7186 unset($users[$userid]);
7190 return $susers;
7194 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7195 * or enrolment has expired or not started.
7197 * @param context $context context in which user enrolment is checked.
7198 * @param bool $usecache Enable or disable (default) the request cache
7199 * @return array list of suspended user id's.
7201 function get_suspended_userids(context $context, $usecache = false) {
7202 global $DB;
7204 if ($usecache) {
7205 $cache = cache::make('core', 'suspended_userids');
7206 $susers = $cache->get($context->id);
7207 if ($susers !== false) {
7208 return $susers;
7212 $coursecontext = $context->get_course_context();
7213 $susers = array();
7215 // Front page users are always enrolled, so suspended list is empty.
7216 if ($coursecontext->instanceid != SITEID) {
7217 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7218 $susers = $DB->get_fieldset_sql($sql, $params);
7219 $susers = array_combine($susers, $susers);
7222 // Cache results for the remainder of this request.
7223 if ($usecache) {
7224 $cache->set($context->id, $susers);
7227 return $susers;
7231 * Gets sql for finding users with capability in the given context
7233 * @param context $context
7234 * @param string|array $capability Capability name or array of names.
7235 * If an array is provided then this is the equivalent of a logical 'OR',
7236 * i.e. the user needs to have one of these capabilities.
7237 * @return array($sql, $params)
7239 function get_with_capability_sql(context $context, $capability) {
7240 static $i = 0;
7241 $i++;
7242 $prefix = 'cu' . $i . '_';
7244 $capjoin = get_with_capability_join($context, $capability, $prefix . 'u.id');
7246 $sql = "SELECT DISTINCT {$prefix}u.id
7247 FROM {user} {$prefix}u
7248 $capjoin->joins
7249 WHERE {$prefix}u.deleted = 0 AND $capjoin->wheres";
7251 return array($sql, $capjoin->params);
7255 * Gets sql joins for finding users with capability in the given context
7257 * @param context $context Context for the join
7258 * @param string|array $capability Capability name or array of names.
7259 * If an array is provided then this is the equivalent of a logical 'OR',
7260 * i.e. the user needs to have one of these capabilities.
7261 * @param string $useridcolumn e.g. 'u.id'
7262 * @return \core\dml\sql_join Contains joins, wheres, params
7264 function get_with_capability_join(context $context, $capability, $useridcolumn) {
7265 global $DB, $CFG;
7267 // Use unique prefix just in case somebody makes some SQL magic with the result.
7268 static $i = 0;
7269 $i++;
7270 $prefix = 'eu' . $i . '_';
7272 // First find the course context.
7273 $coursecontext = $context->get_course_context();
7275 $isfrontpage = ($coursecontext->instanceid == SITEID);
7277 $joins = array();
7278 $wheres = array();
7279 $params = array();
7281 list($contextids, $contextpaths) = get_context_info_list($context);
7283 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
7285 list($incaps, $capsparams) = $DB->get_in_or_equal($capability, SQL_PARAMS_NAMED, 'cap');
7287 $defs = array();
7288 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
7289 FROM {role_capabilities} rc
7290 JOIN {context} ctx on rc.contextid = ctx.id
7291 WHERE rc.contextid $incontexts AND rc.capability $incaps";
7292 $rcs = $DB->get_records_sql($sql, array_merge($cparams, $capsparams));
7293 foreach ($rcs as $rc) {
7294 $defs[$rc->path][$rc->roleid] = $rc->permission;
7297 $access = array();
7298 if (!empty($defs)) {
7299 foreach ($contextpaths as $path) {
7300 if (empty($defs[$path])) {
7301 continue;
7303 foreach ($defs[$path] as $roleid => $perm) {
7304 if ($perm == CAP_PROHIBIT) {
7305 $access[$roleid] = CAP_PROHIBIT;
7306 continue;
7308 if (!isset($access[$roleid])) {
7309 $access[$roleid] = (int) $perm;
7315 unset($defs);
7317 // Make lists of roles that are needed and prohibited.
7318 $needed = array(); // One of these is enough.
7319 $prohibited = array(); // Must not have any of these.
7320 foreach ($access as $roleid => $perm) {
7321 if ($perm == CAP_PROHIBIT) {
7322 unset($needed[$roleid]);
7323 $prohibited[$roleid] = true;
7324 } else {
7325 if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
7326 $needed[$roleid] = true;
7331 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
7332 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
7334 $nobody = false;
7336 if ($isfrontpage) {
7337 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
7338 $nobody = true;
7339 } else {
7340 if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
7341 // Everybody not having prohibit has the capability.
7342 $needed = array();
7343 } else {
7344 if (empty($needed)) {
7345 $nobody = true;
7349 } else {
7350 if (!empty($prohibited[$defaultuserroleid])) {
7351 $nobody = true;
7352 } else {
7353 if (!empty($needed[$defaultuserroleid])) {
7354 // Everybody not having prohibit has the capability.
7355 $needed = array();
7356 } else {
7357 if (empty($needed)) {
7358 $nobody = true;
7364 if ($nobody) {
7365 // Nobody can match so return some SQL that does not return any results.
7366 $wheres[] = "1 = 2";
7368 } else {
7370 if ($needed) {
7371 $ctxids = implode(',', $contextids);
7372 $roleids = implode(',', array_keys($needed));
7373 $joins[] = "JOIN {role_assignments} {$prefix}ra3
7374 ON ({$prefix}ra3.userid = $useridcolumn
7375 AND {$prefix}ra3.roleid IN ($roleids)
7376 AND {$prefix}ra3.contextid IN ($ctxids))";
7379 if ($prohibited) {
7380 $ctxids = implode(',', $contextids);
7381 $roleids = implode(',', array_keys($prohibited));
7382 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4
7383 ON ({$prefix}ra4.userid = $useridcolumn
7384 AND {$prefix}ra4.roleid IN ($roleids)
7385 AND {$prefix}ra4.contextid IN ($ctxids))";
7386 $wheres[] = "{$prefix}ra4.id IS NULL";
7391 $wheres[] = "$useridcolumn <> :{$prefix}guestid";
7392 $params["{$prefix}guestid"] = $CFG->siteguest;
7394 $joins = implode("\n", $joins);
7395 $wheres = "(" . implode(" AND ", $wheres) . ")";
7397 return new \core\dml\sql_join($joins, $wheres, $params);