MDL-62218 analytics: Add missing sample origin checking
[moodle.git] / lib / accesslib.php
blob98aaa06a837b3e0358d8daccd11f103c57afe3f2
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 $ACCESSLIB_PRIVATE->cacheroledefs += array_filter($cache->get_many($uncached));
291 // Check we have the remaining keys from the MUC.
292 if ($uncached = array_diff($roleids, array_keys($ACCESSLIB_PRIVATE->cacheroledefs))) {
293 $uncached = get_role_definitions_uncached($uncached);
294 $ACCESSLIB_PRIVATE->cacheroledefs += $uncached;
295 $cache->set_many($uncached);
299 // Return just the roles we need.
300 return array_intersect_key($ACCESSLIB_PRIVATE->cacheroledefs, array_flip($roleids));
304 * Query raw "site wide" role definitions.
306 * @param array $roleids List of role ids to fetch definitions for.
307 * @return array Complete definition for each requested role.
309 function get_role_definitions_uncached(array $roleids) {
310 global $DB;
312 if (empty($roleids)) {
313 return array();
316 list($sql, $params) = $DB->get_in_or_equal($roleids);
317 $rdefs = array();
319 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
320 FROM {role_capabilities} rc
321 JOIN {context} ctx ON rc.contextid = ctx.id
322 WHERE rc.roleid $sql";
323 $rs = $DB->get_recordset_sql($sql, $params);
325 foreach ($rs as $rd) {
326 if (!isset($rdefs[$rd->roleid][$rd->path])) {
327 if (!isset($rdefs[$rd->roleid])) {
328 $rdefs[$rd->roleid] = array();
330 $rdefs[$rd->roleid][$rd->path] = array();
332 $rdefs[$rd->roleid][$rd->path][$rd->capability] = (int) $rd->permission;
335 $rs->close();
337 // Sometimes (e.g. get_user_capability_course_helper::get_capability_info_at_each_context)
338 // we process role definitinons in a way that requires we see parent contexts
339 // before child contexts. This sort ensures that works (and is faster than
340 // sorting in the SQL query).
341 foreach ($rdefs as $roleid => $rdef) {
342 ksort($rdefs[$roleid]);
345 return $rdefs;
349 * Get the default guest role, this is used for guest account,
350 * search engine spiders, etc.
352 * @return stdClass role record
354 function get_guest_role() {
355 global $CFG, $DB;
357 if (empty($CFG->guestroleid)) {
358 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
359 $guestrole = array_shift($roles); // Pick the first one
360 set_config('guestroleid', $guestrole->id);
361 return $guestrole;
362 } else {
363 debugging('Can not find any guest role!');
364 return false;
366 } else {
367 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
368 return $guestrole;
369 } else {
370 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
371 set_config('guestroleid', '');
372 return get_guest_role();
378 * Check whether a user has a particular capability in a given context.
380 * For example:
381 * $context = context_module::instance($cm->id);
382 * has_capability('mod/forum:replypost', $context)
384 * By default checks the capabilities of the current user, but you can pass a
385 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
387 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
388 * or capabilities with XSS, config or data loss risks.
390 * @category access
392 * @param string $capability the name of the capability to check. For example mod/forum:view
393 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
394 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
395 * @param boolean $doanything If false, ignores effect of admin role assignment
396 * @return boolean true if the user has this capability. Otherwise false.
398 function has_capability($capability, context $context, $user = null, $doanything = true) {
399 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
401 if (during_initial_install()) {
402 if ($SCRIPT === "/$CFG->admin/index.php"
403 or $SCRIPT === "/$CFG->admin/cli/install.php"
404 or $SCRIPT === "/$CFG->admin/cli/install_database.php"
405 or (defined('BEHAT_UTIL') and BEHAT_UTIL)
406 or (defined('PHPUNIT_UTIL') and PHPUNIT_UTIL)) {
407 // we are in an installer - roles can not work yet
408 return true;
409 } else {
410 return false;
414 if (strpos($capability, 'moodle/legacy:') === 0) {
415 throw new coding_exception('Legacy capabilities can not be used any more!');
418 if (!is_bool($doanything)) {
419 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
422 // capability must exist
423 if (!$capinfo = get_capability_info($capability)) {
424 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
425 return false;
428 if (!isset($USER->id)) {
429 // should never happen
430 $USER->id = 0;
431 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER);
434 // make sure there is a real user specified
435 if ($user === null) {
436 $userid = $USER->id;
437 } else {
438 $userid = is_object($user) ? $user->id : $user;
441 // make sure forcelogin cuts off not-logged-in users if enabled
442 if (!empty($CFG->forcelogin) and $userid == 0) {
443 return false;
446 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
447 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
448 if (isguestuser($userid) or $userid == 0) {
449 return false;
453 // somehow make sure the user is not deleted and actually exists
454 if ($userid != 0) {
455 if ($userid == $USER->id and isset($USER->deleted)) {
456 // this prevents one query per page, it is a bit of cheating,
457 // but hopefully session is terminated properly once user is deleted
458 if ($USER->deleted) {
459 return false;
461 } else {
462 if (!context_user::instance($userid, IGNORE_MISSING)) {
463 // no user context == invalid userid
464 return false;
469 // context path/depth must be valid
470 if (empty($context->path) or $context->depth == 0) {
471 // this should not happen often, each upgrade tries to rebuild the context paths
472 debugging('Context id '.$context->id.' does not have valid path, please use context_helper::build_all_paths()');
473 if (is_siteadmin($userid)) {
474 return true;
475 } else {
476 return false;
480 // Find out if user is admin - it is not possible to override the doanything in any way
481 // and it is not possible to switch to admin role either.
482 if ($doanything) {
483 if (is_siteadmin($userid)) {
484 if ($userid != $USER->id) {
485 return true;
487 // make sure switchrole is not used in this context
488 if (empty($USER->access['rsw'])) {
489 return true;
491 $parts = explode('/', trim($context->path, '/'));
492 $path = '';
493 $switched = false;
494 foreach ($parts as $part) {
495 $path .= '/' . $part;
496 if (!empty($USER->access['rsw'][$path])) {
497 $switched = true;
498 break;
501 if (!$switched) {
502 return true;
504 //ok, admin switched role in this context, let's use normal access control rules
508 // Careful check for staleness...
509 $context->reload_if_dirty();
511 if ($USER->id == $userid) {
512 if (!isset($USER->access)) {
513 load_all_capabilities();
515 $access =& $USER->access;
517 } else {
518 // make sure user accessdata is really loaded
519 get_user_accessdata($userid, true);
520 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
523 return has_capability_in_accessdata($capability, $context, $access);
527 * Check if the user has any one of several capabilities from a list.
529 * This is just a utility method that calls has_capability in a loop. Try to put
530 * the capabilities that most users are likely to have first in the list for best
531 * performance.
533 * @category access
534 * @see has_capability()
536 * @param array $capabilities an array of capability names.
537 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
538 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
539 * @param boolean $doanything If false, ignore effect of admin role assignment
540 * @return boolean true if the user has any of these capabilities. Otherwise false.
542 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
543 foreach ($capabilities as $capability) {
544 if (has_capability($capability, $context, $user, $doanything)) {
545 return true;
548 return false;
552 * Check if the user has all the capabilities in a list.
554 * This is just a utility method that calls has_capability in a loop. Try to put
555 * the capabilities that fewest users are likely to have first in the list for best
556 * performance.
558 * @category access
559 * @see has_capability()
561 * @param array $capabilities an array of capability names.
562 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
563 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
564 * @param boolean $doanything If false, ignore effect of admin role assignment
565 * @return boolean true if the user has all of these capabilities. Otherwise false.
567 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
568 foreach ($capabilities as $capability) {
569 if (!has_capability($capability, $context, $user, $doanything)) {
570 return false;
573 return true;
577 * Is course creator going to have capability in a new course?
579 * This is intended to be used in enrolment plugins before or during course creation,
580 * do not use after the course is fully created.
582 * @category access
584 * @param string $capability the name of the capability to check.
585 * @param context $context course or category context where is course going to be created
586 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
587 * @return boolean true if the user will have this capability.
589 * @throws coding_exception if different type of context submitted
591 function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) {
592 global $CFG;
594 if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) {
595 throw new coding_exception('Only course or course category context expected');
598 if (has_capability($capability, $context, $user)) {
599 // User already has the capability, it could be only removed if CAP_PROHIBIT
600 // was involved here, but we ignore that.
601 return true;
604 if (!has_capability('moodle/course:create', $context, $user)) {
605 return false;
608 if (!enrol_is_enabled('manual')) {
609 return false;
612 if (empty($CFG->creatornewroleid)) {
613 return false;
616 if ($context->contextlevel == CONTEXT_COURSE) {
617 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
618 return false;
620 } else {
621 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
622 return false;
626 // Most likely they will be enrolled after the course creation is finished,
627 // does the new role have the required capability?
628 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
629 return isset($neededroles[$CFG->creatornewroleid]);
633 * Check if the user is an admin at the site level.
635 * Please note that use of proper capabilities is always encouraged,
636 * this function is supposed to be used from core or for temporary hacks.
638 * @category access
640 * @param int|stdClass $user_or_id user id or user object
641 * @return bool true if user is one of the administrators, false otherwise
643 function is_siteadmin($user_or_id = null) {
644 global $CFG, $USER;
646 if ($user_or_id === null) {
647 $user_or_id = $USER;
650 if (empty($user_or_id)) {
651 return false;
653 if (!empty($user_or_id->id)) {
654 $userid = $user_or_id->id;
655 } else {
656 $userid = $user_or_id;
659 // Because this script is called many times (150+ for course page) with
660 // the same parameters, it is worth doing minor optimisations. This static
661 // cache stores the value for a single userid, saving about 2ms from course
662 // page load time without using significant memory. As the static cache
663 // also includes the value it depends on, this cannot break unit tests.
664 static $knownid, $knownresult, $knownsiteadmins;
665 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
666 return $knownresult;
668 $knownid = $userid;
669 $knownsiteadmins = $CFG->siteadmins;
671 $siteadmins = explode(',', $CFG->siteadmins);
672 $knownresult = in_array($userid, $siteadmins);
673 return $knownresult;
677 * Returns true if user has at least one role assign
678 * of 'coursecontact' role (is potentially listed in some course descriptions).
680 * @param int $userid
681 * @return bool
683 function has_coursecontact_role($userid) {
684 global $DB, $CFG;
686 if (empty($CFG->coursecontact)) {
687 return false;
689 $sql = "SELECT 1
690 FROM {role_assignments}
691 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
692 return $DB->record_exists_sql($sql, array('userid'=>$userid));
696 * Does the user have a capability to do something?
698 * Walk the accessdata array and return true/false.
699 * Deals with prohibits, role switching, aggregating
700 * capabilities, etc.
702 * The main feature of here is being FAST and with no
703 * side effects.
705 * Notes:
707 * Switch Role merges with default role
708 * ------------------------------------
709 * If you are a teacher in course X, you have at least
710 * teacher-in-X + defaultloggedinuser-sitewide. So in the
711 * course you'll have techer+defaultloggedinuser.
712 * We try to mimic that in switchrole.
714 * Permission evaluation
715 * ---------------------
716 * Originally there was an extremely complicated way
717 * to determine the user access that dealt with
718 * "locality" or role assignments and role overrides.
719 * Now we simply evaluate access for each role separately
720 * and then verify if user has at least one role with allow
721 * and at the same time no role with prohibit.
723 * @access private
724 * @param string $capability
725 * @param context $context
726 * @param array $accessdata
727 * @return bool
729 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
730 global $CFG;
732 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
733 $path = $context->path;
734 $paths = array($path);
735 while($path = rtrim($path, '0123456789')) {
736 $path = rtrim($path, '/');
737 if ($path === '') {
738 break;
740 $paths[] = $path;
743 $roles = array();
744 $switchedrole = false;
746 // Find out if role switched
747 if (!empty($accessdata['rsw'])) {
748 // From the bottom up...
749 foreach ($paths as $path) {
750 if (isset($accessdata['rsw'][$path])) {
751 // Found a switchrole assignment - check for that role _plus_ the default user role
752 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
753 $switchedrole = true;
754 break;
759 if (!$switchedrole) {
760 // get all users roles in this context and above
761 foreach ($paths as $path) {
762 if (isset($accessdata['ra'][$path])) {
763 foreach ($accessdata['ra'][$path] as $roleid) {
764 $roles[$roleid] = null;
770 // Now find out what access is given to each role, going bottom-->up direction
771 $rdefs = get_role_definitions(array_keys($roles));
772 $allowed = false;
774 foreach ($roles as $roleid => $ignored) {
775 foreach ($paths as $path) {
776 if (isset($rdefs[$roleid][$path][$capability])) {
777 $perm = (int)$rdefs[$roleid][$path][$capability];
778 if ($perm === CAP_PROHIBIT) {
779 // any CAP_PROHIBIT found means no permission for the user
780 return false;
782 if (is_null($roles[$roleid])) {
783 $roles[$roleid] = $perm;
787 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
788 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
791 return $allowed;
795 * A convenience function that tests has_capability, and displays an error if
796 * the user does not have that capability.
798 * NOTE before Moodle 2.0, this function attempted to make an appropriate
799 * require_login call before checking the capability. This is no longer the case.
800 * You must call require_login (or one of its variants) if you want to check the
801 * user is logged in, before you call this function.
803 * @see has_capability()
805 * @param string $capability the name of the capability to check. For example mod/forum:view
806 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
807 * @param int $userid A user id. By default (null) checks the permissions of the current user.
808 * @param bool $doanything If false, ignore effect of admin role assignment
809 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
810 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
811 * @return void terminates with an error if the user does not have the given capability.
813 function require_capability($capability, context $context, $userid = null, $doanything = true,
814 $errormessage = 'nopermissions', $stringfile = '') {
815 if (!has_capability($capability, $context, $userid, $doanything)) {
816 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
821 * Return a nested array showing all role assignments for the user.
822 * [ra] => [contextpath][roleid] = roleid
824 * @access private
825 * @param int $userid - the id of the user
826 * @return array access info array
828 function get_user_roles_sitewide_accessdata($userid) {
829 global $CFG, $DB;
831 $accessdata = get_empty_accessdata();
833 // start with the default role
834 if (!empty($CFG->defaultuserroleid)) {
835 $syscontext = context_system::instance();
836 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
839 // load the "default frontpage role"
840 if (!empty($CFG->defaultfrontpageroleid)) {
841 $frontpagecontext = context_course::instance(get_site()->id);
842 if ($frontpagecontext->path) {
843 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
847 // Preload every assigned role.
848 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
849 FROM {role_assignments} ra
850 JOIN {context} ctx ON ctx.id = ra.contextid
851 WHERE ra.userid = :userid";
853 $rs = $DB->get_recordset_sql($sql, array('userid' => $userid));
855 foreach ($rs as $ra) {
856 // RAs leafs are arrays to support multi-role assignments...
857 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
860 $rs->close();
862 return $accessdata;
866 * Returns empty accessdata structure.
868 * @access private
869 * @return array empt accessdata
871 function get_empty_accessdata() {
872 $accessdata = array(); // named list
873 $accessdata['ra'] = array();
874 $accessdata['time'] = time();
875 $accessdata['rsw'] = array();
877 return $accessdata;
881 * Get accessdata for a given user.
883 * @access private
884 * @param int $userid
885 * @param bool $preloadonly true means do not return access array
886 * @return array accessdata
888 function get_user_accessdata($userid, $preloadonly=false) {
889 global $CFG, $ACCESSLIB_PRIVATE, $USER;
891 if (isset($USER->access)) {
892 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->access;
895 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
896 if (empty($userid)) {
897 if (!empty($CFG->notloggedinroleid)) {
898 $accessdata = get_role_access($CFG->notloggedinroleid);
899 } else {
900 // weird
901 return get_empty_accessdata();
904 } else if (isguestuser($userid)) {
905 if ($guestrole = get_guest_role()) {
906 $accessdata = get_role_access($guestrole->id);
907 } else {
908 //weird
909 return get_empty_accessdata();
912 } else {
913 // Includes default role and frontpage role.
914 $accessdata = get_user_roles_sitewide_accessdata($userid);
917 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
920 if ($preloadonly) {
921 return;
922 } else {
923 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
928 * A convenience function to completely load all the capabilities
929 * for the current user. It is called from has_capability() and functions change permissions.
931 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
932 * @see check_enrolment_plugins()
934 * @access private
935 * @return void
937 function load_all_capabilities() {
938 global $USER;
940 // roles not installed yet - we are in the middle of installation
941 if (during_initial_install()) {
942 return;
945 if (!isset($USER->id)) {
946 // this should not happen
947 $USER->id = 0;
950 unset($USER->access);
951 $USER->access = get_user_accessdata($USER->id);
953 // Clear to force a refresh
954 unset($USER->mycourses);
956 // init/reset internal enrol caches - active course enrolments and temp access
957 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
961 * A convenience function to completely reload all the capabilities
962 * for the current user when roles have been updated in a relevant
963 * context -- but PRESERVING switchroles and loginas.
964 * This function resets all accesslib and context caches.
966 * That is - completely transparent to the user.
968 * Note: reloads $USER->access completely.
970 * @access private
971 * @return void
973 function reload_all_capabilities() {
974 global $USER, $DB, $ACCESSLIB_PRIVATE;
976 // copy switchroles
977 $sw = array();
978 if (!empty($USER->access['rsw'])) {
979 $sw = $USER->access['rsw'];
982 accesslib_clear_all_caches(true);
983 unset($USER->access);
984 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
986 load_all_capabilities();
988 foreach ($sw as $path => $roleid) {
989 if ($record = $DB->get_record('context', array('path'=>$path))) {
990 $context = context::instance_by_id($record->id);
991 role_switch($roleid, $context);
997 * Adds a temp role to current USER->access array.
999 * Useful for the "temporary guest" access we grant to logged-in users.
1000 * This is useful for enrol plugins only.
1002 * @since Moodle 2.2
1003 * @param context_course $coursecontext
1004 * @param int $roleid
1005 * @return void
1007 function load_temp_course_role(context_course $coursecontext, $roleid) {
1008 global $USER, $SITE;
1010 if (empty($roleid)) {
1011 debugging('invalid role specified in load_temp_course_role()');
1012 return;
1015 if ($coursecontext->instanceid == $SITE->id) {
1016 debugging('Can not use temp roles on the frontpage');
1017 return;
1020 if (!isset($USER->access)) {
1021 load_all_capabilities();
1024 $coursecontext->reload_if_dirty();
1026 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1027 return;
1030 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1034 * Removes any extra guest roles from current USER->access array.
1035 * This is useful for enrol plugins only.
1037 * @since Moodle 2.2
1038 * @param context_course $coursecontext
1039 * @return void
1041 function remove_temp_course_roles(context_course $coursecontext) {
1042 global $DB, $USER, $SITE;
1044 if ($coursecontext->instanceid == $SITE->id) {
1045 debugging('Can not use temp roles on the frontpage');
1046 return;
1049 if (empty($USER->access['ra'][$coursecontext->path])) {
1050 //no roles here, weird
1051 return;
1054 $sql = "SELECT DISTINCT ra.roleid AS id
1055 FROM {role_assignments} ra
1056 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1057 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1059 $USER->access['ra'][$coursecontext->path] = array();
1060 foreach($ras as $r) {
1061 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1066 * Returns array of all role archetypes.
1068 * @return array
1070 function get_role_archetypes() {
1071 return array(
1072 'manager' => 'manager',
1073 'coursecreator' => 'coursecreator',
1074 'editingteacher' => 'editingteacher',
1075 'teacher' => 'teacher',
1076 'student' => 'student',
1077 'guest' => 'guest',
1078 'user' => 'user',
1079 'frontpage' => 'frontpage'
1084 * Assign the defaults found in this capability definition to roles that have
1085 * the corresponding legacy capabilities assigned to them.
1087 * @param string $capability
1088 * @param array $legacyperms an array in the format (example):
1089 * 'guest' => CAP_PREVENT,
1090 * 'student' => CAP_ALLOW,
1091 * 'teacher' => CAP_ALLOW,
1092 * 'editingteacher' => CAP_ALLOW,
1093 * 'coursecreator' => CAP_ALLOW,
1094 * 'manager' => CAP_ALLOW
1095 * @return boolean success or failure.
1097 function assign_legacy_capabilities($capability, $legacyperms) {
1099 $archetypes = get_role_archetypes();
1101 foreach ($legacyperms as $type => $perm) {
1103 $systemcontext = context_system::instance();
1104 if ($type === 'admin') {
1105 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1106 $type = 'manager';
1109 if (!array_key_exists($type, $archetypes)) {
1110 print_error('invalidlegacy', '', '', $type);
1113 if ($roles = get_archetype_roles($type)) {
1114 foreach ($roles as $role) {
1115 // Assign a site level capability.
1116 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1117 return false;
1122 return true;
1126 * Verify capability risks.
1128 * @param stdClass $capability a capability - a row from the capabilities table.
1129 * @return boolean whether this capability is safe - that is, whether people with the
1130 * safeoverrides capability should be allowed to change it.
1132 function is_safe_capability($capability) {
1133 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1137 * Get the local override (if any) for a given capability in a role in a context
1139 * @param int $roleid
1140 * @param int $contextid
1141 * @param string $capability
1142 * @return stdClass local capability override
1144 function get_local_override($roleid, $contextid, $capability) {
1145 global $DB;
1146 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1150 * Returns context instance plus related course and cm instances
1152 * @param int $contextid
1153 * @return array of ($context, $course, $cm)
1155 function get_context_info_array($contextid) {
1156 global $DB;
1158 $context = context::instance_by_id($contextid, MUST_EXIST);
1159 $course = null;
1160 $cm = null;
1162 if ($context->contextlevel == CONTEXT_COURSE) {
1163 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1165 } else if ($context->contextlevel == CONTEXT_MODULE) {
1166 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1167 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1169 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1170 $parent = $context->get_parent_context();
1172 if ($parent->contextlevel == CONTEXT_COURSE) {
1173 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1174 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1175 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1176 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1180 return array($context, $course, $cm);
1184 * Function that creates a role
1186 * @param string $name role name
1187 * @param string $shortname role short name
1188 * @param string $description role description
1189 * @param string $archetype
1190 * @return int id or dml_exception
1192 function create_role($name, $shortname, $description, $archetype = '') {
1193 global $DB;
1195 if (strpos($archetype, 'moodle/legacy:') !== false) {
1196 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1199 // verify role archetype actually exists
1200 $archetypes = get_role_archetypes();
1201 if (empty($archetypes[$archetype])) {
1202 $archetype = '';
1205 // Insert the role record.
1206 $role = new stdClass();
1207 $role->name = $name;
1208 $role->shortname = $shortname;
1209 $role->description = $description;
1210 $role->archetype = $archetype;
1212 //find free sortorder number
1213 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1214 if (empty($role->sortorder)) {
1215 $role->sortorder = 1;
1217 $id = $DB->insert_record('role', $role);
1219 return $id;
1223 * Function that deletes a role and cleanups up after it
1225 * @param int $roleid id of role to delete
1226 * @return bool always true
1228 function delete_role($roleid) {
1229 global $DB;
1231 // first unssign all users
1232 role_unassign_all(array('roleid'=>$roleid));
1234 // cleanup all references to this role, ignore errors
1235 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1236 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1237 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1238 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1239 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1240 $DB->delete_records('role_names', array('roleid'=>$roleid));
1241 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1243 // Get role record before it's deleted.
1244 $role = $DB->get_record('role', array('id'=>$roleid));
1246 // Finally delete the role itself.
1247 $DB->delete_records('role', array('id'=>$roleid));
1249 // Trigger event.
1250 $event = \core\event\role_deleted::create(
1251 array(
1252 'context' => context_system::instance(),
1253 'objectid' => $roleid,
1254 'other' =>
1255 array(
1256 'shortname' => $role->shortname,
1257 'description' => $role->description,
1258 'archetype' => $role->archetype
1262 $event->add_record_snapshot('role', $role);
1263 $event->trigger();
1265 // Reset any cache of this role, including MUC.
1266 accesslib_clear_role_cache($roleid);
1268 return true;
1272 * Function to write context specific overrides, or default capabilities.
1274 * NOTE: use $context->mark_dirty() after this
1276 * @param string $capability string name
1277 * @param int $permission CAP_ constants
1278 * @param int $roleid role id
1279 * @param int|context $contextid context id
1280 * @param bool $overwrite
1281 * @return bool always true or exception
1283 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1284 global $USER, $DB;
1286 if ($contextid instanceof context) {
1287 $context = $contextid;
1288 } else {
1289 $context = context::instance_by_id($contextid);
1292 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1293 unassign_capability($capability, $roleid, $context->id);
1294 return true;
1297 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1299 if ($existing and !$overwrite) { // We want to keep whatever is there already
1300 return true;
1303 $cap = new stdClass();
1304 $cap->contextid = $context->id;
1305 $cap->roleid = $roleid;
1306 $cap->capability = $capability;
1307 $cap->permission = $permission;
1308 $cap->timemodified = time();
1309 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1311 if ($existing) {
1312 $cap->id = $existing->id;
1313 $DB->update_record('role_capabilities', $cap);
1314 } else {
1315 if ($DB->record_exists('context', array('id'=>$context->id))) {
1316 $DB->insert_record('role_capabilities', $cap);
1320 // Reset any cache of this role, including MUC.
1321 accesslib_clear_role_cache($roleid);
1323 return true;
1327 * Unassign a capability from a role.
1329 * NOTE: use $context->mark_dirty() after this
1331 * @param string $capability the name of the capability
1332 * @param int $roleid the role id
1333 * @param int|context $contextid null means all contexts
1334 * @return boolean true or exception
1336 function unassign_capability($capability, $roleid, $contextid = null) {
1337 global $DB;
1339 if (!empty($contextid)) {
1340 if ($contextid instanceof context) {
1341 $context = $contextid;
1342 } else {
1343 $context = context::instance_by_id($contextid);
1345 // delete from context rel, if this is the last override in this context
1346 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1347 } else {
1348 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1351 // Reset any cache of this role, including MUC.
1352 accesslib_clear_role_cache($roleid);
1354 return true;
1358 * Get the roles that have a given capability assigned to it
1360 * This function does not resolve the actual permission of the capability.
1361 * It just checks for permissions and overrides.
1362 * Use get_roles_with_cap_in_context() if resolution is required.
1364 * @param string $capability capability name (string)
1365 * @param string $permission optional, the permission defined for this capability
1366 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1367 * @param stdClass $context null means any
1368 * @return array of role records
1370 function get_roles_with_capability($capability, $permission = null, $context = null) {
1371 global $DB;
1373 if ($context) {
1374 $contexts = $context->get_parent_context_ids(true);
1375 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1376 $contextsql = "AND rc.contextid $insql";
1377 } else {
1378 $params = array();
1379 $contextsql = '';
1382 if ($permission) {
1383 $permissionsql = " AND rc.permission = :permission";
1384 $params['permission'] = $permission;
1385 } else {
1386 $permissionsql = '';
1389 $sql = "SELECT r.*
1390 FROM {role} r
1391 WHERE r.id IN (SELECT rc.roleid
1392 FROM {role_capabilities} rc
1393 WHERE rc.capability = :capname
1394 $contextsql
1395 $permissionsql)";
1396 $params['capname'] = $capability;
1399 return $DB->get_records_sql($sql, $params);
1403 * This function makes a role-assignment (a role for a user in a particular context)
1405 * @param int $roleid the role of the id
1406 * @param int $userid userid
1407 * @param int|context $contextid id of the context
1408 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1409 * @param int $itemid id of enrolment/auth plugin
1410 * @param string $timemodified defaults to current time
1411 * @return int new/existing id of the assignment
1413 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1414 global $USER, $DB, $CFG;
1416 // first of all detect if somebody is using old style parameters
1417 if ($contextid === 0 or is_numeric($component)) {
1418 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1421 // now validate all parameters
1422 if (empty($roleid)) {
1423 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1426 if (empty($userid)) {
1427 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1430 if ($itemid) {
1431 if (strpos($component, '_') === false) {
1432 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1434 } else {
1435 $itemid = 0;
1436 if ($component !== '' and strpos($component, '_') === false) {
1437 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1441 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1442 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1445 if ($contextid instanceof context) {
1446 $context = $contextid;
1447 } else {
1448 $context = context::instance_by_id($contextid, MUST_EXIST);
1451 if (!$timemodified) {
1452 $timemodified = time();
1455 // Check for existing entry
1456 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1458 if ($ras) {
1459 // role already assigned - this should not happen
1460 if (count($ras) > 1) {
1461 // very weird - remove all duplicates!
1462 $ra = array_shift($ras);
1463 foreach ($ras as $r) {
1464 $DB->delete_records('role_assignments', array('id'=>$r->id));
1466 } else {
1467 $ra = reset($ras);
1470 // actually there is no need to update, reset anything or trigger any event, so just return
1471 return $ra->id;
1474 // Create a new entry
1475 $ra = new stdClass();
1476 $ra->roleid = $roleid;
1477 $ra->contextid = $context->id;
1478 $ra->userid = $userid;
1479 $ra->component = $component;
1480 $ra->itemid = $itemid;
1481 $ra->timemodified = $timemodified;
1482 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1483 $ra->sortorder = 0;
1485 $ra->id = $DB->insert_record('role_assignments', $ra);
1487 // mark context as dirty - again expensive, but needed
1488 $context->mark_dirty();
1490 if (!empty($USER->id) && $USER->id == $userid) {
1491 // If the user is the current user, then do full reload of capabilities too.
1492 reload_all_capabilities();
1495 require_once($CFG->libdir . '/coursecatlib.php');
1496 coursecat::role_assignment_changed($roleid, $context);
1498 $event = \core\event\role_assigned::create(array(
1499 'context' => $context,
1500 'objectid' => $ra->roleid,
1501 'relateduserid' => $ra->userid,
1502 'other' => array(
1503 'id' => $ra->id,
1504 'component' => $ra->component,
1505 'itemid' => $ra->itemid
1508 $event->add_record_snapshot('role_assignments', $ra);
1509 $event->trigger();
1511 return $ra->id;
1515 * Removes one role assignment
1517 * @param int $roleid
1518 * @param int $userid
1519 * @param int $contextid
1520 * @param string $component
1521 * @param int $itemid
1522 * @return void
1524 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1525 // first make sure the params make sense
1526 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1527 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1530 if ($itemid) {
1531 if (strpos($component, '_') === false) {
1532 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1534 } else {
1535 $itemid = 0;
1536 if ($component !== '' and strpos($component, '_') === false) {
1537 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1541 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1545 * Removes multiple role assignments, parameters may contain:
1546 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1548 * @param array $params role assignment parameters
1549 * @param bool $subcontexts unassign in subcontexts too
1550 * @param bool $includemanual include manual role assignments too
1551 * @return void
1553 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1554 global $USER, $CFG, $DB;
1555 require_once($CFG->libdir . '/coursecatlib.php');
1557 if (!$params) {
1558 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1561 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1562 foreach ($params as $key=>$value) {
1563 if (!in_array($key, $allowed)) {
1564 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1568 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1569 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1572 if ($includemanual) {
1573 if (!isset($params['component']) or $params['component'] === '') {
1574 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1578 if ($subcontexts) {
1579 if (empty($params['contextid'])) {
1580 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1584 $ras = $DB->get_records('role_assignments', $params);
1585 foreach($ras as $ra) {
1586 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1587 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1588 // this is a bit expensive but necessary
1589 $context->mark_dirty();
1590 // If the user is the current user, then do full reload of capabilities too.
1591 if (!empty($USER->id) && $USER->id == $ra->userid) {
1592 reload_all_capabilities();
1594 $event = \core\event\role_unassigned::create(array(
1595 'context' => $context,
1596 'objectid' => $ra->roleid,
1597 'relateduserid' => $ra->userid,
1598 'other' => array(
1599 'id' => $ra->id,
1600 'component' => $ra->component,
1601 'itemid' => $ra->itemid
1604 $event->add_record_snapshot('role_assignments', $ra);
1605 $event->trigger();
1606 coursecat::role_assignment_changed($ra->roleid, $context);
1609 unset($ras);
1611 // process subcontexts
1612 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1613 if ($params['contextid'] instanceof context) {
1614 $context = $params['contextid'];
1615 } else {
1616 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1619 if ($context) {
1620 $contexts = $context->get_child_contexts();
1621 $mparams = $params;
1622 foreach($contexts as $context) {
1623 $mparams['contextid'] = $context->id;
1624 $ras = $DB->get_records('role_assignments', $mparams);
1625 foreach($ras as $ra) {
1626 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1627 // this is a bit expensive but necessary
1628 $context->mark_dirty();
1629 // If the user is the current user, then do full reload of capabilities too.
1630 if (!empty($USER->id) && $USER->id == $ra->userid) {
1631 reload_all_capabilities();
1633 $event = \core\event\role_unassigned::create(
1634 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1635 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1636 $event->add_record_snapshot('role_assignments', $ra);
1637 $event->trigger();
1638 coursecat::role_assignment_changed($ra->roleid, $context);
1644 // do this once more for all manual role assignments
1645 if ($includemanual) {
1646 $params['component'] = '';
1647 role_unassign_all($params, $subcontexts, false);
1652 * Determines if a user is currently logged in
1654 * @category access
1656 * @return bool
1658 function isloggedin() {
1659 global $USER;
1661 return (!empty($USER->id));
1665 * Determines if a user is logged in as real guest user with username 'guest'.
1667 * @category access
1669 * @param int|object $user mixed user object or id, $USER if not specified
1670 * @return bool true if user is the real guest user, false if not logged in or other user
1672 function isguestuser($user = null) {
1673 global $USER, $DB, $CFG;
1675 // make sure we have the user id cached in config table, because we are going to use it a lot
1676 if (empty($CFG->siteguest)) {
1677 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1678 // guest does not exist yet, weird
1679 return false;
1681 set_config('siteguest', $guestid);
1683 if ($user === null) {
1684 $user = $USER;
1687 if ($user === null) {
1688 // happens when setting the $USER
1689 return false;
1691 } else if (is_numeric($user)) {
1692 return ($CFG->siteguest == $user);
1694 } else if (is_object($user)) {
1695 if (empty($user->id)) {
1696 return false; // not logged in means is not be guest
1697 } else {
1698 return ($CFG->siteguest == $user->id);
1701 } else {
1702 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1707 * Does user have a (temporary or real) guest access to course?
1709 * @category access
1711 * @param context $context
1712 * @param stdClass|int $user
1713 * @return bool
1715 function is_guest(context $context, $user = null) {
1716 global $USER;
1718 // first find the course context
1719 $coursecontext = $context->get_course_context();
1721 // make sure there is a real user specified
1722 if ($user === null) {
1723 $userid = isset($USER->id) ? $USER->id : 0;
1724 } else {
1725 $userid = is_object($user) ? $user->id : $user;
1728 if (isguestuser($userid)) {
1729 // can not inspect or be enrolled
1730 return true;
1733 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1734 // viewing users appear out of nowhere, they are neither guests nor participants
1735 return false;
1738 // consider only real active enrolments here
1739 if (is_enrolled($coursecontext, $user, '', true)) {
1740 return false;
1743 return true;
1747 * Returns true if the user has moodle/course:view capability in the course,
1748 * this is intended for admins, managers (aka small admins), inspectors, etc.
1750 * @category access
1752 * @param context $context
1753 * @param int|stdClass $user if null $USER is used
1754 * @param string $withcapability extra capability name
1755 * @return bool
1757 function is_viewing(context $context, $user = null, $withcapability = '') {
1758 // first find the course context
1759 $coursecontext = $context->get_course_context();
1761 if (isguestuser($user)) {
1762 // can not inspect
1763 return false;
1766 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1767 // admins are allowed to inspect courses
1768 return false;
1771 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1772 // site admins always have the capability, but the enrolment above blocks
1773 return false;
1776 return true;
1780 * Returns true if the user is able to access the course.
1782 * This function is in no way, shape, or form a substitute for require_login.
1783 * It should only be used in circumstances where it is not possible to call require_login
1784 * such as the navigation.
1786 * This function checks many of the methods of access to a course such as the view
1787 * capability, enrollments, and guest access. It also makes use of the cache
1788 * generated by require_login for guest access.
1790 * The flags within the $USER object that are used here should NEVER be used outside
1791 * of this function can_access_course and require_login. Doing so WILL break future
1792 * versions.
1794 * @param stdClass $course record
1795 * @param stdClass|int|null $user user record or id, current user if null
1796 * @param string $withcapability Check for this capability as well.
1797 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1798 * @return boolean Returns true if the user is able to access the course
1800 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
1801 global $DB, $USER;
1803 // this function originally accepted $coursecontext parameter
1804 if ($course instanceof context) {
1805 if ($course instanceof context_course) {
1806 debugging('deprecated context parameter, please use $course record');
1807 $coursecontext = $course;
1808 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
1809 } else {
1810 debugging('Invalid context parameter, please use $course record');
1811 return false;
1813 } else {
1814 $coursecontext = context_course::instance($course->id);
1817 if (!isset($USER->id)) {
1818 // should never happen
1819 $USER->id = 0;
1820 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
1823 // make sure there is a user specified
1824 if ($user === null) {
1825 $userid = $USER->id;
1826 } else {
1827 $userid = is_object($user) ? $user->id : $user;
1829 unset($user);
1831 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
1832 return false;
1835 if ($userid == $USER->id) {
1836 if (!empty($USER->access['rsw'][$coursecontext->path])) {
1837 // the fact that somebody switched role means they can access the course no matter to what role they switched
1838 return true;
1842 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
1843 return false;
1846 if (is_viewing($coursecontext, $userid)) {
1847 return true;
1850 if ($userid != $USER->id) {
1851 // for performance reasons we do not verify temporary guest access for other users, sorry...
1852 return is_enrolled($coursecontext, $userid, '', $onlyactive);
1855 // === from here we deal only with $USER ===
1857 $coursecontext->reload_if_dirty();
1859 if (isset($USER->enrol['enrolled'][$course->id])) {
1860 if ($USER->enrol['enrolled'][$course->id] > time()) {
1861 return true;
1864 if (isset($USER->enrol['tempguest'][$course->id])) {
1865 if ($USER->enrol['tempguest'][$course->id] > time()) {
1866 return true;
1870 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
1871 return true;
1874 // if not enrolled try to gain temporary guest access
1875 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
1876 $enrols = enrol_get_plugins(true);
1877 foreach($instances as $instance) {
1878 if (!isset($enrols[$instance->enrol])) {
1879 continue;
1881 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
1882 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
1883 if ($until !== false and $until > time()) {
1884 $USER->enrol['tempguest'][$course->id] = $until;
1885 return true;
1888 if (isset($USER->enrol['tempguest'][$course->id])) {
1889 unset($USER->enrol['tempguest'][$course->id]);
1890 remove_temp_course_roles($coursecontext);
1893 return false;
1897 * Loads the capability definitions for the component (from file).
1899 * Loads the capability definitions for the component (from file). If no
1900 * capabilities are defined for the component, we simply return an empty array.
1902 * @access private
1903 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
1904 * @return array array of capabilities
1906 function load_capability_def($component) {
1907 $defpath = core_component::get_component_directory($component).'/db/access.php';
1909 $capabilities = array();
1910 if (file_exists($defpath)) {
1911 require($defpath);
1912 if (!empty(${$component.'_capabilities'})) {
1913 // BC capability array name
1914 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
1915 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
1916 $capabilities = ${$component.'_capabilities'};
1920 return $capabilities;
1924 * Gets the capabilities that have been cached in the database for this component.
1926 * @access private
1927 * @param string $component - examples: 'moodle', 'mod_forum'
1928 * @return array array of capabilities
1930 function get_cached_capabilities($component = 'moodle') {
1931 global $DB;
1932 $caps = get_all_capabilities();
1933 $componentcaps = array();
1934 foreach ($caps as $cap) {
1935 if ($cap['component'] == $component) {
1936 $componentcaps[] = (object) $cap;
1939 return $componentcaps;
1943 * Returns default capabilities for given role archetype.
1945 * @param string $archetype role archetype
1946 * @return array
1948 function get_default_capabilities($archetype) {
1949 global $DB;
1951 if (!$archetype) {
1952 return array();
1955 $alldefs = array();
1956 $defaults = array();
1957 $components = array();
1958 $allcaps = get_all_capabilities();
1960 foreach ($allcaps as $cap) {
1961 if (!in_array($cap['component'], $components)) {
1962 $components[] = $cap['component'];
1963 $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
1966 foreach($alldefs as $name=>$def) {
1967 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
1968 if (isset($def['archetypes'])) {
1969 if (isset($def['archetypes'][$archetype])) {
1970 $defaults[$name] = $def['archetypes'][$archetype];
1972 // 'legacy' is for backward compatibility with 1.9 access.php
1973 } else {
1974 if (isset($def['legacy'][$archetype])) {
1975 $defaults[$name] = $def['legacy'][$archetype];
1980 return $defaults;
1984 * Return default roles that can be assigned, overridden or switched
1985 * by give role archetype.
1987 * @param string $type assign|override|switch|view
1988 * @param string $archetype
1989 * @return array of role ids
1991 function get_default_role_archetype_allows($type, $archetype) {
1992 global $DB;
1994 if (empty($archetype)) {
1995 return array();
1998 $roles = $DB->get_records('role');
1999 $archetypemap = array();
2000 foreach ($roles as $role) {
2001 if ($role->archetype) {
2002 $archetypemap[$role->archetype][$role->id] = $role->id;
2006 $defaults = array(
2007 'assign' => array(
2008 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2009 'coursecreator' => array(),
2010 'editingteacher' => array('teacher', 'student'),
2011 'teacher' => array(),
2012 'student' => array(),
2013 'guest' => array(),
2014 'user' => array(),
2015 'frontpage' => array(),
2017 'override' => array(
2018 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2019 'coursecreator' => array(),
2020 'editingteacher' => array('teacher', 'student', 'guest'),
2021 'teacher' => array(),
2022 'student' => array(),
2023 'guest' => array(),
2024 'user' => array(),
2025 'frontpage' => array(),
2027 'switch' => array(
2028 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2029 'coursecreator' => array(),
2030 'editingteacher' => array('teacher', 'student', 'guest'),
2031 'teacher' => array('student', 'guest'),
2032 'student' => array(),
2033 'guest' => array(),
2034 'user' => array(),
2035 'frontpage' => array(),
2037 'view' => array(
2038 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2039 'coursecreator' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2040 'editingteacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2041 'teacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2042 'student' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2043 'guest' => array(),
2044 'user' => array(),
2045 'frontpage' => array(),
2049 if (!isset($defaults[$type][$archetype])) {
2050 debugging("Unknown type '$type'' or archetype '$archetype''");
2051 return array();
2054 $return = array();
2055 foreach ($defaults[$type][$archetype] as $at) {
2056 if (isset($archetypemap[$at])) {
2057 foreach ($archetypemap[$at] as $roleid) {
2058 $return[$roleid] = $roleid;
2063 return $return;
2067 * Reset role capabilities to default according to selected role archetype.
2068 * If no archetype selected, removes all capabilities.
2070 * This applies to capabilities that are assigned to the role (that you could
2071 * edit in the 'define roles' interface), and not to any capability overrides
2072 * in different locations.
2074 * @param int $roleid ID of role to reset capabilities for
2076 function reset_role_capabilities($roleid) {
2077 global $DB;
2079 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2080 $defaultcaps = get_default_capabilities($role->archetype);
2082 $systemcontext = context_system::instance();
2084 $DB->delete_records('role_capabilities',
2085 array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2087 foreach($defaultcaps as $cap=>$permission) {
2088 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2091 // Reset any cache of this role, including MUC.
2092 accesslib_clear_role_cache($roleid);
2094 // Mark the system context dirty.
2095 context_system::instance()->mark_dirty();
2099 * Updates the capabilities table with the component capability definitions.
2100 * If no parameters are given, the function updates the core moodle
2101 * capabilities.
2103 * Note that the absence of the db/access.php capabilities definition file
2104 * will cause any stored capabilities for the component to be removed from
2105 * the database.
2107 * @access private
2108 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2109 * @return boolean true if success, exception in case of any problems
2111 function update_capabilities($component = 'moodle') {
2112 global $DB, $OUTPUT;
2114 $storedcaps = array();
2116 $filecaps = load_capability_def($component);
2117 foreach($filecaps as $capname=>$unused) {
2118 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2119 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2123 // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2124 // So ensure our updating is based on fresh data.
2125 cache::make('core', 'capabilities')->delete('core_capabilities');
2127 $cachedcaps = get_cached_capabilities($component);
2128 if ($cachedcaps) {
2129 foreach ($cachedcaps as $cachedcap) {
2130 array_push($storedcaps, $cachedcap->name);
2131 // update risk bitmasks and context levels in existing capabilities if needed
2132 if (array_key_exists($cachedcap->name, $filecaps)) {
2133 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2134 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2136 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2137 $updatecap = new stdClass();
2138 $updatecap->id = $cachedcap->id;
2139 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2140 $DB->update_record('capabilities', $updatecap);
2142 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2143 $updatecap = new stdClass();
2144 $updatecap->id = $cachedcap->id;
2145 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2146 $DB->update_record('capabilities', $updatecap);
2149 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2150 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2152 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2153 $updatecap = new stdClass();
2154 $updatecap->id = $cachedcap->id;
2155 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2156 $DB->update_record('capabilities', $updatecap);
2162 // Flush the cached again, as we have changed DB.
2163 cache::make('core', 'capabilities')->delete('core_capabilities');
2165 // Are there new capabilities in the file definition?
2166 $newcaps = array();
2168 foreach ($filecaps as $filecap => $def) {
2169 if (!$storedcaps ||
2170 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2171 if (!array_key_exists('riskbitmask', $def)) {
2172 $def['riskbitmask'] = 0; // no risk if not specified
2174 $newcaps[$filecap] = $def;
2177 // Add new capabilities to the stored definition.
2178 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2179 foreach ($newcaps as $capname => $capdef) {
2180 $capability = new stdClass();
2181 $capability->name = $capname;
2182 $capability->captype = $capdef['captype'];
2183 $capability->contextlevel = $capdef['contextlevel'];
2184 $capability->component = $component;
2185 $capability->riskbitmask = $capdef['riskbitmask'];
2187 $DB->insert_record('capabilities', $capability, false);
2189 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2190 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2191 foreach ($rolecapabilities as $rolecapability){
2192 //assign_capability will update rather than insert if capability exists
2193 if (!assign_capability($capname, $rolecapability->permission,
2194 $rolecapability->roleid, $rolecapability->contextid, true)){
2195 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2199 // we ignore archetype key if we have cloned permissions
2200 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2201 assign_legacy_capabilities($capname, $capdef['archetypes']);
2202 // 'legacy' is for backward compatibility with 1.9 access.php
2203 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2204 assign_legacy_capabilities($capname, $capdef['legacy']);
2207 // Are there any capabilities that have been removed from the file
2208 // definition that we need to delete from the stored capabilities and
2209 // role assignments?
2210 capabilities_cleanup($component, $filecaps);
2212 // reset static caches
2213 accesslib_clear_all_caches(false);
2215 // Flush the cached again, as we have changed DB.
2216 cache::make('core', 'capabilities')->delete('core_capabilities');
2218 return true;
2222 * Deletes cached capabilities that are no longer needed by the component.
2223 * Also unassigns these capabilities from any roles that have them.
2224 * NOTE: this function is called from lib/db/upgrade.php
2226 * @access private
2227 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2228 * @param array $newcapdef array of the new capability definitions that will be
2229 * compared with the cached capabilities
2230 * @return int number of deprecated capabilities that have been removed
2232 function capabilities_cleanup($component, $newcapdef = null) {
2233 global $DB;
2235 $removedcount = 0;
2237 if ($cachedcaps = get_cached_capabilities($component)) {
2238 foreach ($cachedcaps as $cachedcap) {
2239 if (empty($newcapdef) ||
2240 array_key_exists($cachedcap->name, $newcapdef) === false) {
2242 // Remove from capabilities cache.
2243 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2244 $removedcount++;
2245 // Delete from roles.
2246 if ($roles = get_roles_with_capability($cachedcap->name)) {
2247 foreach($roles as $role) {
2248 if (!unassign_capability($cachedcap->name, $role->id)) {
2249 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2253 } // End if.
2256 if ($removedcount) {
2257 cache::make('core', 'capabilities')->delete('core_capabilities');
2259 return $removedcount;
2263 * Returns an array of all the known types of risk
2264 * The array keys can be used, for example as CSS class names, or in calls to
2265 * print_risk_icon. The values are the corresponding RISK_ constants.
2267 * @return array all the known types of risk.
2269 function get_all_risks() {
2270 return array(
2271 'riskmanagetrust' => RISK_MANAGETRUST,
2272 'riskconfig' => RISK_CONFIG,
2273 'riskxss' => RISK_XSS,
2274 'riskpersonal' => RISK_PERSONAL,
2275 'riskspam' => RISK_SPAM,
2276 'riskdataloss' => RISK_DATALOSS,
2281 * Return a link to moodle docs for a given capability name
2283 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2284 * @return string the human-readable capability name as a link to Moodle Docs.
2286 function get_capability_docs_link($capability) {
2287 $url = get_docs_url('Capabilities/' . $capability->name);
2288 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2292 * This function pulls out all the resolved capabilities (overrides and
2293 * defaults) of a role used in capability overrides in contexts at a given
2294 * context.
2296 * @param int $roleid
2297 * @param context $context
2298 * @param string $cap capability, optional, defaults to ''
2299 * @return array Array of capabilities
2301 function role_context_capabilities($roleid, context $context, $cap = '') {
2302 global $DB;
2304 $contexts = $context->get_parent_context_ids(true);
2305 $contexts = '('.implode(',', $contexts).')';
2307 $params = array($roleid);
2309 if ($cap) {
2310 $search = " AND rc.capability = ? ";
2311 $params[] = $cap;
2312 } else {
2313 $search = '';
2316 $sql = "SELECT rc.*
2317 FROM {role_capabilities} rc, {context} c
2318 WHERE rc.contextid in $contexts
2319 AND rc.roleid = ?
2320 AND rc.contextid = c.id $search
2321 ORDER BY c.contextlevel DESC, rc.capability DESC";
2323 $capabilities = array();
2325 if ($records = $DB->get_records_sql($sql, $params)) {
2326 // We are traversing via reverse order.
2327 foreach ($records as $record) {
2328 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2329 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2330 $capabilities[$record->capability] = $record->permission;
2334 return $capabilities;
2338 * Constructs array with contextids as first parameter and context paths,
2339 * in both cases bottom top including self.
2341 * @access private
2342 * @param context $context
2343 * @return array
2345 function get_context_info_list(context $context) {
2346 $contextids = explode('/', ltrim($context->path, '/'));
2347 $contextpaths = array();
2348 $contextids2 = $contextids;
2349 while ($contextids2) {
2350 $contextpaths[] = '/' . implode('/', $contextids2);
2351 array_pop($contextids2);
2353 return array($contextids, $contextpaths);
2357 * Check if context is the front page context or a context inside it
2359 * Returns true if this context is the front page context, or a context inside it,
2360 * otherwise false.
2362 * @param context $context a context object.
2363 * @return bool
2365 function is_inside_frontpage(context $context) {
2366 $frontpagecontext = context_course::instance(SITEID);
2367 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2371 * Returns capability information (cached)
2373 * @param string $capabilityname
2374 * @return stdClass or null if capability not found
2376 function get_capability_info($capabilityname) {
2377 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2379 $caps = get_all_capabilities();
2381 if (!isset($caps[$capabilityname])) {
2382 return null;
2385 return (object) $caps[$capabilityname];
2389 * Returns all capabilitiy records, preferably from MUC and not database.
2391 * @return array All capability records indexed by capability name
2393 function get_all_capabilities() {
2394 global $DB;
2395 $cache = cache::make('core', 'capabilities');
2396 if (!$allcaps = $cache->get('core_capabilities')) {
2397 $rs = $DB->get_recordset('capabilities');
2398 $allcaps = array();
2399 foreach ($rs as $capability) {
2400 $capability->riskbitmask = (int) $capability->riskbitmask;
2401 $allcaps[$capability->name] = (array) $capability;
2403 $rs->close();
2404 $cache->set('core_capabilities', $allcaps);
2406 return $allcaps;
2410 * Returns the human-readable, translated version of the capability.
2411 * Basically a big switch statement.
2413 * @param string $capabilityname e.g. mod/choice:readresponses
2414 * @return string
2416 function get_capability_string($capabilityname) {
2418 // Typical capability name is 'plugintype/pluginname:capabilityname'
2419 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2421 if ($type === 'moodle') {
2422 $component = 'core_role';
2423 } else if ($type === 'quizreport') {
2424 //ugly hack!!
2425 $component = 'quiz_'.$name;
2426 } else {
2427 $component = $type.'_'.$name;
2430 $stringname = $name.':'.$capname;
2432 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2433 return get_string($stringname, $component);
2436 $dir = core_component::get_component_directory($component);
2437 if (!file_exists($dir)) {
2438 // plugin broken or does not exist, do not bother with printing of debug message
2439 return $capabilityname.' ???';
2442 // something is wrong in plugin, better print debug
2443 return get_string($stringname, $component);
2447 * This gets the mod/block/course/core etc strings.
2449 * @param string $component
2450 * @param int $contextlevel
2451 * @return string|bool String is success, false if failed
2453 function get_component_string($component, $contextlevel) {
2455 if ($component === 'moodle' or $component === 'core') {
2456 switch ($contextlevel) {
2457 // TODO MDL-46123: this should probably use context level names instead
2458 case CONTEXT_SYSTEM: return get_string('coresystem');
2459 case CONTEXT_USER: return get_string('users');
2460 case CONTEXT_COURSECAT: return get_string('categories');
2461 case CONTEXT_COURSE: return get_string('course');
2462 case CONTEXT_MODULE: return get_string('activities');
2463 case CONTEXT_BLOCK: return get_string('block');
2464 default: print_error('unknowncontext');
2468 list($type, $name) = core_component::normalize_component($component);
2469 $dir = core_component::get_plugin_directory($type, $name);
2470 if (!file_exists($dir)) {
2471 // plugin not installed, bad luck, there is no way to find the name
2472 return $component.' ???';
2475 switch ($type) {
2476 // TODO MDL-46123: this is really hacky and should be improved.
2477 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2478 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2479 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2480 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2481 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2482 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2483 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2484 case 'mod':
2485 if (get_string_manager()->string_exists('pluginname', $component)) {
2486 return get_string('activity').': '.get_string('pluginname', $component);
2487 } else {
2488 return get_string('activity').': '.get_string('modulename', $component);
2490 default: return get_string('pluginname', $component);
2495 * Gets the list of roles assigned to this context and up (parents)
2496 * from the aggregation of:
2497 * a) the list of roles that are visible on user profile page and participants page (profileroles setting) and;
2498 * b) if applicable, those roles that are assigned in the context.
2500 * @param context $context
2501 * @return array
2503 function get_profile_roles(context $context) {
2504 global $CFG, $DB;
2505 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2506 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2507 if (has_capability('moodle/role:assign', $context)) {
2508 $rolesinscope = array_keys(get_all_roles($context));
2509 } else {
2510 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2513 if (empty($rolesinscope)) {
2514 return [];
2517 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2518 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2519 $params = array_merge($params, $cparams);
2521 if ($coursecontext = $context->get_course_context(false)) {
2522 $params['coursecontext'] = $coursecontext->id;
2523 } else {
2524 $params['coursecontext'] = 0;
2527 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2528 FROM {role_assignments} ra, {role} r
2529 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2530 WHERE r.id = ra.roleid
2531 AND ra.contextid $contextlist
2532 AND r.id $rallowed
2533 ORDER BY r.sortorder ASC";
2535 return $DB->get_records_sql($sql, $params);
2539 * Gets the list of roles assigned to this context and up (parents)
2541 * @param context $context
2542 * @return array
2544 function get_roles_used_in_context(context $context) {
2545 global $DB;
2547 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2549 if ($coursecontext = $context->get_course_context(false)) {
2550 $params['coursecontext'] = $coursecontext->id;
2551 } else {
2552 $params['coursecontext'] = 0;
2555 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2556 FROM {role_assignments} ra, {role} r
2557 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2558 WHERE r.id = ra.roleid
2559 AND ra.contextid $contextlist
2560 ORDER BY r.sortorder ASC";
2562 return $DB->get_records_sql($sql, $params);
2566 * This function is used to print roles column in user profile page.
2567 * It is using the CFG->profileroles to limit the list to only interesting roles.
2568 * (The permission tab has full details of user role assignments.)
2570 * @param int $userid
2571 * @param int $courseid
2572 * @return string
2574 function get_user_roles_in_course($userid, $courseid) {
2575 global $CFG, $DB;
2576 if ($courseid == SITEID) {
2577 $context = context_system::instance();
2578 } else {
2579 $context = context_course::instance($courseid);
2581 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2582 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2583 if (has_capability('moodle/role:assign', $context)) {
2584 $rolesinscope = array_keys(get_all_roles($context));
2585 } else {
2586 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2588 if (empty($rolesinscope)) {
2589 return '';
2592 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2593 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2594 $params = array_merge($params, $cparams);
2596 if ($coursecontext = $context->get_course_context(false)) {
2597 $params['coursecontext'] = $coursecontext->id;
2598 } else {
2599 $params['coursecontext'] = 0;
2602 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2603 FROM {role_assignments} ra, {role} r
2604 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2605 WHERE r.id = ra.roleid
2606 AND ra.contextid $contextlist
2607 AND r.id $rallowed
2608 AND ra.userid = :userid
2609 ORDER BY r.sortorder ASC";
2610 $params['userid'] = $userid;
2612 $rolestring = '';
2614 if ($roles = $DB->get_records_sql($sql, $params)) {
2615 $viewableroles = get_viewable_roles($context, $userid);
2617 $rolenames = array();
2618 foreach ($roles as $roleid => $unused) {
2619 if (isset($viewableroles[$roleid])) {
2620 $url = new moodle_url('/user/index.php', ['contextid' => $context->id, 'roleid' => $roleid]);
2621 $rolenames[] = '<a href="' . $url . '">' . $viewableroles[$roleid] . '</a>';
2624 $rolestring = implode(',', $rolenames);
2627 return $rolestring;
2631 * Checks if a user can assign users to a particular role in this context
2633 * @param context $context
2634 * @param int $targetroleid - the id of the role you want to assign users to
2635 * @return boolean
2637 function user_can_assign(context $context, $targetroleid) {
2638 global $DB;
2640 // First check to see if the user is a site administrator.
2641 if (is_siteadmin()) {
2642 return true;
2645 // Check if user has override capability.
2646 // If not return false.
2647 if (!has_capability('moodle/role:assign', $context)) {
2648 return false;
2650 // pull out all active roles of this user from this context(or above)
2651 if ($userroles = get_user_roles($context)) {
2652 foreach ($userroles as $userrole) {
2653 // if any in the role_allow_override table, then it's ok
2654 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2655 return true;
2660 return false;
2664 * Returns all site roles in correct sort order.
2666 * Note: this method does not localise role names or descriptions,
2667 * use role_get_names() if you need role names.
2669 * @param context $context optional context for course role name aliases
2670 * @return array of role records with optional coursealias property
2672 function get_all_roles(context $context = null) {
2673 global $DB;
2675 if (!$context or !$coursecontext = $context->get_course_context(false)) {
2676 $coursecontext = null;
2679 if ($coursecontext) {
2680 $sql = "SELECT r.*, rn.name AS coursealias
2681 FROM {role} r
2682 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2683 ORDER BY r.sortorder ASC";
2684 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
2686 } else {
2687 return $DB->get_records('role', array(), 'sortorder ASC');
2692 * Returns roles of a specified archetype
2694 * @param string $archetype
2695 * @return array of full role records
2697 function get_archetype_roles($archetype) {
2698 global $DB;
2699 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2703 * Gets all the user roles assigned in this context, or higher contexts for a list of users.
2705 * @param context $context
2706 * @param array $userids. An empty list means fetch all role assignments for the context.
2707 * @param bool $checkparentcontexts defaults to true
2708 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2709 * @return array
2711 function get_users_roles(context $context, $userids = [], $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2712 global $USER, $DB;
2714 if ($checkparentcontexts) {
2715 $contextids = $context->get_parent_context_ids();
2716 } else {
2717 $contextids = array();
2719 $contextids[] = $context->id;
2721 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
2723 // If userids was passed as an empty array, we fetch all role assignments for the course.
2724 if (empty($userids)) {
2725 $useridlist = ' IS NOT NULL ';
2726 $uparams = [];
2727 } else {
2728 list($useridlist, $uparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'uids');
2731 $sql = "SELECT ra.*, r.name, r.shortname, ra.userid
2732 FROM {role_assignments} ra, {role} r, {context} c
2733 WHERE ra.userid $useridlist
2734 AND ra.roleid = r.id
2735 AND ra.contextid = c.id
2736 AND ra.contextid $contextids
2737 ORDER BY $order";
2739 $all = $DB->get_records_sql($sql , array_merge($params, $uparams));
2741 // Return results grouped by userid.
2742 $result = [];
2743 foreach ($all as $id => $record) {
2744 if (!isset($result[$record->userid])) {
2745 $result[$record->userid] = [];
2747 $result[$record->userid][$record->id] = $record;
2750 // Make sure all requested users are included in the result, even if they had no role assignments.
2751 foreach ($userids as $id) {
2752 if (!isset($result[$id])) {
2753 $result[$id] = [];
2757 return $result;
2762 * Gets all the user roles assigned in this context, or higher contexts
2763 * this is mainly used when checking if a user can assign a role, or overriding a role
2764 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2765 * allow_override tables
2767 * @param context $context
2768 * @param int $userid
2769 * @param bool $checkparentcontexts defaults to true
2770 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2771 * @return array
2773 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2774 global $USER, $DB;
2776 if (empty($userid)) {
2777 if (empty($USER->id)) {
2778 return array();
2780 $userid = $USER->id;
2783 if ($checkparentcontexts) {
2784 $contextids = $context->get_parent_context_ids();
2785 } else {
2786 $contextids = array();
2788 $contextids[] = $context->id;
2790 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2792 array_unshift($params, $userid);
2794 $sql = "SELECT ra.*, r.name, r.shortname
2795 FROM {role_assignments} ra, {role} r, {context} c
2796 WHERE ra.userid = ?
2797 AND ra.roleid = r.id
2798 AND ra.contextid = c.id
2799 AND ra.contextid $contextids
2800 ORDER BY $order";
2802 return $DB->get_records_sql($sql ,$params);
2806 * Like get_user_roles, but adds in the authenticated user role, and the front
2807 * page roles, if applicable.
2809 * @param context $context the context.
2810 * @param int $userid optional. Defaults to $USER->id
2811 * @return array of objects with fields ->userid, ->contextid and ->roleid.
2813 function get_user_roles_with_special(context $context, $userid = 0) {
2814 global $CFG, $USER;
2816 if (empty($userid)) {
2817 if (empty($USER->id)) {
2818 return array();
2820 $userid = $USER->id;
2823 $ras = get_user_roles($context, $userid);
2825 // Add front-page role if relevant.
2826 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2827 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
2828 is_inside_frontpage($context);
2829 if ($defaultfrontpageroleid && $isfrontpage) {
2830 $frontpagecontext = context_course::instance(SITEID);
2831 $ra = new stdClass();
2832 $ra->userid = $userid;
2833 $ra->contextid = $frontpagecontext->id;
2834 $ra->roleid = $defaultfrontpageroleid;
2835 $ras[] = $ra;
2838 // Add authenticated user role if relevant.
2839 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2840 if ($defaultuserroleid && !isguestuser($userid)) {
2841 $systemcontext = context_system::instance();
2842 $ra = new stdClass();
2843 $ra->userid = $userid;
2844 $ra->contextid = $systemcontext->id;
2845 $ra->roleid = $defaultuserroleid;
2846 $ras[] = $ra;
2849 return $ras;
2853 * Creates a record in the role_allow_override table
2855 * @param int $fromroleid source roleid
2856 * @param int $targetroleid target roleid
2857 * @return void
2859 function core_role_set_override_allowed($fromroleid, $targetroleid) {
2860 global $DB;
2862 $record = new stdClass();
2863 $record->roleid = $fromroleid;
2864 $record->allowoverride = $targetroleid;
2865 $DB->insert_record('role_allow_override', $record);
2869 * Creates a record in the role_allow_assign table
2871 * @param int $fromroleid source roleid
2872 * @param int $targetroleid target roleid
2873 * @return void
2875 function core_role_set_assign_allowed($fromroleid, $targetroleid) {
2876 global $DB;
2878 $record = new stdClass();
2879 $record->roleid = $fromroleid;
2880 $record->allowassign = $targetroleid;
2881 $DB->insert_record('role_allow_assign', $record);
2885 * Creates a record in the role_allow_switch table
2887 * @param int $fromroleid source roleid
2888 * @param int $targetroleid target roleid
2889 * @return void
2891 function core_role_set_switch_allowed($fromroleid, $targetroleid) {
2892 global $DB;
2894 $record = new stdClass();
2895 $record->roleid = $fromroleid;
2896 $record->allowswitch = $targetroleid;
2897 $DB->insert_record('role_allow_switch', $record);
2901 * Creates a record in the role_allow_view table
2903 * @param int $fromroleid source roleid
2904 * @param int $targetroleid target roleid
2905 * @return void
2907 function core_role_set_view_allowed($fromroleid, $targetroleid) {
2908 global $DB;
2910 $record = new stdClass();
2911 $record->roleid = $fromroleid;
2912 $record->allowview = $targetroleid;
2913 $DB->insert_record('role_allow_view', $record);
2917 * Gets a list of roles that this user can assign in this context
2919 * @param context $context the context.
2920 * @param int $rolenamedisplay the type of role name to display. One of the
2921 * ROLENAME_X constants. Default ROLENAME_ALIAS.
2922 * @param bool $withusercounts if true, count the number of users with each role.
2923 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
2924 * @return array if $withusercounts is false, then an array $roleid => $rolename.
2925 * if $withusercounts is true, returns a list of three arrays,
2926 * $rolenames, $rolecounts, and $nameswithcounts.
2928 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
2929 global $USER, $DB;
2931 // make sure there is a real user specified
2932 if ($user === null) {
2933 $userid = isset($USER->id) ? $USER->id : 0;
2934 } else {
2935 $userid = is_object($user) ? $user->id : $user;
2938 if (!has_capability('moodle/role:assign', $context, $userid)) {
2939 if ($withusercounts) {
2940 return array(array(), array(), array());
2941 } else {
2942 return array();
2946 $params = array();
2947 $extrafields = '';
2949 if ($withusercounts) {
2950 $extrafields = ', (SELECT count(u.id)
2951 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
2952 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
2953 ) AS usercount';
2954 $params['conid'] = $context->id;
2957 if (is_siteadmin($userid)) {
2958 // show all roles allowed in this context to admins
2959 $assignrestriction = "";
2960 } else {
2961 $parents = $context->get_parent_context_ids(true);
2962 $contexts = implode(',' , $parents);
2963 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
2964 FROM {role_allow_assign} raa
2965 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
2966 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
2967 ) ar ON ar.id = r.id";
2968 $params['userid'] = $userid;
2970 $params['contextlevel'] = $context->contextlevel;
2972 if ($coursecontext = $context->get_course_context(false)) {
2973 $params['coursecontext'] = $coursecontext->id;
2974 } else {
2975 $params['coursecontext'] = 0; // no course aliases
2976 $coursecontext = null;
2978 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
2979 FROM {role} r
2980 $assignrestriction
2981 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
2982 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2983 ORDER BY r.sortorder ASC";
2984 $roles = $DB->get_records_sql($sql, $params);
2986 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
2988 if (!$withusercounts) {
2989 return $rolenames;
2992 $rolecounts = array();
2993 $nameswithcounts = array();
2994 foreach ($roles as $role) {
2995 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
2996 $rolecounts[$role->id] = $roles[$role->id]->usercount;
2998 return array($rolenames, $rolecounts, $nameswithcounts);
3002 * Gets a list of roles that this user can switch to in a context
3004 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3005 * This function just process the contents of the role_allow_switch table. You also need to
3006 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3008 * @param context $context a context.
3009 * @return array an array $roleid => $rolename.
3011 function get_switchable_roles(context $context) {
3012 global $USER, $DB;
3014 // You can't switch roles without this capability.
3015 if (!has_capability('moodle/role:switchroles', $context)) {
3016 return [];
3019 $params = array();
3020 $extrajoins = '';
3021 $extrawhere = '';
3022 if (!is_siteadmin()) {
3023 // Admins are allowed to switch to any role with.
3024 // Others are subject to the additional constraint that the switch-to role must be allowed by
3025 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3026 $parents = $context->get_parent_context_ids(true);
3027 $contexts = implode(',' , $parents);
3029 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3030 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3031 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3032 $params['userid'] = $USER->id;
3035 if ($coursecontext = $context->get_course_context(false)) {
3036 $params['coursecontext'] = $coursecontext->id;
3037 } else {
3038 $params['coursecontext'] = 0; // no course aliases
3039 $coursecontext = null;
3042 $query = "
3043 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3044 FROM (SELECT DISTINCT rc.roleid
3045 FROM {role_capabilities} rc
3046 $extrajoins
3047 $extrawhere) idlist
3048 JOIN {role} r ON r.id = idlist.roleid
3049 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3050 ORDER BY r.sortorder";
3051 $roles = $DB->get_records_sql($query, $params);
3053 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3057 * Gets a list of roles that this user can view in a context
3059 * @param context $context a context.
3060 * @param int $userid id of user.
3061 * @return array an array $roleid => $rolename.
3063 function get_viewable_roles(context $context, $userid = null) {
3064 global $USER, $DB;
3066 if ($userid == null) {
3067 $userid = $USER->id;
3070 $params = array();
3071 $extrajoins = '';
3072 $extrawhere = '';
3073 if (!is_siteadmin()) {
3074 // Admins are allowed to view any role.
3075 // Others are subject to the additional constraint that the view role must be allowed by
3076 // 'role_allow_view' for some role they have assigned in this context or any parent.
3077 $contexts = $context->get_parent_context_ids(true);
3078 list($insql, $inparams) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED);
3080 $extrajoins = "JOIN {role_allow_view} ras ON ras.allowview = r.id
3081 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3082 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid $insql";
3084 $params += $inparams;
3085 $params['userid'] = $userid;
3088 if ($coursecontext = $context->get_course_context(false)) {
3089 $params['coursecontext'] = $coursecontext->id;
3090 } else {
3091 $params['coursecontext'] = 0; // No course aliases.
3092 $coursecontext = null;
3095 $query = "
3096 SELECT r.id, r.name, r.shortname, rn.name AS coursealias, r.sortorder
3097 FROM {role} r
3098 $extrajoins
3099 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3100 $extrawhere
3101 GROUP BY r.id, r.name, r.shortname, rn.name, r.sortorder
3102 ORDER BY r.sortorder";
3103 $roles = $DB->get_records_sql($query, $params);
3105 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3109 * Gets a list of roles that this user can override in this context.
3111 * @param context $context the context.
3112 * @param int $rolenamedisplay the type of role name to display. One of the
3113 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3114 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3115 * @return array if $withcounts is false, then an array $roleid => $rolename.
3116 * if $withusercounts is true, returns a list of three arrays,
3117 * $rolenames, $rolecounts, and $nameswithcounts.
3119 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3120 global $USER, $DB;
3122 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3123 if ($withcounts) {
3124 return array(array(), array(), array());
3125 } else {
3126 return array();
3130 $parents = $context->get_parent_context_ids(true);
3131 $contexts = implode(',' , $parents);
3133 $params = array();
3134 $extrafields = '';
3136 $params['userid'] = $USER->id;
3137 if ($withcounts) {
3138 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3139 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3140 $params['conid'] = $context->id;
3143 if ($coursecontext = $context->get_course_context(false)) {
3144 $params['coursecontext'] = $coursecontext->id;
3145 } else {
3146 $params['coursecontext'] = 0; // no course aliases
3147 $coursecontext = null;
3150 if (is_siteadmin()) {
3151 // show all roles to admins
3152 $roles = $DB->get_records_sql("
3153 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3154 FROM {role} ro
3155 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3156 ORDER BY ro.sortorder ASC", $params);
3158 } else {
3159 $roles = $DB->get_records_sql("
3160 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3161 FROM {role} ro
3162 JOIN (SELECT DISTINCT r.id
3163 FROM {role} r
3164 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3165 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3166 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3167 ) inline_view ON ro.id = inline_view.id
3168 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3169 ORDER BY ro.sortorder ASC", $params);
3172 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3174 if (!$withcounts) {
3175 return $rolenames;
3178 $rolecounts = array();
3179 $nameswithcounts = array();
3180 foreach ($roles as $role) {
3181 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3182 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3184 return array($rolenames, $rolecounts, $nameswithcounts);
3188 * Create a role menu suitable for default role selection in enrol plugins.
3190 * @package core_enrol
3192 * @param context $context
3193 * @param int $addroleid current or default role - always added to list
3194 * @return array roleid=>localised role name
3196 function get_default_enrol_roles(context $context, $addroleid = null) {
3197 global $DB;
3199 $params = array('contextlevel'=>CONTEXT_COURSE);
3201 if ($coursecontext = $context->get_course_context(false)) {
3202 $params['coursecontext'] = $coursecontext->id;
3203 } else {
3204 $params['coursecontext'] = 0; // no course names
3205 $coursecontext = null;
3208 if ($addroleid) {
3209 $addrole = "OR r.id = :addroleid";
3210 $params['addroleid'] = $addroleid;
3211 } else {
3212 $addrole = "";
3215 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3216 FROM {role} r
3217 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3218 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3219 WHERE rcl.id IS NOT NULL $addrole
3220 ORDER BY sortorder DESC";
3222 $roles = $DB->get_records_sql($sql, $params);
3224 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3228 * Return context levels where this role is assignable.
3230 * @param integer $roleid the id of a role.
3231 * @return array list of the context levels at which this role may be assigned.
3233 function get_role_contextlevels($roleid) {
3234 global $DB;
3235 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3236 'contextlevel', 'id,contextlevel');
3240 * Return roles suitable for assignment at the specified context level.
3242 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3244 * @param integer $contextlevel a contextlevel.
3245 * @return array list of role ids that are assignable at this context level.
3247 function get_roles_for_contextlevels($contextlevel) {
3248 global $DB;
3249 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3250 '', 'id,roleid');
3254 * Returns default context levels where roles can be assigned.
3256 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3257 * from the array returned by get_role_archetypes();
3258 * @return array list of the context levels at which this type of role may be assigned by default.
3260 function get_default_contextlevels($rolearchetype) {
3261 static $defaults = array(
3262 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3263 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3264 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3265 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3266 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3267 'guest' => array(),
3268 'user' => array(),
3269 'frontpage' => array());
3271 if (isset($defaults[$rolearchetype])) {
3272 return $defaults[$rolearchetype];
3273 } else {
3274 return array();
3279 * Set the context levels at which a particular role can be assigned.
3280 * Throws exceptions in case of error.
3282 * @param integer $roleid the id of a role.
3283 * @param array $contextlevels the context levels at which this role should be assignable,
3284 * duplicate levels are removed.
3285 * @return void
3287 function set_role_contextlevels($roleid, array $contextlevels) {
3288 global $DB;
3289 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3290 $rcl = new stdClass();
3291 $rcl->roleid = $roleid;
3292 $contextlevels = array_unique($contextlevels);
3293 foreach ($contextlevels as $level) {
3294 $rcl->contextlevel = $level;
3295 $DB->insert_record('role_context_levels', $rcl, false, true);
3300 * Who has this capability in this context?
3302 * This can be a very expensive call - use sparingly and keep
3303 * the results if you are going to need them again soon.
3305 * Note if $fields is empty this function attempts to get u.*
3306 * which can get rather large - and has a serious perf impact
3307 * on some DBs.
3309 * @param context $context
3310 * @param string|array $capability - capability name(s)
3311 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3312 * @param string $sort - the sort order. Default is lastaccess time.
3313 * @param mixed $limitfrom - number of records to skip (offset)
3314 * @param mixed $limitnum - number of records to fetch
3315 * @param string|array $groups - single group or array of groups - only return
3316 * users who are in one of these group(s).
3317 * @param string|array $exceptions - list of users to exclude, comma separated or array
3318 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3319 * @param bool $view_ignored - use get_enrolled_sql() instead
3320 * @param bool $useviewallgroups if $groups is set the return users who
3321 * have capability both $capability and moodle/site:accessallgroups
3322 * in this context, as well as users who have $capability and who are
3323 * in $groups.
3324 * @return array of user records
3326 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3327 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3328 global $CFG, $DB;
3330 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3331 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3333 $ctxids = trim($context->path, '/');
3334 $ctxids = str_replace('/', ',', $ctxids);
3336 // Context is the frontpage
3337 $iscoursepage = false; // coursepage other than fp
3338 $isfrontpage = false;
3339 if ($context->contextlevel == CONTEXT_COURSE) {
3340 if ($context->instanceid == SITEID) {
3341 $isfrontpage = true;
3342 } else {
3343 $iscoursepage = true;
3346 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3348 $caps = (array)$capability;
3350 // construct list of context paths bottom-->top
3351 list($contextids, $paths) = get_context_info_list($context);
3353 // we need to find out all roles that have these capabilities either in definition or in overrides
3354 $defs = array();
3355 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3356 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3357 $params = array_merge($params, $params2);
3358 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3359 FROM {role_capabilities} rc
3360 JOIN {context} ctx on rc.contextid = ctx.id
3361 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3363 $rcs = $DB->get_records_sql($sql, $params);
3364 foreach ($rcs as $rc) {
3365 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3368 // go through the permissions bottom-->top direction to evaluate the current permission,
3369 // first one wins (prohibit is an exception that always wins)
3370 $access = array();
3371 foreach ($caps as $cap) {
3372 foreach ($paths as $path) {
3373 if (empty($defs[$cap][$path])) {
3374 continue;
3376 foreach($defs[$cap][$path] as $roleid => $perm) {
3377 if ($perm == CAP_PROHIBIT) {
3378 $access[$cap][$roleid] = CAP_PROHIBIT;
3379 continue;
3381 if (!isset($access[$cap][$roleid])) {
3382 $access[$cap][$roleid] = (int)$perm;
3388 // make lists of roles that are needed and prohibited in this context
3389 $needed = array(); // one of these is enough
3390 $prohibited = array(); // must not have any of these
3391 foreach ($caps as $cap) {
3392 if (empty($access[$cap])) {
3393 continue;
3395 foreach ($access[$cap] as $roleid => $perm) {
3396 if ($perm == CAP_PROHIBIT) {
3397 unset($needed[$cap][$roleid]);
3398 $prohibited[$cap][$roleid] = true;
3399 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3400 $needed[$cap][$roleid] = true;
3403 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3404 // easy, nobody has the permission
3405 unset($needed[$cap]);
3406 unset($prohibited[$cap]);
3407 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3408 // everybody is disqualified on the frontpage
3409 unset($needed[$cap]);
3410 unset($prohibited[$cap]);
3412 if (empty($prohibited[$cap])) {
3413 unset($prohibited[$cap]);
3417 if (empty($needed)) {
3418 // there can not be anybody if no roles match this request
3419 return array();
3422 if (empty($prohibited)) {
3423 // we can compact the needed roles
3424 $n = array();
3425 foreach ($needed as $cap) {
3426 foreach ($cap as $roleid=>$unused) {
3427 $n[$roleid] = true;
3430 $needed = array('any'=>$n);
3431 unset($n);
3434 // ***** Set up default fields ******
3435 if (empty($fields)) {
3436 if ($iscoursepage) {
3437 $fields = 'u.*, ul.timeaccess AS lastaccess';
3438 } else {
3439 $fields = 'u.*';
3441 } else {
3442 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3443 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3447 // Set up default sort
3448 if (empty($sort)) { // default to course lastaccess or just lastaccess
3449 if ($iscoursepage) {
3450 $sort = 'ul.timeaccess';
3451 } else {
3452 $sort = 'u.lastaccess';
3456 // Prepare query clauses
3457 $wherecond = array();
3458 $params = array();
3459 $joins = array();
3461 // User lastaccess JOIN
3462 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3463 // user_lastaccess is not required MDL-13810
3464 } else {
3465 if ($iscoursepage) {
3466 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3467 } else {
3468 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3472 // We never return deleted users or guest account.
3473 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3474 $params['guestid'] = $CFG->siteguest;
3476 // Groups
3477 if ($groups) {
3478 $groups = (array)$groups;
3479 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3480 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3481 $params = array_merge($params, $grpparams);
3483 if ($useviewallgroups) {
3484 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3485 if (!empty($viewallgroupsusers)) {
3486 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3487 } else {
3488 $wherecond[] = "($grouptest)";
3490 } else {
3491 $wherecond[] = "($grouptest)";
3495 // User exceptions
3496 if (!empty($exceptions)) {
3497 $exceptions = (array)$exceptions;
3498 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3499 $params = array_merge($params, $exparams);
3500 $wherecond[] = "u.id $exsql";
3503 // now add the needed and prohibited roles conditions as joins
3504 if (!empty($needed['any'])) {
3505 // simple case - there are no prohibits involved
3506 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3507 // everybody
3508 } else {
3509 $joins[] = "JOIN (SELECT DISTINCT userid
3510 FROM {role_assignments}
3511 WHERE contextid IN ($ctxids)
3512 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3513 ) ra ON ra.userid = u.id";
3515 } else {
3516 $unions = array();
3517 $everybody = false;
3518 foreach ($needed as $cap=>$unused) {
3519 if (empty($prohibited[$cap])) {
3520 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3521 $everybody = true;
3522 break;
3523 } else {
3524 $unions[] = "SELECT userid
3525 FROM {role_assignments}
3526 WHERE contextid IN ($ctxids)
3527 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3529 } else {
3530 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3531 // nobody can have this cap because it is prevented in default roles
3532 continue;
3534 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3535 // everybody except the prohibitted - hiding does not matter
3536 $unions[] = "SELECT id AS userid
3537 FROM {user}
3538 WHERE id NOT IN (SELECT userid
3539 FROM {role_assignments}
3540 WHERE contextid IN ($ctxids)
3541 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3543 } else {
3544 $unions[] = "SELECT userid
3545 FROM {role_assignments}
3546 WHERE contextid IN ($ctxids) AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3547 AND userid NOT IN (
3548 SELECT userid
3549 FROM {role_assignments}
3550 WHERE contextid IN ($ctxids)
3551 AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . ")
3556 if (!$everybody) {
3557 if ($unions) {
3558 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3559 } else {
3560 // only prohibits found - nobody can be matched
3561 $wherecond[] = "1 = 2";
3566 // Collect WHERE conditions and needed joins
3567 $where = implode(' AND ', $wherecond);
3568 if ($where !== '') {
3569 $where = 'WHERE ' . $where;
3571 $joins = implode("\n", $joins);
3573 // Ok, let's get the users!
3574 $sql = "SELECT $fields
3575 FROM {user} u
3576 $joins
3577 $where
3578 ORDER BY $sort";
3580 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3584 * Re-sort a users array based on a sorting policy
3586 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3587 * based on a sorting policy. This is to support the odd practice of
3588 * sorting teachers by 'authority', where authority was "lowest id of the role
3589 * assignment".
3591 * Will execute 1 database query. Only suitable for small numbers of users, as it
3592 * uses an u.id IN() clause.
3594 * Notes about the sorting criteria.
3596 * As a default, we cannot rely on role.sortorder because then
3597 * admins/coursecreators will always win. That is why the sane
3598 * rule "is locality matters most", with sortorder as 2nd
3599 * consideration.
3601 * If you want role.sortorder, use the 'sortorder' policy, and
3602 * name explicitly what roles you want to cover. It's probably
3603 * a good idea to see what roles have the capabilities you want
3604 * (array_diff() them against roiles that have 'can-do-anything'
3605 * to weed out admin-ish roles. Or fetch a list of roles from
3606 * variables like $CFG->coursecontact .
3608 * @param array $users Users array, keyed on userid
3609 * @param context $context
3610 * @param array $roles ids of the roles to include, optional
3611 * @param string $sortpolicy defaults to locality, more about
3612 * @return array sorted copy of the array
3614 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3615 global $DB;
3617 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3618 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3619 if (empty($roles)) {
3620 $roleswhere = '';
3621 } else {
3622 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3625 $sql = "SELECT ra.userid
3626 FROM {role_assignments} ra
3627 JOIN {role} r
3628 ON ra.roleid=r.id
3629 JOIN {context} ctx
3630 ON ra.contextid=ctx.id
3631 WHERE $userswhere
3632 $contextwhere
3633 $roleswhere";
3635 // Default 'locality' policy -- read PHPDoc notes
3636 // about sort policies...
3637 $orderby = 'ORDER BY '
3638 .'ctx.depth DESC, ' /* locality wins */
3639 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3640 .'ra.id'; /* role assignment order tie-breaker */
3641 if ($sortpolicy === 'sortorder') {
3642 $orderby = 'ORDER BY '
3643 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3644 .'ra.id'; /* role assignment order tie-breaker */
3647 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3648 $sortedusers = array();
3649 $seen = array();
3651 foreach ($sortedids as $id) {
3652 // Avoid duplicates
3653 if (isset($seen[$id])) {
3654 continue;
3656 $seen[$id] = true;
3658 // assign
3659 $sortedusers[$id] = $users[$id];
3661 return $sortedusers;
3665 * Gets all the users assigned this role in this context or higher
3667 * Note that moodle is based on capabilities and it is usually better
3668 * to check permissions than to check role ids as the capabilities
3669 * system is more flexible. If you really need, you can to use this
3670 * function but consider has_capability() as a possible substitute.
3672 * All $sort fields are added into $fields if not present there yet.
3674 * If $roleid is an array or is empty (all roles) you need to set $fields
3675 * (and $sort by extension) params according to it, as the first field
3676 * returned by the database should be unique (ra.id is the best candidate).
3678 * @param int $roleid (can also be an array of ints!)
3679 * @param context $context
3680 * @param bool $parent if true, get list of users assigned in higher context too
3681 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3682 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3683 * null => use default sort from users_order_by_sql.
3684 * @param bool $all true means all, false means limit to enrolled users
3685 * @param string $group defaults to ''
3686 * @param mixed $limitfrom defaults to ''
3687 * @param mixed $limitnum defaults to ''
3688 * @param string $extrawheretest defaults to ''
3689 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3690 * @return array
3692 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3693 $sort = null, $all = true, $group = '',
3694 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3695 global $DB;
3697 if (empty($fields)) {
3698 $allnames = get_all_user_name_fields(true, 'u');
3699 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
3700 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3701 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3702 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3703 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3706 // Prevent wrong function uses.
3707 if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
3708 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
3709 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
3711 if (!empty($roleid)) {
3712 // Solving partially the issue when specifying multiple roles.
3713 $users = array();
3714 foreach ($roleid as $id) {
3715 // Ignoring duplicated keys keeping the first user appearance.
3716 $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
3717 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
3719 return $users;
3723 $parentcontexts = '';
3724 if ($parent) {
3725 $parentcontexts = substr($context->path, 1); // kill leading slash
3726 $parentcontexts = str_replace('/', ',', $parentcontexts);
3727 if ($parentcontexts !== '') {
3728 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3732 if ($roleid) {
3733 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
3734 $roleselect = "AND ra.roleid $rids";
3735 } else {
3736 $params = array();
3737 $roleselect = '';
3740 if ($coursecontext = $context->get_course_context(false)) {
3741 $params['coursecontext'] = $coursecontext->id;
3742 } else {
3743 $params['coursecontext'] = 0;
3746 if ($group) {
3747 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3748 $groupselect = " AND gm.groupid = :groupid ";
3749 $params['groupid'] = $group;
3750 } else {
3751 $groupjoin = '';
3752 $groupselect = '';
3755 $params['contextid'] = $context->id;
3757 if ($extrawheretest) {
3758 $extrawheretest = ' AND ' . $extrawheretest;
3761 if ($whereorsortparams) {
3762 $params = array_merge($params, $whereorsortparams);
3765 if (!$sort) {
3766 list($sort, $sortparams) = users_order_by_sql('u');
3767 $params = array_merge($params, $sortparams);
3770 // Adding the fields from $sort that are not present in $fields.
3771 $sortarray = preg_split('/,\s*/', $sort);
3772 $fieldsarray = preg_split('/,\s*/', $fields);
3774 // Discarding aliases from the fields.
3775 $fieldnames = array();
3776 foreach ($fieldsarray as $key => $field) {
3777 list($fieldnames[$key]) = explode(' ', $field);
3780 $addedfields = array();
3781 foreach ($sortarray as $sortfield) {
3782 // Throw away any additional arguments to the sort (e.g. ASC/DESC).
3783 list($sortfield) = explode(' ', $sortfield);
3784 list($tableprefix) = explode('.', $sortfield);
3785 $fieldpresent = false;
3786 foreach ($fieldnames as $fieldname) {
3787 if ($fieldname === $sortfield || $fieldname === $tableprefix.'.*') {
3788 $fieldpresent = true;
3789 break;
3793 if (!$fieldpresent) {
3794 $fieldsarray[] = $sortfield;
3795 $addedfields[] = $sortfield;
3799 $fields = implode(', ', $fieldsarray);
3800 if (!empty($addedfields)) {
3801 $addedfields = implode(', ', $addedfields);
3802 debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
3805 if ($all === null) {
3806 // Previously null was used to indicate that parameter was not used.
3807 $all = true;
3809 if (!$all and $coursecontext) {
3810 // Do not use get_enrolled_sql() here for performance reasons.
3811 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
3812 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
3813 $params['ecourseid'] = $coursecontext->instanceid;
3814 } else {
3815 $ejoin = "";
3818 $sql = "SELECT DISTINCT $fields, ra.roleid
3819 FROM {role_assignments} ra
3820 JOIN {user} u ON u.id = ra.userid
3821 JOIN {role} r ON ra.roleid = r.id
3822 $ejoin
3823 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3824 $groupjoin
3825 WHERE (ra.contextid = :contextid $parentcontexts)
3826 $roleselect
3827 $groupselect
3828 $extrawheretest
3829 ORDER BY $sort"; // join now so that we can just use fullname() later
3831 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3835 * Counts all the users assigned this role in this context or higher
3837 * @param int|array $roleid either int or an array of ints
3838 * @param context $context
3839 * @param bool $parent if true, get list of users assigned in higher context too
3840 * @return int Returns the result count
3842 function count_role_users($roleid, context $context, $parent = false) {
3843 global $DB;
3845 if ($parent) {
3846 if ($contexts = $context->get_parent_context_ids()) {
3847 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3848 } else {
3849 $parentcontexts = '';
3851 } else {
3852 $parentcontexts = '';
3855 if ($roleid) {
3856 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3857 $roleselect = "AND r.roleid $rids";
3858 } else {
3859 $params = array();
3860 $roleselect = '';
3863 array_unshift($params, $context->id);
3865 $sql = "SELECT COUNT(DISTINCT u.id)
3866 FROM {role_assignments} r
3867 JOIN {user} u ON u.id = r.userid
3868 WHERE (r.contextid = ? $parentcontexts)
3869 $roleselect
3870 AND u.deleted = 0";
3872 return $DB->count_records_sql($sql, $params);
3876 * This function gets the list of courses that this user has a particular capability in.
3878 * It is now reasonably efficient, but bear in mind that if there are users who have the capability
3879 * everywhere, it may return an array of all courses.
3881 * @param string $capability Capability in question
3882 * @param int $userid User ID or null for current user
3883 * @param bool $doanything True if 'doanything' is permitted (default)
3884 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3885 * otherwise use a comma-separated list of the fields you require, not including id.
3886 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
3887 * @param string $orderby If set, use a comma-separated list of fields from course
3888 * table with sql modifiers (DESC) if needed
3889 * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
3890 * @return array|bool Array of courses, if none found false is returned.
3892 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '',
3893 $limit = 0) {
3894 global $DB, $USER;
3896 // Default to current user.
3897 if (!$userid) {
3898 $userid = $USER->id;
3901 if ($doanything && is_siteadmin($userid)) {
3902 // If the user is a site admin and $doanything is enabled then there is no need to restrict
3903 // the list of courses.
3904 $contextlimitsql = '';
3905 $contextlimitparams = [];
3906 } else {
3907 // Gets SQL to limit contexts ('x' table) to those where the user has this capability.
3908 list ($contextlimitsql, $contextlimitparams) = \core\access\get_user_capability_course_helper::get_sql(
3909 $userid, $capability);
3910 if (!$contextlimitsql) {
3911 // If the does not have this capability in any context, return false without querying.
3912 return false;
3915 $contextlimitsql = 'WHERE' . $contextlimitsql;
3918 // Convert fields list and ordering
3919 $fieldlist = '';
3920 if ($fieldsexceptid) {
3921 $fields = array_map('trim', explode(',', $fieldsexceptid));
3922 foreach($fields as $field) {
3923 // Context fields have a different alias.
3924 if (strpos($field, 'ctx') === 0) {
3925 switch($field) {
3926 case 'ctxlevel' :
3927 $realfield = 'contextlevel';
3928 break;
3929 case 'ctxinstance' :
3930 $realfield = 'instanceid';
3931 break;
3932 default:
3933 $realfield = substr($field, 3);
3934 break;
3936 $fieldlist .= ',x.' . $realfield . ' AS ' . $field;
3937 } else {
3938 $fieldlist .= ',c.'.$field;
3942 if ($orderby) {
3943 $fields = explode(',', $orderby);
3944 $orderby = '';
3945 foreach($fields as $field) {
3946 if ($orderby) {
3947 $orderby .= ',';
3949 $orderby .= 'c.'.$field;
3951 $orderby = 'ORDER BY '.$orderby;
3954 $courses = array();
3955 $rs = $DB->get_recordset_sql("
3956 SELECT c.id $fieldlist
3957 FROM {course} c
3958 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
3959 $contextlimitsql
3960 $orderby", array_merge([CONTEXT_COURSE], $contextlimitparams));
3961 foreach ($rs as $course) {
3962 $courses[] = $course;
3963 $limit--;
3964 if ($limit == 0) {
3965 break;
3968 $rs->close();
3969 return empty($courses) ? false : $courses;
3973 * This function finds the roles assigned directly to this context only
3974 * i.e. no roles in parent contexts
3976 * @param context $context
3977 * @return array
3979 function get_roles_on_exact_context(context $context) {
3980 global $DB;
3982 return $DB->get_records_sql("SELECT r.*
3983 FROM {role_assignments} ra, {role} r
3984 WHERE ra.roleid = r.id AND ra.contextid = ?",
3985 array($context->id));
3989 * Switches the current user to another role for the current session and only
3990 * in the given context.
3992 * The caller *must* check
3993 * - that this op is allowed
3994 * - that the requested role can be switched to in this context (use get_switchable_roles)
3995 * - that the requested role is NOT $CFG->defaultuserroleid
3997 * To "unswitch" pass 0 as the roleid.
3999 * This function *will* modify $USER->access - beware
4001 * @param integer $roleid the role to switch to.
4002 * @param context $context the context in which to perform the switch.
4003 * @return bool success or failure.
4005 function role_switch($roleid, context $context) {
4006 global $USER;
4008 // Add the ghost RA to $USER->access as $USER->access['rsw'][$path] = $roleid.
4009 // To un-switch just unset($USER->access['rsw'][$path]).
4011 // Note: it is not possible to switch to roles that do not have course:view
4013 if (!isset($USER->access)) {
4014 load_all_capabilities();
4017 // Add the switch RA
4018 if ($roleid == 0) {
4019 unset($USER->access['rsw'][$context->path]);
4020 return true;
4023 $USER->access['rsw'][$context->path] = $roleid;
4025 return true;
4029 * Checks if the user has switched roles within the given course.
4031 * Note: You can only switch roles within the course, hence it takes a course id
4032 * rather than a context. On that note Petr volunteered to implement this across
4033 * all other contexts, all requests for this should be forwarded to him ;)
4035 * @param int $courseid The id of the course to check
4036 * @return bool True if the user has switched roles within the course.
4038 function is_role_switched($courseid) {
4039 global $USER;
4040 $context = context_course::instance($courseid, MUST_EXIST);
4041 return (!empty($USER->access['rsw'][$context->path]));
4045 * Get any role that has an override on exact context
4047 * @param context $context The context to check
4048 * @return array An array of roles
4050 function get_roles_with_override_on_context(context $context) {
4051 global $DB;
4053 return $DB->get_records_sql("SELECT r.*
4054 FROM {role_capabilities} rc, {role} r
4055 WHERE rc.roleid = r.id AND rc.contextid = ?",
4056 array($context->id));
4060 * Get all capabilities for this role on this context (overrides)
4062 * @param stdClass $role
4063 * @param context $context
4064 * @return array
4066 function get_capabilities_from_role_on_context($role, context $context) {
4067 global $DB;
4069 return $DB->get_records_sql("SELECT *
4070 FROM {role_capabilities}
4071 WHERE contextid = ? AND roleid = ?",
4072 array($context->id, $role->id));
4076 * Find out which roles has assignment on this context
4078 * @param context $context
4079 * @return array
4082 function get_roles_with_assignment_on_context(context $context) {
4083 global $DB;
4085 return $DB->get_records_sql("SELECT r.*
4086 FROM {role_assignments} ra, {role} r
4087 WHERE ra.roleid = r.id AND ra.contextid = ?",
4088 array($context->id));
4092 * Find all user assignment of users for this role, on this context
4094 * @param stdClass $role
4095 * @param context $context
4096 * @return array
4098 function get_users_from_role_on_context($role, context $context) {
4099 global $DB;
4101 return $DB->get_records_sql("SELECT *
4102 FROM {role_assignments}
4103 WHERE contextid = ? AND roleid = ?",
4104 array($context->id, $role->id));
4108 * Simple function returning a boolean true if user has roles
4109 * in context or parent contexts, otherwise false.
4111 * @param int $userid
4112 * @param int $roleid
4113 * @param int $contextid empty means any context
4114 * @return bool
4116 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4117 global $DB;
4119 if ($contextid) {
4120 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4121 return false;
4123 $parents = $context->get_parent_context_ids(true);
4124 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4125 $params['userid'] = $userid;
4126 $params['roleid'] = $roleid;
4128 $sql = "SELECT COUNT(ra.id)
4129 FROM {role_assignments} ra
4130 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4132 $count = $DB->get_field_sql($sql, $params);
4133 return ($count > 0);
4135 } else {
4136 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4141 * Get localised role name or alias if exists and format the text.
4143 * @param stdClass $role role object
4144 * - optional 'coursealias' property should be included for performance reasons if course context used
4145 * - description property is not required here
4146 * @param context|bool $context empty means system context
4147 * @param int $rolenamedisplay type of role name
4148 * @return string localised role name or course role name alias
4150 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4151 global $DB;
4153 if ($rolenamedisplay == ROLENAME_SHORT) {
4154 return $role->shortname;
4157 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4158 $coursecontext = null;
4161 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4162 $role = clone($role); // Do not modify parameters.
4163 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4164 $role->coursealias = $r->name;
4165 } else {
4166 $role->coursealias = null;
4170 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4171 if ($coursecontext) {
4172 return $role->coursealias;
4173 } else {
4174 return null;
4178 if (trim($role->name) !== '') {
4179 // For filtering always use context where was the thing defined - system for roles here.
4180 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4182 } else {
4183 // Empty role->name means we want to see localised role name based on shortname,
4184 // only default roles are supposed to be localised.
4185 switch ($role->shortname) {
4186 case 'manager': $original = get_string('manager', 'role'); break;
4187 case 'coursecreator': $original = get_string('coursecreators'); break;
4188 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4189 case 'teacher': $original = get_string('noneditingteacher'); break;
4190 case 'student': $original = get_string('defaultcoursestudent'); break;
4191 case 'guest': $original = get_string('guest'); break;
4192 case 'user': $original = get_string('authenticateduser'); break;
4193 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4194 // We should not get here, the role UI should require the name for custom roles!
4195 default: $original = $role->shortname; break;
4199 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4200 return $original;
4203 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4204 return "$original ($role->shortname)";
4207 if ($rolenamedisplay == ROLENAME_ALIAS) {
4208 if ($coursecontext and trim($role->coursealias) !== '') {
4209 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4210 } else {
4211 return $original;
4215 if ($rolenamedisplay == ROLENAME_BOTH) {
4216 if ($coursecontext and trim($role->coursealias) !== '') {
4217 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4218 } else {
4219 return $original;
4223 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4227 * Returns localised role description if available.
4228 * If the name is empty it tries to find the default role name using
4229 * hardcoded list of default role names or other methods in the future.
4231 * @param stdClass $role
4232 * @return string localised role name
4234 function role_get_description(stdClass $role) {
4235 if (!html_is_blank($role->description)) {
4236 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4239 switch ($role->shortname) {
4240 case 'manager': return get_string('managerdescription', 'role');
4241 case 'coursecreator': return get_string('coursecreatorsdescription');
4242 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4243 case 'teacher': return get_string('noneditingteacherdescription');
4244 case 'student': return get_string('defaultcoursestudentdescription');
4245 case 'guest': return get_string('guestdescription');
4246 case 'user': return get_string('authenticateduserdescription');
4247 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4248 default: return '';
4253 * Get all the localised role names for a context.
4255 * In new installs default roles have empty names, this function
4256 * add localised role names using current language pack.
4258 * @param context $context the context, null means system context
4259 * @param array of role objects with a ->localname field containing the context-specific role name.
4260 * @param int $rolenamedisplay
4261 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4262 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4264 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4265 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4269 * Prepare list of roles for display, apply aliases and localise default role names.
4271 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4272 * @param context $context the context, null means system context
4273 * @param int $rolenamedisplay
4274 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4275 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4277 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4278 global $DB;
4280 if (empty($roleoptions)) {
4281 return array();
4284 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4285 $coursecontext = null;
4288 // We usually need all role columns...
4289 $first = reset($roleoptions);
4290 if ($returnmenu === null) {
4291 $returnmenu = !is_object($first);
4294 if (!is_object($first) or !property_exists($first, 'shortname')) {
4295 $allroles = get_all_roles($context);
4296 foreach ($roleoptions as $rid => $unused) {
4297 $roleoptions[$rid] = $allroles[$rid];
4301 // Inject coursealias if necessary.
4302 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4303 $first = reset($roleoptions);
4304 if (!property_exists($first, 'coursealias')) {
4305 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4306 foreach ($aliasnames as $alias) {
4307 if (isset($roleoptions[$alias->roleid])) {
4308 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4314 // Add localname property.
4315 foreach ($roleoptions as $rid => $role) {
4316 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4319 if (!$returnmenu) {
4320 return $roleoptions;
4323 $menu = array();
4324 foreach ($roleoptions as $rid => $role) {
4325 $menu[$rid] = $role->localname;
4328 return $menu;
4332 * Aids in detecting if a new line is required when reading a new capability
4334 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4335 * when we read in a new capability.
4336 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4337 * but when we are in grade, all reports/import/export capabilities should be together
4339 * @param string $cap component string a
4340 * @param string $comp component string b
4341 * @param int $contextlevel
4342 * @return bool whether 2 component are in different "sections"
4344 function component_level_changed($cap, $comp, $contextlevel) {
4346 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4347 $compsa = explode('/', $cap->component);
4348 $compsb = explode('/', $comp);
4350 // list of system reports
4351 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4352 return false;
4355 // we are in gradebook, still
4356 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4357 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4358 return false;
4361 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4362 return false;
4366 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4370 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4371 * and return an array of roleids in order.
4373 * @param array $allroles array of roles, as returned by get_all_roles();
4374 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4376 function fix_role_sortorder($allroles) {
4377 global $DB;
4379 $rolesort = array();
4380 $i = 0;
4381 foreach ($allroles as $role) {
4382 $rolesort[$i] = $role->id;
4383 if ($role->sortorder != $i) {
4384 $r = new stdClass();
4385 $r->id = $role->id;
4386 $r->sortorder = $i;
4387 $DB->update_record('role', $r);
4388 $allroles[$role->id]->sortorder = $i;
4390 $i++;
4392 return $rolesort;
4396 * Switch the sort order of two roles (used in admin/roles/manage.php).
4398 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4399 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4400 * @return boolean success or failure
4402 function switch_roles($first, $second) {
4403 global $DB;
4404 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4405 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4406 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4407 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4408 return $result;
4412 * Duplicates all the base definitions of a role
4414 * @param stdClass $sourcerole role to copy from
4415 * @param int $targetrole id of role to copy to
4417 function role_cap_duplicate($sourcerole, $targetrole) {
4418 global $DB;
4420 $systemcontext = context_system::instance();
4421 $caps = $DB->get_records_sql("SELECT *
4422 FROM {role_capabilities}
4423 WHERE roleid = ? AND contextid = ?",
4424 array($sourcerole->id, $systemcontext->id));
4425 // adding capabilities
4426 foreach ($caps as $cap) {
4427 unset($cap->id);
4428 $cap->roleid = $targetrole;
4429 $DB->insert_record('role_capabilities', $cap);
4432 // Reset any cache of this role, including MUC.
4433 accesslib_clear_role_cache($targetrole);
4437 * Returns two lists, this can be used to find out if user has capability.
4438 * Having any needed role and no forbidden role in this context means
4439 * user has this capability in this context.
4440 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4442 * @param stdClass $context
4443 * @param string $capability
4444 * @return array($neededroles, $forbiddenroles)
4446 function get_roles_with_cap_in_context($context, $capability) {
4447 global $DB;
4449 $ctxids = trim($context->path, '/'); // kill leading slash
4450 $ctxids = str_replace('/', ',', $ctxids);
4452 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4453 FROM {role_capabilities} rc
4454 JOIN {context} ctx ON ctx.id = rc.contextid
4455 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4456 ORDER BY rc.roleid ASC, ctx.depth DESC";
4457 $params = array('cap'=>$capability);
4459 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4460 // no cap definitions --> no capability
4461 return array(array(), array());
4464 $forbidden = array();
4465 $needed = array();
4466 foreach($capdefs as $def) {
4467 if (isset($forbidden[$def->roleid])) {
4468 continue;
4470 if ($def->permission == CAP_PROHIBIT) {
4471 $forbidden[$def->roleid] = $def->roleid;
4472 unset($needed[$def->roleid]);
4473 continue;
4475 if (!isset($needed[$def->roleid])) {
4476 if ($def->permission == CAP_ALLOW) {
4477 $needed[$def->roleid] = true;
4478 } else if ($def->permission == CAP_PREVENT) {
4479 $needed[$def->roleid] = false;
4483 unset($capdefs);
4485 // remove all those roles not allowing
4486 foreach($needed as $key=>$value) {
4487 if (!$value) {
4488 unset($needed[$key]);
4489 } else {
4490 $needed[$key] = $key;
4494 return array($needed, $forbidden);
4498 * Returns an array of role IDs that have ALL of the the supplied capabilities
4499 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4501 * @param stdClass $context
4502 * @param array $capabilities An array of capabilities
4503 * @return array of roles with all of the required capabilities
4505 function get_roles_with_caps_in_context($context, $capabilities) {
4506 $neededarr = array();
4507 $forbiddenarr = array();
4508 foreach($capabilities as $caprequired) {
4509 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4512 $rolesthatcanrate = array();
4513 if (!empty($neededarr)) {
4514 foreach ($neededarr as $needed) {
4515 if (empty($rolesthatcanrate)) {
4516 $rolesthatcanrate = $needed;
4517 } else {
4518 //only want roles that have all caps
4519 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4523 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4524 foreach ($forbiddenarr as $forbidden) {
4525 //remove any roles that are forbidden any of the caps
4526 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4529 return $rolesthatcanrate;
4533 * Returns an array of role names that have ALL of the the supplied capabilities
4534 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4536 * @param stdClass $context
4537 * @param array $capabilities An array of capabilities
4538 * @return array of roles with all of the required capabilities
4540 function get_role_names_with_caps_in_context($context, $capabilities) {
4541 global $DB;
4543 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4544 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4546 $roles = array();
4547 foreach ($rolesthatcanrate as $r) {
4548 $roles[$r] = $allroles[$r];
4551 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4555 * This function verifies the prohibit comes from this context
4556 * and there are no more prohibits in parent contexts.
4558 * @param int $roleid
4559 * @param context $context
4560 * @param string $capability name
4561 * @return bool
4563 function prohibit_is_removable($roleid, context $context, $capability) {
4564 global $DB;
4566 $ctxids = trim($context->path, '/'); // kill leading slash
4567 $ctxids = str_replace('/', ',', $ctxids);
4569 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4571 $sql = "SELECT ctx.id
4572 FROM {role_capabilities} rc
4573 JOIN {context} ctx ON ctx.id = rc.contextid
4574 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4575 ORDER BY ctx.depth DESC";
4577 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4578 // no prohibits == nothing to remove
4579 return true;
4582 if (count($prohibits) > 1) {
4583 // more prohibits can not be removed
4584 return false;
4587 return !empty($prohibits[$context->id]);
4591 * More user friendly role permission changing,
4592 * it should produce as few overrides as possible.
4594 * @param int $roleid
4595 * @param stdClass $context
4596 * @param string $capname capability name
4597 * @param int $permission
4598 * @return void
4600 function role_change_permission($roleid, $context, $capname, $permission) {
4601 global $DB;
4603 if ($permission == CAP_INHERIT) {
4604 unassign_capability($capname, $roleid, $context->id);
4605 $context->mark_dirty();
4606 return;
4609 $ctxids = trim($context->path, '/'); // kill leading slash
4610 $ctxids = str_replace('/', ',', $ctxids);
4612 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4614 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4615 FROM {role_capabilities} rc
4616 JOIN {context} ctx ON ctx.id = rc.contextid
4617 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4618 ORDER BY ctx.depth DESC";
4620 if ($existing = $DB->get_records_sql($sql, $params)) {
4621 foreach($existing as $e) {
4622 if ($e->permission == CAP_PROHIBIT) {
4623 // prohibit can not be overridden, no point in changing anything
4624 return;
4627 $lowest = array_shift($existing);
4628 if ($lowest->permission == $permission) {
4629 // permission already set in this context or parent - nothing to do
4630 return;
4632 if ($existing) {
4633 $parent = array_shift($existing);
4634 if ($parent->permission == $permission) {
4635 // permission already set in parent context or parent - just unset in this context
4636 // we do this because we want as few overrides as possible for performance reasons
4637 unassign_capability($capname, $roleid, $context->id);
4638 $context->mark_dirty();
4639 return;
4643 } else {
4644 if ($permission == CAP_PREVENT) {
4645 // nothing means role does not have permission
4646 return;
4650 // assign the needed capability
4651 assign_capability($capname, $permission, $roleid, $context->id, true);
4653 // force cap reloading
4654 $context->mark_dirty();
4659 * Basic moodle context abstraction class.
4661 * Google confirms that no other important framework is using "context" class,
4662 * we could use something else like mcontext or moodle_context, but we need to type
4663 * this very often which would be annoying and it would take too much space...
4665 * This class is derived from stdClass for backwards compatibility with
4666 * odl $context record that was returned from DML $DB->get_record()
4668 * @package core_access
4669 * @category access
4670 * @copyright Petr Skoda {@link http://skodak.org}
4671 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4672 * @since Moodle 2.2
4674 * @property-read int $id context id
4675 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4676 * @property-read int $instanceid id of related instance in each context
4677 * @property-read string $path path to context, starts with system context
4678 * @property-read int $depth
4680 abstract class context extends stdClass implements IteratorAggregate {
4683 * The context id
4684 * Can be accessed publicly through $context->id
4685 * @var int
4687 protected $_id;
4690 * The context level
4691 * Can be accessed publicly through $context->contextlevel
4692 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4694 protected $_contextlevel;
4697 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4698 * Can be accessed publicly through $context->instanceid
4699 * @var int
4701 protected $_instanceid;
4704 * The path to the context always starting from the system context
4705 * Can be accessed publicly through $context->path
4706 * @var string
4708 protected $_path;
4711 * The depth of the context in relation to parent contexts
4712 * Can be accessed publicly through $context->depth
4713 * @var int
4715 protected $_depth;
4718 * @var array Context caching info
4720 private static $cache_contextsbyid = array();
4723 * @var array Context caching info
4725 private static $cache_contexts = array();
4728 * Context count
4729 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4730 * @var int
4732 protected static $cache_count = 0;
4735 * @var array Context caching info
4737 protected static $cache_preloaded = array();
4740 * @var context_system The system context once initialised
4742 protected static $systemcontext = null;
4745 * Resets the cache to remove all data.
4746 * @static
4748 protected static function reset_caches() {
4749 self::$cache_contextsbyid = array();
4750 self::$cache_contexts = array();
4751 self::$cache_count = 0;
4752 self::$cache_preloaded = array();
4754 self::$systemcontext = null;
4758 * Adds a context to the cache. If the cache is full, discards a batch of
4759 * older entries.
4761 * @static
4762 * @param context $context New context to add
4763 * @return void
4765 protected static function cache_add(context $context) {
4766 if (isset(self::$cache_contextsbyid[$context->id])) {
4767 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4768 return;
4771 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4772 $i = 0;
4773 foreach(self::$cache_contextsbyid as $ctx) {
4774 $i++;
4775 if ($i <= 100) {
4776 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4777 continue;
4779 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4780 // we remove oldest third of the contexts to make room for more contexts
4781 break;
4783 unset(self::$cache_contextsbyid[$ctx->id]);
4784 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4785 self::$cache_count--;
4789 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4790 self::$cache_contextsbyid[$context->id] = $context;
4791 self::$cache_count++;
4795 * Removes a context from the cache.
4797 * @static
4798 * @param context $context Context object to remove
4799 * @return void
4801 protected static function cache_remove(context $context) {
4802 if (!isset(self::$cache_contextsbyid[$context->id])) {
4803 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4804 return;
4806 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4807 unset(self::$cache_contextsbyid[$context->id]);
4809 self::$cache_count--;
4811 if (self::$cache_count < 0) {
4812 self::$cache_count = 0;
4817 * Gets a context from the cache.
4819 * @static
4820 * @param int $contextlevel Context level
4821 * @param int $instance Instance ID
4822 * @return context|bool Context or false if not in cache
4824 protected static function cache_get($contextlevel, $instance) {
4825 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4826 return self::$cache_contexts[$contextlevel][$instance];
4828 return false;
4832 * Gets a context from the cache based on its id.
4834 * @static
4835 * @param int $id Context ID
4836 * @return context|bool Context or false if not in cache
4838 protected static function cache_get_by_id($id) {
4839 if (isset(self::$cache_contextsbyid[$id])) {
4840 return self::$cache_contextsbyid[$id];
4842 return false;
4846 * Preloads context information from db record and strips the cached info.
4848 * @static
4849 * @param stdClass $rec
4850 * @return void (modifies $rec)
4852 protected static function preload_from_record(stdClass $rec) {
4853 if (empty($rec->ctxid) or empty($rec->ctxlevel) or !isset($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
4854 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4855 return;
4858 // note: in PHP5 the objects are passed by reference, no need to return $rec
4859 $record = new stdClass();
4860 $record->id = $rec->ctxid; unset($rec->ctxid);
4861 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
4862 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
4863 $record->path = $rec->ctxpath; unset($rec->ctxpath);
4864 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
4866 return context::create_instance_from_record($record);
4870 // ====== magic methods =======
4873 * Magic setter method, we do not want anybody to modify properties from the outside
4874 * @param string $name
4875 * @param mixed $value
4877 public function __set($name, $value) {
4878 debugging('Can not change context instance properties!');
4882 * Magic method getter, redirects to read only values.
4883 * @param string $name
4884 * @return mixed
4886 public function __get($name) {
4887 switch ($name) {
4888 case 'id': return $this->_id;
4889 case 'contextlevel': return $this->_contextlevel;
4890 case 'instanceid': return $this->_instanceid;
4891 case 'path': return $this->_path;
4892 case 'depth': return $this->_depth;
4894 default:
4895 debugging('Invalid context property accessed! '.$name);
4896 return null;
4901 * Full support for isset on our magic read only properties.
4902 * @param string $name
4903 * @return bool
4905 public function __isset($name) {
4906 switch ($name) {
4907 case 'id': return isset($this->_id);
4908 case 'contextlevel': return isset($this->_contextlevel);
4909 case 'instanceid': return isset($this->_instanceid);
4910 case 'path': return isset($this->_path);
4911 case 'depth': return isset($this->_depth);
4913 default: return false;
4919 * ALl properties are read only, sorry.
4920 * @param string $name
4922 public function __unset($name) {
4923 debugging('Can not unset context instance properties!');
4926 // ====== implementing method from interface IteratorAggregate ======
4929 * Create an iterator because magic vars can't be seen by 'foreach'.
4931 * Now we can convert context object to array using convert_to_array(),
4932 * and feed it properly to json_encode().
4934 public function getIterator() {
4935 $ret = array(
4936 'id' => $this->id,
4937 'contextlevel' => $this->contextlevel,
4938 'instanceid' => $this->instanceid,
4939 'path' => $this->path,
4940 'depth' => $this->depth
4942 return new ArrayIterator($ret);
4945 // ====== general context methods ======
4948 * Constructor is protected so that devs are forced to
4949 * use context_xxx::instance() or context::instance_by_id().
4951 * @param stdClass $record
4953 protected function __construct(stdClass $record) {
4954 $this->_id = (int)$record->id;
4955 $this->_contextlevel = (int)$record->contextlevel;
4956 $this->_instanceid = $record->instanceid;
4957 $this->_path = $record->path;
4958 $this->_depth = $record->depth;
4962 * This function is also used to work around 'protected' keyword problems in context_helper.
4963 * @static
4964 * @param stdClass $record
4965 * @return context instance
4967 protected static function create_instance_from_record(stdClass $record) {
4968 $classname = context_helper::get_class_for_level($record->contextlevel);
4970 if ($context = context::cache_get_by_id($record->id)) {
4971 return $context;
4974 $context = new $classname($record);
4975 context::cache_add($context);
4977 return $context;
4981 * Copy prepared new contexts from temp table to context table,
4982 * we do this in db specific way for perf reasons only.
4983 * @static
4985 protected static function merge_context_temp_table() {
4986 global $DB;
4988 /* MDL-11347:
4989 * - mysql does not allow to use FROM in UPDATE statements
4990 * - using two tables after UPDATE works in mysql, but might give unexpected
4991 * results in pg 8 (depends on configuration)
4992 * - using table alias in UPDATE does not work in pg < 8.2
4994 * Different code for each database - mostly for performance reasons
4997 $dbfamily = $DB->get_dbfamily();
4998 if ($dbfamily == 'mysql') {
4999 $updatesql = "UPDATE {context} ct, {context_temp} temp
5000 SET ct.path = temp.path,
5001 ct.depth = temp.depth
5002 WHERE ct.id = temp.id";
5003 } else if ($dbfamily == 'oracle') {
5004 $updatesql = "UPDATE {context} ct
5005 SET (ct.path, ct.depth) =
5006 (SELECT temp.path, temp.depth
5007 FROM {context_temp} temp
5008 WHERE temp.id=ct.id)
5009 WHERE EXISTS (SELECT 'x'
5010 FROM {context_temp} temp
5011 WHERE temp.id = ct.id)";
5012 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5013 $updatesql = "UPDATE {context}
5014 SET path = temp.path,
5015 depth = temp.depth
5016 FROM {context_temp} temp
5017 WHERE temp.id={context}.id";
5018 } else {
5019 // sqlite and others
5020 $updatesql = "UPDATE {context}
5021 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5022 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5023 WHERE id IN (SELECT id FROM {context_temp})";
5026 $DB->execute($updatesql);
5030 * Get a context instance as an object, from a given context id.
5032 * @static
5033 * @param int $id context id
5034 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5035 * MUST_EXIST means throw exception if no record found
5036 * @return context|bool the context object or false if not found
5038 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5039 global $DB;
5041 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5042 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5043 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5046 if ($id == SYSCONTEXTID) {
5047 return context_system::instance(0, $strictness);
5050 if (is_array($id) or is_object($id) or empty($id)) {
5051 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5054 if ($context = context::cache_get_by_id($id)) {
5055 return $context;
5058 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5059 return context::create_instance_from_record($record);
5062 return false;
5066 * Update context info after moving context in the tree structure.
5068 * @param context $newparent
5069 * @return void
5071 public function update_moved(context $newparent) {
5072 global $DB;
5074 $frompath = $this->_path;
5075 $newpath = $newparent->path . '/' . $this->_id;
5077 $trans = $DB->start_delegated_transaction();
5079 $this->mark_dirty();
5081 $setdepth = '';
5082 if (($newparent->depth +1) != $this->_depth) {
5083 $diff = $newparent->depth - $this->_depth + 1;
5084 $setdepth = ", depth = depth + $diff";
5086 $sql = "UPDATE {context}
5087 SET path = ?
5088 $setdepth
5089 WHERE id = ?";
5090 $params = array($newpath, $this->_id);
5091 $DB->execute($sql, $params);
5093 $this->_path = $newpath;
5094 $this->_depth = $newparent->depth + 1;
5096 $sql = "UPDATE {context}
5097 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5098 $setdepth
5099 WHERE path LIKE ?";
5100 $params = array($newpath, "{$frompath}/%");
5101 $DB->execute($sql, $params);
5103 $this->mark_dirty();
5105 context::reset_caches();
5107 $trans->allow_commit();
5111 * Remove all context path info and optionally rebuild it.
5113 * @param bool $rebuild
5114 * @return void
5116 public function reset_paths($rebuild = true) {
5117 global $DB;
5119 if ($this->_path) {
5120 $this->mark_dirty();
5122 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5123 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5124 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5125 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5126 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5127 $this->_depth = 0;
5128 $this->_path = null;
5131 if ($rebuild) {
5132 context_helper::build_all_paths(false);
5135 context::reset_caches();
5139 * Delete all data linked to content, do not delete the context record itself
5141 public function delete_content() {
5142 global $CFG, $DB;
5144 blocks_delete_all_for_context($this->_id);
5145 filter_delete_all_for_context($this->_id);
5147 require_once($CFG->dirroot . '/comment/lib.php');
5148 comment::delete_comments(array('contextid'=>$this->_id));
5150 require_once($CFG->dirroot.'/rating/lib.php');
5151 $delopt = new stdclass();
5152 $delopt->contextid = $this->_id;
5153 $rm = new rating_manager();
5154 $rm->delete_ratings($delopt);
5156 // delete all files attached to this context
5157 $fs = get_file_storage();
5158 $fs->delete_area_files($this->_id);
5160 // Delete all repository instances attached to this context.
5161 require_once($CFG->dirroot . '/repository/lib.php');
5162 repository::delete_all_for_context($this->_id);
5164 // delete all advanced grading data attached to this context
5165 require_once($CFG->dirroot.'/grade/grading/lib.php');
5166 grading_manager::delete_all_for_context($this->_id);
5168 $ids = $DB->get_fieldset_select('role_capabilities', 'DISTINCT roleid', 'contextid = ?', array($this->_id));
5170 // now delete stuff from role related tables, role_unassign_all
5171 // and unenrol should be called earlier to do proper cleanup
5172 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5173 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5174 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5176 if ($ids) {
5177 // Reset any cache of these roles, including MUC.
5178 accesslib_clear_role_cache($ids);
5183 * Delete the context content and the context record itself
5185 public function delete() {
5186 global $DB;
5188 if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5189 throw new coding_exception('Cannot delete system context');
5192 // double check the context still exists
5193 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5194 context::cache_remove($this);
5195 return;
5198 $this->delete_content();
5199 $DB->delete_records('context', array('id'=>$this->_id));
5200 // purge static context cache if entry present
5201 context::cache_remove($this);
5203 // do not mark dirty contexts if parents unknown
5204 if (!is_null($this->_path) and $this->_depth > 0) {
5205 $this->mark_dirty();
5209 // ====== context level related methods ======
5212 * Utility method for context creation
5214 * @static
5215 * @param int $contextlevel
5216 * @param int $instanceid
5217 * @param string $parentpath
5218 * @return stdClass context record
5220 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5221 global $DB;
5223 $record = new stdClass();
5224 $record->contextlevel = $contextlevel;
5225 $record->instanceid = $instanceid;
5226 $record->depth = 0;
5227 $record->path = null; //not known before insert
5229 $record->id = $DB->insert_record('context', $record);
5231 // now add path if known - it can be added later
5232 if (!is_null($parentpath)) {
5233 $record->path = $parentpath.'/'.$record->id;
5234 $record->depth = substr_count($record->path, '/');
5235 $DB->update_record('context', $record);
5238 return $record;
5242 * Returns human readable context identifier.
5244 * @param boolean $withprefix whether to prefix the name of the context with the
5245 * type of context, e.g. User, Course, Forum, etc.
5246 * @param boolean $short whether to use the short name of the thing. Only applies
5247 * to course contexts
5248 * @return string the human readable context name.
5250 public function get_context_name($withprefix = true, $short = false) {
5251 // must be implemented in all context levels
5252 throw new coding_exception('can not get name of abstract context');
5256 * Returns the most relevant URL for this context.
5258 * @return moodle_url
5260 public abstract function get_url();
5263 * Returns array of relevant context capability records.
5265 * @return array
5267 public abstract function get_capabilities();
5270 * Recursive function which, given a context, find all its children context ids.
5272 * For course category contexts it will return immediate children and all subcategory contexts.
5273 * It will NOT recurse into courses or subcategories categories.
5274 * If you want to do that, call it on the returned courses/categories.
5276 * When called for a course context, it will return the modules and blocks
5277 * displayed in the course page and blocks displayed on the module pages.
5279 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5280 * contexts ;-)
5282 * @return array Array of child records
5284 public function get_child_contexts() {
5285 global $DB;
5287 if (empty($this->_path) or empty($this->_depth)) {
5288 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5289 return array();
5292 $sql = "SELECT ctx.*
5293 FROM {context} ctx
5294 WHERE ctx.path LIKE ?";
5295 $params = array($this->_path.'/%');
5296 $records = $DB->get_records_sql($sql, $params);
5298 $result = array();
5299 foreach ($records as $record) {
5300 $result[$record->id] = context::create_instance_from_record($record);
5303 return $result;
5307 * Returns parent contexts of this context in reversed order, i.e. parent first,
5308 * then grand parent, etc.
5310 * @param bool $includeself tre means include self too
5311 * @return array of context instances
5313 public function get_parent_contexts($includeself = false) {
5314 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5315 return array();
5318 $result = array();
5319 foreach ($contextids as $contextid) {
5320 $parent = context::instance_by_id($contextid, MUST_EXIST);
5321 $result[$parent->id] = $parent;
5324 return $result;
5328 * Returns parent contexts of this context in reversed order, i.e. parent first,
5329 * then grand parent, etc.
5331 * @param bool $includeself tre means include self too
5332 * @return array of context ids
5334 public function get_parent_context_ids($includeself = false) {
5335 if (empty($this->_path)) {
5336 return array();
5339 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5340 $parentcontexts = explode('/', $parentcontexts);
5341 if (!$includeself) {
5342 array_pop($parentcontexts); // and remove its own id
5345 return array_reverse($parentcontexts);
5349 * Returns parent context
5351 * @return context
5353 public function get_parent_context() {
5354 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5355 return false;
5358 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5359 $parentcontexts = explode('/', $parentcontexts);
5360 array_pop($parentcontexts); // self
5361 $contextid = array_pop($parentcontexts); // immediate parent
5363 return context::instance_by_id($contextid, MUST_EXIST);
5367 * Is this context part of any course? If yes return course context.
5369 * @param bool $strict true means throw exception if not found, false means return false if not found
5370 * @return context_course context of the enclosing course, null if not found or exception
5372 public function get_course_context($strict = true) {
5373 if ($strict) {
5374 throw new coding_exception('Context does not belong to any course.');
5375 } else {
5376 return false;
5381 * Returns sql necessary for purging of stale context instances.
5383 * @static
5384 * @return string cleanup SQL
5386 protected static function get_cleanup_sql() {
5387 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5391 * Rebuild context paths and depths at context level.
5393 * @static
5394 * @param bool $force
5395 * @return void
5397 protected static function build_paths($force) {
5398 throw new coding_exception('build_paths() method must be implemented in all context levels');
5402 * Create missing context instances at given level
5404 * @static
5405 * @return void
5407 protected static function create_level_instances() {
5408 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5412 * Reset all cached permissions and definitions if the necessary.
5413 * @return void
5415 public function reload_if_dirty() {
5416 global $ACCESSLIB_PRIVATE, $USER;
5418 // Load dirty contexts list if needed
5419 if (CLI_SCRIPT) {
5420 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5421 // we do not load dirty flags in CLI and cron
5422 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5424 } else {
5425 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5426 if (!isset($USER->access['time'])) {
5427 // nothing was loaded yet, we do not need to check dirty contexts now
5428 return;
5430 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5431 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5435 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5436 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5437 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5438 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5439 reload_all_capabilities();
5440 break;
5446 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5448 public function mark_dirty() {
5449 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5451 if (during_initial_install()) {
5452 return;
5455 // only if it is a non-empty string
5456 if (is_string($this->_path) && $this->_path !== '') {
5457 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5458 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5459 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5460 } else {
5461 if (CLI_SCRIPT) {
5462 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5463 } else {
5464 if (isset($USER->access['time'])) {
5465 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5466 } else {
5467 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5469 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5478 * Context maintenance and helper methods.
5480 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5481 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5482 * level implementation from the rest of code, the code completion returns what developers need.
5484 * Thank you Tim Hunt for helping me with this nasty trick.
5486 * @package core_access
5487 * @category access
5488 * @copyright Petr Skoda {@link http://skodak.org}
5489 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5490 * @since Moodle 2.2
5492 class context_helper extends context {
5495 * @var array An array mapping context levels to classes
5497 private static $alllevels;
5500 * Instance does not make sense here, only static use
5502 protected function __construct() {
5506 * Reset internal context levels array.
5508 public static function reset_levels() {
5509 self::$alllevels = null;
5513 * Initialise context levels, call before using self::$alllevels.
5515 private static function init_levels() {
5516 global $CFG;
5518 if (isset(self::$alllevels)) {
5519 return;
5521 self::$alllevels = array(
5522 CONTEXT_SYSTEM => 'context_system',
5523 CONTEXT_USER => 'context_user',
5524 CONTEXT_COURSECAT => 'context_coursecat',
5525 CONTEXT_COURSE => 'context_course',
5526 CONTEXT_MODULE => 'context_module',
5527 CONTEXT_BLOCK => 'context_block',
5530 if (empty($CFG->custom_context_classes)) {
5531 return;
5534 $levels = $CFG->custom_context_classes;
5535 if (!is_array($levels)) {
5536 $levels = @unserialize($levels);
5538 if (!is_array($levels)) {
5539 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
5540 return;
5543 // Unsupported custom levels, use with care!!!
5544 foreach ($levels as $level => $classname) {
5545 self::$alllevels[$level] = $classname;
5547 ksort(self::$alllevels);
5551 * Returns a class name of the context level class
5553 * @static
5554 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5555 * @return string class name of the context class
5557 public static function get_class_for_level($contextlevel) {
5558 self::init_levels();
5559 if (isset(self::$alllevels[$contextlevel])) {
5560 return self::$alllevels[$contextlevel];
5561 } else {
5562 throw new coding_exception('Invalid context level specified');
5567 * Returns a list of all context levels
5569 * @static
5570 * @return array int=>string (level=>level class name)
5572 public static function get_all_levels() {
5573 self::init_levels();
5574 return self::$alllevels;
5578 * Remove stale contexts that belonged to deleted instances.
5579 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5581 * @static
5582 * @return void
5584 public static function cleanup_instances() {
5585 global $DB;
5586 self::init_levels();
5588 $sqls = array();
5589 foreach (self::$alllevels as $level=>$classname) {
5590 $sqls[] = $classname::get_cleanup_sql();
5593 $sql = implode(" UNION ", $sqls);
5595 // it is probably better to use transactions, it might be faster too
5596 $transaction = $DB->start_delegated_transaction();
5598 $rs = $DB->get_recordset_sql($sql);
5599 foreach ($rs as $record) {
5600 $context = context::create_instance_from_record($record);
5601 $context->delete();
5603 $rs->close();
5605 $transaction->allow_commit();
5609 * Create all context instances at the given level and above.
5611 * @static
5612 * @param int $contextlevel null means all levels
5613 * @param bool $buildpaths
5614 * @return void
5616 public static function create_instances($contextlevel = null, $buildpaths = true) {
5617 self::init_levels();
5618 foreach (self::$alllevels as $level=>$classname) {
5619 if ($contextlevel and $level > $contextlevel) {
5620 // skip potential sub-contexts
5621 continue;
5623 $classname::create_level_instances();
5624 if ($buildpaths) {
5625 $classname::build_paths(false);
5631 * Rebuild paths and depths in all context levels.
5633 * @static
5634 * @param bool $force false means add missing only
5635 * @return void
5637 public static function build_all_paths($force = false) {
5638 self::init_levels();
5639 foreach (self::$alllevels as $classname) {
5640 $classname::build_paths($force);
5643 // reset static course cache - it might have incorrect cached data
5644 accesslib_clear_all_caches(true);
5648 * Resets the cache to remove all data.
5649 * @static
5651 public static function reset_caches() {
5652 context::reset_caches();
5656 * Returns all fields necessary for context preloading from user $rec.
5658 * This helps with performance when dealing with hundreds of contexts.
5660 * @static
5661 * @param string $tablealias context table alias in the query
5662 * @return array (table.column=>alias, ...)
5664 public static function get_preload_record_columns($tablealias) {
5665 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5669 * Returns all fields necessary for context preloading from user $rec.
5671 * This helps with performance when dealing with hundreds of contexts.
5673 * @static
5674 * @param string $tablealias context table alias in the query
5675 * @return string
5677 public static function get_preload_record_columns_sql($tablealias) {
5678 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5682 * Preloads context information from db record and strips the cached info.
5684 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5686 * @static
5687 * @param stdClass $rec
5688 * @return void (modifies $rec)
5690 public static function preload_from_record(stdClass $rec) {
5691 context::preload_from_record($rec);
5695 * Preload all contexts instances from course.
5697 * To be used if you expect multiple queries for course activities...
5699 * @static
5700 * @param int $courseid
5702 public static function preload_course($courseid) {
5703 // Users can call this multiple times without doing any harm
5704 if (isset(context::$cache_preloaded[$courseid])) {
5705 return;
5707 $coursecontext = context_course::instance($courseid);
5708 $coursecontext->get_child_contexts();
5710 context::$cache_preloaded[$courseid] = true;
5714 * Delete context instance
5716 * @static
5717 * @param int $contextlevel
5718 * @param int $instanceid
5719 * @return void
5721 public static function delete_instance($contextlevel, $instanceid) {
5722 global $DB;
5724 // double check the context still exists
5725 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5726 $context = context::create_instance_from_record($record);
5727 $context->delete();
5728 } else {
5729 // we should try to purge the cache anyway
5734 * Returns the name of specified context level
5736 * @static
5737 * @param int $contextlevel
5738 * @return string name of the context level
5740 public static function get_level_name($contextlevel) {
5741 $classname = context_helper::get_class_for_level($contextlevel);
5742 return $classname::get_level_name();
5746 * not used
5748 public function get_url() {
5752 * not used
5754 public function get_capabilities() {
5760 * System context class
5762 * @package core_access
5763 * @category access
5764 * @copyright Petr Skoda {@link http://skodak.org}
5765 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5766 * @since Moodle 2.2
5768 class context_system extends context {
5770 * Please use context_system::instance() if you need the instance of context.
5772 * @param stdClass $record
5774 protected function __construct(stdClass $record) {
5775 parent::__construct($record);
5776 if ($record->contextlevel != CONTEXT_SYSTEM) {
5777 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5782 * Returns human readable context level name.
5784 * @static
5785 * @return string the human readable context level name.
5787 public static function get_level_name() {
5788 return get_string('coresystem');
5792 * Returns human readable context identifier.
5794 * @param boolean $withprefix does not apply to system context
5795 * @param boolean $short does not apply to system context
5796 * @return string the human readable context name.
5798 public function get_context_name($withprefix = true, $short = false) {
5799 return self::get_level_name();
5803 * Returns the most relevant URL for this context.
5805 * @return moodle_url
5807 public function get_url() {
5808 return new moodle_url('/');
5812 * Returns array of relevant context capability records.
5814 * @return array
5816 public function get_capabilities() {
5817 global $DB;
5819 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5821 $params = array();
5822 $sql = "SELECT *
5823 FROM {capabilities}";
5825 return $DB->get_records_sql($sql.' '.$sort, $params);
5829 * Create missing context instances at system context
5830 * @static
5832 protected static function create_level_instances() {
5833 // nothing to do here, the system context is created automatically in installer
5834 self::instance(0);
5838 * Returns system context instance.
5840 * @static
5841 * @param int $instanceid should be 0
5842 * @param int $strictness
5843 * @param bool $cache
5844 * @return context_system context instance
5846 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
5847 global $DB;
5849 if ($instanceid != 0) {
5850 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5853 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5854 if (!isset(context::$systemcontext)) {
5855 $record = new stdClass();
5856 $record->id = SYSCONTEXTID;
5857 $record->contextlevel = CONTEXT_SYSTEM;
5858 $record->instanceid = 0;
5859 $record->path = '/'.SYSCONTEXTID;
5860 $record->depth = 1;
5861 context::$systemcontext = new context_system($record);
5863 return context::$systemcontext;
5867 try {
5868 // We ignore the strictness completely because system context must exist except during install.
5869 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5870 } catch (dml_exception $e) {
5871 //table or record does not exist
5872 if (!during_initial_install()) {
5873 // do not mess with system context after install, it simply must exist
5874 throw $e;
5876 $record = null;
5879 if (!$record) {
5880 $record = new stdClass();
5881 $record->contextlevel = CONTEXT_SYSTEM;
5882 $record->instanceid = 0;
5883 $record->depth = 1;
5884 $record->path = null; //not known before insert
5886 try {
5887 if ($DB->count_records('context')) {
5888 // contexts already exist, this is very weird, system must be first!!!
5889 return null;
5891 if (defined('SYSCONTEXTID')) {
5892 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5893 $record->id = SYSCONTEXTID;
5894 $DB->import_record('context', $record);
5895 $DB->get_manager()->reset_sequence('context');
5896 } else {
5897 $record->id = $DB->insert_record('context', $record);
5899 } catch (dml_exception $e) {
5900 // can not create context - table does not exist yet, sorry
5901 return null;
5905 if ($record->instanceid != 0) {
5906 // this is very weird, somebody must be messing with context table
5907 debugging('Invalid system context detected');
5910 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5911 // fix path if necessary, initial install or path reset
5912 $record->depth = 1;
5913 $record->path = '/'.$record->id;
5914 $DB->update_record('context', $record);
5917 if (!defined('SYSCONTEXTID')) {
5918 define('SYSCONTEXTID', $record->id);
5921 context::$systemcontext = new context_system($record);
5922 return context::$systemcontext;
5926 * Returns all site contexts except the system context, DO NOT call on production servers!!
5928 * Contexts are not cached.
5930 * @return array
5932 public function get_child_contexts() {
5933 global $DB;
5935 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
5937 // Just get all the contexts except for CONTEXT_SYSTEM level
5938 // and hope we don't OOM in the process - don't cache
5939 $sql = "SELECT c.*
5940 FROM {context} c
5941 WHERE contextlevel > ".CONTEXT_SYSTEM;
5942 $records = $DB->get_records_sql($sql);
5944 $result = array();
5945 foreach ($records as $record) {
5946 $result[$record->id] = context::create_instance_from_record($record);
5949 return $result;
5953 * Returns sql necessary for purging of stale context instances.
5955 * @static
5956 * @return string cleanup SQL
5958 protected static function get_cleanup_sql() {
5959 $sql = "
5960 SELECT c.*
5961 FROM {context} c
5962 WHERE 1=2
5965 return $sql;
5969 * Rebuild context paths and depths at system context level.
5971 * @static
5972 * @param bool $force
5974 protected static function build_paths($force) {
5975 global $DB;
5977 /* note: ignore $force here, we always do full test of system context */
5979 // exactly one record must exist
5980 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5982 if ($record->instanceid != 0) {
5983 debugging('Invalid system context detected');
5986 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
5987 debugging('Invalid SYSCONTEXTID detected');
5990 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5991 // fix path if necessary, initial install or path reset
5992 $record->depth = 1;
5993 $record->path = '/'.$record->id;
5994 $DB->update_record('context', $record);
6001 * User context class
6003 * @package core_access
6004 * @category access
6005 * @copyright Petr Skoda {@link http://skodak.org}
6006 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6007 * @since Moodle 2.2
6009 class context_user extends context {
6011 * Please use context_user::instance($userid) if you need the instance of context.
6012 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6014 * @param stdClass $record
6016 protected function __construct(stdClass $record) {
6017 parent::__construct($record);
6018 if ($record->contextlevel != CONTEXT_USER) {
6019 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6024 * Returns human readable context level name.
6026 * @static
6027 * @return string the human readable context level name.
6029 public static function get_level_name() {
6030 return get_string('user');
6034 * Returns human readable context identifier.
6036 * @param boolean $withprefix whether to prefix the name of the context with User
6037 * @param boolean $short does not apply to user context
6038 * @return string the human readable context name.
6040 public function get_context_name($withprefix = true, $short = false) {
6041 global $DB;
6043 $name = '';
6044 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6045 if ($withprefix){
6046 $name = get_string('user').': ';
6048 $name .= fullname($user);
6050 return $name;
6054 * Returns the most relevant URL for this context.
6056 * @return moodle_url
6058 public function get_url() {
6059 global $COURSE;
6061 if ($COURSE->id == SITEID) {
6062 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6063 } else {
6064 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6066 return $url;
6070 * Returns array of relevant context capability records.
6072 * @return array
6074 public function get_capabilities() {
6075 global $DB;
6077 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6079 $extracaps = array('moodle/grade:viewall');
6080 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6081 $sql = "SELECT *
6082 FROM {capabilities}
6083 WHERE contextlevel = ".CONTEXT_USER."
6084 OR name $extra";
6086 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6090 * Returns user context instance.
6092 * @static
6093 * @param int $userid id from {user} table
6094 * @param int $strictness
6095 * @return context_user context instance
6097 public static function instance($userid, $strictness = MUST_EXIST) {
6098 global $DB;
6100 if ($context = context::cache_get(CONTEXT_USER, $userid)) {
6101 return $context;
6104 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER, 'instanceid' => $userid))) {
6105 if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6106 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6110 if ($record) {
6111 $context = new context_user($record);
6112 context::cache_add($context);
6113 return $context;
6116 return false;
6120 * Create missing context instances at user context level
6121 * @static
6123 protected static function create_level_instances() {
6124 global $DB;
6126 $sql = "SELECT ".CONTEXT_USER.", u.id
6127 FROM {user} u
6128 WHERE u.deleted = 0
6129 AND NOT EXISTS (SELECT 'x'
6130 FROM {context} cx
6131 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6132 $contextdata = $DB->get_recordset_sql($sql);
6133 foreach ($contextdata as $context) {
6134 context::insert_context_record(CONTEXT_USER, $context->id, null);
6136 $contextdata->close();
6140 * Returns sql necessary for purging of stale context instances.
6142 * @static
6143 * @return string cleanup SQL
6145 protected static function get_cleanup_sql() {
6146 $sql = "
6147 SELECT c.*
6148 FROM {context} c
6149 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6150 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6153 return $sql;
6157 * Rebuild context paths and depths at user context level.
6159 * @static
6160 * @param bool $force
6162 protected static function build_paths($force) {
6163 global $DB;
6165 // First update normal users.
6166 $path = $DB->sql_concat('?', 'id');
6167 $pathstart = '/' . SYSCONTEXTID . '/';
6168 $params = array($pathstart);
6170 if ($force) {
6171 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6172 $params[] = $pathstart;
6173 } else {
6174 $where = "depth = 0 OR path IS NULL";
6177 $sql = "UPDATE {context}
6178 SET depth = 2,
6179 path = {$path}
6180 WHERE contextlevel = " . CONTEXT_USER . "
6181 AND ($where)";
6182 $DB->execute($sql, $params);
6188 * Course category context class
6190 * @package core_access
6191 * @category access
6192 * @copyright Petr Skoda {@link http://skodak.org}
6193 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6194 * @since Moodle 2.2
6196 class context_coursecat extends context {
6198 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6199 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6201 * @param stdClass $record
6203 protected function __construct(stdClass $record) {
6204 parent::__construct($record);
6205 if ($record->contextlevel != CONTEXT_COURSECAT) {
6206 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6211 * Returns human readable context level name.
6213 * @static
6214 * @return string the human readable context level name.
6216 public static function get_level_name() {
6217 return get_string('category');
6221 * Returns human readable context identifier.
6223 * @param boolean $withprefix whether to prefix the name of the context with Category
6224 * @param boolean $short does not apply to course categories
6225 * @return string the human readable context name.
6227 public function get_context_name($withprefix = true, $short = false) {
6228 global $DB;
6230 $name = '';
6231 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6232 if ($withprefix){
6233 $name = get_string('category').': ';
6235 $name .= format_string($category->name, true, array('context' => $this));
6237 return $name;
6241 * Returns the most relevant URL for this context.
6243 * @return moodle_url
6245 public function get_url() {
6246 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6250 * Returns array of relevant context capability records.
6252 * @return array
6254 public function get_capabilities() {
6255 global $DB;
6257 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6259 $params = array();
6260 $sql = "SELECT *
6261 FROM {capabilities}
6262 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6264 return $DB->get_records_sql($sql.' '.$sort, $params);
6268 * Returns course category context instance.
6270 * @static
6271 * @param int $categoryid id from {course_categories} table
6272 * @param int $strictness
6273 * @return context_coursecat context instance
6275 public static function instance($categoryid, $strictness = MUST_EXIST) {
6276 global $DB;
6278 if ($context = context::cache_get(CONTEXT_COURSECAT, $categoryid)) {
6279 return $context;
6282 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT, 'instanceid' => $categoryid))) {
6283 if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6284 if ($category->parent) {
6285 $parentcontext = context_coursecat::instance($category->parent);
6286 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6287 } else {
6288 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6293 if ($record) {
6294 $context = new context_coursecat($record);
6295 context::cache_add($context);
6296 return $context;
6299 return false;
6303 * Returns immediate child contexts of category and all subcategories,
6304 * children of subcategories and courses are not returned.
6306 * @return array
6308 public function get_child_contexts() {
6309 global $DB;
6311 if (empty($this->_path) or empty($this->_depth)) {
6312 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6313 return array();
6316 $sql = "SELECT ctx.*
6317 FROM {context} ctx
6318 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6319 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6320 $records = $DB->get_records_sql($sql, $params);
6322 $result = array();
6323 foreach ($records as $record) {
6324 $result[$record->id] = context::create_instance_from_record($record);
6327 return $result;
6331 * Create missing context instances at course category context level
6332 * @static
6334 protected static function create_level_instances() {
6335 global $DB;
6337 $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6338 FROM {course_categories} cc
6339 WHERE NOT EXISTS (SELECT 'x'
6340 FROM {context} cx
6341 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6342 $contextdata = $DB->get_recordset_sql($sql);
6343 foreach ($contextdata as $context) {
6344 context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6346 $contextdata->close();
6350 * Returns sql necessary for purging of stale context instances.
6352 * @static
6353 * @return string cleanup SQL
6355 protected static function get_cleanup_sql() {
6356 $sql = "
6357 SELECT c.*
6358 FROM {context} c
6359 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6360 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6363 return $sql;
6367 * Rebuild context paths and depths at course category context level.
6369 * @static
6370 * @param bool $force
6372 protected static function build_paths($force) {
6373 global $DB;
6375 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6376 if ($force) {
6377 $ctxemptyclause = $emptyclause = '';
6378 } else {
6379 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6380 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6383 $base = '/'.SYSCONTEXTID;
6385 // Normal top level categories
6386 $sql = "UPDATE {context}
6387 SET depth=2,
6388 path=".$DB->sql_concat("'$base/'", 'id')."
6389 WHERE contextlevel=".CONTEXT_COURSECAT."
6390 AND EXISTS (SELECT 'x'
6391 FROM {course_categories} cc
6392 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6393 $emptyclause";
6394 $DB->execute($sql);
6396 // Deeper categories - one query per depthlevel
6397 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6398 for ($n=2; $n<=$maxdepth; $n++) {
6399 $sql = "INSERT INTO {context_temp} (id, path, depth)
6400 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6401 FROM {context} ctx
6402 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6403 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6404 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6405 $ctxemptyclause";
6406 $trans = $DB->start_delegated_transaction();
6407 $DB->delete_records('context_temp');
6408 $DB->execute($sql);
6409 context::merge_context_temp_table();
6410 $DB->delete_records('context_temp');
6411 $trans->allow_commit();
6420 * Course context class
6422 * @package core_access
6423 * @category access
6424 * @copyright Petr Skoda {@link http://skodak.org}
6425 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6426 * @since Moodle 2.2
6428 class context_course extends context {
6430 * Please use context_course::instance($courseid) if you need the instance of context.
6431 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6433 * @param stdClass $record
6435 protected function __construct(stdClass $record) {
6436 parent::__construct($record);
6437 if ($record->contextlevel != CONTEXT_COURSE) {
6438 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6443 * Returns human readable context level name.
6445 * @static
6446 * @return string the human readable context level name.
6448 public static function get_level_name() {
6449 return get_string('course');
6453 * Returns human readable context identifier.
6455 * @param boolean $withprefix whether to prefix the name of the context with Course
6456 * @param boolean $short whether to use the short name of the thing.
6457 * @return string the human readable context name.
6459 public function get_context_name($withprefix = true, $short = false) {
6460 global $DB;
6462 $name = '';
6463 if ($this->_instanceid == SITEID) {
6464 $name = get_string('frontpage', 'admin');
6465 } else {
6466 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6467 if ($withprefix){
6468 $name = get_string('course').': ';
6470 if ($short){
6471 $name .= format_string($course->shortname, true, array('context' => $this));
6472 } else {
6473 $name .= format_string(get_course_display_name_for_list($course));
6477 return $name;
6481 * Returns the most relevant URL for this context.
6483 * @return moodle_url
6485 public function get_url() {
6486 if ($this->_instanceid != SITEID) {
6487 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6490 return new moodle_url('/');
6494 * Returns array of relevant context capability records.
6496 * @return array
6498 public function get_capabilities() {
6499 global $DB;
6501 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6503 $params = array();
6504 $sql = "SELECT *
6505 FROM {capabilities}
6506 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6508 return $DB->get_records_sql($sql.' '.$sort, $params);
6512 * Is this context part of any course? If yes return course context.
6514 * @param bool $strict true means throw exception if not found, false means return false if not found
6515 * @return context_course context of the enclosing course, null if not found or exception
6517 public function get_course_context($strict = true) {
6518 return $this;
6522 * Returns course context instance.
6524 * @static
6525 * @param int $courseid id from {course} table
6526 * @param int $strictness
6527 * @return context_course context instance
6529 public static function instance($courseid, $strictness = MUST_EXIST) {
6530 global $DB;
6532 if ($context = context::cache_get(CONTEXT_COURSE, $courseid)) {
6533 return $context;
6536 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $courseid))) {
6537 if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
6538 if ($course->category) {
6539 $parentcontext = context_coursecat::instance($course->category);
6540 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6541 } else {
6542 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6547 if ($record) {
6548 $context = new context_course($record);
6549 context::cache_add($context);
6550 return $context;
6553 return false;
6557 * Create missing context instances at course context level
6558 * @static
6560 protected static function create_level_instances() {
6561 global $DB;
6563 $sql = "SELECT ".CONTEXT_COURSE.", c.id
6564 FROM {course} c
6565 WHERE NOT EXISTS (SELECT 'x'
6566 FROM {context} cx
6567 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6568 $contextdata = $DB->get_recordset_sql($sql);
6569 foreach ($contextdata as $context) {
6570 context::insert_context_record(CONTEXT_COURSE, $context->id, null);
6572 $contextdata->close();
6576 * Returns sql necessary for purging of stale context instances.
6578 * @static
6579 * @return string cleanup SQL
6581 protected static function get_cleanup_sql() {
6582 $sql = "
6583 SELECT c.*
6584 FROM {context} c
6585 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6586 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6589 return $sql;
6593 * Rebuild context paths and depths at course context level.
6595 * @static
6596 * @param bool $force
6598 protected static function build_paths($force) {
6599 global $DB;
6601 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6602 if ($force) {
6603 $ctxemptyclause = $emptyclause = '';
6604 } else {
6605 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6606 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6609 $base = '/'.SYSCONTEXTID;
6611 // Standard frontpage
6612 $sql = "UPDATE {context}
6613 SET depth = 2,
6614 path = ".$DB->sql_concat("'$base/'", 'id')."
6615 WHERE contextlevel = ".CONTEXT_COURSE."
6616 AND EXISTS (SELECT 'x'
6617 FROM {course} c
6618 WHERE c.id = {context}.instanceid AND c.category = 0)
6619 $emptyclause";
6620 $DB->execute($sql);
6622 // standard courses
6623 $sql = "INSERT INTO {context_temp} (id, path, depth)
6624 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6625 FROM {context} ctx
6626 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6627 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6628 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6629 $ctxemptyclause";
6630 $trans = $DB->start_delegated_transaction();
6631 $DB->delete_records('context_temp');
6632 $DB->execute($sql);
6633 context::merge_context_temp_table();
6634 $DB->delete_records('context_temp');
6635 $trans->allow_commit();
6642 * Course module context class
6644 * @package core_access
6645 * @category access
6646 * @copyright Petr Skoda {@link http://skodak.org}
6647 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6648 * @since Moodle 2.2
6650 class context_module extends context {
6652 * Please use context_module::instance($cmid) if you need the instance of context.
6653 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6655 * @param stdClass $record
6657 protected function __construct(stdClass $record) {
6658 parent::__construct($record);
6659 if ($record->contextlevel != CONTEXT_MODULE) {
6660 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6665 * Returns human readable context level name.
6667 * @static
6668 * @return string the human readable context level name.
6670 public static function get_level_name() {
6671 return get_string('activitymodule');
6675 * Returns human readable context identifier.
6677 * @param boolean $withprefix whether to prefix the name of the context with the
6678 * module name, e.g. Forum, Glossary, etc.
6679 * @param boolean $short does not apply to module context
6680 * @return string the human readable context name.
6682 public function get_context_name($withprefix = true, $short = false) {
6683 global $DB;
6685 $name = '';
6686 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6687 FROM {course_modules} cm
6688 JOIN {modules} md ON md.id = cm.module
6689 WHERE cm.id = ?", array($this->_instanceid))) {
6690 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6691 if ($withprefix){
6692 $name = get_string('modulename', $cm->modname).': ';
6694 $name .= format_string($mod->name, true, array('context' => $this));
6697 return $name;
6701 * Returns the most relevant URL for this context.
6703 * @return moodle_url
6705 public function get_url() {
6706 global $DB;
6708 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6709 FROM {course_modules} cm
6710 JOIN {modules} md ON md.id = cm.module
6711 WHERE cm.id = ?", array($this->_instanceid))) {
6712 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6715 return new moodle_url('/');
6719 * Returns array of relevant context capability records.
6721 * @return array
6723 public function get_capabilities() {
6724 global $DB, $CFG;
6726 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6728 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6729 $module = $DB->get_record('modules', array('id'=>$cm->module));
6731 $subcaps = array();
6732 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6733 if (file_exists($subpluginsfile)) {
6734 $subplugins = array(); // should be redefined in the file
6735 include($subpluginsfile);
6736 if (!empty($subplugins)) {
6737 foreach (array_keys($subplugins) as $subplugintype) {
6738 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
6739 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6745 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6746 $extracaps = array();
6747 if (file_exists($modfile)) {
6748 include_once($modfile);
6749 $modfunction = $module->name.'_get_extra_capabilities';
6750 if (function_exists($modfunction)) {
6751 $extracaps = $modfunction();
6755 $extracaps = array_merge($subcaps, $extracaps);
6756 $extra = '';
6757 list($extra, $params) = $DB->get_in_or_equal(
6758 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
6759 if (!empty($extra)) {
6760 $extra = "OR name $extra";
6762 $sql = "SELECT *
6763 FROM {capabilities}
6764 WHERE (contextlevel = ".CONTEXT_MODULE."
6765 AND (component = :component OR component = 'moodle'))
6766 $extra";
6767 $params['component'] = "mod_$module->name";
6769 return $DB->get_records_sql($sql.' '.$sort, $params);
6773 * Is this context part of any course? If yes return course context.
6775 * @param bool $strict true means throw exception if not found, false means return false if not found
6776 * @return context_course context of the enclosing course, null if not found or exception
6778 public function get_course_context($strict = true) {
6779 return $this->get_parent_context();
6783 * Returns module context instance.
6785 * @static
6786 * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
6787 * @param int $strictness
6788 * @return context_module context instance
6790 public static function instance($cmid, $strictness = MUST_EXIST) {
6791 global $DB;
6793 if ($context = context::cache_get(CONTEXT_MODULE, $cmid)) {
6794 return $context;
6797 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE, 'instanceid' => $cmid))) {
6798 if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
6799 $parentcontext = context_course::instance($cm->course);
6800 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
6804 if ($record) {
6805 $context = new context_module($record);
6806 context::cache_add($context);
6807 return $context;
6810 return false;
6814 * Create missing context instances at module context level
6815 * @static
6817 protected static function create_level_instances() {
6818 global $DB;
6820 $sql = "SELECT ".CONTEXT_MODULE.", cm.id
6821 FROM {course_modules} cm
6822 WHERE NOT EXISTS (SELECT 'x'
6823 FROM {context} cx
6824 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
6825 $contextdata = $DB->get_recordset_sql($sql);
6826 foreach ($contextdata as $context) {
6827 context::insert_context_record(CONTEXT_MODULE, $context->id, null);
6829 $contextdata->close();
6833 * Returns sql necessary for purging of stale context instances.
6835 * @static
6836 * @return string cleanup SQL
6838 protected static function get_cleanup_sql() {
6839 $sql = "
6840 SELECT c.*
6841 FROM {context} c
6842 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6843 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
6846 return $sql;
6850 * Rebuild context paths and depths at module context level.
6852 * @static
6853 * @param bool $force
6855 protected static function build_paths($force) {
6856 global $DB;
6858 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
6859 if ($force) {
6860 $ctxemptyclause = '';
6861 } else {
6862 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6865 $sql = "INSERT INTO {context_temp} (id, path, depth)
6866 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6867 FROM {context} ctx
6868 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
6869 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
6870 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6871 $ctxemptyclause";
6872 $trans = $DB->start_delegated_transaction();
6873 $DB->delete_records('context_temp');
6874 $DB->execute($sql);
6875 context::merge_context_temp_table();
6876 $DB->delete_records('context_temp');
6877 $trans->allow_commit();
6884 * Block context class
6886 * @package core_access
6887 * @category access
6888 * @copyright Petr Skoda {@link http://skodak.org}
6889 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6890 * @since Moodle 2.2
6892 class context_block extends context {
6894 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6895 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6897 * @param stdClass $record
6899 protected function __construct(stdClass $record) {
6900 parent::__construct($record);
6901 if ($record->contextlevel != CONTEXT_BLOCK) {
6902 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6907 * Returns human readable context level name.
6909 * @static
6910 * @return string the human readable context level name.
6912 public static function get_level_name() {
6913 return get_string('block');
6917 * Returns human readable context identifier.
6919 * @param boolean $withprefix whether to prefix the name of the context with Block
6920 * @param boolean $short does not apply to block context
6921 * @return string the human readable context name.
6923 public function get_context_name($withprefix = true, $short = false) {
6924 global $DB, $CFG;
6926 $name = '';
6927 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
6928 global $CFG;
6929 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
6930 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
6931 $blockname = "block_$blockinstance->blockname";
6932 if ($blockobject = new $blockname()) {
6933 if ($withprefix){
6934 $name = get_string('block').': ';
6936 $name .= $blockobject->title;
6940 return $name;
6944 * Returns the most relevant URL for this context.
6946 * @return moodle_url
6948 public function get_url() {
6949 $parentcontexts = $this->get_parent_context();
6950 return $parentcontexts->get_url();
6954 * Returns array of relevant context capability records.
6956 * @return array
6958 public function get_capabilities() {
6959 global $DB;
6961 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6963 $params = array();
6964 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
6966 $extra = '';
6967 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
6968 if ($extracaps) {
6969 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6970 $extra = "OR name $extra";
6973 $sql = "SELECT *
6974 FROM {capabilities}
6975 WHERE (contextlevel = ".CONTEXT_BLOCK."
6976 AND component = :component)
6977 $extra";
6978 $params['component'] = 'block_' . $bi->blockname;
6980 return $DB->get_records_sql($sql.' '.$sort, $params);
6984 * Is this context part of any course? If yes return course context.
6986 * @param bool $strict true means throw exception if not found, false means return false if not found
6987 * @return context_course context of the enclosing course, null if not found or exception
6989 public function get_course_context($strict = true) {
6990 $parentcontext = $this->get_parent_context();
6991 return $parentcontext->get_course_context($strict);
6995 * Returns block context instance.
6997 * @static
6998 * @param int $blockinstanceid id from {block_instances} table.
6999 * @param int $strictness
7000 * @return context_block context instance
7002 public static function instance($blockinstanceid, $strictness = MUST_EXIST) {
7003 global $DB;
7005 if ($context = context::cache_get(CONTEXT_BLOCK, $blockinstanceid)) {
7006 return $context;
7009 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $blockinstanceid))) {
7010 if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
7011 $parentcontext = context::instance_by_id($bi->parentcontextid);
7012 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7016 if ($record) {
7017 $context = new context_block($record);
7018 context::cache_add($context);
7019 return $context;
7022 return false;
7026 * Block do not have child contexts...
7027 * @return array
7029 public function get_child_contexts() {
7030 return array();
7034 * Create missing context instances at block context level
7035 * @static
7037 protected static function create_level_instances() {
7038 global $DB;
7040 $sql = "SELECT ".CONTEXT_BLOCK.", bi.id
7041 FROM {block_instances} bi
7042 WHERE NOT EXISTS (SELECT 'x'
7043 FROM {context} cx
7044 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7045 $contextdata = $DB->get_recordset_sql($sql);
7046 foreach ($contextdata as $context) {
7047 context::insert_context_record(CONTEXT_BLOCK, $context->id, null);
7049 $contextdata->close();
7053 * Returns sql necessary for purging of stale context instances.
7055 * @static
7056 * @return string cleanup SQL
7058 protected static function get_cleanup_sql() {
7059 $sql = "
7060 SELECT c.*
7061 FROM {context} c
7062 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7063 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7066 return $sql;
7070 * Rebuild context paths and depths at block context level.
7072 * @static
7073 * @param bool $force
7075 protected static function build_paths($force) {
7076 global $DB;
7078 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7079 if ($force) {
7080 $ctxemptyclause = '';
7081 } else {
7082 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7085 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7086 $sql = "INSERT INTO {context_temp} (id, path, depth)
7087 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7088 FROM {context} ctx
7089 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7090 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7091 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7092 $ctxemptyclause";
7093 $trans = $DB->start_delegated_transaction();
7094 $DB->delete_records('context_temp');
7095 $DB->execute($sql);
7096 context::merge_context_temp_table();
7097 $DB->delete_records('context_temp');
7098 $trans->allow_commit();
7104 // ============== DEPRECATED FUNCTIONS ==========================================
7105 // Old context related functions were deprecated in 2.0, it is recommended
7106 // to use context classes in new code. Old function can be used when
7107 // creating patches that are supposed to be backported to older stable branches.
7108 // These deprecated functions will not be removed in near future,
7109 // before removing devs will be warned with a debugging message first,
7110 // then we will add error message and only after that we can remove the functions
7111 // completely.
7114 * Runs get_records select on context table and returns the result
7115 * Does get_records_select on the context table, and returns the results ordered
7116 * by contextlevel, and then the natural sort order within each level.
7117 * for the purpose of $select, you need to know that the context table has been
7118 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7120 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7121 * @param array $params any parameters required by $select.
7122 * @return array the requested context records.
7124 function get_sorted_contexts($select, $params = array()) {
7126 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7128 global $DB;
7129 if ($select) {
7130 $select = 'WHERE ' . $select;
7132 return $DB->get_records_sql("
7133 SELECT ctx.*
7134 FROM {context} ctx
7135 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7136 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7137 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7138 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7139 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7140 $select
7141 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7142 ", $params);
7146 * Given context and array of users, returns array of users whose enrolment status is suspended,
7147 * or enrolment has expired or has not started. Also removes those users from the given array
7149 * @param context $context context in which suspended users should be extracted.
7150 * @param array $users list of users.
7151 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7152 * @return array list of suspended users.
7154 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7155 global $DB;
7157 // Get active enrolled users.
7158 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7159 $activeusers = $DB->get_records_sql($sql, $params);
7161 // Move suspended users to a separate array & remove from the initial one.
7162 $susers = array();
7163 if (sizeof($activeusers)) {
7164 foreach ($users as $userid => $user) {
7165 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7166 $susers[$userid] = $user;
7167 unset($users[$userid]);
7171 return $susers;
7175 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7176 * or enrolment has expired or not started.
7178 * @param context $context context in which user enrolment is checked.
7179 * @param bool $usecache Enable or disable (default) the request cache
7180 * @return array list of suspended user id's.
7182 function get_suspended_userids(context $context, $usecache = false) {
7183 global $DB;
7185 if ($usecache) {
7186 $cache = cache::make('core', 'suspended_userids');
7187 $susers = $cache->get($context->id);
7188 if ($susers !== false) {
7189 return $susers;
7193 $coursecontext = $context->get_course_context();
7194 $susers = array();
7196 // Front page users are always enrolled, so suspended list is empty.
7197 if ($coursecontext->instanceid != SITEID) {
7198 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7199 $susers = $DB->get_fieldset_sql($sql, $params);
7200 $susers = array_combine($susers, $susers);
7203 // Cache results for the remainder of this request.
7204 if ($usecache) {
7205 $cache->set($context->id, $susers);
7208 return $susers;
7212 * Gets sql for finding users with capability in the given context
7214 * @param context $context
7215 * @param string|array $capability Capability name or array of names.
7216 * If an array is provided then this is the equivalent of a logical 'OR',
7217 * i.e. the user needs to have one of these capabilities.
7218 * @return array($sql, $params)
7220 function get_with_capability_sql(context $context, $capability) {
7221 static $i = 0;
7222 $i++;
7223 $prefix = 'cu' . $i . '_';
7225 $capjoin = get_with_capability_join($context, $capability, $prefix . 'u.id');
7227 $sql = "SELECT DISTINCT {$prefix}u.id
7228 FROM {user} {$prefix}u
7229 $capjoin->joins
7230 WHERE {$prefix}u.deleted = 0 AND $capjoin->wheres";
7232 return array($sql, $capjoin->params);
7236 * Gets sql joins for finding users with capability in the given context
7238 * @param context $context Context for the join
7239 * @param string|array $capability Capability name or array of names.
7240 * If an array is provided then this is the equivalent of a logical 'OR',
7241 * i.e. the user needs to have one of these capabilities.
7242 * @param string $useridcolumn e.g. 'u.id'
7243 * @return \core\dml\sql_join Contains joins, wheres, params
7245 function get_with_capability_join(context $context, $capability, $useridcolumn) {
7246 global $DB, $CFG;
7248 // Use unique prefix just in case somebody makes some SQL magic with the result.
7249 static $i = 0;
7250 $i++;
7251 $prefix = 'eu' . $i . '_';
7253 // First find the course context.
7254 $coursecontext = $context->get_course_context();
7256 $isfrontpage = ($coursecontext->instanceid == SITEID);
7258 $joins = array();
7259 $wheres = array();
7260 $params = array();
7262 list($contextids, $contextpaths) = get_context_info_list($context);
7264 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
7266 list($incaps, $capsparams) = $DB->get_in_or_equal($capability, SQL_PARAMS_NAMED, 'cap');
7268 $defs = array();
7269 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
7270 FROM {role_capabilities} rc
7271 JOIN {context} ctx on rc.contextid = ctx.id
7272 WHERE rc.contextid $incontexts AND rc.capability $incaps";
7273 $rcs = $DB->get_records_sql($sql, array_merge($cparams, $capsparams));
7274 foreach ($rcs as $rc) {
7275 $defs[$rc->path][$rc->roleid] = $rc->permission;
7278 $access = array();
7279 if (!empty($defs)) {
7280 foreach ($contextpaths as $path) {
7281 if (empty($defs[$path])) {
7282 continue;
7284 foreach ($defs[$path] as $roleid => $perm) {
7285 if ($perm == CAP_PROHIBIT) {
7286 $access[$roleid] = CAP_PROHIBIT;
7287 continue;
7289 if (!isset($access[$roleid])) {
7290 $access[$roleid] = (int) $perm;
7296 unset($defs);
7298 // Make lists of roles that are needed and prohibited.
7299 $needed = array(); // One of these is enough.
7300 $prohibited = array(); // Must not have any of these.
7301 foreach ($access as $roleid => $perm) {
7302 if ($perm == CAP_PROHIBIT) {
7303 unset($needed[$roleid]);
7304 $prohibited[$roleid] = true;
7305 } else {
7306 if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
7307 $needed[$roleid] = true;
7312 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
7313 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
7315 $nobody = false;
7317 if ($isfrontpage) {
7318 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
7319 $nobody = true;
7320 } else {
7321 if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
7322 // Everybody not having prohibit has the capability.
7323 $needed = array();
7324 } else {
7325 if (empty($needed)) {
7326 $nobody = true;
7330 } else {
7331 if (!empty($prohibited[$defaultuserroleid])) {
7332 $nobody = true;
7333 } else {
7334 if (!empty($needed[$defaultuserroleid])) {
7335 // Everybody not having prohibit has the capability.
7336 $needed = array();
7337 } else {
7338 if (empty($needed)) {
7339 $nobody = true;
7345 if ($nobody) {
7346 // Nobody can match so return some SQL that does not return any results.
7347 $wheres[] = "1 = 2";
7349 } else {
7351 if ($needed) {
7352 $ctxids = implode(',', $contextids);
7353 $roleids = implode(',', array_keys($needed));
7354 $joins[] = "JOIN {role_assignments} {$prefix}ra3
7355 ON ({$prefix}ra3.userid = $useridcolumn
7356 AND {$prefix}ra3.roleid IN ($roleids)
7357 AND {$prefix}ra3.contextid IN ($ctxids))";
7360 if ($prohibited) {
7361 $ctxids = implode(',', $contextids);
7362 $roleids = implode(',', array_keys($prohibited));
7363 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4
7364 ON ({$prefix}ra4.userid = $useridcolumn
7365 AND {$prefix}ra4.roleid IN ($roleids)
7366 AND {$prefix}ra4.contextid IN ($ctxids))";
7367 $wheres[] = "{$prefix}ra4.id IS NULL";
7372 $wheres[] = "$useridcolumn <> :{$prefix}guestid";
7373 $params["{$prefix}guestid"] = $CFG->siteguest;
7375 $joins = implode("\n", $joins);
7376 $wheres = "(" . implode(" AND ", $wheres) . ")";
7378 return new \core\dml\sql_join($joins, $wheres, $params);