Merge branch 'MDL-57455_master-fix' of https://github.com/markn86/moodle
[moodle.git] / lib / accesslib.php
blobbd400e4e35119d038894a56344e10d098eeddbb0
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 ORDER BY ctx.path, rc.roleid, rc.capability";
324 $rs = $DB->get_recordset_sql($sql, $params);
326 foreach ($rs as $rd) {
327 if (!isset($rdefs[$rd->roleid][$rd->path])) {
328 if (!isset($rdefs[$rd->roleid])) {
329 $rdefs[$rd->roleid] = array();
331 $rdefs[$rd->roleid][$rd->path] = array();
333 $rdefs[$rd->roleid][$rd->path][$rd->capability] = (int) $rd->permission;
336 $rs->close();
337 return $rdefs;
341 * Get the default guest role, this is used for guest account,
342 * search engine spiders, etc.
344 * @return stdClass role record
346 function get_guest_role() {
347 global $CFG, $DB;
349 if (empty($CFG->guestroleid)) {
350 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
351 $guestrole = array_shift($roles); // Pick the first one
352 set_config('guestroleid', $guestrole->id);
353 return $guestrole;
354 } else {
355 debugging('Can not find any guest role!');
356 return false;
358 } else {
359 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
360 return $guestrole;
361 } else {
362 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
363 set_config('guestroleid', '');
364 return get_guest_role();
370 * Check whether a user has a particular capability in a given context.
372 * For example:
373 * $context = context_module::instance($cm->id);
374 * has_capability('mod/forum:replypost', $context)
376 * By default checks the capabilities of the current user, but you can pass a
377 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
379 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
380 * or capabilities with XSS, config or data loss risks.
382 * @category access
384 * @param string $capability the name of the capability to check. For example mod/forum:view
385 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
386 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
387 * @param boolean $doanything If false, ignores effect of admin role assignment
388 * @return boolean true if the user has this capability. Otherwise false.
390 function has_capability($capability, context $context, $user = null, $doanything = true) {
391 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
393 if (during_initial_install()) {
394 if ($SCRIPT === "/$CFG->admin/index.php"
395 or $SCRIPT === "/$CFG->admin/cli/install.php"
396 or $SCRIPT === "/$CFG->admin/cli/install_database.php"
397 or (defined('BEHAT_UTIL') and BEHAT_UTIL)
398 or (defined('PHPUNIT_UTIL') and PHPUNIT_UTIL)) {
399 // we are in an installer - roles can not work yet
400 return true;
401 } else {
402 return false;
406 if (strpos($capability, 'moodle/legacy:') === 0) {
407 throw new coding_exception('Legacy capabilities can not be used any more!');
410 if (!is_bool($doanything)) {
411 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
414 // capability must exist
415 if (!$capinfo = get_capability_info($capability)) {
416 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
417 return false;
420 if (!isset($USER->id)) {
421 // should never happen
422 $USER->id = 0;
423 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER);
426 // make sure there is a real user specified
427 if ($user === null) {
428 $userid = $USER->id;
429 } else {
430 $userid = is_object($user) ? $user->id : $user;
433 // make sure forcelogin cuts off not-logged-in users if enabled
434 if (!empty($CFG->forcelogin) and $userid == 0) {
435 return false;
438 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
439 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
440 if (isguestuser($userid) or $userid == 0) {
441 return false;
445 // somehow make sure the user is not deleted and actually exists
446 if ($userid != 0) {
447 if ($userid == $USER->id and isset($USER->deleted)) {
448 // this prevents one query per page, it is a bit of cheating,
449 // but hopefully session is terminated properly once user is deleted
450 if ($USER->deleted) {
451 return false;
453 } else {
454 if (!context_user::instance($userid, IGNORE_MISSING)) {
455 // no user context == invalid userid
456 return false;
461 // context path/depth must be valid
462 if (empty($context->path) or $context->depth == 0) {
463 // this should not happen often, each upgrade tries to rebuild the context paths
464 debugging('Context id '.$context->id.' does not have valid path, please use context_helper::build_all_paths()');
465 if (is_siteadmin($userid)) {
466 return true;
467 } else {
468 return false;
472 // Find out if user is admin - it is not possible to override the doanything in any way
473 // and it is not possible to switch to admin role either.
474 if ($doanything) {
475 if (is_siteadmin($userid)) {
476 if ($userid != $USER->id) {
477 return true;
479 // make sure switchrole is not used in this context
480 if (empty($USER->access['rsw'])) {
481 return true;
483 $parts = explode('/', trim($context->path, '/'));
484 $path = '';
485 $switched = false;
486 foreach ($parts as $part) {
487 $path .= '/' . $part;
488 if (!empty($USER->access['rsw'][$path])) {
489 $switched = true;
490 break;
493 if (!$switched) {
494 return true;
496 //ok, admin switched role in this context, let's use normal access control rules
500 // Careful check for staleness...
501 $context->reload_if_dirty();
503 if ($USER->id == $userid) {
504 if (!isset($USER->access)) {
505 load_all_capabilities();
507 $access =& $USER->access;
509 } else {
510 // make sure user accessdata is really loaded
511 get_user_accessdata($userid, true);
512 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
515 return has_capability_in_accessdata($capability, $context, $access);
519 * Check if the user has any one of several capabilities from a list.
521 * This is just a utility method that calls has_capability in a loop. Try to put
522 * the capabilities that most users are likely to have first in the list for best
523 * performance.
525 * @category access
526 * @see has_capability()
528 * @param array $capabilities an array of capability names.
529 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
530 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
531 * @param boolean $doanything If false, ignore effect of admin role assignment
532 * @return boolean true if the user has any of these capabilities. Otherwise false.
534 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
535 foreach ($capabilities as $capability) {
536 if (has_capability($capability, $context, $user, $doanything)) {
537 return true;
540 return false;
544 * Check if the user has all the capabilities in a list.
546 * This is just a utility method that calls has_capability in a loop. Try to put
547 * the capabilities that fewest users are likely to have first in the list for best
548 * performance.
550 * @category access
551 * @see has_capability()
553 * @param array $capabilities an array of capability names.
554 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
555 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
556 * @param boolean $doanything If false, ignore effect of admin role assignment
557 * @return boolean true if the user has all of these capabilities. Otherwise false.
559 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
560 foreach ($capabilities as $capability) {
561 if (!has_capability($capability, $context, $user, $doanything)) {
562 return false;
565 return true;
569 * Is course creator going to have capability in a new course?
571 * This is intended to be used in enrolment plugins before or during course creation,
572 * do not use after the course is fully created.
574 * @category access
576 * @param string $capability the name of the capability to check.
577 * @param context $context course or category context where is course going to be created
578 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
579 * @return boolean true if the user will have this capability.
581 * @throws coding_exception if different type of context submitted
583 function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) {
584 global $CFG;
586 if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) {
587 throw new coding_exception('Only course or course category context expected');
590 if (has_capability($capability, $context, $user)) {
591 // User already has the capability, it could be only removed if CAP_PROHIBIT
592 // was involved here, but we ignore that.
593 return true;
596 if (!has_capability('moodle/course:create', $context, $user)) {
597 return false;
600 if (!enrol_is_enabled('manual')) {
601 return false;
604 if (empty($CFG->creatornewroleid)) {
605 return false;
608 if ($context->contextlevel == CONTEXT_COURSE) {
609 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
610 return false;
612 } else {
613 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
614 return false;
618 // Most likely they will be enrolled after the course creation is finished,
619 // does the new role have the required capability?
620 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
621 return isset($neededroles[$CFG->creatornewroleid]);
625 * Check if the user is an admin at the site level.
627 * Please note that use of proper capabilities is always encouraged,
628 * this function is supposed to be used from core or for temporary hacks.
630 * @category access
632 * @param int|stdClass $user_or_id user id or user object
633 * @return bool true if user is one of the administrators, false otherwise
635 function is_siteadmin($user_or_id = null) {
636 global $CFG, $USER;
638 if ($user_or_id === null) {
639 $user_or_id = $USER;
642 if (empty($user_or_id)) {
643 return false;
645 if (!empty($user_or_id->id)) {
646 $userid = $user_or_id->id;
647 } else {
648 $userid = $user_or_id;
651 // Because this script is called many times (150+ for course page) with
652 // the same parameters, it is worth doing minor optimisations. This static
653 // cache stores the value for a single userid, saving about 2ms from course
654 // page load time without using significant memory. As the static cache
655 // also includes the value it depends on, this cannot break unit tests.
656 static $knownid, $knownresult, $knownsiteadmins;
657 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
658 return $knownresult;
660 $knownid = $userid;
661 $knownsiteadmins = $CFG->siteadmins;
663 $siteadmins = explode(',', $CFG->siteadmins);
664 $knownresult = in_array($userid, $siteadmins);
665 return $knownresult;
669 * Returns true if user has at least one role assign
670 * of 'coursecontact' role (is potentially listed in some course descriptions).
672 * @param int $userid
673 * @return bool
675 function has_coursecontact_role($userid) {
676 global $DB, $CFG;
678 if (empty($CFG->coursecontact)) {
679 return false;
681 $sql = "SELECT 1
682 FROM {role_assignments}
683 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
684 return $DB->record_exists_sql($sql, array('userid'=>$userid));
688 * Does the user have a capability to do something?
690 * Walk the accessdata array and return true/false.
691 * Deals with prohibits, role switching, aggregating
692 * capabilities, etc.
694 * The main feature of here is being FAST and with no
695 * side effects.
697 * Notes:
699 * Switch Role merges with default role
700 * ------------------------------------
701 * If you are a teacher in course X, you have at least
702 * teacher-in-X + defaultloggedinuser-sitewide. So in the
703 * course you'll have techer+defaultloggedinuser.
704 * We try to mimic that in switchrole.
706 * Permission evaluation
707 * ---------------------
708 * Originally there was an extremely complicated way
709 * to determine the user access that dealt with
710 * "locality" or role assignments and role overrides.
711 * Now we simply evaluate access for each role separately
712 * and then verify if user has at least one role with allow
713 * and at the same time no role with prohibit.
715 * @access private
716 * @param string $capability
717 * @param context $context
718 * @param array $accessdata
719 * @return bool
721 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
722 global $CFG;
724 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
725 $path = $context->path;
726 $paths = array($path);
727 while($path = rtrim($path, '0123456789')) {
728 $path = rtrim($path, '/');
729 if ($path === '') {
730 break;
732 $paths[] = $path;
735 $roles = array();
736 $switchedrole = false;
738 // Find out if role switched
739 if (!empty($accessdata['rsw'])) {
740 // From the bottom up...
741 foreach ($paths as $path) {
742 if (isset($accessdata['rsw'][$path])) {
743 // Found a switchrole assignment - check for that role _plus_ the default user role
744 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
745 $switchedrole = true;
746 break;
751 if (!$switchedrole) {
752 // get all users roles in this context and above
753 foreach ($paths as $path) {
754 if (isset($accessdata['ra'][$path])) {
755 foreach ($accessdata['ra'][$path] as $roleid) {
756 $roles[$roleid] = null;
762 // Now find out what access is given to each role, going bottom-->up direction
763 $rdefs = get_role_definitions(array_keys($roles));
764 $allowed = false;
766 foreach ($roles as $roleid => $ignored) {
767 foreach ($paths as $path) {
768 if (isset($rdefs[$roleid][$path][$capability])) {
769 $perm = (int)$rdefs[$roleid][$path][$capability];
770 if ($perm === CAP_PROHIBIT) {
771 // any CAP_PROHIBIT found means no permission for the user
772 return false;
774 if (is_null($roles[$roleid])) {
775 $roles[$roleid] = $perm;
779 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
780 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
783 return $allowed;
787 * A convenience function that tests has_capability, and displays an error if
788 * the user does not have that capability.
790 * NOTE before Moodle 2.0, this function attempted to make an appropriate
791 * require_login call before checking the capability. This is no longer the case.
792 * You must call require_login (or one of its variants) if you want to check the
793 * user is logged in, before you call this function.
795 * @see has_capability()
797 * @param string $capability the name of the capability to check. For example mod/forum:view
798 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
799 * @param int $userid A user id. By default (null) checks the permissions of the current user.
800 * @param bool $doanything If false, ignore effect of admin role assignment
801 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
802 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
803 * @return void terminates with an error if the user does not have the given capability.
805 function require_capability($capability, context $context, $userid = null, $doanything = true,
806 $errormessage = 'nopermissions', $stringfile = '') {
807 if (!has_capability($capability, $context, $userid, $doanything)) {
808 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
813 * Return a nested array showing all role assignments for the user.
814 * [ra] => [contextpath][roleid] = roleid
816 * @access private
817 * @param int $userid - the id of the user
818 * @return array access info array
820 function get_user_roles_sitewide_accessdata($userid) {
821 global $CFG, $DB;
823 $accessdata = get_empty_accessdata();
825 // start with the default role
826 if (!empty($CFG->defaultuserroleid)) {
827 $syscontext = context_system::instance();
828 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
831 // load the "default frontpage role"
832 if (!empty($CFG->defaultfrontpageroleid)) {
833 $frontpagecontext = context_course::instance(get_site()->id);
834 if ($frontpagecontext->path) {
835 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
839 // Preload every assigned role.
840 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
841 FROM {role_assignments} ra
842 JOIN {context} ctx ON ctx.id = ra.contextid
843 WHERE ra.userid = :userid";
845 $rs = $DB->get_recordset_sql($sql, array('userid' => $userid));
847 foreach ($rs as $ra) {
848 // RAs leafs are arrays to support multi-role assignments...
849 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
852 $rs->close();
854 return $accessdata;
858 * Returns empty accessdata structure.
860 * @access private
861 * @return array empt accessdata
863 function get_empty_accessdata() {
864 $accessdata = array(); // named list
865 $accessdata['ra'] = array();
866 $accessdata['time'] = time();
867 $accessdata['rsw'] = array();
869 return $accessdata;
873 * Get accessdata for a given user.
875 * @access private
876 * @param int $userid
877 * @param bool $preloadonly true means do not return access array
878 * @return array accessdata
880 function get_user_accessdata($userid, $preloadonly=false) {
881 global $CFG, $ACCESSLIB_PRIVATE, $USER;
883 if (isset($USER->access)) {
884 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->access;
887 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
888 if (empty($userid)) {
889 if (!empty($CFG->notloggedinroleid)) {
890 $accessdata = get_role_access($CFG->notloggedinroleid);
891 } else {
892 // weird
893 return get_empty_accessdata();
896 } else if (isguestuser($userid)) {
897 if ($guestrole = get_guest_role()) {
898 $accessdata = get_role_access($guestrole->id);
899 } else {
900 //weird
901 return get_empty_accessdata();
904 } else {
905 // Includes default role and frontpage role.
906 $accessdata = get_user_roles_sitewide_accessdata($userid);
909 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
912 if ($preloadonly) {
913 return;
914 } else {
915 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
920 * A convenience function to completely load all the capabilities
921 * for the current user. It is called from has_capability() and functions change permissions.
923 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
924 * @see check_enrolment_plugins()
926 * @access private
927 * @return void
929 function load_all_capabilities() {
930 global $USER;
932 // roles not installed yet - we are in the middle of installation
933 if (during_initial_install()) {
934 return;
937 if (!isset($USER->id)) {
938 // this should not happen
939 $USER->id = 0;
942 unset($USER->access);
943 $USER->access = get_user_accessdata($USER->id);
945 // Clear to force a refresh
946 unset($USER->mycourses);
948 // init/reset internal enrol caches - active course enrolments and temp access
949 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
953 * A convenience function to completely reload all the capabilities
954 * for the current user when roles have been updated in a relevant
955 * context -- but PRESERVING switchroles and loginas.
956 * This function resets all accesslib and context caches.
958 * That is - completely transparent to the user.
960 * Note: reloads $USER->access completely.
962 * @access private
963 * @return void
965 function reload_all_capabilities() {
966 global $USER, $DB, $ACCESSLIB_PRIVATE;
968 // copy switchroles
969 $sw = array();
970 if (!empty($USER->access['rsw'])) {
971 $sw = $USER->access['rsw'];
974 accesslib_clear_all_caches(true);
975 unset($USER->access);
976 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
978 load_all_capabilities();
980 foreach ($sw as $path => $roleid) {
981 if ($record = $DB->get_record('context', array('path'=>$path))) {
982 $context = context::instance_by_id($record->id);
983 role_switch($roleid, $context);
989 * Adds a temp role to current USER->access array.
991 * Useful for the "temporary guest" access we grant to logged-in users.
992 * This is useful for enrol plugins only.
994 * @since Moodle 2.2
995 * @param context_course $coursecontext
996 * @param int $roleid
997 * @return void
999 function load_temp_course_role(context_course $coursecontext, $roleid) {
1000 global $USER, $SITE;
1002 if (empty($roleid)) {
1003 debugging('invalid role specified in load_temp_course_role()');
1004 return;
1007 if ($coursecontext->instanceid == $SITE->id) {
1008 debugging('Can not use temp roles on the frontpage');
1009 return;
1012 if (!isset($USER->access)) {
1013 load_all_capabilities();
1016 $coursecontext->reload_if_dirty();
1018 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1019 return;
1022 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1026 * Removes any extra guest roles from current USER->access array.
1027 * This is useful for enrol plugins only.
1029 * @since Moodle 2.2
1030 * @param context_course $coursecontext
1031 * @return void
1033 function remove_temp_course_roles(context_course $coursecontext) {
1034 global $DB, $USER, $SITE;
1036 if ($coursecontext->instanceid == $SITE->id) {
1037 debugging('Can not use temp roles on the frontpage');
1038 return;
1041 if (empty($USER->access['ra'][$coursecontext->path])) {
1042 //no roles here, weird
1043 return;
1046 $sql = "SELECT DISTINCT ra.roleid AS id
1047 FROM {role_assignments} ra
1048 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1049 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1051 $USER->access['ra'][$coursecontext->path] = array();
1052 foreach($ras as $r) {
1053 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1058 * Returns array of all role archetypes.
1060 * @return array
1062 function get_role_archetypes() {
1063 return array(
1064 'manager' => 'manager',
1065 'coursecreator' => 'coursecreator',
1066 'editingteacher' => 'editingteacher',
1067 'teacher' => 'teacher',
1068 'student' => 'student',
1069 'guest' => 'guest',
1070 'user' => 'user',
1071 'frontpage' => 'frontpage'
1076 * Assign the defaults found in this capability definition to roles that have
1077 * the corresponding legacy capabilities assigned to them.
1079 * @param string $capability
1080 * @param array $legacyperms an array in the format (example):
1081 * 'guest' => CAP_PREVENT,
1082 * 'student' => CAP_ALLOW,
1083 * 'teacher' => CAP_ALLOW,
1084 * 'editingteacher' => CAP_ALLOW,
1085 * 'coursecreator' => CAP_ALLOW,
1086 * 'manager' => CAP_ALLOW
1087 * @return boolean success or failure.
1089 function assign_legacy_capabilities($capability, $legacyperms) {
1091 $archetypes = get_role_archetypes();
1093 foreach ($legacyperms as $type => $perm) {
1095 $systemcontext = context_system::instance();
1096 if ($type === 'admin') {
1097 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1098 $type = 'manager';
1101 if (!array_key_exists($type, $archetypes)) {
1102 print_error('invalidlegacy', '', '', $type);
1105 if ($roles = get_archetype_roles($type)) {
1106 foreach ($roles as $role) {
1107 // Assign a site level capability.
1108 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1109 return false;
1114 return true;
1118 * Verify capability risks.
1120 * @param stdClass $capability a capability - a row from the capabilities table.
1121 * @return boolean whether this capability is safe - that is, whether people with the
1122 * safeoverrides capability should be allowed to change it.
1124 function is_safe_capability($capability) {
1125 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1129 * Get the local override (if any) for a given capability in a role in a context
1131 * @param int $roleid
1132 * @param int $contextid
1133 * @param string $capability
1134 * @return stdClass local capability override
1136 function get_local_override($roleid, $contextid, $capability) {
1137 global $DB;
1138 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1142 * Returns context instance plus related course and cm instances
1144 * @param int $contextid
1145 * @return array of ($context, $course, $cm)
1147 function get_context_info_array($contextid) {
1148 global $DB;
1150 $context = context::instance_by_id($contextid, MUST_EXIST);
1151 $course = null;
1152 $cm = null;
1154 if ($context->contextlevel == CONTEXT_COURSE) {
1155 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1157 } else if ($context->contextlevel == CONTEXT_MODULE) {
1158 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1159 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1161 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1162 $parent = $context->get_parent_context();
1164 if ($parent->contextlevel == CONTEXT_COURSE) {
1165 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1166 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1167 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1168 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1172 return array($context, $course, $cm);
1176 * Function that creates a role
1178 * @param string $name role name
1179 * @param string $shortname role short name
1180 * @param string $description role description
1181 * @param string $archetype
1182 * @return int id or dml_exception
1184 function create_role($name, $shortname, $description, $archetype = '') {
1185 global $DB;
1187 if (strpos($archetype, 'moodle/legacy:') !== false) {
1188 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1191 // verify role archetype actually exists
1192 $archetypes = get_role_archetypes();
1193 if (empty($archetypes[$archetype])) {
1194 $archetype = '';
1197 // Insert the role record.
1198 $role = new stdClass();
1199 $role->name = $name;
1200 $role->shortname = $shortname;
1201 $role->description = $description;
1202 $role->archetype = $archetype;
1204 //find free sortorder number
1205 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1206 if (empty($role->sortorder)) {
1207 $role->sortorder = 1;
1209 $id = $DB->insert_record('role', $role);
1211 return $id;
1215 * Function that deletes a role and cleanups up after it
1217 * @param int $roleid id of role to delete
1218 * @return bool always true
1220 function delete_role($roleid) {
1221 global $DB;
1223 // first unssign all users
1224 role_unassign_all(array('roleid'=>$roleid));
1226 // cleanup all references to this role, ignore errors
1227 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1228 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1229 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1230 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1231 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1232 $DB->delete_records('role_names', array('roleid'=>$roleid));
1233 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1235 // Get role record before it's deleted.
1236 $role = $DB->get_record('role', array('id'=>$roleid));
1238 // Finally delete the role itself.
1239 $DB->delete_records('role', array('id'=>$roleid));
1241 // Trigger event.
1242 $event = \core\event\role_deleted::create(
1243 array(
1244 'context' => context_system::instance(),
1245 'objectid' => $roleid,
1246 'other' =>
1247 array(
1248 'shortname' => $role->shortname,
1249 'description' => $role->description,
1250 'archetype' => $role->archetype
1254 $event->add_record_snapshot('role', $role);
1255 $event->trigger();
1257 // Reset any cache of this role, including MUC.
1258 accesslib_clear_role_cache($roleid);
1260 return true;
1264 * Function to write context specific overrides, or default capabilities.
1266 * NOTE: use $context->mark_dirty() after this
1268 * @param string $capability string name
1269 * @param int $permission CAP_ constants
1270 * @param int $roleid role id
1271 * @param int|context $contextid context id
1272 * @param bool $overwrite
1273 * @return bool always true or exception
1275 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1276 global $USER, $DB;
1278 if ($contextid instanceof context) {
1279 $context = $contextid;
1280 } else {
1281 $context = context::instance_by_id($contextid);
1284 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1285 unassign_capability($capability, $roleid, $context->id);
1286 return true;
1289 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1291 if ($existing and !$overwrite) { // We want to keep whatever is there already
1292 return true;
1295 $cap = new stdClass();
1296 $cap->contextid = $context->id;
1297 $cap->roleid = $roleid;
1298 $cap->capability = $capability;
1299 $cap->permission = $permission;
1300 $cap->timemodified = time();
1301 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1303 if ($existing) {
1304 $cap->id = $existing->id;
1305 $DB->update_record('role_capabilities', $cap);
1306 } else {
1307 if ($DB->record_exists('context', array('id'=>$context->id))) {
1308 $DB->insert_record('role_capabilities', $cap);
1312 // Reset any cache of this role, including MUC.
1313 accesslib_clear_role_cache($roleid);
1315 return true;
1319 * Unassign a capability from a role.
1321 * NOTE: use $context->mark_dirty() after this
1323 * @param string $capability the name of the capability
1324 * @param int $roleid the role id
1325 * @param int|context $contextid null means all contexts
1326 * @return boolean true or exception
1328 function unassign_capability($capability, $roleid, $contextid = null) {
1329 global $DB;
1331 if (!empty($contextid)) {
1332 if ($contextid instanceof context) {
1333 $context = $contextid;
1334 } else {
1335 $context = context::instance_by_id($contextid);
1337 // delete from context rel, if this is the last override in this context
1338 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1339 } else {
1340 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1343 // Reset any cache of this role, including MUC.
1344 accesslib_clear_role_cache($roleid);
1346 return true;
1350 * Get the roles that have a given capability assigned to it
1352 * This function does not resolve the actual permission of the capability.
1353 * It just checks for permissions and overrides.
1354 * Use get_roles_with_cap_in_context() if resolution is required.
1356 * @param string $capability capability name (string)
1357 * @param string $permission optional, the permission defined for this capability
1358 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1359 * @param stdClass $context null means any
1360 * @return array of role records
1362 function get_roles_with_capability($capability, $permission = null, $context = null) {
1363 global $DB;
1365 if ($context) {
1366 $contexts = $context->get_parent_context_ids(true);
1367 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1368 $contextsql = "AND rc.contextid $insql";
1369 } else {
1370 $params = array();
1371 $contextsql = '';
1374 if ($permission) {
1375 $permissionsql = " AND rc.permission = :permission";
1376 $params['permission'] = $permission;
1377 } else {
1378 $permissionsql = '';
1381 $sql = "SELECT r.*
1382 FROM {role} r
1383 WHERE r.id IN (SELECT rc.roleid
1384 FROM {role_capabilities} rc
1385 WHERE rc.capability = :capname
1386 $contextsql
1387 $permissionsql)";
1388 $params['capname'] = $capability;
1391 return $DB->get_records_sql($sql, $params);
1395 * This function makes a role-assignment (a role for a user in a particular context)
1397 * @param int $roleid the role of the id
1398 * @param int $userid userid
1399 * @param int|context $contextid id of the context
1400 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1401 * @param int $itemid id of enrolment/auth plugin
1402 * @param string $timemodified defaults to current time
1403 * @return int new/existing id of the assignment
1405 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1406 global $USER, $DB, $CFG;
1408 // first of all detect if somebody is using old style parameters
1409 if ($contextid === 0 or is_numeric($component)) {
1410 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1413 // now validate all parameters
1414 if (empty($roleid)) {
1415 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1418 if (empty($userid)) {
1419 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1422 if ($itemid) {
1423 if (strpos($component, '_') === false) {
1424 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1426 } else {
1427 $itemid = 0;
1428 if ($component !== '' and strpos($component, '_') === false) {
1429 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1433 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1434 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1437 if ($contextid instanceof context) {
1438 $context = $contextid;
1439 } else {
1440 $context = context::instance_by_id($contextid, MUST_EXIST);
1443 if (!$timemodified) {
1444 $timemodified = time();
1447 // Check for existing entry
1448 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1450 if ($ras) {
1451 // role already assigned - this should not happen
1452 if (count($ras) > 1) {
1453 // very weird - remove all duplicates!
1454 $ra = array_shift($ras);
1455 foreach ($ras as $r) {
1456 $DB->delete_records('role_assignments', array('id'=>$r->id));
1458 } else {
1459 $ra = reset($ras);
1462 // actually there is no need to update, reset anything or trigger any event, so just return
1463 return $ra->id;
1466 // Create a new entry
1467 $ra = new stdClass();
1468 $ra->roleid = $roleid;
1469 $ra->contextid = $context->id;
1470 $ra->userid = $userid;
1471 $ra->component = $component;
1472 $ra->itemid = $itemid;
1473 $ra->timemodified = $timemodified;
1474 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1475 $ra->sortorder = 0;
1477 $ra->id = $DB->insert_record('role_assignments', $ra);
1479 // mark context as dirty - again expensive, but needed
1480 $context->mark_dirty();
1482 if (!empty($USER->id) && $USER->id == $userid) {
1483 // If the user is the current user, then do full reload of capabilities too.
1484 reload_all_capabilities();
1487 require_once($CFG->libdir . '/coursecatlib.php');
1488 coursecat::role_assignment_changed($roleid, $context);
1490 $event = \core\event\role_assigned::create(array(
1491 'context' => $context,
1492 'objectid' => $ra->roleid,
1493 'relateduserid' => $ra->userid,
1494 'other' => array(
1495 'id' => $ra->id,
1496 'component' => $ra->component,
1497 'itemid' => $ra->itemid
1500 $event->add_record_snapshot('role_assignments', $ra);
1501 $event->trigger();
1503 return $ra->id;
1507 * Removes one role assignment
1509 * @param int $roleid
1510 * @param int $userid
1511 * @param int $contextid
1512 * @param string $component
1513 * @param int $itemid
1514 * @return void
1516 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1517 // first make sure the params make sense
1518 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1519 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1522 if ($itemid) {
1523 if (strpos($component, '_') === false) {
1524 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1526 } else {
1527 $itemid = 0;
1528 if ($component !== '' and strpos($component, '_') === false) {
1529 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1533 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1537 * Removes multiple role assignments, parameters may contain:
1538 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1540 * @param array $params role assignment parameters
1541 * @param bool $subcontexts unassign in subcontexts too
1542 * @param bool $includemanual include manual role assignments too
1543 * @return void
1545 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1546 global $USER, $CFG, $DB;
1547 require_once($CFG->libdir . '/coursecatlib.php');
1549 if (!$params) {
1550 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1553 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1554 foreach ($params as $key=>$value) {
1555 if (!in_array($key, $allowed)) {
1556 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1560 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1561 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1564 if ($includemanual) {
1565 if (!isset($params['component']) or $params['component'] === '') {
1566 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1570 if ($subcontexts) {
1571 if (empty($params['contextid'])) {
1572 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1576 $ras = $DB->get_records('role_assignments', $params);
1577 foreach($ras as $ra) {
1578 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1579 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1580 // this is a bit expensive but necessary
1581 $context->mark_dirty();
1582 // If the user is the current user, then do full reload of capabilities too.
1583 if (!empty($USER->id) && $USER->id == $ra->userid) {
1584 reload_all_capabilities();
1586 $event = \core\event\role_unassigned::create(array(
1587 'context' => $context,
1588 'objectid' => $ra->roleid,
1589 'relateduserid' => $ra->userid,
1590 'other' => array(
1591 'id' => $ra->id,
1592 'component' => $ra->component,
1593 'itemid' => $ra->itemid
1596 $event->add_record_snapshot('role_assignments', $ra);
1597 $event->trigger();
1598 coursecat::role_assignment_changed($ra->roleid, $context);
1601 unset($ras);
1603 // process subcontexts
1604 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1605 if ($params['contextid'] instanceof context) {
1606 $context = $params['contextid'];
1607 } else {
1608 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1611 if ($context) {
1612 $contexts = $context->get_child_contexts();
1613 $mparams = $params;
1614 foreach($contexts as $context) {
1615 $mparams['contextid'] = $context->id;
1616 $ras = $DB->get_records('role_assignments', $mparams);
1617 foreach($ras as $ra) {
1618 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1619 // this is a bit expensive but necessary
1620 $context->mark_dirty();
1621 // If the user is the current user, then do full reload of capabilities too.
1622 if (!empty($USER->id) && $USER->id == $ra->userid) {
1623 reload_all_capabilities();
1625 $event = \core\event\role_unassigned::create(
1626 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1627 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1628 $event->add_record_snapshot('role_assignments', $ra);
1629 $event->trigger();
1630 coursecat::role_assignment_changed($ra->roleid, $context);
1636 // do this once more for all manual role assignments
1637 if ($includemanual) {
1638 $params['component'] = '';
1639 role_unassign_all($params, $subcontexts, false);
1644 * Determines if a user is currently logged in
1646 * @category access
1648 * @return bool
1650 function isloggedin() {
1651 global $USER;
1653 return (!empty($USER->id));
1657 * Determines if a user is logged in as real guest user with username 'guest'.
1659 * @category access
1661 * @param int|object $user mixed user object or id, $USER if not specified
1662 * @return bool true if user is the real guest user, false if not logged in or other user
1664 function isguestuser($user = null) {
1665 global $USER, $DB, $CFG;
1667 // make sure we have the user id cached in config table, because we are going to use it a lot
1668 if (empty($CFG->siteguest)) {
1669 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1670 // guest does not exist yet, weird
1671 return false;
1673 set_config('siteguest', $guestid);
1675 if ($user === null) {
1676 $user = $USER;
1679 if ($user === null) {
1680 // happens when setting the $USER
1681 return false;
1683 } else if (is_numeric($user)) {
1684 return ($CFG->siteguest == $user);
1686 } else if (is_object($user)) {
1687 if (empty($user->id)) {
1688 return false; // not logged in means is not be guest
1689 } else {
1690 return ($CFG->siteguest == $user->id);
1693 } else {
1694 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1699 * Does user have a (temporary or real) guest access to course?
1701 * @category access
1703 * @param context $context
1704 * @param stdClass|int $user
1705 * @return bool
1707 function is_guest(context $context, $user = null) {
1708 global $USER;
1710 // first find the course context
1711 $coursecontext = $context->get_course_context();
1713 // make sure there is a real user specified
1714 if ($user === null) {
1715 $userid = isset($USER->id) ? $USER->id : 0;
1716 } else {
1717 $userid = is_object($user) ? $user->id : $user;
1720 if (isguestuser($userid)) {
1721 // can not inspect or be enrolled
1722 return true;
1725 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1726 // viewing users appear out of nowhere, they are neither guests nor participants
1727 return false;
1730 // consider only real active enrolments here
1731 if (is_enrolled($coursecontext, $user, '', true)) {
1732 return false;
1735 return true;
1739 * Returns true if the user has moodle/course:view capability in the course,
1740 * this is intended for admins, managers (aka small admins), inspectors, etc.
1742 * @category access
1744 * @param context $context
1745 * @param int|stdClass $user if null $USER is used
1746 * @param string $withcapability extra capability name
1747 * @return bool
1749 function is_viewing(context $context, $user = null, $withcapability = '') {
1750 // first find the course context
1751 $coursecontext = $context->get_course_context();
1753 if (isguestuser($user)) {
1754 // can not inspect
1755 return false;
1758 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1759 // admins are allowed to inspect courses
1760 return false;
1763 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1764 // site admins always have the capability, but the enrolment above blocks
1765 return false;
1768 return true;
1772 * Returns true if the user is able to access the course.
1774 * This function is in no way, shape, or form a substitute for require_login.
1775 * It should only be used in circumstances where it is not possible to call require_login
1776 * such as the navigation.
1778 * This function checks many of the methods of access to a course such as the view
1779 * capability, enrollments, and guest access. It also makes use of the cache
1780 * generated by require_login for guest access.
1782 * The flags within the $USER object that are used here should NEVER be used outside
1783 * of this function can_access_course and require_login. Doing so WILL break future
1784 * versions.
1786 * @param stdClass $course record
1787 * @param stdClass|int|null $user user record or id, current user if null
1788 * @param string $withcapability Check for this capability as well.
1789 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1790 * @return boolean Returns true if the user is able to access the course
1792 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
1793 global $DB, $USER;
1795 // this function originally accepted $coursecontext parameter
1796 if ($course instanceof context) {
1797 if ($course instanceof context_course) {
1798 debugging('deprecated context parameter, please use $course record');
1799 $coursecontext = $course;
1800 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
1801 } else {
1802 debugging('Invalid context parameter, please use $course record');
1803 return false;
1805 } else {
1806 $coursecontext = context_course::instance($course->id);
1809 if (!isset($USER->id)) {
1810 // should never happen
1811 $USER->id = 0;
1812 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
1815 // make sure there is a user specified
1816 if ($user === null) {
1817 $userid = $USER->id;
1818 } else {
1819 $userid = is_object($user) ? $user->id : $user;
1821 unset($user);
1823 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
1824 return false;
1827 if ($userid == $USER->id) {
1828 if (!empty($USER->access['rsw'][$coursecontext->path])) {
1829 // the fact that somebody switched role means they can access the course no matter to what role they switched
1830 return true;
1834 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
1835 return false;
1838 if (is_viewing($coursecontext, $userid)) {
1839 return true;
1842 if ($userid != $USER->id) {
1843 // for performance reasons we do not verify temporary guest access for other users, sorry...
1844 return is_enrolled($coursecontext, $userid, '', $onlyactive);
1847 // === from here we deal only with $USER ===
1849 $coursecontext->reload_if_dirty();
1851 if (isset($USER->enrol['enrolled'][$course->id])) {
1852 if ($USER->enrol['enrolled'][$course->id] > time()) {
1853 return true;
1856 if (isset($USER->enrol['tempguest'][$course->id])) {
1857 if ($USER->enrol['tempguest'][$course->id] > time()) {
1858 return true;
1862 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
1863 return true;
1866 // if not enrolled try to gain temporary guest access
1867 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
1868 $enrols = enrol_get_plugins(true);
1869 foreach($instances as $instance) {
1870 if (!isset($enrols[$instance->enrol])) {
1871 continue;
1873 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
1874 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
1875 if ($until !== false and $until > time()) {
1876 $USER->enrol['tempguest'][$course->id] = $until;
1877 return true;
1880 if (isset($USER->enrol['tempguest'][$course->id])) {
1881 unset($USER->enrol['tempguest'][$course->id]);
1882 remove_temp_course_roles($coursecontext);
1885 return false;
1889 * Loads the capability definitions for the component (from file).
1891 * Loads the capability definitions for the component (from file). If no
1892 * capabilities are defined for the component, we simply return an empty array.
1894 * @access private
1895 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
1896 * @return array array of capabilities
1898 function load_capability_def($component) {
1899 $defpath = core_component::get_component_directory($component).'/db/access.php';
1901 $capabilities = array();
1902 if (file_exists($defpath)) {
1903 require($defpath);
1904 if (!empty(${$component.'_capabilities'})) {
1905 // BC capability array name
1906 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
1907 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
1908 $capabilities = ${$component.'_capabilities'};
1912 return $capabilities;
1916 * Gets the capabilities that have been cached in the database for this component.
1918 * @access private
1919 * @param string $component - examples: 'moodle', 'mod_forum'
1920 * @return array array of capabilities
1922 function get_cached_capabilities($component = 'moodle') {
1923 global $DB;
1924 $caps = get_all_capabilities();
1925 $componentcaps = array();
1926 foreach ($caps as $cap) {
1927 if ($cap['component'] == $component) {
1928 $componentcaps[] = (object) $cap;
1931 return $componentcaps;
1935 * Returns default capabilities for given role archetype.
1937 * @param string $archetype role archetype
1938 * @return array
1940 function get_default_capabilities($archetype) {
1941 global $DB;
1943 if (!$archetype) {
1944 return array();
1947 $alldefs = array();
1948 $defaults = array();
1949 $components = array();
1950 $allcaps = get_all_capabilities();
1952 foreach ($allcaps as $cap) {
1953 if (!in_array($cap['component'], $components)) {
1954 $components[] = $cap['component'];
1955 $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
1958 foreach($alldefs as $name=>$def) {
1959 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
1960 if (isset($def['archetypes'])) {
1961 if (isset($def['archetypes'][$archetype])) {
1962 $defaults[$name] = $def['archetypes'][$archetype];
1964 // 'legacy' is for backward compatibility with 1.9 access.php
1965 } else {
1966 if (isset($def['legacy'][$archetype])) {
1967 $defaults[$name] = $def['legacy'][$archetype];
1972 return $defaults;
1976 * Return default roles that can be assigned, overridden or switched
1977 * by give role archetype.
1979 * @param string $type assign|override|switch
1980 * @param string $archetype
1981 * @return array of role ids
1983 function get_default_role_archetype_allows($type, $archetype) {
1984 global $DB;
1986 if (empty($archetype)) {
1987 return array();
1990 $roles = $DB->get_records('role');
1991 $archetypemap = array();
1992 foreach ($roles as $role) {
1993 if ($role->archetype) {
1994 $archetypemap[$role->archetype][$role->id] = $role->id;
1998 $defaults = array(
1999 'assign' => array(
2000 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2001 'coursecreator' => array(),
2002 'editingteacher' => array('teacher', 'student'),
2003 'teacher' => array(),
2004 'student' => array(),
2005 'guest' => array(),
2006 'user' => array(),
2007 'frontpage' => array(),
2009 'override' => array(
2010 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2011 'coursecreator' => array(),
2012 'editingteacher' => array('teacher', 'student', 'guest'),
2013 'teacher' => array(),
2014 'student' => array(),
2015 'guest' => array(),
2016 'user' => array(),
2017 'frontpage' => array(),
2019 'switch' => array(
2020 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2021 'coursecreator' => array(),
2022 'editingteacher' => array('teacher', 'student', 'guest'),
2023 'teacher' => array('student', 'guest'),
2024 'student' => array(),
2025 'guest' => array(),
2026 'user' => array(),
2027 'frontpage' => array(),
2031 if (!isset($defaults[$type][$archetype])) {
2032 debugging("Unknown type '$type'' or archetype '$archetype''");
2033 return array();
2036 $return = array();
2037 foreach ($defaults[$type][$archetype] as $at) {
2038 if (isset($archetypemap[$at])) {
2039 foreach ($archetypemap[$at] as $roleid) {
2040 $return[$roleid] = $roleid;
2045 return $return;
2049 * Reset role capabilities to default according to selected role archetype.
2050 * If no archetype selected, removes all capabilities.
2052 * This applies to capabilities that are assigned to the role (that you could
2053 * edit in the 'define roles' interface), and not to any capability overrides
2054 * in different locations.
2056 * @param int $roleid ID of role to reset capabilities for
2058 function reset_role_capabilities($roleid) {
2059 global $DB;
2061 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2062 $defaultcaps = get_default_capabilities($role->archetype);
2064 $systemcontext = context_system::instance();
2066 $DB->delete_records('role_capabilities',
2067 array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2069 foreach($defaultcaps as $cap=>$permission) {
2070 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2073 // Reset any cache of this role, including MUC.
2074 accesslib_clear_role_cache($roleid);
2076 // Mark the system context dirty.
2077 context_system::instance()->mark_dirty();
2081 * Updates the capabilities table with the component capability definitions.
2082 * If no parameters are given, the function updates the core moodle
2083 * capabilities.
2085 * Note that the absence of the db/access.php capabilities definition file
2086 * will cause any stored capabilities for the component to be removed from
2087 * the database.
2089 * @access private
2090 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2091 * @return boolean true if success, exception in case of any problems
2093 function update_capabilities($component = 'moodle') {
2094 global $DB, $OUTPUT;
2096 $storedcaps = array();
2098 $filecaps = load_capability_def($component);
2099 foreach($filecaps as $capname=>$unused) {
2100 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2101 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2105 // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2106 // So ensure our updating is based on fresh data.
2107 cache::make('core', 'capabilities')->delete('core_capabilities');
2109 $cachedcaps = get_cached_capabilities($component);
2110 if ($cachedcaps) {
2111 foreach ($cachedcaps as $cachedcap) {
2112 array_push($storedcaps, $cachedcap->name);
2113 // update risk bitmasks and context levels in existing capabilities if needed
2114 if (array_key_exists($cachedcap->name, $filecaps)) {
2115 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2116 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2118 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2119 $updatecap = new stdClass();
2120 $updatecap->id = $cachedcap->id;
2121 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2122 $DB->update_record('capabilities', $updatecap);
2124 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2125 $updatecap = new stdClass();
2126 $updatecap->id = $cachedcap->id;
2127 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2128 $DB->update_record('capabilities', $updatecap);
2131 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2132 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2134 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2135 $updatecap = new stdClass();
2136 $updatecap->id = $cachedcap->id;
2137 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2138 $DB->update_record('capabilities', $updatecap);
2144 // Flush the cached again, as we have changed DB.
2145 cache::make('core', 'capabilities')->delete('core_capabilities');
2147 // Are there new capabilities in the file definition?
2148 $newcaps = array();
2150 foreach ($filecaps as $filecap => $def) {
2151 if (!$storedcaps ||
2152 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2153 if (!array_key_exists('riskbitmask', $def)) {
2154 $def['riskbitmask'] = 0; // no risk if not specified
2156 $newcaps[$filecap] = $def;
2159 // Add new capabilities to the stored definition.
2160 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2161 foreach ($newcaps as $capname => $capdef) {
2162 $capability = new stdClass();
2163 $capability->name = $capname;
2164 $capability->captype = $capdef['captype'];
2165 $capability->contextlevel = $capdef['contextlevel'];
2166 $capability->component = $component;
2167 $capability->riskbitmask = $capdef['riskbitmask'];
2169 $DB->insert_record('capabilities', $capability, false);
2171 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2172 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2173 foreach ($rolecapabilities as $rolecapability){
2174 //assign_capability will update rather than insert if capability exists
2175 if (!assign_capability($capname, $rolecapability->permission,
2176 $rolecapability->roleid, $rolecapability->contextid, true)){
2177 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2181 // we ignore archetype key if we have cloned permissions
2182 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2183 assign_legacy_capabilities($capname, $capdef['archetypes']);
2184 // 'legacy' is for backward compatibility with 1.9 access.php
2185 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2186 assign_legacy_capabilities($capname, $capdef['legacy']);
2189 // Are there any capabilities that have been removed from the file
2190 // definition that we need to delete from the stored capabilities and
2191 // role assignments?
2192 capabilities_cleanup($component, $filecaps);
2194 // reset static caches
2195 accesslib_clear_all_caches(false);
2197 // Flush the cached again, as we have changed DB.
2198 cache::make('core', 'capabilities')->delete('core_capabilities');
2200 return true;
2204 * Deletes cached capabilities that are no longer needed by the component.
2205 * Also unassigns these capabilities from any roles that have them.
2206 * NOTE: this function is called from lib/db/upgrade.php
2208 * @access private
2209 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2210 * @param array $newcapdef array of the new capability definitions that will be
2211 * compared with the cached capabilities
2212 * @return int number of deprecated capabilities that have been removed
2214 function capabilities_cleanup($component, $newcapdef = null) {
2215 global $DB;
2217 $removedcount = 0;
2219 if ($cachedcaps = get_cached_capabilities($component)) {
2220 foreach ($cachedcaps as $cachedcap) {
2221 if (empty($newcapdef) ||
2222 array_key_exists($cachedcap->name, $newcapdef) === false) {
2224 // Remove from capabilities cache.
2225 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2226 $removedcount++;
2227 // Delete from roles.
2228 if ($roles = get_roles_with_capability($cachedcap->name)) {
2229 foreach($roles as $role) {
2230 if (!unassign_capability($cachedcap->name, $role->id)) {
2231 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2235 } // End if.
2238 if ($removedcount) {
2239 cache::make('core', 'capabilities')->delete('core_capabilities');
2241 return $removedcount;
2245 * Returns an array of all the known types of risk
2246 * The array keys can be used, for example as CSS class names, or in calls to
2247 * print_risk_icon. The values are the corresponding RISK_ constants.
2249 * @return array all the known types of risk.
2251 function get_all_risks() {
2252 return array(
2253 'riskmanagetrust' => RISK_MANAGETRUST,
2254 'riskconfig' => RISK_CONFIG,
2255 'riskxss' => RISK_XSS,
2256 'riskpersonal' => RISK_PERSONAL,
2257 'riskspam' => RISK_SPAM,
2258 'riskdataloss' => RISK_DATALOSS,
2263 * Return a link to moodle docs for a given capability name
2265 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2266 * @return string the human-readable capability name as a link to Moodle Docs.
2268 function get_capability_docs_link($capability) {
2269 $url = get_docs_url('Capabilities/' . $capability->name);
2270 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2274 * This function pulls out all the resolved capabilities (overrides and
2275 * defaults) of a role used in capability overrides in contexts at a given
2276 * context.
2278 * @param int $roleid
2279 * @param context $context
2280 * @param string $cap capability, optional, defaults to ''
2281 * @return array Array of capabilities
2283 function role_context_capabilities($roleid, context $context, $cap = '') {
2284 global $DB;
2286 $contexts = $context->get_parent_context_ids(true);
2287 $contexts = '('.implode(',', $contexts).')';
2289 $params = array($roleid);
2291 if ($cap) {
2292 $search = " AND rc.capability = ? ";
2293 $params[] = $cap;
2294 } else {
2295 $search = '';
2298 $sql = "SELECT rc.*
2299 FROM {role_capabilities} rc, {context} c
2300 WHERE rc.contextid in $contexts
2301 AND rc.roleid = ?
2302 AND rc.contextid = c.id $search
2303 ORDER BY c.contextlevel DESC, rc.capability DESC";
2305 $capabilities = array();
2307 if ($records = $DB->get_records_sql($sql, $params)) {
2308 // We are traversing via reverse order.
2309 foreach ($records as $record) {
2310 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2311 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2312 $capabilities[$record->capability] = $record->permission;
2316 return $capabilities;
2320 * Constructs array with contextids as first parameter and context paths,
2321 * in both cases bottom top including self.
2323 * @access private
2324 * @param context $context
2325 * @return array
2327 function get_context_info_list(context $context) {
2328 $contextids = explode('/', ltrim($context->path, '/'));
2329 $contextpaths = array();
2330 $contextids2 = $contextids;
2331 while ($contextids2) {
2332 $contextpaths[] = '/' . implode('/', $contextids2);
2333 array_pop($contextids2);
2335 return array($contextids, $contextpaths);
2339 * Check if context is the front page context or a context inside it
2341 * Returns true if this context is the front page context, or a context inside it,
2342 * otherwise false.
2344 * @param context $context a context object.
2345 * @return bool
2347 function is_inside_frontpage(context $context) {
2348 $frontpagecontext = context_course::instance(SITEID);
2349 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2353 * Returns capability information (cached)
2355 * @param string $capabilityname
2356 * @return stdClass or null if capability not found
2358 function get_capability_info($capabilityname) {
2359 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2361 $caps = get_all_capabilities();
2363 if (!isset($caps[$capabilityname])) {
2364 return null;
2367 return (object) $caps[$capabilityname];
2371 * Returns all capabilitiy records, preferably from MUC and not database.
2373 * @return array All capability records indexed by capability name
2375 function get_all_capabilities() {
2376 global $DB;
2377 $cache = cache::make('core', 'capabilities');
2378 if (!$allcaps = $cache->get('core_capabilities')) {
2379 $rs = $DB->get_recordset('capabilities');
2380 $allcaps = array();
2381 foreach ($rs as $capability) {
2382 $capability->riskbitmask = (int) $capability->riskbitmask;
2383 $allcaps[$capability->name] = (array) $capability;
2385 $rs->close();
2386 $cache->set('core_capabilities', $allcaps);
2388 return $allcaps;
2392 * Returns the human-readable, translated version of the capability.
2393 * Basically a big switch statement.
2395 * @param string $capabilityname e.g. mod/choice:readresponses
2396 * @return string
2398 function get_capability_string($capabilityname) {
2400 // Typical capability name is 'plugintype/pluginname:capabilityname'
2401 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2403 if ($type === 'moodle') {
2404 $component = 'core_role';
2405 } else if ($type === 'quizreport') {
2406 //ugly hack!!
2407 $component = 'quiz_'.$name;
2408 } else {
2409 $component = $type.'_'.$name;
2412 $stringname = $name.':'.$capname;
2414 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2415 return get_string($stringname, $component);
2418 $dir = core_component::get_component_directory($component);
2419 if (!file_exists($dir)) {
2420 // plugin broken or does not exist, do not bother with printing of debug message
2421 return $capabilityname.' ???';
2424 // something is wrong in plugin, better print debug
2425 return get_string($stringname, $component);
2429 * This gets the mod/block/course/core etc strings.
2431 * @param string $component
2432 * @param int $contextlevel
2433 * @return string|bool String is success, false if failed
2435 function get_component_string($component, $contextlevel) {
2437 if ($component === 'moodle' or $component === 'core') {
2438 switch ($contextlevel) {
2439 // TODO MDL-46123: this should probably use context level names instead
2440 case CONTEXT_SYSTEM: return get_string('coresystem');
2441 case CONTEXT_USER: return get_string('users');
2442 case CONTEXT_COURSECAT: return get_string('categories');
2443 case CONTEXT_COURSE: return get_string('course');
2444 case CONTEXT_MODULE: return get_string('activities');
2445 case CONTEXT_BLOCK: return get_string('block');
2446 default: print_error('unknowncontext');
2450 list($type, $name) = core_component::normalize_component($component);
2451 $dir = core_component::get_plugin_directory($type, $name);
2452 if (!file_exists($dir)) {
2453 // plugin not installed, bad luck, there is no way to find the name
2454 return $component.' ???';
2457 switch ($type) {
2458 // TODO MDL-46123: this is really hacky and should be improved.
2459 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2460 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2461 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2462 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2463 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2464 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2465 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2466 case 'mod':
2467 if (get_string_manager()->string_exists('pluginname', $component)) {
2468 return get_string('activity').': '.get_string('pluginname', $component);
2469 } else {
2470 return get_string('activity').': '.get_string('modulename', $component);
2472 default: return get_string('pluginname', $component);
2477 * Gets the list of roles assigned to this context and up (parents)
2478 * from the aggregation of:
2479 * a) the list of roles that are visible on user profile page and participants page (profileroles setting) and;
2480 * b) if applicable, those roles that are assigned in the context.
2482 * @param context $context
2483 * @return array
2485 function get_profile_roles(context $context) {
2486 global $CFG, $DB;
2487 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2488 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2489 if (has_capability('moodle/role:assign', $context)) {
2490 $rolesinscope = array_keys(get_all_roles($context));
2491 } else {
2492 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2495 if (empty($rolesinscope)) {
2496 return [];
2499 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2500 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2501 $params = array_merge($params, $cparams);
2503 if ($coursecontext = $context->get_course_context(false)) {
2504 $params['coursecontext'] = $coursecontext->id;
2505 } else {
2506 $params['coursecontext'] = 0;
2509 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2510 FROM {role_assignments} ra, {role} r
2511 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2512 WHERE r.id = ra.roleid
2513 AND ra.contextid $contextlist
2514 AND r.id $rallowed
2515 ORDER BY r.sortorder ASC";
2517 return $DB->get_records_sql($sql, $params);
2521 * Gets the list of roles assigned to this context and up (parents)
2523 * @param context $context
2524 * @return array
2526 function get_roles_used_in_context(context $context) {
2527 global $DB;
2529 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2531 if ($coursecontext = $context->get_course_context(false)) {
2532 $params['coursecontext'] = $coursecontext->id;
2533 } else {
2534 $params['coursecontext'] = 0;
2537 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2538 FROM {role_assignments} ra, {role} r
2539 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2540 WHERE r.id = ra.roleid
2541 AND ra.contextid $contextlist
2542 ORDER BY r.sortorder ASC";
2544 return $DB->get_records_sql($sql, $params);
2548 * This function is used to print roles column in user profile page.
2549 * It is using the CFG->profileroles to limit the list to only interesting roles.
2550 * (The permission tab has full details of user role assignments.)
2552 * @param int $userid
2553 * @param int $courseid
2554 * @return string
2556 function get_user_roles_in_course($userid, $courseid) {
2557 global $CFG, $DB;
2558 if ($courseid == SITEID) {
2559 $context = context_system::instance();
2560 } else {
2561 $context = context_course::instance($courseid);
2563 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2564 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2565 if (has_capability('moodle/role:assign', $context)) {
2566 $rolesinscope = array_keys(get_all_roles($context));
2567 } else {
2568 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2570 if (empty($rolesinscope)) {
2571 return '';
2574 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2575 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2576 $params = array_merge($params, $cparams);
2578 if ($coursecontext = $context->get_course_context(false)) {
2579 $params['coursecontext'] = $coursecontext->id;
2580 } else {
2581 $params['coursecontext'] = 0;
2584 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2585 FROM {role_assignments} ra, {role} r
2586 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2587 WHERE r.id = ra.roleid
2588 AND ra.contextid $contextlist
2589 AND r.id $rallowed
2590 AND ra.userid = :userid
2591 ORDER BY r.sortorder ASC";
2592 $params['userid'] = $userid;
2594 $rolestring = '';
2596 if ($roles = $DB->get_records_sql($sql, $params)) {
2597 $rolenames = role_fix_names($roles, $context, ROLENAME_ALIAS, true); // Substitute aliases
2599 foreach ($rolenames as $roleid => $rolename) {
2600 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
2602 $rolestring = implode(',', $rolenames);
2605 return $rolestring;
2609 * Checks if a user can assign users to a particular role in this context
2611 * @param context $context
2612 * @param int $targetroleid - the id of the role you want to assign users to
2613 * @return boolean
2615 function user_can_assign(context $context, $targetroleid) {
2616 global $DB;
2618 // First check to see if the user is a site administrator.
2619 if (is_siteadmin()) {
2620 return true;
2623 // Check if user has override capability.
2624 // If not return false.
2625 if (!has_capability('moodle/role:assign', $context)) {
2626 return false;
2628 // pull out all active roles of this user from this context(or above)
2629 if ($userroles = get_user_roles($context)) {
2630 foreach ($userroles as $userrole) {
2631 // if any in the role_allow_override table, then it's ok
2632 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2633 return true;
2638 return false;
2642 * Returns all site roles in correct sort order.
2644 * Note: this method does not localise role names or descriptions,
2645 * use role_get_names() if you need role names.
2647 * @param context $context optional context for course role name aliases
2648 * @return array of role records with optional coursealias property
2650 function get_all_roles(context $context = null) {
2651 global $DB;
2653 if (!$context or !$coursecontext = $context->get_course_context(false)) {
2654 $coursecontext = null;
2657 if ($coursecontext) {
2658 $sql = "SELECT r.*, rn.name AS coursealias
2659 FROM {role} r
2660 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2661 ORDER BY r.sortorder ASC";
2662 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
2664 } else {
2665 return $DB->get_records('role', array(), 'sortorder ASC');
2670 * Returns roles of a specified archetype
2672 * @param string $archetype
2673 * @return array of full role records
2675 function get_archetype_roles($archetype) {
2676 global $DB;
2677 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2681 * Gets all the user roles assigned in this context, or higher contexts for a list of users.
2683 * @param context $context
2684 * @param array $userids. An empty list means fetch all role assignments for the context.
2685 * @param bool $checkparentcontexts defaults to true
2686 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2687 * @return array
2689 function get_users_roles(context $context, $userids = [], $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2690 global $USER, $DB;
2692 if ($checkparentcontexts) {
2693 $contextids = $context->get_parent_context_ids();
2694 } else {
2695 $contextids = array();
2697 $contextids[] = $context->id;
2699 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
2701 // If userids was passed as an empty array, we fetch all role assignments for the course.
2702 if (empty($userids)) {
2703 $useridlist = ' IS NOT NULL ';
2704 $uparams = [];
2705 } else {
2706 list($useridlist, $uparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'uids');
2709 $sql = "SELECT ra.*, r.name, r.shortname, ra.userid
2710 FROM {role_assignments} ra, {role} r, {context} c
2711 WHERE ra.userid $useridlist
2712 AND ra.roleid = r.id
2713 AND ra.contextid = c.id
2714 AND ra.contextid $contextids
2715 ORDER BY $order";
2717 $all = $DB->get_records_sql($sql , array_merge($params, $uparams));
2719 // Return results grouped by userid.
2720 $result = [];
2721 foreach ($all as $id => $record) {
2722 if (!isset($result[$record->userid])) {
2723 $result[$record->userid] = [];
2725 $result[$record->userid][$record->id] = $record;
2728 // Make sure all requested users are included in the result, even if they had no role assignments.
2729 foreach ($userids as $id) {
2730 if (!isset($result[$id])) {
2731 $result[$id] = [];
2735 return $result;
2740 * Gets all the user roles assigned in this context, or higher contexts
2741 * this is mainly used when checking if a user can assign a role, or overriding a role
2742 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2743 * allow_override tables
2745 * @param context $context
2746 * @param int $userid
2747 * @param bool $checkparentcontexts defaults to true
2748 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2749 * @return array
2751 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2752 global $USER, $DB;
2754 if (empty($userid)) {
2755 if (empty($USER->id)) {
2756 return array();
2758 $userid = $USER->id;
2761 if ($checkparentcontexts) {
2762 $contextids = $context->get_parent_context_ids();
2763 } else {
2764 $contextids = array();
2766 $contextids[] = $context->id;
2768 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2770 array_unshift($params, $userid);
2772 $sql = "SELECT ra.*, r.name, r.shortname
2773 FROM {role_assignments} ra, {role} r, {context} c
2774 WHERE ra.userid = ?
2775 AND ra.roleid = r.id
2776 AND ra.contextid = c.id
2777 AND ra.contextid $contextids
2778 ORDER BY $order";
2780 return $DB->get_records_sql($sql ,$params);
2784 * Like get_user_roles, but adds in the authenticated user role, and the front
2785 * page roles, if applicable.
2787 * @param context $context the context.
2788 * @param int $userid optional. Defaults to $USER->id
2789 * @return array of objects with fields ->userid, ->contextid and ->roleid.
2791 function get_user_roles_with_special(context $context, $userid = 0) {
2792 global $CFG, $USER;
2794 if (empty($userid)) {
2795 if (empty($USER->id)) {
2796 return array();
2798 $userid = $USER->id;
2801 $ras = get_user_roles($context, $userid);
2803 // Add front-page role if relevant.
2804 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2805 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
2806 is_inside_frontpage($context);
2807 if ($defaultfrontpageroleid && $isfrontpage) {
2808 $frontpagecontext = context_course::instance(SITEID);
2809 $ra = new stdClass();
2810 $ra->userid = $userid;
2811 $ra->contextid = $frontpagecontext->id;
2812 $ra->roleid = $defaultfrontpageroleid;
2813 $ras[] = $ra;
2816 // Add authenticated user role if relevant.
2817 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2818 if ($defaultuserroleid && !isguestuser($userid)) {
2819 $systemcontext = context_system::instance();
2820 $ra = new stdClass();
2821 $ra->userid = $userid;
2822 $ra->contextid = $systemcontext->id;
2823 $ra->roleid = $defaultuserroleid;
2824 $ras[] = $ra;
2827 return $ras;
2831 * Creates a record in the role_allow_override table
2833 * @param int $sroleid source roleid
2834 * @param int $troleid target roleid
2835 * @return void
2837 function allow_override($sroleid, $troleid) {
2838 global $DB;
2840 $record = new stdClass();
2841 $record->roleid = $sroleid;
2842 $record->allowoverride = $troleid;
2843 $DB->insert_record('role_allow_override', $record);
2847 * Creates a record in the role_allow_assign table
2849 * @param int $fromroleid source roleid
2850 * @param int $targetroleid target roleid
2851 * @return void
2853 function allow_assign($fromroleid, $targetroleid) {
2854 global $DB;
2856 $record = new stdClass();
2857 $record->roleid = $fromroleid;
2858 $record->allowassign = $targetroleid;
2859 $DB->insert_record('role_allow_assign', $record);
2863 * Creates a record in the role_allow_switch table
2865 * @param int $fromroleid source roleid
2866 * @param int $targetroleid target roleid
2867 * @return void
2869 function allow_switch($fromroleid, $targetroleid) {
2870 global $DB;
2872 $record = new stdClass();
2873 $record->roleid = $fromroleid;
2874 $record->allowswitch = $targetroleid;
2875 $DB->insert_record('role_allow_switch', $record);
2879 * Gets a list of roles that this user can assign in this context
2881 * @param context $context the context.
2882 * @param int $rolenamedisplay the type of role name to display. One of the
2883 * ROLENAME_X constants. Default ROLENAME_ALIAS.
2884 * @param bool $withusercounts if true, count the number of users with each role.
2885 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
2886 * @return array if $withusercounts is false, then an array $roleid => $rolename.
2887 * if $withusercounts is true, returns a list of three arrays,
2888 * $rolenames, $rolecounts, and $nameswithcounts.
2890 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
2891 global $USER, $DB;
2893 // make sure there is a real user specified
2894 if ($user === null) {
2895 $userid = isset($USER->id) ? $USER->id : 0;
2896 } else {
2897 $userid = is_object($user) ? $user->id : $user;
2900 if (!has_capability('moodle/role:assign', $context, $userid)) {
2901 if ($withusercounts) {
2902 return array(array(), array(), array());
2903 } else {
2904 return array();
2908 $params = array();
2909 $extrafields = '';
2911 if ($withusercounts) {
2912 $extrafields = ', (SELECT count(u.id)
2913 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
2914 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
2915 ) AS usercount';
2916 $params['conid'] = $context->id;
2919 if (is_siteadmin($userid)) {
2920 // show all roles allowed in this context to admins
2921 $assignrestriction = "";
2922 } else {
2923 $parents = $context->get_parent_context_ids(true);
2924 $contexts = implode(',' , $parents);
2925 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
2926 FROM {role_allow_assign} raa
2927 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
2928 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
2929 ) ar ON ar.id = r.id";
2930 $params['userid'] = $userid;
2932 $params['contextlevel'] = $context->contextlevel;
2934 if ($coursecontext = $context->get_course_context(false)) {
2935 $params['coursecontext'] = $coursecontext->id;
2936 } else {
2937 $params['coursecontext'] = 0; // no course aliases
2938 $coursecontext = null;
2940 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
2941 FROM {role} r
2942 $assignrestriction
2943 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
2944 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2945 ORDER BY r.sortorder ASC";
2946 $roles = $DB->get_records_sql($sql, $params);
2948 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
2950 if (!$withusercounts) {
2951 return $rolenames;
2954 $rolecounts = array();
2955 $nameswithcounts = array();
2956 foreach ($roles as $role) {
2957 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
2958 $rolecounts[$role->id] = $roles[$role->id]->usercount;
2960 return array($rolenames, $rolecounts, $nameswithcounts);
2964 * Gets a list of roles that this user can switch to in a context
2966 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
2967 * This function just process the contents of the role_allow_switch table. You also need to
2968 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
2970 * @param context $context a context.
2971 * @return array an array $roleid => $rolename.
2973 function get_switchable_roles(context $context) {
2974 global $USER, $DB;
2976 // You can't switch roles without this capability.
2977 if (!has_capability('moodle/role:switchroles', $context)) {
2978 return [];
2981 $params = array();
2982 $extrajoins = '';
2983 $extrawhere = '';
2984 if (!is_siteadmin()) {
2985 // Admins are allowed to switch to any role with.
2986 // Others are subject to the additional constraint that the switch-to role must be allowed by
2987 // 'role_allow_switch' for some role they have assigned in this context or any parent.
2988 $parents = $context->get_parent_context_ids(true);
2989 $contexts = implode(',' , $parents);
2991 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
2992 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
2993 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
2994 $params['userid'] = $USER->id;
2997 if ($coursecontext = $context->get_course_context(false)) {
2998 $params['coursecontext'] = $coursecontext->id;
2999 } else {
3000 $params['coursecontext'] = 0; // no course aliases
3001 $coursecontext = null;
3004 $query = "
3005 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3006 FROM (SELECT DISTINCT rc.roleid
3007 FROM {role_capabilities} rc
3008 $extrajoins
3009 $extrawhere) idlist
3010 JOIN {role} r ON r.id = idlist.roleid
3011 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3012 ORDER BY r.sortorder";
3013 $roles = $DB->get_records_sql($query, $params);
3015 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3019 * Gets a list of roles that this user can override in this context.
3021 * @param context $context the context.
3022 * @param int $rolenamedisplay the type of role name to display. One of the
3023 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3024 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3025 * @return array if $withcounts is false, then an array $roleid => $rolename.
3026 * if $withusercounts is true, returns a list of three arrays,
3027 * $rolenames, $rolecounts, and $nameswithcounts.
3029 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3030 global $USER, $DB;
3032 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3033 if ($withcounts) {
3034 return array(array(), array(), array());
3035 } else {
3036 return array();
3040 $parents = $context->get_parent_context_ids(true);
3041 $contexts = implode(',' , $parents);
3043 $params = array();
3044 $extrafields = '';
3046 $params['userid'] = $USER->id;
3047 if ($withcounts) {
3048 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3049 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3050 $params['conid'] = $context->id;
3053 if ($coursecontext = $context->get_course_context(false)) {
3054 $params['coursecontext'] = $coursecontext->id;
3055 } else {
3056 $params['coursecontext'] = 0; // no course aliases
3057 $coursecontext = null;
3060 if (is_siteadmin()) {
3061 // show all roles to admins
3062 $roles = $DB->get_records_sql("
3063 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3064 FROM {role} ro
3065 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3066 ORDER BY ro.sortorder ASC", $params);
3068 } else {
3069 $roles = $DB->get_records_sql("
3070 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3071 FROM {role} ro
3072 JOIN (SELECT DISTINCT r.id
3073 FROM {role} r
3074 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3075 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3076 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3077 ) inline_view ON ro.id = inline_view.id
3078 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3079 ORDER BY ro.sortorder ASC", $params);
3082 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3084 if (!$withcounts) {
3085 return $rolenames;
3088 $rolecounts = array();
3089 $nameswithcounts = array();
3090 foreach ($roles as $role) {
3091 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3092 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3094 return array($rolenames, $rolecounts, $nameswithcounts);
3098 * Create a role menu suitable for default role selection in enrol plugins.
3100 * @package core_enrol
3102 * @param context $context
3103 * @param int $addroleid current or default role - always added to list
3104 * @return array roleid=>localised role name
3106 function get_default_enrol_roles(context $context, $addroleid = null) {
3107 global $DB;
3109 $params = array('contextlevel'=>CONTEXT_COURSE);
3111 if ($coursecontext = $context->get_course_context(false)) {
3112 $params['coursecontext'] = $coursecontext->id;
3113 } else {
3114 $params['coursecontext'] = 0; // no course names
3115 $coursecontext = null;
3118 if ($addroleid) {
3119 $addrole = "OR r.id = :addroleid";
3120 $params['addroleid'] = $addroleid;
3121 } else {
3122 $addrole = "";
3125 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3126 FROM {role} r
3127 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3128 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3129 WHERE rcl.id IS NOT NULL $addrole
3130 ORDER BY sortorder DESC";
3132 $roles = $DB->get_records_sql($sql, $params);
3134 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3138 * Return context levels where this role is assignable.
3140 * @param integer $roleid the id of a role.
3141 * @return array list of the context levels at which this role may be assigned.
3143 function get_role_contextlevels($roleid) {
3144 global $DB;
3145 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3146 'contextlevel', 'id,contextlevel');
3150 * Return roles suitable for assignment at the specified context level.
3152 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3154 * @param integer $contextlevel a contextlevel.
3155 * @return array list of role ids that are assignable at this context level.
3157 function get_roles_for_contextlevels($contextlevel) {
3158 global $DB;
3159 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3160 '', 'id,roleid');
3164 * Returns default context levels where roles can be assigned.
3166 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3167 * from the array returned by get_role_archetypes();
3168 * @return array list of the context levels at which this type of role may be assigned by default.
3170 function get_default_contextlevels($rolearchetype) {
3171 static $defaults = array(
3172 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3173 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3174 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3175 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3176 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3177 'guest' => array(),
3178 'user' => array(),
3179 'frontpage' => array());
3181 if (isset($defaults[$rolearchetype])) {
3182 return $defaults[$rolearchetype];
3183 } else {
3184 return array();
3189 * Set the context levels at which a particular role can be assigned.
3190 * Throws exceptions in case of error.
3192 * @param integer $roleid the id of a role.
3193 * @param array $contextlevels the context levels at which this role should be assignable,
3194 * duplicate levels are removed.
3195 * @return void
3197 function set_role_contextlevels($roleid, array $contextlevels) {
3198 global $DB;
3199 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3200 $rcl = new stdClass();
3201 $rcl->roleid = $roleid;
3202 $contextlevels = array_unique($contextlevels);
3203 foreach ($contextlevels as $level) {
3204 $rcl->contextlevel = $level;
3205 $DB->insert_record('role_context_levels', $rcl, false, true);
3210 * Who has this capability in this context?
3212 * This can be a very expensive call - use sparingly and keep
3213 * the results if you are going to need them again soon.
3215 * Note if $fields is empty this function attempts to get u.*
3216 * which can get rather large - and has a serious perf impact
3217 * on some DBs.
3219 * @param context $context
3220 * @param string|array $capability - capability name(s)
3221 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3222 * @param string $sort - the sort order. Default is lastaccess time.
3223 * @param mixed $limitfrom - number of records to skip (offset)
3224 * @param mixed $limitnum - number of records to fetch
3225 * @param string|array $groups - single group or array of groups - only return
3226 * users who are in one of these group(s).
3227 * @param string|array $exceptions - list of users to exclude, comma separated or array
3228 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3229 * @param bool $view_ignored - use get_enrolled_sql() instead
3230 * @param bool $useviewallgroups if $groups is set the return users who
3231 * have capability both $capability and moodle/site:accessallgroups
3232 * in this context, as well as users who have $capability and who are
3233 * in $groups.
3234 * @return array of user records
3236 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3237 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3238 global $CFG, $DB;
3240 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3241 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3243 $ctxids = trim($context->path, '/');
3244 $ctxids = str_replace('/', ',', $ctxids);
3246 // Context is the frontpage
3247 $iscoursepage = false; // coursepage other than fp
3248 $isfrontpage = false;
3249 if ($context->contextlevel == CONTEXT_COURSE) {
3250 if ($context->instanceid == SITEID) {
3251 $isfrontpage = true;
3252 } else {
3253 $iscoursepage = true;
3256 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3258 $caps = (array)$capability;
3260 // construct list of context paths bottom-->top
3261 list($contextids, $paths) = get_context_info_list($context);
3263 // we need to find out all roles that have these capabilities either in definition or in overrides
3264 $defs = array();
3265 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3266 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3267 $params = array_merge($params, $params2);
3268 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3269 FROM {role_capabilities} rc
3270 JOIN {context} ctx on rc.contextid = ctx.id
3271 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3273 $rcs = $DB->get_records_sql($sql, $params);
3274 foreach ($rcs as $rc) {
3275 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3278 // go through the permissions bottom-->top direction to evaluate the current permission,
3279 // first one wins (prohibit is an exception that always wins)
3280 $access = array();
3281 foreach ($caps as $cap) {
3282 foreach ($paths as $path) {
3283 if (empty($defs[$cap][$path])) {
3284 continue;
3286 foreach($defs[$cap][$path] as $roleid => $perm) {
3287 if ($perm == CAP_PROHIBIT) {
3288 $access[$cap][$roleid] = CAP_PROHIBIT;
3289 continue;
3291 if (!isset($access[$cap][$roleid])) {
3292 $access[$cap][$roleid] = (int)$perm;
3298 // make lists of roles that are needed and prohibited in this context
3299 $needed = array(); // one of these is enough
3300 $prohibited = array(); // must not have any of these
3301 foreach ($caps as $cap) {
3302 if (empty($access[$cap])) {
3303 continue;
3305 foreach ($access[$cap] as $roleid => $perm) {
3306 if ($perm == CAP_PROHIBIT) {
3307 unset($needed[$cap][$roleid]);
3308 $prohibited[$cap][$roleid] = true;
3309 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3310 $needed[$cap][$roleid] = true;
3313 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3314 // easy, nobody has the permission
3315 unset($needed[$cap]);
3316 unset($prohibited[$cap]);
3317 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3318 // everybody is disqualified on the frontpage
3319 unset($needed[$cap]);
3320 unset($prohibited[$cap]);
3322 if (empty($prohibited[$cap])) {
3323 unset($prohibited[$cap]);
3327 if (empty($needed)) {
3328 // there can not be anybody if no roles match this request
3329 return array();
3332 if (empty($prohibited)) {
3333 // we can compact the needed roles
3334 $n = array();
3335 foreach ($needed as $cap) {
3336 foreach ($cap as $roleid=>$unused) {
3337 $n[$roleid] = true;
3340 $needed = array('any'=>$n);
3341 unset($n);
3344 // ***** Set up default fields ******
3345 if (empty($fields)) {
3346 if ($iscoursepage) {
3347 $fields = 'u.*, ul.timeaccess AS lastaccess';
3348 } else {
3349 $fields = 'u.*';
3351 } else {
3352 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3353 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3357 // Set up default sort
3358 if (empty($sort)) { // default to course lastaccess or just lastaccess
3359 if ($iscoursepage) {
3360 $sort = 'ul.timeaccess';
3361 } else {
3362 $sort = 'u.lastaccess';
3366 // Prepare query clauses
3367 $wherecond = array();
3368 $params = array();
3369 $joins = array();
3371 // User lastaccess JOIN
3372 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3373 // user_lastaccess is not required MDL-13810
3374 } else {
3375 if ($iscoursepage) {
3376 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3377 } else {
3378 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3382 // We never return deleted users or guest account.
3383 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3384 $params['guestid'] = $CFG->siteguest;
3386 // Groups
3387 if ($groups) {
3388 $groups = (array)$groups;
3389 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3390 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3391 $params = array_merge($params, $grpparams);
3393 if ($useviewallgroups) {
3394 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3395 if (!empty($viewallgroupsusers)) {
3396 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3397 } else {
3398 $wherecond[] = "($grouptest)";
3400 } else {
3401 $wherecond[] = "($grouptest)";
3405 // User exceptions
3406 if (!empty($exceptions)) {
3407 $exceptions = (array)$exceptions;
3408 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3409 $params = array_merge($params, $exparams);
3410 $wherecond[] = "u.id $exsql";
3413 // now add the needed and prohibited roles conditions as joins
3414 if (!empty($needed['any'])) {
3415 // simple case - there are no prohibits involved
3416 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3417 // everybody
3418 } else {
3419 $joins[] = "JOIN (SELECT DISTINCT userid
3420 FROM {role_assignments}
3421 WHERE contextid IN ($ctxids)
3422 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3423 ) ra ON ra.userid = u.id";
3425 } else {
3426 $unions = array();
3427 $everybody = false;
3428 foreach ($needed as $cap=>$unused) {
3429 if (empty($prohibited[$cap])) {
3430 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3431 $everybody = true;
3432 break;
3433 } else {
3434 $unions[] = "SELECT userid
3435 FROM {role_assignments}
3436 WHERE contextid IN ($ctxids)
3437 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3439 } else {
3440 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3441 // nobody can have this cap because it is prevented in default roles
3442 continue;
3444 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3445 // everybody except the prohibitted - hiding does not matter
3446 $unions[] = "SELECT id AS userid
3447 FROM {user}
3448 WHERE id NOT IN (SELECT userid
3449 FROM {role_assignments}
3450 WHERE contextid IN ($ctxids)
3451 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3453 } else {
3454 $unions[] = "SELECT userid
3455 FROM {role_assignments}
3456 WHERE contextid IN ($ctxids) AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3457 AND userid NOT IN (
3458 SELECT userid
3459 FROM {role_assignments}
3460 WHERE contextid IN ($ctxids)
3461 AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . ")
3466 if (!$everybody) {
3467 if ($unions) {
3468 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3469 } else {
3470 // only prohibits found - nobody can be matched
3471 $wherecond[] = "1 = 2";
3476 // Collect WHERE conditions and needed joins
3477 $where = implode(' AND ', $wherecond);
3478 if ($where !== '') {
3479 $where = 'WHERE ' . $where;
3481 $joins = implode("\n", $joins);
3483 // Ok, let's get the users!
3484 $sql = "SELECT $fields
3485 FROM {user} u
3486 $joins
3487 $where
3488 ORDER BY $sort";
3490 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3494 * Re-sort a users array based on a sorting policy
3496 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3497 * based on a sorting policy. This is to support the odd practice of
3498 * sorting teachers by 'authority', where authority was "lowest id of the role
3499 * assignment".
3501 * Will execute 1 database query. Only suitable for small numbers of users, as it
3502 * uses an u.id IN() clause.
3504 * Notes about the sorting criteria.
3506 * As a default, we cannot rely on role.sortorder because then
3507 * admins/coursecreators will always win. That is why the sane
3508 * rule "is locality matters most", with sortorder as 2nd
3509 * consideration.
3511 * If you want role.sortorder, use the 'sortorder' policy, and
3512 * name explicitly what roles you want to cover. It's probably
3513 * a good idea to see what roles have the capabilities you want
3514 * (array_diff() them against roiles that have 'can-do-anything'
3515 * to weed out admin-ish roles. Or fetch a list of roles from
3516 * variables like $CFG->coursecontact .
3518 * @param array $users Users array, keyed on userid
3519 * @param context $context
3520 * @param array $roles ids of the roles to include, optional
3521 * @param string $sortpolicy defaults to locality, more about
3522 * @return array sorted copy of the array
3524 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3525 global $DB;
3527 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3528 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3529 if (empty($roles)) {
3530 $roleswhere = '';
3531 } else {
3532 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3535 $sql = "SELECT ra.userid
3536 FROM {role_assignments} ra
3537 JOIN {role} r
3538 ON ra.roleid=r.id
3539 JOIN {context} ctx
3540 ON ra.contextid=ctx.id
3541 WHERE $userswhere
3542 $contextwhere
3543 $roleswhere";
3545 // Default 'locality' policy -- read PHPDoc notes
3546 // about sort policies...
3547 $orderby = 'ORDER BY '
3548 .'ctx.depth DESC, ' /* locality wins */
3549 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3550 .'ra.id'; /* role assignment order tie-breaker */
3551 if ($sortpolicy === 'sortorder') {
3552 $orderby = 'ORDER BY '
3553 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3554 .'ra.id'; /* role assignment order tie-breaker */
3557 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3558 $sortedusers = array();
3559 $seen = array();
3561 foreach ($sortedids as $id) {
3562 // Avoid duplicates
3563 if (isset($seen[$id])) {
3564 continue;
3566 $seen[$id] = true;
3568 // assign
3569 $sortedusers[$id] = $users[$id];
3571 return $sortedusers;
3575 * Gets all the users assigned this role in this context or higher
3577 * Note that moodle is based on capabilities and it is usually better
3578 * to check permissions than to check role ids as the capabilities
3579 * system is more flexible. If you really need, you can to use this
3580 * function but consider has_capability() as a possible substitute.
3582 * All $sort fields are added into $fields if not present there yet.
3584 * If $roleid is an array or is empty (all roles) you need to set $fields
3585 * (and $sort by extension) params according to it, as the first field
3586 * returned by the database should be unique (ra.id is the best candidate).
3588 * @param int $roleid (can also be an array of ints!)
3589 * @param context $context
3590 * @param bool $parent if true, get list of users assigned in higher context too
3591 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3592 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3593 * null => use default sort from users_order_by_sql.
3594 * @param bool $all true means all, false means limit to enrolled users
3595 * @param string $group defaults to ''
3596 * @param mixed $limitfrom defaults to ''
3597 * @param mixed $limitnum defaults to ''
3598 * @param string $extrawheretest defaults to ''
3599 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3600 * @return array
3602 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3603 $sort = null, $all = true, $group = '',
3604 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3605 global $DB;
3607 if (empty($fields)) {
3608 $allnames = get_all_user_name_fields(true, 'u');
3609 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
3610 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3611 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3612 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3613 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3616 // Prevent wrong function uses.
3617 if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
3618 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
3619 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
3621 if (!empty($roleid)) {
3622 // Solving partially the issue when specifying multiple roles.
3623 $users = array();
3624 foreach ($roleid as $id) {
3625 // Ignoring duplicated keys keeping the first user appearance.
3626 $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
3627 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
3629 return $users;
3633 $parentcontexts = '';
3634 if ($parent) {
3635 $parentcontexts = substr($context->path, 1); // kill leading slash
3636 $parentcontexts = str_replace('/', ',', $parentcontexts);
3637 if ($parentcontexts !== '') {
3638 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3642 if ($roleid) {
3643 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
3644 $roleselect = "AND ra.roleid $rids";
3645 } else {
3646 $params = array();
3647 $roleselect = '';
3650 if ($coursecontext = $context->get_course_context(false)) {
3651 $params['coursecontext'] = $coursecontext->id;
3652 } else {
3653 $params['coursecontext'] = 0;
3656 if ($group) {
3657 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3658 $groupselect = " AND gm.groupid = :groupid ";
3659 $params['groupid'] = $group;
3660 } else {
3661 $groupjoin = '';
3662 $groupselect = '';
3665 $params['contextid'] = $context->id;
3667 if ($extrawheretest) {
3668 $extrawheretest = ' AND ' . $extrawheretest;
3671 if ($whereorsortparams) {
3672 $params = array_merge($params, $whereorsortparams);
3675 if (!$sort) {
3676 list($sort, $sortparams) = users_order_by_sql('u');
3677 $params = array_merge($params, $sortparams);
3680 // Adding the fields from $sort that are not present in $fields.
3681 $sortarray = preg_split('/,\s*/', $sort);
3682 $fieldsarray = preg_split('/,\s*/', $fields);
3684 // Discarding aliases from the fields.
3685 $fieldnames = array();
3686 foreach ($fieldsarray as $key => $field) {
3687 list($fieldnames[$key]) = explode(' ', $field);
3690 $addedfields = array();
3691 foreach ($sortarray as $sortfield) {
3692 // Throw away any additional arguments to the sort (e.g. ASC/DESC).
3693 list($sortfield) = explode(' ', $sortfield);
3694 list($tableprefix) = explode('.', $sortfield);
3695 $fieldpresent = false;
3696 foreach ($fieldnames as $fieldname) {
3697 if ($fieldname === $sortfield || $fieldname === $tableprefix.'.*') {
3698 $fieldpresent = true;
3699 break;
3703 if (!$fieldpresent) {
3704 $fieldsarray[] = $sortfield;
3705 $addedfields[] = $sortfield;
3709 $fields = implode(', ', $fieldsarray);
3710 if (!empty($addedfields)) {
3711 $addedfields = implode(', ', $addedfields);
3712 debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
3715 if ($all === null) {
3716 // Previously null was used to indicate that parameter was not used.
3717 $all = true;
3719 if (!$all and $coursecontext) {
3720 // Do not use get_enrolled_sql() here for performance reasons.
3721 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
3722 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
3723 $params['ecourseid'] = $coursecontext->instanceid;
3724 } else {
3725 $ejoin = "";
3728 $sql = "SELECT DISTINCT $fields, ra.roleid
3729 FROM {role_assignments} ra
3730 JOIN {user} u ON u.id = ra.userid
3731 JOIN {role} r ON ra.roleid = r.id
3732 $ejoin
3733 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3734 $groupjoin
3735 WHERE (ra.contextid = :contextid $parentcontexts)
3736 $roleselect
3737 $groupselect
3738 $extrawheretest
3739 ORDER BY $sort"; // join now so that we can just use fullname() later
3741 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3745 * Counts all the users assigned this role in this context or higher
3747 * @param int|array $roleid either int or an array of ints
3748 * @param context $context
3749 * @param bool $parent if true, get list of users assigned in higher context too
3750 * @return int Returns the result count
3752 function count_role_users($roleid, context $context, $parent = false) {
3753 global $DB;
3755 if ($parent) {
3756 if ($contexts = $context->get_parent_context_ids()) {
3757 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3758 } else {
3759 $parentcontexts = '';
3761 } else {
3762 $parentcontexts = '';
3765 if ($roleid) {
3766 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3767 $roleselect = "AND r.roleid $rids";
3768 } else {
3769 $params = array();
3770 $roleselect = '';
3773 array_unshift($params, $context->id);
3775 $sql = "SELECT COUNT(DISTINCT u.id)
3776 FROM {role_assignments} r
3777 JOIN {user} u ON u.id = r.userid
3778 WHERE (r.contextid = ? $parentcontexts)
3779 $roleselect
3780 AND u.deleted = 0";
3782 return $DB->count_records_sql($sql, $params);
3786 * This function gets the list of courses that this user has a particular capability in.
3788 * It is now reasonably efficient, but bear in mind that if there are users who have the capability
3789 * everywhere, it may return an array of all courses.
3791 * @param string $capability Capability in question
3792 * @param int $userid User ID or null for current user
3793 * @param bool $doanything True if 'doanything' is permitted (default)
3794 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3795 * otherwise use a comma-separated list of the fields you require, not including id.
3796 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
3797 * @param string $orderby If set, use a comma-separated list of fields from course
3798 * table with sql modifiers (DESC) if needed
3799 * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
3800 * @return array|bool Array of courses, if none found false is returned.
3802 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '',
3803 $limit = 0) {
3804 global $DB, $USER;
3806 // Default to current user.
3807 if (!$userid) {
3808 $userid = $USER->id;
3811 if ($doanything && is_siteadmin($userid)) {
3812 // If the user is a site admin and $doanything is enabled then there is no need to restrict
3813 // the list of courses.
3814 $contextlimitsql = '';
3815 $contextlimitparams = [];
3816 } else {
3817 // Gets SQL to limit contexts ('x' table) to those where the user has this capability.
3818 list ($contextlimitsql, $contextlimitparams) = \core\access\get_user_capability_course_helper::get_sql(
3819 $userid, $capability);
3820 if (!$contextlimitsql) {
3821 // If the does not have this capability in any context, return false without querying.
3822 return false;
3825 $contextlimitsql = 'WHERE' . $contextlimitsql;
3828 // Convert fields list and ordering
3829 $fieldlist = '';
3830 if ($fieldsexceptid) {
3831 $fields = array_map('trim', explode(',', $fieldsexceptid));
3832 foreach($fields as $field) {
3833 // Context fields have a different alias.
3834 if (strpos($field, 'ctx') === 0) {
3835 switch($field) {
3836 case 'ctxlevel' :
3837 $realfield = 'contextlevel';
3838 break;
3839 case 'ctxinstance' :
3840 $realfield = 'instanceid';
3841 break;
3842 default:
3843 $realfield = substr($field, 3);
3844 break;
3846 $fieldlist .= ',x.' . $realfield . ' AS ' . $field;
3847 } else {
3848 $fieldlist .= ',c.'.$field;
3852 if ($orderby) {
3853 $fields = explode(',', $orderby);
3854 $orderby = '';
3855 foreach($fields as $field) {
3856 if ($orderby) {
3857 $orderby .= ',';
3859 $orderby .= 'c.'.$field;
3861 $orderby = 'ORDER BY '.$orderby;
3864 $courses = array();
3865 $rs = $DB->get_recordset_sql("
3866 SELECT c.id $fieldlist
3867 FROM {course} c
3868 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
3869 $contextlimitsql
3870 $orderby", array_merge([CONTEXT_COURSE], $contextlimitparams));
3871 foreach ($rs as $course) {
3872 $courses[] = $course;
3873 $limit--;
3874 if ($limit == 0) {
3875 break;
3878 $rs->close();
3879 return empty($courses) ? false : $courses;
3883 * This function finds the roles assigned directly to this context only
3884 * i.e. no roles in parent contexts
3886 * @param context $context
3887 * @return array
3889 function get_roles_on_exact_context(context $context) {
3890 global $DB;
3892 return $DB->get_records_sql("SELECT r.*
3893 FROM {role_assignments} ra, {role} r
3894 WHERE ra.roleid = r.id AND ra.contextid = ?",
3895 array($context->id));
3899 * Switches the current user to another role for the current session and only
3900 * in the given context.
3902 * The caller *must* check
3903 * - that this op is allowed
3904 * - that the requested role can be switched to in this context (use get_switchable_roles)
3905 * - that the requested role is NOT $CFG->defaultuserroleid
3907 * To "unswitch" pass 0 as the roleid.
3909 * This function *will* modify $USER->access - beware
3911 * @param integer $roleid the role to switch to.
3912 * @param context $context the context in which to perform the switch.
3913 * @return bool success or failure.
3915 function role_switch($roleid, context $context) {
3916 global $USER;
3918 // Add the ghost RA to $USER->access as $USER->access['rsw'][$path] = $roleid.
3919 // To un-switch just unset($USER->access['rsw'][$path]).
3921 // Note: it is not possible to switch to roles that do not have course:view
3923 if (!isset($USER->access)) {
3924 load_all_capabilities();
3927 // Add the switch RA
3928 if ($roleid == 0) {
3929 unset($USER->access['rsw'][$context->path]);
3930 return true;
3933 $USER->access['rsw'][$context->path] = $roleid;
3935 return true;
3939 * Checks if the user has switched roles within the given course.
3941 * Note: You can only switch roles within the course, hence it takes a course id
3942 * rather than a context. On that note Petr volunteered to implement this across
3943 * all other contexts, all requests for this should be forwarded to him ;)
3945 * @param int $courseid The id of the course to check
3946 * @return bool True if the user has switched roles within the course.
3948 function is_role_switched($courseid) {
3949 global $USER;
3950 $context = context_course::instance($courseid, MUST_EXIST);
3951 return (!empty($USER->access['rsw'][$context->path]));
3955 * Get any role that has an override on exact context
3957 * @param context $context The context to check
3958 * @return array An array of roles
3960 function get_roles_with_override_on_context(context $context) {
3961 global $DB;
3963 return $DB->get_records_sql("SELECT r.*
3964 FROM {role_capabilities} rc, {role} r
3965 WHERE rc.roleid = r.id AND rc.contextid = ?",
3966 array($context->id));
3970 * Get all capabilities for this role on this context (overrides)
3972 * @param stdClass $role
3973 * @param context $context
3974 * @return array
3976 function get_capabilities_from_role_on_context($role, context $context) {
3977 global $DB;
3979 return $DB->get_records_sql("SELECT *
3980 FROM {role_capabilities}
3981 WHERE contextid = ? AND roleid = ?",
3982 array($context->id, $role->id));
3986 * Find out which roles has assignment on this context
3988 * @param context $context
3989 * @return array
3992 function get_roles_with_assignment_on_context(context $context) {
3993 global $DB;
3995 return $DB->get_records_sql("SELECT r.*
3996 FROM {role_assignments} ra, {role} r
3997 WHERE ra.roleid = r.id AND ra.contextid = ?",
3998 array($context->id));
4002 * Find all user assignment of users for this role, on this context
4004 * @param stdClass $role
4005 * @param context $context
4006 * @return array
4008 function get_users_from_role_on_context($role, context $context) {
4009 global $DB;
4011 return $DB->get_records_sql("SELECT *
4012 FROM {role_assignments}
4013 WHERE contextid = ? AND roleid = ?",
4014 array($context->id, $role->id));
4018 * Simple function returning a boolean true if user has roles
4019 * in context or parent contexts, otherwise false.
4021 * @param int $userid
4022 * @param int $roleid
4023 * @param int $contextid empty means any context
4024 * @return bool
4026 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4027 global $DB;
4029 if ($contextid) {
4030 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4031 return false;
4033 $parents = $context->get_parent_context_ids(true);
4034 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4035 $params['userid'] = $userid;
4036 $params['roleid'] = $roleid;
4038 $sql = "SELECT COUNT(ra.id)
4039 FROM {role_assignments} ra
4040 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4042 $count = $DB->get_field_sql($sql, $params);
4043 return ($count > 0);
4045 } else {
4046 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4051 * Get localised role name or alias if exists and format the text.
4053 * @param stdClass $role role object
4054 * - optional 'coursealias' property should be included for performance reasons if course context used
4055 * - description property is not required here
4056 * @param context|bool $context empty means system context
4057 * @param int $rolenamedisplay type of role name
4058 * @return string localised role name or course role name alias
4060 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4061 global $DB;
4063 if ($rolenamedisplay == ROLENAME_SHORT) {
4064 return $role->shortname;
4067 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4068 $coursecontext = null;
4071 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4072 $role = clone($role); // Do not modify parameters.
4073 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4074 $role->coursealias = $r->name;
4075 } else {
4076 $role->coursealias = null;
4080 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4081 if ($coursecontext) {
4082 return $role->coursealias;
4083 } else {
4084 return null;
4088 if (trim($role->name) !== '') {
4089 // For filtering always use context where was the thing defined - system for roles here.
4090 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4092 } else {
4093 // Empty role->name means we want to see localised role name based on shortname,
4094 // only default roles are supposed to be localised.
4095 switch ($role->shortname) {
4096 case 'manager': $original = get_string('manager', 'role'); break;
4097 case 'coursecreator': $original = get_string('coursecreators'); break;
4098 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4099 case 'teacher': $original = get_string('noneditingteacher'); break;
4100 case 'student': $original = get_string('defaultcoursestudent'); break;
4101 case 'guest': $original = get_string('guest'); break;
4102 case 'user': $original = get_string('authenticateduser'); break;
4103 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4104 // We should not get here, the role UI should require the name for custom roles!
4105 default: $original = $role->shortname; break;
4109 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4110 return $original;
4113 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4114 return "$original ($role->shortname)";
4117 if ($rolenamedisplay == ROLENAME_ALIAS) {
4118 if ($coursecontext and trim($role->coursealias) !== '') {
4119 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4120 } else {
4121 return $original;
4125 if ($rolenamedisplay == ROLENAME_BOTH) {
4126 if ($coursecontext and trim($role->coursealias) !== '') {
4127 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4128 } else {
4129 return $original;
4133 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4137 * Returns localised role description if available.
4138 * If the name is empty it tries to find the default role name using
4139 * hardcoded list of default role names or other methods in the future.
4141 * @param stdClass $role
4142 * @return string localised role name
4144 function role_get_description(stdClass $role) {
4145 if (!html_is_blank($role->description)) {
4146 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4149 switch ($role->shortname) {
4150 case 'manager': return get_string('managerdescription', 'role');
4151 case 'coursecreator': return get_string('coursecreatorsdescription');
4152 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4153 case 'teacher': return get_string('noneditingteacherdescription');
4154 case 'student': return get_string('defaultcoursestudentdescription');
4155 case 'guest': return get_string('guestdescription');
4156 case 'user': return get_string('authenticateduserdescription');
4157 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4158 default: return '';
4163 * Get all the localised role names for a context.
4165 * In new installs default roles have empty names, this function
4166 * add localised role names using current language pack.
4168 * @param context $context the context, null means system context
4169 * @param array of role objects with a ->localname field containing the context-specific role name.
4170 * @param int $rolenamedisplay
4171 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4172 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4174 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4175 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4179 * Prepare list of roles for display, apply aliases and localise default role names.
4181 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4182 * @param context $context the context, null means system context
4183 * @param int $rolenamedisplay
4184 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4185 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4187 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4188 global $DB;
4190 if (empty($roleoptions)) {
4191 return array();
4194 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4195 $coursecontext = null;
4198 // We usually need all role columns...
4199 $first = reset($roleoptions);
4200 if ($returnmenu === null) {
4201 $returnmenu = !is_object($first);
4204 if (!is_object($first) or !property_exists($first, 'shortname')) {
4205 $allroles = get_all_roles($context);
4206 foreach ($roleoptions as $rid => $unused) {
4207 $roleoptions[$rid] = $allroles[$rid];
4211 // Inject coursealias if necessary.
4212 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4213 $first = reset($roleoptions);
4214 if (!property_exists($first, 'coursealias')) {
4215 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4216 foreach ($aliasnames as $alias) {
4217 if (isset($roleoptions[$alias->roleid])) {
4218 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4224 // Add localname property.
4225 foreach ($roleoptions as $rid => $role) {
4226 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4229 if (!$returnmenu) {
4230 return $roleoptions;
4233 $menu = array();
4234 foreach ($roleoptions as $rid => $role) {
4235 $menu[$rid] = $role->localname;
4238 return $menu;
4242 * Aids in detecting if a new line is required when reading a new capability
4244 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4245 * when we read in a new capability.
4246 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4247 * but when we are in grade, all reports/import/export capabilities should be together
4249 * @param string $cap component string a
4250 * @param string $comp component string b
4251 * @param int $contextlevel
4252 * @return bool whether 2 component are in different "sections"
4254 function component_level_changed($cap, $comp, $contextlevel) {
4256 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4257 $compsa = explode('/', $cap->component);
4258 $compsb = explode('/', $comp);
4260 // list of system reports
4261 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4262 return false;
4265 // we are in gradebook, still
4266 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4267 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4268 return false;
4271 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4272 return false;
4276 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4280 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4281 * and return an array of roleids in order.
4283 * @param array $allroles array of roles, as returned by get_all_roles();
4284 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4286 function fix_role_sortorder($allroles) {
4287 global $DB;
4289 $rolesort = array();
4290 $i = 0;
4291 foreach ($allroles as $role) {
4292 $rolesort[$i] = $role->id;
4293 if ($role->sortorder != $i) {
4294 $r = new stdClass();
4295 $r->id = $role->id;
4296 $r->sortorder = $i;
4297 $DB->update_record('role', $r);
4298 $allroles[$role->id]->sortorder = $i;
4300 $i++;
4302 return $rolesort;
4306 * Switch the sort order of two roles (used in admin/roles/manage.php).
4308 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4309 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4310 * @return boolean success or failure
4312 function switch_roles($first, $second) {
4313 global $DB;
4314 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4315 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4316 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4317 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4318 return $result;
4322 * Duplicates all the base definitions of a role
4324 * @param stdClass $sourcerole role to copy from
4325 * @param int $targetrole id of role to copy to
4327 function role_cap_duplicate($sourcerole, $targetrole) {
4328 global $DB;
4330 $systemcontext = context_system::instance();
4331 $caps = $DB->get_records_sql("SELECT *
4332 FROM {role_capabilities}
4333 WHERE roleid = ? AND contextid = ?",
4334 array($sourcerole->id, $systemcontext->id));
4335 // adding capabilities
4336 foreach ($caps as $cap) {
4337 unset($cap->id);
4338 $cap->roleid = $targetrole;
4339 $DB->insert_record('role_capabilities', $cap);
4342 // Reset any cache of this role, including MUC.
4343 accesslib_clear_role_cache($targetrole);
4347 * Returns two lists, this can be used to find out if user has capability.
4348 * Having any needed role and no forbidden role in this context means
4349 * user has this capability in this context.
4350 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4352 * @param stdClass $context
4353 * @param string $capability
4354 * @return array($neededroles, $forbiddenroles)
4356 function get_roles_with_cap_in_context($context, $capability) {
4357 global $DB;
4359 $ctxids = trim($context->path, '/'); // kill leading slash
4360 $ctxids = str_replace('/', ',', $ctxids);
4362 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4363 FROM {role_capabilities} rc
4364 JOIN {context} ctx ON ctx.id = rc.contextid
4365 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4366 ORDER BY rc.roleid ASC, ctx.depth DESC";
4367 $params = array('cap'=>$capability);
4369 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4370 // no cap definitions --> no capability
4371 return array(array(), array());
4374 $forbidden = array();
4375 $needed = array();
4376 foreach($capdefs as $def) {
4377 if (isset($forbidden[$def->roleid])) {
4378 continue;
4380 if ($def->permission == CAP_PROHIBIT) {
4381 $forbidden[$def->roleid] = $def->roleid;
4382 unset($needed[$def->roleid]);
4383 continue;
4385 if (!isset($needed[$def->roleid])) {
4386 if ($def->permission == CAP_ALLOW) {
4387 $needed[$def->roleid] = true;
4388 } else if ($def->permission == CAP_PREVENT) {
4389 $needed[$def->roleid] = false;
4393 unset($capdefs);
4395 // remove all those roles not allowing
4396 foreach($needed as $key=>$value) {
4397 if (!$value) {
4398 unset($needed[$key]);
4399 } else {
4400 $needed[$key] = $key;
4404 return array($needed, $forbidden);
4408 * Returns an array of role IDs that have ALL of the the supplied capabilities
4409 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4411 * @param stdClass $context
4412 * @param array $capabilities An array of capabilities
4413 * @return array of roles with all of the required capabilities
4415 function get_roles_with_caps_in_context($context, $capabilities) {
4416 $neededarr = array();
4417 $forbiddenarr = array();
4418 foreach($capabilities as $caprequired) {
4419 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4422 $rolesthatcanrate = array();
4423 if (!empty($neededarr)) {
4424 foreach ($neededarr as $needed) {
4425 if (empty($rolesthatcanrate)) {
4426 $rolesthatcanrate = $needed;
4427 } else {
4428 //only want roles that have all caps
4429 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4433 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4434 foreach ($forbiddenarr as $forbidden) {
4435 //remove any roles that are forbidden any of the caps
4436 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4439 return $rolesthatcanrate;
4443 * Returns an array of role names that have ALL of the the supplied capabilities
4444 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4446 * @param stdClass $context
4447 * @param array $capabilities An array of capabilities
4448 * @return array of roles with all of the required capabilities
4450 function get_role_names_with_caps_in_context($context, $capabilities) {
4451 global $DB;
4453 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4454 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4456 $roles = array();
4457 foreach ($rolesthatcanrate as $r) {
4458 $roles[$r] = $allroles[$r];
4461 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4465 * This function verifies the prohibit comes from this context
4466 * and there are no more prohibits in parent contexts.
4468 * @param int $roleid
4469 * @param context $context
4470 * @param string $capability name
4471 * @return bool
4473 function prohibit_is_removable($roleid, context $context, $capability) {
4474 global $DB;
4476 $ctxids = trim($context->path, '/'); // kill leading slash
4477 $ctxids = str_replace('/', ',', $ctxids);
4479 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4481 $sql = "SELECT ctx.id
4482 FROM {role_capabilities} rc
4483 JOIN {context} ctx ON ctx.id = rc.contextid
4484 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4485 ORDER BY ctx.depth DESC";
4487 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4488 // no prohibits == nothing to remove
4489 return true;
4492 if (count($prohibits) > 1) {
4493 // more prohibits can not be removed
4494 return false;
4497 return !empty($prohibits[$context->id]);
4501 * More user friendly role permission changing,
4502 * it should produce as few overrides as possible.
4504 * @param int $roleid
4505 * @param stdClass $context
4506 * @param string $capname capability name
4507 * @param int $permission
4508 * @return void
4510 function role_change_permission($roleid, $context, $capname, $permission) {
4511 global $DB;
4513 if ($permission == CAP_INHERIT) {
4514 unassign_capability($capname, $roleid, $context->id);
4515 $context->mark_dirty();
4516 return;
4519 $ctxids = trim($context->path, '/'); // kill leading slash
4520 $ctxids = str_replace('/', ',', $ctxids);
4522 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4524 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4525 FROM {role_capabilities} rc
4526 JOIN {context} ctx ON ctx.id = rc.contextid
4527 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4528 ORDER BY ctx.depth DESC";
4530 if ($existing = $DB->get_records_sql($sql, $params)) {
4531 foreach($existing as $e) {
4532 if ($e->permission == CAP_PROHIBIT) {
4533 // prohibit can not be overridden, no point in changing anything
4534 return;
4537 $lowest = array_shift($existing);
4538 if ($lowest->permission == $permission) {
4539 // permission already set in this context or parent - nothing to do
4540 return;
4542 if ($existing) {
4543 $parent = array_shift($existing);
4544 if ($parent->permission == $permission) {
4545 // permission already set in parent context or parent - just unset in this context
4546 // we do this because we want as few overrides as possible for performance reasons
4547 unassign_capability($capname, $roleid, $context->id);
4548 $context->mark_dirty();
4549 return;
4553 } else {
4554 if ($permission == CAP_PREVENT) {
4555 // nothing means role does not have permission
4556 return;
4560 // assign the needed capability
4561 assign_capability($capname, $permission, $roleid, $context->id, true);
4563 // force cap reloading
4564 $context->mark_dirty();
4569 * Basic moodle context abstraction class.
4571 * Google confirms that no other important framework is using "context" class,
4572 * we could use something else like mcontext or moodle_context, but we need to type
4573 * this very often which would be annoying and it would take too much space...
4575 * This class is derived from stdClass for backwards compatibility with
4576 * odl $context record that was returned from DML $DB->get_record()
4578 * @package core_access
4579 * @category access
4580 * @copyright Petr Skoda {@link http://skodak.org}
4581 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4582 * @since Moodle 2.2
4584 * @property-read int $id context id
4585 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4586 * @property-read int $instanceid id of related instance in each context
4587 * @property-read string $path path to context, starts with system context
4588 * @property-read int $depth
4590 abstract class context extends stdClass implements IteratorAggregate {
4593 * The context id
4594 * Can be accessed publicly through $context->id
4595 * @var int
4597 protected $_id;
4600 * The context level
4601 * Can be accessed publicly through $context->contextlevel
4602 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4604 protected $_contextlevel;
4607 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4608 * Can be accessed publicly through $context->instanceid
4609 * @var int
4611 protected $_instanceid;
4614 * The path to the context always starting from the system context
4615 * Can be accessed publicly through $context->path
4616 * @var string
4618 protected $_path;
4621 * The depth of the context in relation to parent contexts
4622 * Can be accessed publicly through $context->depth
4623 * @var int
4625 protected $_depth;
4628 * @var array Context caching info
4630 private static $cache_contextsbyid = array();
4633 * @var array Context caching info
4635 private static $cache_contexts = array();
4638 * Context count
4639 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4640 * @var int
4642 protected static $cache_count = 0;
4645 * @var array Context caching info
4647 protected static $cache_preloaded = array();
4650 * @var context_system The system context once initialised
4652 protected static $systemcontext = null;
4655 * Resets the cache to remove all data.
4656 * @static
4658 protected static function reset_caches() {
4659 self::$cache_contextsbyid = array();
4660 self::$cache_contexts = array();
4661 self::$cache_count = 0;
4662 self::$cache_preloaded = array();
4664 self::$systemcontext = null;
4668 * Adds a context to the cache. If the cache is full, discards a batch of
4669 * older entries.
4671 * @static
4672 * @param context $context New context to add
4673 * @return void
4675 protected static function cache_add(context $context) {
4676 if (isset(self::$cache_contextsbyid[$context->id])) {
4677 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4678 return;
4681 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4682 $i = 0;
4683 foreach(self::$cache_contextsbyid as $ctx) {
4684 $i++;
4685 if ($i <= 100) {
4686 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4687 continue;
4689 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4690 // we remove oldest third of the contexts to make room for more contexts
4691 break;
4693 unset(self::$cache_contextsbyid[$ctx->id]);
4694 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4695 self::$cache_count--;
4699 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4700 self::$cache_contextsbyid[$context->id] = $context;
4701 self::$cache_count++;
4705 * Removes a context from the cache.
4707 * @static
4708 * @param context $context Context object to remove
4709 * @return void
4711 protected static function cache_remove(context $context) {
4712 if (!isset(self::$cache_contextsbyid[$context->id])) {
4713 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4714 return;
4716 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4717 unset(self::$cache_contextsbyid[$context->id]);
4719 self::$cache_count--;
4721 if (self::$cache_count < 0) {
4722 self::$cache_count = 0;
4727 * Gets a context from the cache.
4729 * @static
4730 * @param int $contextlevel Context level
4731 * @param int $instance Instance ID
4732 * @return context|bool Context or false if not in cache
4734 protected static function cache_get($contextlevel, $instance) {
4735 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4736 return self::$cache_contexts[$contextlevel][$instance];
4738 return false;
4742 * Gets a context from the cache based on its id.
4744 * @static
4745 * @param int $id Context ID
4746 * @return context|bool Context or false if not in cache
4748 protected static function cache_get_by_id($id) {
4749 if (isset(self::$cache_contextsbyid[$id])) {
4750 return self::$cache_contextsbyid[$id];
4752 return false;
4756 * Preloads context information from db record and strips the cached info.
4758 * @static
4759 * @param stdClass $rec
4760 * @return void (modifies $rec)
4762 protected static function preload_from_record(stdClass $rec) {
4763 if (empty($rec->ctxid) or empty($rec->ctxlevel) or !isset($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
4764 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4765 return;
4768 // note: in PHP5 the objects are passed by reference, no need to return $rec
4769 $record = new stdClass();
4770 $record->id = $rec->ctxid; unset($rec->ctxid);
4771 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
4772 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
4773 $record->path = $rec->ctxpath; unset($rec->ctxpath);
4774 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
4776 return context::create_instance_from_record($record);
4780 // ====== magic methods =======
4783 * Magic setter method, we do not want anybody to modify properties from the outside
4784 * @param string $name
4785 * @param mixed $value
4787 public function __set($name, $value) {
4788 debugging('Can not change context instance properties!');
4792 * Magic method getter, redirects to read only values.
4793 * @param string $name
4794 * @return mixed
4796 public function __get($name) {
4797 switch ($name) {
4798 case 'id': return $this->_id;
4799 case 'contextlevel': return $this->_contextlevel;
4800 case 'instanceid': return $this->_instanceid;
4801 case 'path': return $this->_path;
4802 case 'depth': return $this->_depth;
4804 default:
4805 debugging('Invalid context property accessed! '.$name);
4806 return null;
4811 * Full support for isset on our magic read only properties.
4812 * @param string $name
4813 * @return bool
4815 public function __isset($name) {
4816 switch ($name) {
4817 case 'id': return isset($this->_id);
4818 case 'contextlevel': return isset($this->_contextlevel);
4819 case 'instanceid': return isset($this->_instanceid);
4820 case 'path': return isset($this->_path);
4821 case 'depth': return isset($this->_depth);
4823 default: return false;
4829 * ALl properties are read only, sorry.
4830 * @param string $name
4832 public function __unset($name) {
4833 debugging('Can not unset context instance properties!');
4836 // ====== implementing method from interface IteratorAggregate ======
4839 * Create an iterator because magic vars can't be seen by 'foreach'.
4841 * Now we can convert context object to array using convert_to_array(),
4842 * and feed it properly to json_encode().
4844 public function getIterator() {
4845 $ret = array(
4846 'id' => $this->id,
4847 'contextlevel' => $this->contextlevel,
4848 'instanceid' => $this->instanceid,
4849 'path' => $this->path,
4850 'depth' => $this->depth
4852 return new ArrayIterator($ret);
4855 // ====== general context methods ======
4858 * Constructor is protected so that devs are forced to
4859 * use context_xxx::instance() or context::instance_by_id().
4861 * @param stdClass $record
4863 protected function __construct(stdClass $record) {
4864 $this->_id = (int)$record->id;
4865 $this->_contextlevel = (int)$record->contextlevel;
4866 $this->_instanceid = $record->instanceid;
4867 $this->_path = $record->path;
4868 $this->_depth = $record->depth;
4872 * This function is also used to work around 'protected' keyword problems in context_helper.
4873 * @static
4874 * @param stdClass $record
4875 * @return context instance
4877 protected static function create_instance_from_record(stdClass $record) {
4878 $classname = context_helper::get_class_for_level($record->contextlevel);
4880 if ($context = context::cache_get_by_id($record->id)) {
4881 return $context;
4884 $context = new $classname($record);
4885 context::cache_add($context);
4887 return $context;
4891 * Copy prepared new contexts from temp table to context table,
4892 * we do this in db specific way for perf reasons only.
4893 * @static
4895 protected static function merge_context_temp_table() {
4896 global $DB;
4898 /* MDL-11347:
4899 * - mysql does not allow to use FROM in UPDATE statements
4900 * - using two tables after UPDATE works in mysql, but might give unexpected
4901 * results in pg 8 (depends on configuration)
4902 * - using table alias in UPDATE does not work in pg < 8.2
4904 * Different code for each database - mostly for performance reasons
4907 $dbfamily = $DB->get_dbfamily();
4908 if ($dbfamily == 'mysql') {
4909 $updatesql = "UPDATE {context} ct, {context_temp} temp
4910 SET ct.path = temp.path,
4911 ct.depth = temp.depth
4912 WHERE ct.id = temp.id";
4913 } else if ($dbfamily == 'oracle') {
4914 $updatesql = "UPDATE {context} ct
4915 SET (ct.path, ct.depth) =
4916 (SELECT temp.path, temp.depth
4917 FROM {context_temp} temp
4918 WHERE temp.id=ct.id)
4919 WHERE EXISTS (SELECT 'x'
4920 FROM {context_temp} temp
4921 WHERE temp.id = ct.id)";
4922 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
4923 $updatesql = "UPDATE {context}
4924 SET path = temp.path,
4925 depth = temp.depth
4926 FROM {context_temp} temp
4927 WHERE temp.id={context}.id";
4928 } else {
4929 // sqlite and others
4930 $updatesql = "UPDATE {context}
4931 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
4932 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
4933 WHERE id IN (SELECT id FROM {context_temp})";
4936 $DB->execute($updatesql);
4940 * Get a context instance as an object, from a given context id.
4942 * @static
4943 * @param int $id context id
4944 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
4945 * MUST_EXIST means throw exception if no record found
4946 * @return context|bool the context object or false if not found
4948 public static function instance_by_id($id, $strictness = MUST_EXIST) {
4949 global $DB;
4951 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
4952 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
4953 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
4956 if ($id == SYSCONTEXTID) {
4957 return context_system::instance(0, $strictness);
4960 if (is_array($id) or is_object($id) or empty($id)) {
4961 throw new coding_exception('Invalid context id specified context::instance_by_id()');
4964 if ($context = context::cache_get_by_id($id)) {
4965 return $context;
4968 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
4969 return context::create_instance_from_record($record);
4972 return false;
4976 * Update context info after moving context in the tree structure.
4978 * @param context $newparent
4979 * @return void
4981 public function update_moved(context $newparent) {
4982 global $DB;
4984 $frompath = $this->_path;
4985 $newpath = $newparent->path . '/' . $this->_id;
4987 $trans = $DB->start_delegated_transaction();
4989 $this->mark_dirty();
4991 $setdepth = '';
4992 if (($newparent->depth +1) != $this->_depth) {
4993 $diff = $newparent->depth - $this->_depth + 1;
4994 $setdepth = ", depth = depth + $diff";
4996 $sql = "UPDATE {context}
4997 SET path = ?
4998 $setdepth
4999 WHERE id = ?";
5000 $params = array($newpath, $this->_id);
5001 $DB->execute($sql, $params);
5003 $this->_path = $newpath;
5004 $this->_depth = $newparent->depth + 1;
5006 $sql = "UPDATE {context}
5007 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5008 $setdepth
5009 WHERE path LIKE ?";
5010 $params = array($newpath, "{$frompath}/%");
5011 $DB->execute($sql, $params);
5013 $this->mark_dirty();
5015 context::reset_caches();
5017 $trans->allow_commit();
5021 * Remove all context path info and optionally rebuild it.
5023 * @param bool $rebuild
5024 * @return void
5026 public function reset_paths($rebuild = true) {
5027 global $DB;
5029 if ($this->_path) {
5030 $this->mark_dirty();
5032 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5033 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5034 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5035 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5036 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5037 $this->_depth = 0;
5038 $this->_path = null;
5041 if ($rebuild) {
5042 context_helper::build_all_paths(false);
5045 context::reset_caches();
5049 * Delete all data linked to content, do not delete the context record itself
5051 public function delete_content() {
5052 global $CFG, $DB;
5054 blocks_delete_all_for_context($this->_id);
5055 filter_delete_all_for_context($this->_id);
5057 require_once($CFG->dirroot . '/comment/lib.php');
5058 comment::delete_comments(array('contextid'=>$this->_id));
5060 require_once($CFG->dirroot.'/rating/lib.php');
5061 $delopt = new stdclass();
5062 $delopt->contextid = $this->_id;
5063 $rm = new rating_manager();
5064 $rm->delete_ratings($delopt);
5066 // delete all files attached to this context
5067 $fs = get_file_storage();
5068 $fs->delete_area_files($this->_id);
5070 // Delete all repository instances attached to this context.
5071 require_once($CFG->dirroot . '/repository/lib.php');
5072 repository::delete_all_for_context($this->_id);
5074 // delete all advanced grading data attached to this context
5075 require_once($CFG->dirroot.'/grade/grading/lib.php');
5076 grading_manager::delete_all_for_context($this->_id);
5078 $ids = $DB->get_fieldset_select('role_capabilities', 'DISTINCT roleid', 'contextid = ?', array($this->_id));
5080 // now delete stuff from role related tables, role_unassign_all
5081 // and unenrol should be called earlier to do proper cleanup
5082 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5083 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5084 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5086 if ($ids) {
5087 // Reset any cache of these roles, including MUC.
5088 accesslib_clear_role_cache($ids);
5093 * Delete the context content and the context record itself
5095 public function delete() {
5096 global $DB;
5098 if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5099 throw new coding_exception('Cannot delete system context');
5102 // double check the context still exists
5103 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5104 context::cache_remove($this);
5105 return;
5108 $this->delete_content();
5109 $DB->delete_records('context', array('id'=>$this->_id));
5110 // purge static context cache if entry present
5111 context::cache_remove($this);
5113 // do not mark dirty contexts if parents unknown
5114 if (!is_null($this->_path) and $this->_depth > 0) {
5115 $this->mark_dirty();
5119 // ====== context level related methods ======
5122 * Utility method for context creation
5124 * @static
5125 * @param int $contextlevel
5126 * @param int $instanceid
5127 * @param string $parentpath
5128 * @return stdClass context record
5130 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5131 global $DB;
5133 $record = new stdClass();
5134 $record->contextlevel = $contextlevel;
5135 $record->instanceid = $instanceid;
5136 $record->depth = 0;
5137 $record->path = null; //not known before insert
5139 $record->id = $DB->insert_record('context', $record);
5141 // now add path if known - it can be added later
5142 if (!is_null($parentpath)) {
5143 $record->path = $parentpath.'/'.$record->id;
5144 $record->depth = substr_count($record->path, '/');
5145 $DB->update_record('context', $record);
5148 return $record;
5152 * Returns human readable context identifier.
5154 * @param boolean $withprefix whether to prefix the name of the context with the
5155 * type of context, e.g. User, Course, Forum, etc.
5156 * @param boolean $short whether to use the short name of the thing. Only applies
5157 * to course contexts
5158 * @return string the human readable context name.
5160 public function get_context_name($withprefix = true, $short = false) {
5161 // must be implemented in all context levels
5162 throw new coding_exception('can not get name of abstract context');
5166 * Returns the most relevant URL for this context.
5168 * @return moodle_url
5170 public abstract function get_url();
5173 * Returns array of relevant context capability records.
5175 * @return array
5177 public abstract function get_capabilities();
5180 * Recursive function which, given a context, find all its children context ids.
5182 * For course category contexts it will return immediate children and all subcategory contexts.
5183 * It will NOT recurse into courses or subcategories categories.
5184 * If you want to do that, call it on the returned courses/categories.
5186 * When called for a course context, it will return the modules and blocks
5187 * displayed in the course page and blocks displayed on the module pages.
5189 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5190 * contexts ;-)
5192 * @return array Array of child records
5194 public function get_child_contexts() {
5195 global $DB;
5197 if (empty($this->_path) or empty($this->_depth)) {
5198 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5199 return array();
5202 $sql = "SELECT ctx.*
5203 FROM {context} ctx
5204 WHERE ctx.path LIKE ?";
5205 $params = array($this->_path.'/%');
5206 $records = $DB->get_records_sql($sql, $params);
5208 $result = array();
5209 foreach ($records as $record) {
5210 $result[$record->id] = context::create_instance_from_record($record);
5213 return $result;
5217 * Returns parent contexts of this context in reversed order, i.e. parent first,
5218 * then grand parent, etc.
5220 * @param bool $includeself tre means include self too
5221 * @return array of context instances
5223 public function get_parent_contexts($includeself = false) {
5224 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5225 return array();
5228 $result = array();
5229 foreach ($contextids as $contextid) {
5230 $parent = context::instance_by_id($contextid, MUST_EXIST);
5231 $result[$parent->id] = $parent;
5234 return $result;
5238 * Returns parent contexts of this context in reversed order, i.e. parent first,
5239 * then grand parent, etc.
5241 * @param bool $includeself tre means include self too
5242 * @return array of context ids
5244 public function get_parent_context_ids($includeself = false) {
5245 if (empty($this->_path)) {
5246 return array();
5249 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5250 $parentcontexts = explode('/', $parentcontexts);
5251 if (!$includeself) {
5252 array_pop($parentcontexts); // and remove its own id
5255 return array_reverse($parentcontexts);
5259 * Returns parent context
5261 * @return context
5263 public function get_parent_context() {
5264 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5265 return false;
5268 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5269 $parentcontexts = explode('/', $parentcontexts);
5270 array_pop($parentcontexts); // self
5271 $contextid = array_pop($parentcontexts); // immediate parent
5273 return context::instance_by_id($contextid, MUST_EXIST);
5277 * Is this context part of any course? If yes return course context.
5279 * @param bool $strict true means throw exception if not found, false means return false if not found
5280 * @return context_course context of the enclosing course, null if not found or exception
5282 public function get_course_context($strict = true) {
5283 if ($strict) {
5284 throw new coding_exception('Context does not belong to any course.');
5285 } else {
5286 return false;
5291 * Returns sql necessary for purging of stale context instances.
5293 * @static
5294 * @return string cleanup SQL
5296 protected static function get_cleanup_sql() {
5297 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5301 * Rebuild context paths and depths at context level.
5303 * @static
5304 * @param bool $force
5305 * @return void
5307 protected static function build_paths($force) {
5308 throw new coding_exception('build_paths() method must be implemented in all context levels');
5312 * Create missing context instances at given level
5314 * @static
5315 * @return void
5317 protected static function create_level_instances() {
5318 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5322 * Reset all cached permissions and definitions if the necessary.
5323 * @return void
5325 public function reload_if_dirty() {
5326 global $ACCESSLIB_PRIVATE, $USER;
5328 // Load dirty contexts list if needed
5329 if (CLI_SCRIPT) {
5330 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5331 // we do not load dirty flags in CLI and cron
5332 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5334 } else {
5335 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5336 if (!isset($USER->access['time'])) {
5337 // nothing was loaded yet, we do not need to check dirty contexts now
5338 return;
5340 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5341 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5345 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5346 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5347 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5348 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5349 reload_all_capabilities();
5350 break;
5356 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5358 public function mark_dirty() {
5359 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5361 if (during_initial_install()) {
5362 return;
5365 // only if it is a non-empty string
5366 if (is_string($this->_path) && $this->_path !== '') {
5367 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5368 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5369 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5370 } else {
5371 if (CLI_SCRIPT) {
5372 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5373 } else {
5374 if (isset($USER->access['time'])) {
5375 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5376 } else {
5377 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5379 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5388 * Context maintenance and helper methods.
5390 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5391 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5392 * level implementation from the rest of code, the code completion returns what developers need.
5394 * Thank you Tim Hunt for helping me with this nasty trick.
5396 * @package core_access
5397 * @category access
5398 * @copyright Petr Skoda {@link http://skodak.org}
5399 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5400 * @since Moodle 2.2
5402 class context_helper extends context {
5405 * @var array An array mapping context levels to classes
5407 private static $alllevels;
5410 * Instance does not make sense here, only static use
5412 protected function __construct() {
5416 * Reset internal context levels array.
5418 public static function reset_levels() {
5419 self::$alllevels = null;
5423 * Initialise context levels, call before using self::$alllevels.
5425 private static function init_levels() {
5426 global $CFG;
5428 if (isset(self::$alllevels)) {
5429 return;
5431 self::$alllevels = array(
5432 CONTEXT_SYSTEM => 'context_system',
5433 CONTEXT_USER => 'context_user',
5434 CONTEXT_COURSECAT => 'context_coursecat',
5435 CONTEXT_COURSE => 'context_course',
5436 CONTEXT_MODULE => 'context_module',
5437 CONTEXT_BLOCK => 'context_block',
5440 if (empty($CFG->custom_context_classes)) {
5441 return;
5444 $levels = $CFG->custom_context_classes;
5445 if (!is_array($levels)) {
5446 $levels = @unserialize($levels);
5448 if (!is_array($levels)) {
5449 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
5450 return;
5453 // Unsupported custom levels, use with care!!!
5454 foreach ($levels as $level => $classname) {
5455 self::$alllevels[$level] = $classname;
5457 ksort(self::$alllevels);
5461 * Returns a class name of the context level class
5463 * @static
5464 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5465 * @return string class name of the context class
5467 public static function get_class_for_level($contextlevel) {
5468 self::init_levels();
5469 if (isset(self::$alllevels[$contextlevel])) {
5470 return self::$alllevels[$contextlevel];
5471 } else {
5472 throw new coding_exception('Invalid context level specified');
5477 * Returns a list of all context levels
5479 * @static
5480 * @return array int=>string (level=>level class name)
5482 public static function get_all_levels() {
5483 self::init_levels();
5484 return self::$alllevels;
5488 * Remove stale contexts that belonged to deleted instances.
5489 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5491 * @static
5492 * @return void
5494 public static function cleanup_instances() {
5495 global $DB;
5496 self::init_levels();
5498 $sqls = array();
5499 foreach (self::$alllevels as $level=>$classname) {
5500 $sqls[] = $classname::get_cleanup_sql();
5503 $sql = implode(" UNION ", $sqls);
5505 // it is probably better to use transactions, it might be faster too
5506 $transaction = $DB->start_delegated_transaction();
5508 $rs = $DB->get_recordset_sql($sql);
5509 foreach ($rs as $record) {
5510 $context = context::create_instance_from_record($record);
5511 $context->delete();
5513 $rs->close();
5515 $transaction->allow_commit();
5519 * Create all context instances at the given level and above.
5521 * @static
5522 * @param int $contextlevel null means all levels
5523 * @param bool $buildpaths
5524 * @return void
5526 public static function create_instances($contextlevel = null, $buildpaths = true) {
5527 self::init_levels();
5528 foreach (self::$alllevels as $level=>$classname) {
5529 if ($contextlevel and $level > $contextlevel) {
5530 // skip potential sub-contexts
5531 continue;
5533 $classname::create_level_instances();
5534 if ($buildpaths) {
5535 $classname::build_paths(false);
5541 * Rebuild paths and depths in all context levels.
5543 * @static
5544 * @param bool $force false means add missing only
5545 * @return void
5547 public static function build_all_paths($force = false) {
5548 self::init_levels();
5549 foreach (self::$alllevels as $classname) {
5550 $classname::build_paths($force);
5553 // reset static course cache - it might have incorrect cached data
5554 accesslib_clear_all_caches(true);
5558 * Resets the cache to remove all data.
5559 * @static
5561 public static function reset_caches() {
5562 context::reset_caches();
5566 * Returns all fields necessary for context preloading from user $rec.
5568 * This helps with performance when dealing with hundreds of contexts.
5570 * @static
5571 * @param string $tablealias context table alias in the query
5572 * @return array (table.column=>alias, ...)
5574 public static function get_preload_record_columns($tablealias) {
5575 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5579 * Returns all fields necessary for context preloading from user $rec.
5581 * This helps with performance when dealing with hundreds of contexts.
5583 * @static
5584 * @param string $tablealias context table alias in the query
5585 * @return string
5587 public static function get_preload_record_columns_sql($tablealias) {
5588 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5592 * Preloads context information from db record and strips the cached info.
5594 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5596 * @static
5597 * @param stdClass $rec
5598 * @return void (modifies $rec)
5600 public static function preload_from_record(stdClass $rec) {
5601 context::preload_from_record($rec);
5605 * Preload all contexts instances from course.
5607 * To be used if you expect multiple queries for course activities...
5609 * @static
5610 * @param int $courseid
5612 public static function preload_course($courseid) {
5613 // Users can call this multiple times without doing any harm
5614 if (isset(context::$cache_preloaded[$courseid])) {
5615 return;
5617 $coursecontext = context_course::instance($courseid);
5618 $coursecontext->get_child_contexts();
5620 context::$cache_preloaded[$courseid] = true;
5624 * Delete context instance
5626 * @static
5627 * @param int $contextlevel
5628 * @param int $instanceid
5629 * @return void
5631 public static function delete_instance($contextlevel, $instanceid) {
5632 global $DB;
5634 // double check the context still exists
5635 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5636 $context = context::create_instance_from_record($record);
5637 $context->delete();
5638 } else {
5639 // we should try to purge the cache anyway
5644 * Returns the name of specified context level
5646 * @static
5647 * @param int $contextlevel
5648 * @return string name of the context level
5650 public static function get_level_name($contextlevel) {
5651 $classname = context_helper::get_class_for_level($contextlevel);
5652 return $classname::get_level_name();
5656 * not used
5658 public function get_url() {
5662 * not used
5664 public function get_capabilities() {
5670 * System context class
5672 * @package core_access
5673 * @category access
5674 * @copyright Petr Skoda {@link http://skodak.org}
5675 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5676 * @since Moodle 2.2
5678 class context_system extends context {
5680 * Please use context_system::instance() if you need the instance of context.
5682 * @param stdClass $record
5684 protected function __construct(stdClass $record) {
5685 parent::__construct($record);
5686 if ($record->contextlevel != CONTEXT_SYSTEM) {
5687 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5692 * Returns human readable context level name.
5694 * @static
5695 * @return string the human readable context level name.
5697 public static function get_level_name() {
5698 return get_string('coresystem');
5702 * Returns human readable context identifier.
5704 * @param boolean $withprefix does not apply to system context
5705 * @param boolean $short does not apply to system context
5706 * @return string the human readable context name.
5708 public function get_context_name($withprefix = true, $short = false) {
5709 return self::get_level_name();
5713 * Returns the most relevant URL for this context.
5715 * @return moodle_url
5717 public function get_url() {
5718 return new moodle_url('/');
5722 * Returns array of relevant context capability records.
5724 * @return array
5726 public function get_capabilities() {
5727 global $DB;
5729 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5731 $params = array();
5732 $sql = "SELECT *
5733 FROM {capabilities}";
5735 return $DB->get_records_sql($sql.' '.$sort, $params);
5739 * Create missing context instances at system context
5740 * @static
5742 protected static function create_level_instances() {
5743 // nothing to do here, the system context is created automatically in installer
5744 self::instance(0);
5748 * Returns system context instance.
5750 * @static
5751 * @param int $instanceid should be 0
5752 * @param int $strictness
5753 * @param bool $cache
5754 * @return context_system context instance
5756 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
5757 global $DB;
5759 if ($instanceid != 0) {
5760 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5763 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5764 if (!isset(context::$systemcontext)) {
5765 $record = new stdClass();
5766 $record->id = SYSCONTEXTID;
5767 $record->contextlevel = CONTEXT_SYSTEM;
5768 $record->instanceid = 0;
5769 $record->path = '/'.SYSCONTEXTID;
5770 $record->depth = 1;
5771 context::$systemcontext = new context_system($record);
5773 return context::$systemcontext;
5777 try {
5778 // We ignore the strictness completely because system context must exist except during install.
5779 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5780 } catch (dml_exception $e) {
5781 //table or record does not exist
5782 if (!during_initial_install()) {
5783 // do not mess with system context after install, it simply must exist
5784 throw $e;
5786 $record = null;
5789 if (!$record) {
5790 $record = new stdClass();
5791 $record->contextlevel = CONTEXT_SYSTEM;
5792 $record->instanceid = 0;
5793 $record->depth = 1;
5794 $record->path = null; //not known before insert
5796 try {
5797 if ($DB->count_records('context')) {
5798 // contexts already exist, this is very weird, system must be first!!!
5799 return null;
5801 if (defined('SYSCONTEXTID')) {
5802 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5803 $record->id = SYSCONTEXTID;
5804 $DB->import_record('context', $record);
5805 $DB->get_manager()->reset_sequence('context');
5806 } else {
5807 $record->id = $DB->insert_record('context', $record);
5809 } catch (dml_exception $e) {
5810 // can not create context - table does not exist yet, sorry
5811 return null;
5815 if ($record->instanceid != 0) {
5816 // this is very weird, somebody must be messing with context table
5817 debugging('Invalid system context detected');
5820 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5821 // fix path if necessary, initial install or path reset
5822 $record->depth = 1;
5823 $record->path = '/'.$record->id;
5824 $DB->update_record('context', $record);
5827 if (!defined('SYSCONTEXTID')) {
5828 define('SYSCONTEXTID', $record->id);
5831 context::$systemcontext = new context_system($record);
5832 return context::$systemcontext;
5836 * Returns all site contexts except the system context, DO NOT call on production servers!!
5838 * Contexts are not cached.
5840 * @return array
5842 public function get_child_contexts() {
5843 global $DB;
5845 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
5847 // Just get all the contexts except for CONTEXT_SYSTEM level
5848 // and hope we don't OOM in the process - don't cache
5849 $sql = "SELECT c.*
5850 FROM {context} c
5851 WHERE contextlevel > ".CONTEXT_SYSTEM;
5852 $records = $DB->get_records_sql($sql);
5854 $result = array();
5855 foreach ($records as $record) {
5856 $result[$record->id] = context::create_instance_from_record($record);
5859 return $result;
5863 * Returns sql necessary for purging of stale context instances.
5865 * @static
5866 * @return string cleanup SQL
5868 protected static function get_cleanup_sql() {
5869 $sql = "
5870 SELECT c.*
5871 FROM {context} c
5872 WHERE 1=2
5875 return $sql;
5879 * Rebuild context paths and depths at system context level.
5881 * @static
5882 * @param bool $force
5884 protected static function build_paths($force) {
5885 global $DB;
5887 /* note: ignore $force here, we always do full test of system context */
5889 // exactly one record must exist
5890 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5892 if ($record->instanceid != 0) {
5893 debugging('Invalid system context detected');
5896 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
5897 debugging('Invalid SYSCONTEXTID detected');
5900 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5901 // fix path if necessary, initial install or path reset
5902 $record->depth = 1;
5903 $record->path = '/'.$record->id;
5904 $DB->update_record('context', $record);
5911 * User context class
5913 * @package core_access
5914 * @category access
5915 * @copyright Petr Skoda {@link http://skodak.org}
5916 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5917 * @since Moodle 2.2
5919 class context_user extends context {
5921 * Please use context_user::instance($userid) if you need the instance of context.
5922 * Alternatively if you know only the context id use context::instance_by_id($contextid)
5924 * @param stdClass $record
5926 protected function __construct(stdClass $record) {
5927 parent::__construct($record);
5928 if ($record->contextlevel != CONTEXT_USER) {
5929 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
5934 * Returns human readable context level name.
5936 * @static
5937 * @return string the human readable context level name.
5939 public static function get_level_name() {
5940 return get_string('user');
5944 * Returns human readable context identifier.
5946 * @param boolean $withprefix whether to prefix the name of the context with User
5947 * @param boolean $short does not apply to user context
5948 * @return string the human readable context name.
5950 public function get_context_name($withprefix = true, $short = false) {
5951 global $DB;
5953 $name = '';
5954 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
5955 if ($withprefix){
5956 $name = get_string('user').': ';
5958 $name .= fullname($user);
5960 return $name;
5964 * Returns the most relevant URL for this context.
5966 * @return moodle_url
5968 public function get_url() {
5969 global $COURSE;
5971 if ($COURSE->id == SITEID) {
5972 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
5973 } else {
5974 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
5976 return $url;
5980 * Returns array of relevant context capability records.
5982 * @return array
5984 public function get_capabilities() {
5985 global $DB;
5987 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5989 $extracaps = array('moodle/grade:viewall');
5990 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
5991 $sql = "SELECT *
5992 FROM {capabilities}
5993 WHERE contextlevel = ".CONTEXT_USER."
5994 OR name $extra";
5996 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6000 * Returns user context instance.
6002 * @static
6003 * @param int $userid id from {user} table
6004 * @param int $strictness
6005 * @return context_user context instance
6007 public static function instance($userid, $strictness = MUST_EXIST) {
6008 global $DB;
6010 if ($context = context::cache_get(CONTEXT_USER, $userid)) {
6011 return $context;
6014 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER, 'instanceid' => $userid))) {
6015 if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6016 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6020 if ($record) {
6021 $context = new context_user($record);
6022 context::cache_add($context);
6023 return $context;
6026 return false;
6030 * Create missing context instances at user context level
6031 * @static
6033 protected static function create_level_instances() {
6034 global $DB;
6036 $sql = "SELECT ".CONTEXT_USER.", u.id
6037 FROM {user} u
6038 WHERE u.deleted = 0
6039 AND NOT EXISTS (SELECT 'x'
6040 FROM {context} cx
6041 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6042 $contextdata = $DB->get_recordset_sql($sql);
6043 foreach ($contextdata as $context) {
6044 context::insert_context_record(CONTEXT_USER, $context->id, null);
6046 $contextdata->close();
6050 * Returns sql necessary for purging of stale context instances.
6052 * @static
6053 * @return string cleanup SQL
6055 protected static function get_cleanup_sql() {
6056 $sql = "
6057 SELECT c.*
6058 FROM {context} c
6059 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6060 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6063 return $sql;
6067 * Rebuild context paths and depths at user context level.
6069 * @static
6070 * @param bool $force
6072 protected static function build_paths($force) {
6073 global $DB;
6075 // First update normal users.
6076 $path = $DB->sql_concat('?', 'id');
6077 $pathstart = '/' . SYSCONTEXTID . '/';
6078 $params = array($pathstart);
6080 if ($force) {
6081 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6082 $params[] = $pathstart;
6083 } else {
6084 $where = "depth = 0 OR path IS NULL";
6087 $sql = "UPDATE {context}
6088 SET depth = 2,
6089 path = {$path}
6090 WHERE contextlevel = " . CONTEXT_USER . "
6091 AND ($where)";
6092 $DB->execute($sql, $params);
6098 * Course category context class
6100 * @package core_access
6101 * @category access
6102 * @copyright Petr Skoda {@link http://skodak.org}
6103 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6104 * @since Moodle 2.2
6106 class context_coursecat extends context {
6108 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6109 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6111 * @param stdClass $record
6113 protected function __construct(stdClass $record) {
6114 parent::__construct($record);
6115 if ($record->contextlevel != CONTEXT_COURSECAT) {
6116 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6121 * Returns human readable context level name.
6123 * @static
6124 * @return string the human readable context level name.
6126 public static function get_level_name() {
6127 return get_string('category');
6131 * Returns human readable context identifier.
6133 * @param boolean $withprefix whether to prefix the name of the context with Category
6134 * @param boolean $short does not apply to course categories
6135 * @return string the human readable context name.
6137 public function get_context_name($withprefix = true, $short = false) {
6138 global $DB;
6140 $name = '';
6141 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6142 if ($withprefix){
6143 $name = get_string('category').': ';
6145 $name .= format_string($category->name, true, array('context' => $this));
6147 return $name;
6151 * Returns the most relevant URL for this context.
6153 * @return moodle_url
6155 public function get_url() {
6156 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6160 * Returns array of relevant context capability records.
6162 * @return array
6164 public function get_capabilities() {
6165 global $DB;
6167 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6169 $params = array();
6170 $sql = "SELECT *
6171 FROM {capabilities}
6172 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6174 return $DB->get_records_sql($sql.' '.$sort, $params);
6178 * Returns course category context instance.
6180 * @static
6181 * @param int $categoryid id from {course_categories} table
6182 * @param int $strictness
6183 * @return context_coursecat context instance
6185 public static function instance($categoryid, $strictness = MUST_EXIST) {
6186 global $DB;
6188 if ($context = context::cache_get(CONTEXT_COURSECAT, $categoryid)) {
6189 return $context;
6192 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT, 'instanceid' => $categoryid))) {
6193 if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6194 if ($category->parent) {
6195 $parentcontext = context_coursecat::instance($category->parent);
6196 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6197 } else {
6198 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6203 if ($record) {
6204 $context = new context_coursecat($record);
6205 context::cache_add($context);
6206 return $context;
6209 return false;
6213 * Returns immediate child contexts of category and all subcategories,
6214 * children of subcategories and courses are not returned.
6216 * @return array
6218 public function get_child_contexts() {
6219 global $DB;
6221 if (empty($this->_path) or empty($this->_depth)) {
6222 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6223 return array();
6226 $sql = "SELECT ctx.*
6227 FROM {context} ctx
6228 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6229 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6230 $records = $DB->get_records_sql($sql, $params);
6232 $result = array();
6233 foreach ($records as $record) {
6234 $result[$record->id] = context::create_instance_from_record($record);
6237 return $result;
6241 * Create missing context instances at course category context level
6242 * @static
6244 protected static function create_level_instances() {
6245 global $DB;
6247 $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6248 FROM {course_categories} cc
6249 WHERE NOT EXISTS (SELECT 'x'
6250 FROM {context} cx
6251 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6252 $contextdata = $DB->get_recordset_sql($sql);
6253 foreach ($contextdata as $context) {
6254 context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6256 $contextdata->close();
6260 * Returns sql necessary for purging of stale context instances.
6262 * @static
6263 * @return string cleanup SQL
6265 protected static function get_cleanup_sql() {
6266 $sql = "
6267 SELECT c.*
6268 FROM {context} c
6269 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6270 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6273 return $sql;
6277 * Rebuild context paths and depths at course category context level.
6279 * @static
6280 * @param bool $force
6282 protected static function build_paths($force) {
6283 global $DB;
6285 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6286 if ($force) {
6287 $ctxemptyclause = $emptyclause = '';
6288 } else {
6289 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6290 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6293 $base = '/'.SYSCONTEXTID;
6295 // Normal top level categories
6296 $sql = "UPDATE {context}
6297 SET depth=2,
6298 path=".$DB->sql_concat("'$base/'", 'id')."
6299 WHERE contextlevel=".CONTEXT_COURSECAT."
6300 AND EXISTS (SELECT 'x'
6301 FROM {course_categories} cc
6302 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6303 $emptyclause";
6304 $DB->execute($sql);
6306 // Deeper categories - one query per depthlevel
6307 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6308 for ($n=2; $n<=$maxdepth; $n++) {
6309 $sql = "INSERT INTO {context_temp} (id, path, depth)
6310 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6311 FROM {context} ctx
6312 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6313 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6314 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6315 $ctxemptyclause";
6316 $trans = $DB->start_delegated_transaction();
6317 $DB->delete_records('context_temp');
6318 $DB->execute($sql);
6319 context::merge_context_temp_table();
6320 $DB->delete_records('context_temp');
6321 $trans->allow_commit();
6330 * Course context class
6332 * @package core_access
6333 * @category access
6334 * @copyright Petr Skoda {@link http://skodak.org}
6335 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6336 * @since Moodle 2.2
6338 class context_course extends context {
6340 * Please use context_course::instance($courseid) if you need the instance of context.
6341 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6343 * @param stdClass $record
6345 protected function __construct(stdClass $record) {
6346 parent::__construct($record);
6347 if ($record->contextlevel != CONTEXT_COURSE) {
6348 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6353 * Returns human readable context level name.
6355 * @static
6356 * @return string the human readable context level name.
6358 public static function get_level_name() {
6359 return get_string('course');
6363 * Returns human readable context identifier.
6365 * @param boolean $withprefix whether to prefix the name of the context with Course
6366 * @param boolean $short whether to use the short name of the thing.
6367 * @return string the human readable context name.
6369 public function get_context_name($withprefix = true, $short = false) {
6370 global $DB;
6372 $name = '';
6373 if ($this->_instanceid == SITEID) {
6374 $name = get_string('frontpage', 'admin');
6375 } else {
6376 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6377 if ($withprefix){
6378 $name = get_string('course').': ';
6380 if ($short){
6381 $name .= format_string($course->shortname, true, array('context' => $this));
6382 } else {
6383 $name .= format_string(get_course_display_name_for_list($course));
6387 return $name;
6391 * Returns the most relevant URL for this context.
6393 * @return moodle_url
6395 public function get_url() {
6396 if ($this->_instanceid != SITEID) {
6397 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6400 return new moodle_url('/');
6404 * Returns array of relevant context capability records.
6406 * @return array
6408 public function get_capabilities() {
6409 global $DB;
6411 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6413 $params = array();
6414 $sql = "SELECT *
6415 FROM {capabilities}
6416 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6418 return $DB->get_records_sql($sql.' '.$sort, $params);
6422 * Is this context part of any course? If yes return course context.
6424 * @param bool $strict true means throw exception if not found, false means return false if not found
6425 * @return context_course context of the enclosing course, null if not found or exception
6427 public function get_course_context($strict = true) {
6428 return $this;
6432 * Returns course context instance.
6434 * @static
6435 * @param int $courseid id from {course} table
6436 * @param int $strictness
6437 * @return context_course context instance
6439 public static function instance($courseid, $strictness = MUST_EXIST) {
6440 global $DB;
6442 if ($context = context::cache_get(CONTEXT_COURSE, $courseid)) {
6443 return $context;
6446 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $courseid))) {
6447 if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
6448 if ($course->category) {
6449 $parentcontext = context_coursecat::instance($course->category);
6450 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6451 } else {
6452 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6457 if ($record) {
6458 $context = new context_course($record);
6459 context::cache_add($context);
6460 return $context;
6463 return false;
6467 * Create missing context instances at course context level
6468 * @static
6470 protected static function create_level_instances() {
6471 global $DB;
6473 $sql = "SELECT ".CONTEXT_COURSE.", c.id
6474 FROM {course} c
6475 WHERE NOT EXISTS (SELECT 'x'
6476 FROM {context} cx
6477 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6478 $contextdata = $DB->get_recordset_sql($sql);
6479 foreach ($contextdata as $context) {
6480 context::insert_context_record(CONTEXT_COURSE, $context->id, null);
6482 $contextdata->close();
6486 * Returns sql necessary for purging of stale context instances.
6488 * @static
6489 * @return string cleanup SQL
6491 protected static function get_cleanup_sql() {
6492 $sql = "
6493 SELECT c.*
6494 FROM {context} c
6495 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6496 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6499 return $sql;
6503 * Rebuild context paths and depths at course context level.
6505 * @static
6506 * @param bool $force
6508 protected static function build_paths($force) {
6509 global $DB;
6511 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6512 if ($force) {
6513 $ctxemptyclause = $emptyclause = '';
6514 } else {
6515 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6516 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6519 $base = '/'.SYSCONTEXTID;
6521 // Standard frontpage
6522 $sql = "UPDATE {context}
6523 SET depth = 2,
6524 path = ".$DB->sql_concat("'$base/'", 'id')."
6525 WHERE contextlevel = ".CONTEXT_COURSE."
6526 AND EXISTS (SELECT 'x'
6527 FROM {course} c
6528 WHERE c.id = {context}.instanceid AND c.category = 0)
6529 $emptyclause";
6530 $DB->execute($sql);
6532 // standard courses
6533 $sql = "INSERT INTO {context_temp} (id, path, depth)
6534 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6535 FROM {context} ctx
6536 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6537 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6538 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6539 $ctxemptyclause";
6540 $trans = $DB->start_delegated_transaction();
6541 $DB->delete_records('context_temp');
6542 $DB->execute($sql);
6543 context::merge_context_temp_table();
6544 $DB->delete_records('context_temp');
6545 $trans->allow_commit();
6552 * Course module context class
6554 * @package core_access
6555 * @category access
6556 * @copyright Petr Skoda {@link http://skodak.org}
6557 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6558 * @since Moodle 2.2
6560 class context_module extends context {
6562 * Please use context_module::instance($cmid) if you need the instance of context.
6563 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6565 * @param stdClass $record
6567 protected function __construct(stdClass $record) {
6568 parent::__construct($record);
6569 if ($record->contextlevel != CONTEXT_MODULE) {
6570 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6575 * Returns human readable context level name.
6577 * @static
6578 * @return string the human readable context level name.
6580 public static function get_level_name() {
6581 return get_string('activitymodule');
6585 * Returns human readable context identifier.
6587 * @param boolean $withprefix whether to prefix the name of the context with the
6588 * module name, e.g. Forum, Glossary, etc.
6589 * @param boolean $short does not apply to module context
6590 * @return string the human readable context name.
6592 public function get_context_name($withprefix = true, $short = false) {
6593 global $DB;
6595 $name = '';
6596 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6597 FROM {course_modules} cm
6598 JOIN {modules} md ON md.id = cm.module
6599 WHERE cm.id = ?", array($this->_instanceid))) {
6600 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6601 if ($withprefix){
6602 $name = get_string('modulename', $cm->modname).': ';
6604 $name .= format_string($mod->name, true, array('context' => $this));
6607 return $name;
6611 * Returns the most relevant URL for this context.
6613 * @return moodle_url
6615 public function get_url() {
6616 global $DB;
6618 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6619 FROM {course_modules} cm
6620 JOIN {modules} md ON md.id = cm.module
6621 WHERE cm.id = ?", array($this->_instanceid))) {
6622 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6625 return new moodle_url('/');
6629 * Returns array of relevant context capability records.
6631 * @return array
6633 public function get_capabilities() {
6634 global $DB, $CFG;
6636 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6638 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6639 $module = $DB->get_record('modules', array('id'=>$cm->module));
6641 $subcaps = array();
6642 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6643 if (file_exists($subpluginsfile)) {
6644 $subplugins = array(); // should be redefined in the file
6645 include($subpluginsfile);
6646 if (!empty($subplugins)) {
6647 foreach (array_keys($subplugins) as $subplugintype) {
6648 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
6649 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6655 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6656 $extracaps = array();
6657 if (file_exists($modfile)) {
6658 include_once($modfile);
6659 $modfunction = $module->name.'_get_extra_capabilities';
6660 if (function_exists($modfunction)) {
6661 $extracaps = $modfunction();
6665 $extracaps = array_merge($subcaps, $extracaps);
6666 $extra = '';
6667 list($extra, $params) = $DB->get_in_or_equal(
6668 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
6669 if (!empty($extra)) {
6670 $extra = "OR name $extra";
6672 $sql = "SELECT *
6673 FROM {capabilities}
6674 WHERE (contextlevel = ".CONTEXT_MODULE."
6675 AND (component = :component OR component = 'moodle'))
6676 $extra";
6677 $params['component'] = "mod_$module->name";
6679 return $DB->get_records_sql($sql.' '.$sort, $params);
6683 * Is this context part of any course? If yes return course context.
6685 * @param bool $strict true means throw exception if not found, false means return false if not found
6686 * @return context_course context of the enclosing course, null if not found or exception
6688 public function get_course_context($strict = true) {
6689 return $this->get_parent_context();
6693 * Returns module context instance.
6695 * @static
6696 * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
6697 * @param int $strictness
6698 * @return context_module context instance
6700 public static function instance($cmid, $strictness = MUST_EXIST) {
6701 global $DB;
6703 if ($context = context::cache_get(CONTEXT_MODULE, $cmid)) {
6704 return $context;
6707 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE, 'instanceid' => $cmid))) {
6708 if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
6709 $parentcontext = context_course::instance($cm->course);
6710 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
6714 if ($record) {
6715 $context = new context_module($record);
6716 context::cache_add($context);
6717 return $context;
6720 return false;
6724 * Create missing context instances at module context level
6725 * @static
6727 protected static function create_level_instances() {
6728 global $DB;
6730 $sql = "SELECT ".CONTEXT_MODULE.", cm.id
6731 FROM {course_modules} cm
6732 WHERE NOT EXISTS (SELECT 'x'
6733 FROM {context} cx
6734 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
6735 $contextdata = $DB->get_recordset_sql($sql);
6736 foreach ($contextdata as $context) {
6737 context::insert_context_record(CONTEXT_MODULE, $context->id, null);
6739 $contextdata->close();
6743 * Returns sql necessary for purging of stale context instances.
6745 * @static
6746 * @return string cleanup SQL
6748 protected static function get_cleanup_sql() {
6749 $sql = "
6750 SELECT c.*
6751 FROM {context} c
6752 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6753 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
6756 return $sql;
6760 * Rebuild context paths and depths at module context level.
6762 * @static
6763 * @param bool $force
6765 protected static function build_paths($force) {
6766 global $DB;
6768 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
6769 if ($force) {
6770 $ctxemptyclause = '';
6771 } else {
6772 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6775 $sql = "INSERT INTO {context_temp} (id, path, depth)
6776 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6777 FROM {context} ctx
6778 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
6779 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
6780 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6781 $ctxemptyclause";
6782 $trans = $DB->start_delegated_transaction();
6783 $DB->delete_records('context_temp');
6784 $DB->execute($sql);
6785 context::merge_context_temp_table();
6786 $DB->delete_records('context_temp');
6787 $trans->allow_commit();
6794 * Block context class
6796 * @package core_access
6797 * @category access
6798 * @copyright Petr Skoda {@link http://skodak.org}
6799 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6800 * @since Moodle 2.2
6802 class context_block extends context {
6804 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6805 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6807 * @param stdClass $record
6809 protected function __construct(stdClass $record) {
6810 parent::__construct($record);
6811 if ($record->contextlevel != CONTEXT_BLOCK) {
6812 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6817 * Returns human readable context level name.
6819 * @static
6820 * @return string the human readable context level name.
6822 public static function get_level_name() {
6823 return get_string('block');
6827 * Returns human readable context identifier.
6829 * @param boolean $withprefix whether to prefix the name of the context with Block
6830 * @param boolean $short does not apply to block context
6831 * @return string the human readable context name.
6833 public function get_context_name($withprefix = true, $short = false) {
6834 global $DB, $CFG;
6836 $name = '';
6837 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
6838 global $CFG;
6839 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
6840 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
6841 $blockname = "block_$blockinstance->blockname";
6842 if ($blockobject = new $blockname()) {
6843 if ($withprefix){
6844 $name = get_string('block').': ';
6846 $name .= $blockobject->title;
6850 return $name;
6854 * Returns the most relevant URL for this context.
6856 * @return moodle_url
6858 public function get_url() {
6859 $parentcontexts = $this->get_parent_context();
6860 return $parentcontexts->get_url();
6864 * Returns array of relevant context capability records.
6866 * @return array
6868 public function get_capabilities() {
6869 global $DB;
6871 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6873 $params = array();
6874 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
6876 $extra = '';
6877 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
6878 if ($extracaps) {
6879 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6880 $extra = "OR name $extra";
6883 $sql = "SELECT *
6884 FROM {capabilities}
6885 WHERE (contextlevel = ".CONTEXT_BLOCK."
6886 AND component = :component)
6887 $extra";
6888 $params['component'] = 'block_' . $bi->blockname;
6890 return $DB->get_records_sql($sql.' '.$sort, $params);
6894 * Is this context part of any course? If yes return course context.
6896 * @param bool $strict true means throw exception if not found, false means return false if not found
6897 * @return context_course context of the enclosing course, null if not found or exception
6899 public function get_course_context($strict = true) {
6900 $parentcontext = $this->get_parent_context();
6901 return $parentcontext->get_course_context($strict);
6905 * Returns block context instance.
6907 * @static
6908 * @param int $blockinstanceid id from {block_instances} table.
6909 * @param int $strictness
6910 * @return context_block context instance
6912 public static function instance($blockinstanceid, $strictness = MUST_EXIST) {
6913 global $DB;
6915 if ($context = context::cache_get(CONTEXT_BLOCK, $blockinstanceid)) {
6916 return $context;
6919 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $blockinstanceid))) {
6920 if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
6921 $parentcontext = context::instance_by_id($bi->parentcontextid);
6922 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
6926 if ($record) {
6927 $context = new context_block($record);
6928 context::cache_add($context);
6929 return $context;
6932 return false;
6936 * Block do not have child contexts...
6937 * @return array
6939 public function get_child_contexts() {
6940 return array();
6944 * Create missing context instances at block context level
6945 * @static
6947 protected static function create_level_instances() {
6948 global $DB;
6950 $sql = "SELECT ".CONTEXT_BLOCK.", bi.id
6951 FROM {block_instances} bi
6952 WHERE NOT EXISTS (SELECT 'x'
6953 FROM {context} cx
6954 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
6955 $contextdata = $DB->get_recordset_sql($sql);
6956 foreach ($contextdata as $context) {
6957 context::insert_context_record(CONTEXT_BLOCK, $context->id, null);
6959 $contextdata->close();
6963 * Returns sql necessary for purging of stale context instances.
6965 * @static
6966 * @return string cleanup SQL
6968 protected static function get_cleanup_sql() {
6969 $sql = "
6970 SELECT c.*
6971 FROM {context} c
6972 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
6973 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
6976 return $sql;
6980 * Rebuild context paths and depths at block context level.
6982 * @static
6983 * @param bool $force
6985 protected static function build_paths($force) {
6986 global $DB;
6988 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
6989 if ($force) {
6990 $ctxemptyclause = '';
6991 } else {
6992 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6995 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
6996 $sql = "INSERT INTO {context_temp} (id, path, depth)
6997 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6998 FROM {context} ctx
6999 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7000 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7001 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7002 $ctxemptyclause";
7003 $trans = $DB->start_delegated_transaction();
7004 $DB->delete_records('context_temp');
7005 $DB->execute($sql);
7006 context::merge_context_temp_table();
7007 $DB->delete_records('context_temp');
7008 $trans->allow_commit();
7014 // ============== DEPRECATED FUNCTIONS ==========================================
7015 // Old context related functions were deprecated in 2.0, it is recommended
7016 // to use context classes in new code. Old function can be used when
7017 // creating patches that are supposed to be backported to older stable branches.
7018 // These deprecated functions will not be removed in near future,
7019 // before removing devs will be warned with a debugging message first,
7020 // then we will add error message and only after that we can remove the functions
7021 // completely.
7024 * Runs get_records select on context table and returns the result
7025 * Does get_records_select on the context table, and returns the results ordered
7026 * by contextlevel, and then the natural sort order within each level.
7027 * for the purpose of $select, you need to know that the context table has been
7028 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7030 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7031 * @param array $params any parameters required by $select.
7032 * @return array the requested context records.
7034 function get_sorted_contexts($select, $params = array()) {
7036 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7038 global $DB;
7039 if ($select) {
7040 $select = 'WHERE ' . $select;
7042 return $DB->get_records_sql("
7043 SELECT ctx.*
7044 FROM {context} ctx
7045 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7046 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7047 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7048 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7049 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7050 $select
7051 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7052 ", $params);
7056 * Given context and array of users, returns array of users whose enrolment status is suspended,
7057 * or enrolment has expired or has not started. Also removes those users from the given array
7059 * @param context $context context in which suspended users should be extracted.
7060 * @param array $users list of users.
7061 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7062 * @return array list of suspended users.
7064 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7065 global $DB;
7067 // Get active enrolled users.
7068 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7069 $activeusers = $DB->get_records_sql($sql, $params);
7071 // Move suspended users to a separate array & remove from the initial one.
7072 $susers = array();
7073 if (sizeof($activeusers)) {
7074 foreach ($users as $userid => $user) {
7075 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7076 $susers[$userid] = $user;
7077 unset($users[$userid]);
7081 return $susers;
7085 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7086 * or enrolment has expired or not started.
7088 * @param context $context context in which user enrolment is checked.
7089 * @param bool $usecache Enable or disable (default) the request cache
7090 * @return array list of suspended user id's.
7092 function get_suspended_userids(context $context, $usecache = false) {
7093 global $DB;
7095 if ($usecache) {
7096 $cache = cache::make('core', 'suspended_userids');
7097 $susers = $cache->get($context->id);
7098 if ($susers !== false) {
7099 return $susers;
7103 $coursecontext = $context->get_course_context();
7104 $susers = array();
7106 // Front page users are always enrolled, so suspended list is empty.
7107 if ($coursecontext->instanceid != SITEID) {
7108 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7109 $susers = $DB->get_fieldset_sql($sql, $params);
7110 $susers = array_combine($susers, $susers);
7113 // Cache results for the remainder of this request.
7114 if ($usecache) {
7115 $cache->set($context->id, $susers);
7118 return $susers;
7122 * Gets sql for finding users with capability in the given context
7124 * @param context $context
7125 * @param string|array $capability Capability name or array of names.
7126 * If an array is provided then this is the equivalent of a logical 'OR',
7127 * i.e. the user needs to have one of these capabilities.
7128 * @return array($sql, $params)
7130 function get_with_capability_sql(context $context, $capability) {
7131 static $i = 0;
7132 $i++;
7133 $prefix = 'cu' . $i . '_';
7135 $capjoin = get_with_capability_join($context, $capability, $prefix . 'u.id');
7137 $sql = "SELECT DISTINCT {$prefix}u.id
7138 FROM {user} {$prefix}u
7139 $capjoin->joins
7140 WHERE {$prefix}u.deleted = 0 AND $capjoin->wheres";
7142 return array($sql, $capjoin->params);
7146 * Gets sql joins for finding users with capability in the given context
7148 * @param context $context Context for the join
7149 * @param string|array $capability Capability name or array of names.
7150 * If an array is provided then this is the equivalent of a logical 'OR',
7151 * i.e. the user needs to have one of these capabilities.
7152 * @param string $useridcolumn e.g. 'u.id'
7153 * @return \core\dml\sql_join Contains joins, wheres, params
7155 function get_with_capability_join(context $context, $capability, $useridcolumn) {
7156 global $DB, $CFG;
7158 // Use unique prefix just in case somebody makes some SQL magic with the result.
7159 static $i = 0;
7160 $i++;
7161 $prefix = 'eu' . $i . '_';
7163 // First find the course context.
7164 $coursecontext = $context->get_course_context();
7166 $isfrontpage = ($coursecontext->instanceid == SITEID);
7168 $joins = array();
7169 $wheres = array();
7170 $params = array();
7172 list($contextids, $contextpaths) = get_context_info_list($context);
7174 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
7176 list($incaps, $capsparams) = $DB->get_in_or_equal($capability, SQL_PARAMS_NAMED, 'cap');
7178 $defs = array();
7179 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
7180 FROM {role_capabilities} rc
7181 JOIN {context} ctx on rc.contextid = ctx.id
7182 WHERE rc.contextid $incontexts AND rc.capability $incaps";
7183 $rcs = $DB->get_records_sql($sql, array_merge($cparams, $capsparams));
7184 foreach ($rcs as $rc) {
7185 $defs[$rc->path][$rc->roleid] = $rc->permission;
7188 $access = array();
7189 if (!empty($defs)) {
7190 foreach ($contextpaths as $path) {
7191 if (empty($defs[$path])) {
7192 continue;
7194 foreach ($defs[$path] as $roleid => $perm) {
7195 if ($perm == CAP_PROHIBIT) {
7196 $access[$roleid] = CAP_PROHIBIT;
7197 continue;
7199 if (!isset($access[$roleid])) {
7200 $access[$roleid] = (int) $perm;
7206 unset($defs);
7208 // Make lists of roles that are needed and prohibited.
7209 $needed = array(); // One of these is enough.
7210 $prohibited = array(); // Must not have any of these.
7211 foreach ($access as $roleid => $perm) {
7212 if ($perm == CAP_PROHIBIT) {
7213 unset($needed[$roleid]);
7214 $prohibited[$roleid] = true;
7215 } else {
7216 if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
7217 $needed[$roleid] = true;
7222 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
7223 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
7225 $nobody = false;
7227 if ($isfrontpage) {
7228 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
7229 $nobody = true;
7230 } else {
7231 if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
7232 // Everybody not having prohibit has the capability.
7233 $needed = array();
7234 } else {
7235 if (empty($needed)) {
7236 $nobody = true;
7240 } else {
7241 if (!empty($prohibited[$defaultuserroleid])) {
7242 $nobody = true;
7243 } else {
7244 if (!empty($needed[$defaultuserroleid])) {
7245 // Everybody not having prohibit has the capability.
7246 $needed = array();
7247 } else {
7248 if (empty($needed)) {
7249 $nobody = true;
7255 if ($nobody) {
7256 // Nobody can match so return some SQL that does not return any results.
7257 $wheres[] = "1 = 2";
7259 } else {
7261 if ($needed) {
7262 $ctxids = implode(',', $contextids);
7263 $roleids = implode(',', array_keys($needed));
7264 $joins[] = "JOIN {role_assignments} {$prefix}ra3
7265 ON ({$prefix}ra3.userid = $useridcolumn
7266 AND {$prefix}ra3.roleid IN ($roleids)
7267 AND {$prefix}ra3.contextid IN ($ctxids))";
7270 if ($prohibited) {
7271 $ctxids = implode(',', $contextids);
7272 $roleids = implode(',', array_keys($prohibited));
7273 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4
7274 ON ({$prefix}ra4.userid = $useridcolumn
7275 AND {$prefix}ra4.roleid IN ($roleids)
7276 AND {$prefix}ra4.contextid IN ($ctxids))";
7277 $wheres[] = "{$prefix}ra4.id IS NULL";
7282 $wheres[] = "$useridcolumn <> :{$prefix}guestid";
7283 $params["{$prefix}guestid"] = $CFG->siteguest;
7285 $joins = implode("\n", $joins);
7286 $wheres = "(" . implode(" AND ", $wheres) . ")";
7288 return new \core\dml\sql_join($joins, $wheres, $params);