MDL-63119 calendar: now showing event end in modal
[moodle.git] / lib / accesslib.php
blob8211ffb2b788bfa47a90cafea07745837ba61044
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains functions for managing user access
20 * <b>Public API vs internals</b>
22 * General users probably only care about
24 * Context handling
25 * - context_course::instance($courseid), context_module::instance($cm->id), context_coursecat::instance($catid)
26 * - context::instance_by_id($contextid)
27 * - $context->get_parent_contexts();
28 * - $context->get_child_contexts();
30 * Whether the user can do something...
31 * - has_capability()
32 * - has_any_capability()
33 * - has_all_capabilities()
34 * - require_capability()
35 * - require_login() (from moodlelib)
36 * - is_enrolled()
37 * - is_viewing()
38 * - is_guest()
39 * - is_siteadmin()
40 * - isguestuser()
41 * - isloggedin()
43 * What courses has this user access to?
44 * - get_enrolled_users()
46 * What users can do X in this context?
47 * - get_enrolled_users() - at and bellow course context
48 * - get_users_by_capability() - above course context
50 * Modify roles
51 * - role_assign()
52 * - role_unassign()
53 * - role_unassign_all()
55 * Advanced - for internal use only
56 * - load_all_capabilities()
57 * - reload_all_capabilities()
58 * - has_capability_in_accessdata()
59 * - get_user_roles_sitewide_accessdata()
60 * - etc.
62 * <b>Name conventions</b>
64 * "ctx" means context
66 * <b>accessdata</b>
68 * Access control data is held in the "accessdata" array
69 * which - for the logged-in user, will be in $USER->access
71 * For other users can be generated and passed around (but may also be cached
72 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser).
74 * $accessdata is a multidimensional array, holding
75 * role assignments (RAs), role-capabilities-perm sets
76 * (role defs) and a list of courses we have loaded
77 * data for.
79 * Things are keyed on "contextpaths" (the path field of
80 * the context table) for fast walking up/down the tree.
81 * <code>
82 * $accessdata['ra'][$contextpath] = array($roleid=>$roleid)
83 * [$contextpath] = array($roleid=>$roleid)
84 * [$contextpath] = array($roleid=>$roleid)
85 * </code>
87 * <b>Stale accessdata</b>
89 * For the logged-in user, accessdata is long-lived.
91 * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
92 * context paths affected by changes. Any check at-or-below
93 * a dirty context will trigger a transparent reload of accessdata.
95 * Changes at the system level will force the reload for everyone.
97 * <b>Default role caps</b>
98 * The default role assignment is not in the DB, so we
99 * add it manually to accessdata.
101 * This means that functions that work directly off the
102 * DB need to ensure that the default role caps
103 * are dealt with appropriately.
105 * @package core_access
106 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
107 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
110 defined('MOODLE_INTERNAL') || die();
112 /** No capability change */
113 define('CAP_INHERIT', 0);
114 /** Allow permission, overrides CAP_PREVENT defined in parent contexts */
115 define('CAP_ALLOW', 1);
116 /** Prevent permission, overrides CAP_ALLOW defined in parent contexts */
117 define('CAP_PREVENT', -1);
118 /** Prohibit permission, overrides everything in current and child contexts */
119 define('CAP_PROHIBIT', -1000);
121 /** System context level - only one instance in every system */
122 define('CONTEXT_SYSTEM', 10);
123 /** User context level - one instance for each user describing what others can do to user */
124 define('CONTEXT_USER', 30);
125 /** Course category context level - one instance for each category */
126 define('CONTEXT_COURSECAT', 40);
127 /** Course context level - one instances for each course */
128 define('CONTEXT_COURSE', 50);
129 /** Course module context level - one instance for each course module */
130 define('CONTEXT_MODULE', 70);
132 * Block context level - one instance for each block, sticky blocks are tricky
133 * because ppl think they should be able to override them at lower contexts.
134 * Any other context level instance can be parent of block context.
136 define('CONTEXT_BLOCK', 80);
138 /** Capability allow management of trusts - NOT IMPLEMENTED YET - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
139 define('RISK_MANAGETRUST', 0x0001);
140 /** Capability allows changes in system configuration - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
141 define('RISK_CONFIG', 0x0002);
142 /** Capability allows user to add scripted content - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
143 define('RISK_XSS', 0x0004);
144 /** Capability allows access to personal user information - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
145 define('RISK_PERSONAL', 0x0008);
146 /** Capability allows users to add content others may see - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
147 define('RISK_SPAM', 0x0010);
148 /** capability allows mass delete of data belonging to other users - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
149 define('RISK_DATALOSS', 0x0020);
151 /** rolename displays - the name as defined in the role definition, localised if name empty */
152 define('ROLENAME_ORIGINAL', 0);
153 /** rolename displays - the name as defined by a role alias at the course level, falls back to ROLENAME_ORIGINAL if alias not present */
154 define('ROLENAME_ALIAS', 1);
155 /** rolename displays - Both, like this: Role alias (Original) */
156 define('ROLENAME_BOTH', 2);
157 /** rolename displays - the name as defined in the role definition and the shortname in brackets */
158 define('ROLENAME_ORIGINALANDSHORT', 3);
159 /** rolename displays - the name as defined by a role alias, in raw form suitable for editing */
160 define('ROLENAME_ALIAS_RAW', 4);
161 /** rolename displays - the name is simply short role name */
162 define('ROLENAME_SHORT', 5);
164 if (!defined('CONTEXT_CACHE_MAX_SIZE')) {
165 /** maximum size of context cache - it is possible to tweak this config.php or in any script before inclusion of context.php */
166 define('CONTEXT_CACHE_MAX_SIZE', 2500);
170 * Although this looks like a global variable, it isn't really.
172 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
173 * It is used to cache various bits of data between function calls for performance reasons.
174 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
175 * as methods of a class, instead of functions.
177 * @access private
178 * @global stdClass $ACCESSLIB_PRIVATE
179 * @name $ACCESSLIB_PRIVATE
181 global $ACCESSLIB_PRIVATE;
182 $ACCESSLIB_PRIVATE = new stdClass();
183 $ACCESSLIB_PRIVATE->cacheroledefs = array(); // Holds site-wide role definitions.
184 $ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache, loaded from DB once per page
185 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
188 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
190 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
191 * accesslib's private caches. You need to do this before setting up test data,
192 * and also at the end of the tests.
194 * @access private
195 * @return void
197 function accesslib_clear_all_caches_for_unit_testing() {
198 global $USER;
199 if (!PHPUNIT_TEST) {
200 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
203 accesslib_clear_all_caches(true);
205 unset($USER->access);
209 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
211 * This reset does not touch global $USER.
213 * @access private
214 * @param bool $resetcontexts
215 * @return void
217 function accesslib_clear_all_caches($resetcontexts) {
218 global $ACCESSLIB_PRIVATE;
220 $ACCESSLIB_PRIVATE->dirtycontexts = null;
221 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
222 $ACCESSLIB_PRIVATE->cacheroledefs = array();
224 $cache = cache::make('core', 'roledefs');
225 $cache->purge();
227 if ($resetcontexts) {
228 context_helper::reset_caches();
233 * Clears accesslib's private cache of a specific role or roles. ONLY BE USED FROM THIS LIBRARY FILE!
235 * This reset does not touch global $USER.
237 * @access private
238 * @param int|array $roles
239 * @return void
241 function accesslib_clear_role_cache($roles) {
242 global $ACCESSLIB_PRIVATE;
244 if (!is_array($roles)) {
245 $roles = [$roles];
248 foreach ($roles as $role) {
249 if (isset($ACCESSLIB_PRIVATE->cacheroledefs[$role])) {
250 unset($ACCESSLIB_PRIVATE->cacheroledefs[$role]);
254 $cache = cache::make('core', 'roledefs');
255 $cache->delete_many($roles);
259 * Role is assigned at system context.
261 * @access private
262 * @param int $roleid
263 * @return array
265 function get_role_access($roleid) {
266 $accessdata = get_empty_accessdata();
267 $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
268 return $accessdata;
272 * Fetch raw "site wide" role definitions.
273 * Even MUC static acceleration cache appears a bit slow for this.
274 * Important as can be hit hundreds of times per page.
276 * @param array $roleids List of role ids to fetch definitions for.
277 * @return array Complete definition for each requested role.
279 function get_role_definitions(array $roleids) {
280 global $ACCESSLIB_PRIVATE;
282 if (empty($roleids)) {
283 return array();
286 // Grab all keys we have not yet got in our static cache.
287 if ($uncached = array_diff($roleids, array_keys($ACCESSLIB_PRIVATE->cacheroledefs))) {
288 $cache = cache::make('core', 'roledefs');
289 foreach ($cache->get_many($uncached) as $roleid => $cachedroledef) {
290 if (is_array($cachedroledef)) {
291 $ACCESSLIB_PRIVATE->cacheroledefs[$roleid] = $cachedroledef;
295 // Check we have the remaining keys from the MUC.
296 if ($uncached = array_diff($roleids, array_keys($ACCESSLIB_PRIVATE->cacheroledefs))) {
297 $uncached = get_role_definitions_uncached($uncached);
298 $ACCESSLIB_PRIVATE->cacheroledefs += $uncached;
299 $cache->set_many($uncached);
303 // Return just the roles we need.
304 return array_intersect_key($ACCESSLIB_PRIVATE->cacheroledefs, array_flip($roleids));
308 * Query raw "site wide" role definitions.
310 * @param array $roleids List of role ids to fetch definitions for.
311 * @return array Complete definition for each requested role.
313 function get_role_definitions_uncached(array $roleids) {
314 global $DB;
316 if (empty($roleids)) {
317 return array();
320 // Create a blank results array: even if a role has no capabilities,
321 // we need to ensure it is included in the results to show we have
322 // loaded all the capabilities that there are.
323 $rdefs = array();
324 foreach ($roleids as $roleid) {
325 $rdefs[$roleid] = array();
328 // Load all the capabilities for these roles in all contexts.
329 list($sql, $params) = $DB->get_in_or_equal($roleids);
330 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
331 FROM {role_capabilities} rc
332 JOIN {context} ctx ON rc.contextid = ctx.id
333 WHERE rc.roleid $sql";
334 $rs = $DB->get_recordset_sql($sql, $params);
336 // Store the capabilities into the expected data structure.
337 foreach ($rs as $rd) {
338 if (!isset($rdefs[$rd->roleid][$rd->path])) {
339 $rdefs[$rd->roleid][$rd->path] = array();
341 $rdefs[$rd->roleid][$rd->path][$rd->capability] = (int) $rd->permission;
344 $rs->close();
346 // Sometimes (e.g. get_user_capability_course_helper::get_capability_info_at_each_context)
347 // we process role definitinons in a way that requires we see parent contexts
348 // before child contexts. This sort ensures that works (and is faster than
349 // sorting in the SQL query).
350 foreach ($rdefs as $roleid => $rdef) {
351 ksort($rdefs[$roleid]);
354 return $rdefs;
358 * Get the default guest role, this is used for guest account,
359 * search engine spiders, etc.
361 * @return stdClass role record
363 function get_guest_role() {
364 global $CFG, $DB;
366 if (empty($CFG->guestroleid)) {
367 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
368 $guestrole = array_shift($roles); // Pick the first one
369 set_config('guestroleid', $guestrole->id);
370 return $guestrole;
371 } else {
372 debugging('Can not find any guest role!');
373 return false;
375 } else {
376 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
377 return $guestrole;
378 } else {
379 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
380 set_config('guestroleid', '');
381 return get_guest_role();
387 * Check whether a user has a particular capability in a given context.
389 * For example:
390 * $context = context_module::instance($cm->id);
391 * has_capability('mod/forum:replypost', $context)
393 * By default checks the capabilities of the current user, but you can pass a
394 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
396 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
397 * or capabilities with XSS, config or data loss risks.
399 * @category access
401 * @param string $capability the name of the capability to check. For example mod/forum:view
402 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
403 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
404 * @param boolean $doanything If false, ignores effect of admin role assignment
405 * @return boolean true if the user has this capability. Otherwise false.
407 function has_capability($capability, context $context, $user = null, $doanything = true) {
408 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
410 if (during_initial_install()) {
411 if ($SCRIPT === "/$CFG->admin/index.php"
412 or $SCRIPT === "/$CFG->admin/cli/install.php"
413 or $SCRIPT === "/$CFG->admin/cli/install_database.php"
414 or (defined('BEHAT_UTIL') and BEHAT_UTIL)
415 or (defined('PHPUNIT_UTIL') and PHPUNIT_UTIL)) {
416 // we are in an installer - roles can not work yet
417 return true;
418 } else {
419 return false;
423 if (strpos($capability, 'moodle/legacy:') === 0) {
424 throw new coding_exception('Legacy capabilities can not be used any more!');
427 if (!is_bool($doanything)) {
428 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
431 // capability must exist
432 if (!$capinfo = get_capability_info($capability)) {
433 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
434 return false;
437 if (!isset($USER->id)) {
438 // should never happen
439 $USER->id = 0;
440 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER);
443 // make sure there is a real user specified
444 if ($user === null) {
445 $userid = $USER->id;
446 } else {
447 $userid = is_object($user) ? $user->id : $user;
450 // make sure forcelogin cuts off not-logged-in users if enabled
451 if (!empty($CFG->forcelogin) and $userid == 0) {
452 return false;
455 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
456 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
457 if (isguestuser($userid) or $userid == 0) {
458 return false;
462 // somehow make sure the user is not deleted and actually exists
463 if ($userid != 0) {
464 if ($userid == $USER->id and isset($USER->deleted)) {
465 // this prevents one query per page, it is a bit of cheating,
466 // but hopefully session is terminated properly once user is deleted
467 if ($USER->deleted) {
468 return false;
470 } else {
471 if (!context_user::instance($userid, IGNORE_MISSING)) {
472 // no user context == invalid userid
473 return false;
478 // context path/depth must be valid
479 if (empty($context->path) or $context->depth == 0) {
480 // this should not happen often, each upgrade tries to rebuild the context paths
481 debugging('Context id '.$context->id.' does not have valid path, please use context_helper::build_all_paths()');
482 if (is_siteadmin($userid)) {
483 return true;
484 } else {
485 return false;
489 // Find out if user is admin - it is not possible to override the doanything in any way
490 // and it is not possible to switch to admin role either.
491 if ($doanything) {
492 if (is_siteadmin($userid)) {
493 if ($userid != $USER->id) {
494 return true;
496 // make sure switchrole is not used in this context
497 if (empty($USER->access['rsw'])) {
498 return true;
500 $parts = explode('/', trim($context->path, '/'));
501 $path = '';
502 $switched = false;
503 foreach ($parts as $part) {
504 $path .= '/' . $part;
505 if (!empty($USER->access['rsw'][$path])) {
506 $switched = true;
507 break;
510 if (!$switched) {
511 return true;
513 //ok, admin switched role in this context, let's use normal access control rules
517 // Careful check for staleness...
518 $context->reload_if_dirty();
520 if ($USER->id == $userid) {
521 if (!isset($USER->access)) {
522 load_all_capabilities();
524 $access =& $USER->access;
526 } else {
527 // make sure user accessdata is really loaded
528 get_user_accessdata($userid, true);
529 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
532 return has_capability_in_accessdata($capability, $context, $access);
536 * Check if the user has any one of several capabilities from a list.
538 * This is just a utility method that calls has_capability in a loop. Try to put
539 * the capabilities that most users are likely to have first in the list for best
540 * performance.
542 * @category access
543 * @see has_capability()
545 * @param array $capabilities an array of capability names.
546 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
547 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
548 * @param boolean $doanything If false, ignore effect of admin role assignment
549 * @return boolean true if the user has any of these capabilities. Otherwise false.
551 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
552 foreach ($capabilities as $capability) {
553 if (has_capability($capability, $context, $user, $doanything)) {
554 return true;
557 return false;
561 * Check if the user has all the capabilities in a list.
563 * This is just a utility method that calls has_capability in a loop. Try to put
564 * the capabilities that fewest users are likely to have first in the list for best
565 * performance.
567 * @category access
568 * @see has_capability()
570 * @param array $capabilities an array of capability names.
571 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
572 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
573 * @param boolean $doanything If false, ignore effect of admin role assignment
574 * @return boolean true if the user has all of these capabilities. Otherwise false.
576 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
577 foreach ($capabilities as $capability) {
578 if (!has_capability($capability, $context, $user, $doanything)) {
579 return false;
582 return true;
586 * Is course creator going to have capability in a new course?
588 * This is intended to be used in enrolment plugins before or during course creation,
589 * do not use after the course is fully created.
591 * @category access
593 * @param string $capability the name of the capability to check.
594 * @param context $context course or category context where is course going to be created
595 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
596 * @return boolean true if the user will have this capability.
598 * @throws coding_exception if different type of context submitted
600 function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) {
601 global $CFG;
603 if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) {
604 throw new coding_exception('Only course or course category context expected');
607 if (has_capability($capability, $context, $user)) {
608 // User already has the capability, it could be only removed if CAP_PROHIBIT
609 // was involved here, but we ignore that.
610 return true;
613 if (!has_capability('moodle/course:create', $context, $user)) {
614 return false;
617 if (!enrol_is_enabled('manual')) {
618 return false;
621 if (empty($CFG->creatornewroleid)) {
622 return false;
625 if ($context->contextlevel == CONTEXT_COURSE) {
626 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
627 return false;
629 } else {
630 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
631 return false;
635 // Most likely they will be enrolled after the course creation is finished,
636 // does the new role have the required capability?
637 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
638 return isset($neededroles[$CFG->creatornewroleid]);
642 * Check if the user is an admin at the site level.
644 * Please note that use of proper capabilities is always encouraged,
645 * this function is supposed to be used from core or for temporary hacks.
647 * @category access
649 * @param int|stdClass $user_or_id user id or user object
650 * @return bool true if user is one of the administrators, false otherwise
652 function is_siteadmin($user_or_id = null) {
653 global $CFG, $USER;
655 if ($user_or_id === null) {
656 $user_or_id = $USER;
659 if (empty($user_or_id)) {
660 return false;
662 if (!empty($user_or_id->id)) {
663 $userid = $user_or_id->id;
664 } else {
665 $userid = $user_or_id;
668 // Because this script is called many times (150+ for course page) with
669 // the same parameters, it is worth doing minor optimisations. This static
670 // cache stores the value for a single userid, saving about 2ms from course
671 // page load time without using significant memory. As the static cache
672 // also includes the value it depends on, this cannot break unit tests.
673 static $knownid, $knownresult, $knownsiteadmins;
674 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
675 return $knownresult;
677 $knownid = $userid;
678 $knownsiteadmins = $CFG->siteadmins;
680 $siteadmins = explode(',', $CFG->siteadmins);
681 $knownresult = in_array($userid, $siteadmins);
682 return $knownresult;
686 * Returns true if user has at least one role assign
687 * of 'coursecontact' role (is potentially listed in some course descriptions).
689 * @param int $userid
690 * @return bool
692 function has_coursecontact_role($userid) {
693 global $DB, $CFG;
695 if (empty($CFG->coursecontact)) {
696 return false;
698 $sql = "SELECT 1
699 FROM {role_assignments}
700 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
701 return $DB->record_exists_sql($sql, array('userid'=>$userid));
705 * Does the user have a capability to do something?
707 * Walk the accessdata array and return true/false.
708 * Deals with prohibits, role switching, aggregating
709 * capabilities, etc.
711 * The main feature of here is being FAST and with no
712 * side effects.
714 * Notes:
716 * Switch Role merges with default role
717 * ------------------------------------
718 * If you are a teacher in course X, you have at least
719 * teacher-in-X + defaultloggedinuser-sitewide. So in the
720 * course you'll have techer+defaultloggedinuser.
721 * We try to mimic that in switchrole.
723 * Permission evaluation
724 * ---------------------
725 * Originally there was an extremely complicated way
726 * to determine the user access that dealt with
727 * "locality" or role assignments and role overrides.
728 * Now we simply evaluate access for each role separately
729 * and then verify if user has at least one role with allow
730 * and at the same time no role with prohibit.
732 * @access private
733 * @param string $capability
734 * @param context $context
735 * @param array $accessdata
736 * @return bool
738 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
739 global $CFG;
741 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
742 $path = $context->path;
743 $paths = array($path);
744 while($path = rtrim($path, '0123456789')) {
745 $path = rtrim($path, '/');
746 if ($path === '') {
747 break;
749 $paths[] = $path;
752 $roles = array();
753 $switchedrole = false;
755 // Find out if role switched
756 if (!empty($accessdata['rsw'])) {
757 // From the bottom up...
758 foreach ($paths as $path) {
759 if (isset($accessdata['rsw'][$path])) {
760 // Found a switchrole assignment - check for that role _plus_ the default user role
761 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
762 $switchedrole = true;
763 break;
768 if (!$switchedrole) {
769 // get all users roles in this context and above
770 foreach ($paths as $path) {
771 if (isset($accessdata['ra'][$path])) {
772 foreach ($accessdata['ra'][$path] as $roleid) {
773 $roles[$roleid] = null;
779 // Now find out what access is given to each role, going bottom-->up direction
780 $rdefs = get_role_definitions(array_keys($roles));
781 $allowed = false;
783 foreach ($roles as $roleid => $ignored) {
784 foreach ($paths as $path) {
785 if (isset($rdefs[$roleid][$path][$capability])) {
786 $perm = (int)$rdefs[$roleid][$path][$capability];
787 if ($perm === CAP_PROHIBIT) {
788 // any CAP_PROHIBIT found means no permission for the user
789 return false;
791 if (is_null($roles[$roleid])) {
792 $roles[$roleid] = $perm;
796 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
797 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
800 return $allowed;
804 * A convenience function that tests has_capability, and displays an error if
805 * the user does not have that capability.
807 * NOTE before Moodle 2.0, this function attempted to make an appropriate
808 * require_login call before checking the capability. This is no longer the case.
809 * You must call require_login (or one of its variants) if you want to check the
810 * user is logged in, before you call this function.
812 * @see has_capability()
814 * @param string $capability the name of the capability to check. For example mod/forum:view
815 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
816 * @param int $userid A user id. By default (null) checks the permissions of the current user.
817 * @param bool $doanything If false, ignore effect of admin role assignment
818 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
819 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
820 * @return void terminates with an error if the user does not have the given capability.
822 function require_capability($capability, context $context, $userid = null, $doanything = true,
823 $errormessage = 'nopermissions', $stringfile = '') {
824 if (!has_capability($capability, $context, $userid, $doanything)) {
825 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
830 * Return a nested array showing all role assignments for the user.
831 * [ra] => [contextpath][roleid] = roleid
833 * @access private
834 * @param int $userid - the id of the user
835 * @return array access info array
837 function get_user_roles_sitewide_accessdata($userid) {
838 global $CFG, $DB;
840 $accessdata = get_empty_accessdata();
842 // start with the default role
843 if (!empty($CFG->defaultuserroleid)) {
844 $syscontext = context_system::instance();
845 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
848 // load the "default frontpage role"
849 if (!empty($CFG->defaultfrontpageroleid)) {
850 $frontpagecontext = context_course::instance(get_site()->id);
851 if ($frontpagecontext->path) {
852 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
856 // Preload every assigned role.
857 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
858 FROM {role_assignments} ra
859 JOIN {context} ctx ON ctx.id = ra.contextid
860 WHERE ra.userid = :userid";
862 $rs = $DB->get_recordset_sql($sql, array('userid' => $userid));
864 foreach ($rs as $ra) {
865 // RAs leafs are arrays to support multi-role assignments...
866 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
869 $rs->close();
871 return $accessdata;
875 * Returns empty accessdata structure.
877 * @access private
878 * @return array empt accessdata
880 function get_empty_accessdata() {
881 $accessdata = array(); // named list
882 $accessdata['ra'] = array();
883 $accessdata['time'] = time();
884 $accessdata['rsw'] = array();
886 return $accessdata;
890 * Get accessdata for a given user.
892 * @access private
893 * @param int $userid
894 * @param bool $preloadonly true means do not return access array
895 * @return array accessdata
897 function get_user_accessdata($userid, $preloadonly=false) {
898 global $CFG, $ACCESSLIB_PRIVATE, $USER;
900 if (isset($USER->access)) {
901 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->access;
904 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
905 if (empty($userid)) {
906 if (!empty($CFG->notloggedinroleid)) {
907 $accessdata = get_role_access($CFG->notloggedinroleid);
908 } else {
909 // weird
910 return get_empty_accessdata();
913 } else if (isguestuser($userid)) {
914 if ($guestrole = get_guest_role()) {
915 $accessdata = get_role_access($guestrole->id);
916 } else {
917 //weird
918 return get_empty_accessdata();
921 } else {
922 // Includes default role and frontpage role.
923 $accessdata = get_user_roles_sitewide_accessdata($userid);
926 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
929 if ($preloadonly) {
930 return;
931 } else {
932 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
937 * A convenience function to completely load all the capabilities
938 * for the current user. It is called from has_capability() and functions change permissions.
940 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
941 * @see check_enrolment_plugins()
943 * @access private
944 * @return void
946 function load_all_capabilities() {
947 global $USER;
949 // roles not installed yet - we are in the middle of installation
950 if (during_initial_install()) {
951 return;
954 if (!isset($USER->id)) {
955 // this should not happen
956 $USER->id = 0;
959 unset($USER->access);
960 $USER->access = get_user_accessdata($USER->id);
962 // Clear to force a refresh
963 unset($USER->mycourses);
965 // init/reset internal enrol caches - active course enrolments and temp access
966 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
970 * A convenience function to completely reload all the capabilities
971 * for the current user when roles have been updated in a relevant
972 * context -- but PRESERVING switchroles and loginas.
973 * This function resets all accesslib and context caches.
975 * That is - completely transparent to the user.
977 * Note: reloads $USER->access completely.
979 * @access private
980 * @return void
982 function reload_all_capabilities() {
983 global $USER, $DB, $ACCESSLIB_PRIVATE;
985 // copy switchroles
986 $sw = array();
987 if (!empty($USER->access['rsw'])) {
988 $sw = $USER->access['rsw'];
991 accesslib_clear_all_caches(true);
992 unset($USER->access);
993 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
995 load_all_capabilities();
997 foreach ($sw as $path => $roleid) {
998 if ($record = $DB->get_record('context', array('path'=>$path))) {
999 $context = context::instance_by_id($record->id);
1000 role_switch($roleid, $context);
1006 * Adds a temp role to current USER->access array.
1008 * Useful for the "temporary guest" access we grant to logged-in users.
1009 * This is useful for enrol plugins only.
1011 * @since Moodle 2.2
1012 * @param context_course $coursecontext
1013 * @param int $roleid
1014 * @return void
1016 function load_temp_course_role(context_course $coursecontext, $roleid) {
1017 global $USER, $SITE;
1019 if (empty($roleid)) {
1020 debugging('invalid role specified in load_temp_course_role()');
1021 return;
1024 if ($coursecontext->instanceid == $SITE->id) {
1025 debugging('Can not use temp roles on the frontpage');
1026 return;
1029 if (!isset($USER->access)) {
1030 load_all_capabilities();
1033 $coursecontext->reload_if_dirty();
1035 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1036 return;
1039 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1043 * Removes any extra guest roles from current USER->access array.
1044 * This is useful for enrol plugins only.
1046 * @since Moodle 2.2
1047 * @param context_course $coursecontext
1048 * @return void
1050 function remove_temp_course_roles(context_course $coursecontext) {
1051 global $DB, $USER, $SITE;
1053 if ($coursecontext->instanceid == $SITE->id) {
1054 debugging('Can not use temp roles on the frontpage');
1055 return;
1058 if (empty($USER->access['ra'][$coursecontext->path])) {
1059 //no roles here, weird
1060 return;
1063 $sql = "SELECT DISTINCT ra.roleid AS id
1064 FROM {role_assignments} ra
1065 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1066 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1068 $USER->access['ra'][$coursecontext->path] = array();
1069 foreach($ras as $r) {
1070 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1075 * Returns array of all role archetypes.
1077 * @return array
1079 function get_role_archetypes() {
1080 return array(
1081 'manager' => 'manager',
1082 'coursecreator' => 'coursecreator',
1083 'editingteacher' => 'editingteacher',
1084 'teacher' => 'teacher',
1085 'student' => 'student',
1086 'guest' => 'guest',
1087 'user' => 'user',
1088 'frontpage' => 'frontpage'
1093 * Assign the defaults found in this capability definition to roles that have
1094 * the corresponding legacy capabilities assigned to them.
1096 * @param string $capability
1097 * @param array $legacyperms an array in the format (example):
1098 * 'guest' => CAP_PREVENT,
1099 * 'student' => CAP_ALLOW,
1100 * 'teacher' => CAP_ALLOW,
1101 * 'editingteacher' => CAP_ALLOW,
1102 * 'coursecreator' => CAP_ALLOW,
1103 * 'manager' => CAP_ALLOW
1104 * @return boolean success or failure.
1106 function assign_legacy_capabilities($capability, $legacyperms) {
1108 $archetypes = get_role_archetypes();
1110 foreach ($legacyperms as $type => $perm) {
1112 $systemcontext = context_system::instance();
1113 if ($type === 'admin') {
1114 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1115 $type = 'manager';
1118 if (!array_key_exists($type, $archetypes)) {
1119 print_error('invalidlegacy', '', '', $type);
1122 if ($roles = get_archetype_roles($type)) {
1123 foreach ($roles as $role) {
1124 // Assign a site level capability.
1125 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1126 return false;
1131 return true;
1135 * Verify capability risks.
1137 * @param stdClass $capability a capability - a row from the capabilities table.
1138 * @return boolean whether this capability is safe - that is, whether people with the
1139 * safeoverrides capability should be allowed to change it.
1141 function is_safe_capability($capability) {
1142 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1146 * Get the local override (if any) for a given capability in a role in a context
1148 * @param int $roleid
1149 * @param int $contextid
1150 * @param string $capability
1151 * @return stdClass local capability override
1153 function get_local_override($roleid, $contextid, $capability) {
1154 global $DB;
1155 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1159 * Returns context instance plus related course and cm instances
1161 * @param int $contextid
1162 * @return array of ($context, $course, $cm)
1164 function get_context_info_array($contextid) {
1165 global $DB;
1167 $context = context::instance_by_id($contextid, MUST_EXIST);
1168 $course = null;
1169 $cm = null;
1171 if ($context->contextlevel == CONTEXT_COURSE) {
1172 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1174 } else if ($context->contextlevel == CONTEXT_MODULE) {
1175 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1176 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1178 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1179 $parent = $context->get_parent_context();
1181 if ($parent->contextlevel == CONTEXT_COURSE) {
1182 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1183 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1184 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1185 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1189 return array($context, $course, $cm);
1193 * Function that creates a role
1195 * @param string $name role name
1196 * @param string $shortname role short name
1197 * @param string $description role description
1198 * @param string $archetype
1199 * @return int id or dml_exception
1201 function create_role($name, $shortname, $description, $archetype = '') {
1202 global $DB;
1204 if (strpos($archetype, 'moodle/legacy:') !== false) {
1205 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1208 // verify role archetype actually exists
1209 $archetypes = get_role_archetypes();
1210 if (empty($archetypes[$archetype])) {
1211 $archetype = '';
1214 // Insert the role record.
1215 $role = new stdClass();
1216 $role->name = $name;
1217 $role->shortname = $shortname;
1218 $role->description = $description;
1219 $role->archetype = $archetype;
1221 //find free sortorder number
1222 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1223 if (empty($role->sortorder)) {
1224 $role->sortorder = 1;
1226 $id = $DB->insert_record('role', $role);
1228 return $id;
1232 * Function that deletes a role and cleanups up after it
1234 * @param int $roleid id of role to delete
1235 * @return bool always true
1237 function delete_role($roleid) {
1238 global $DB;
1240 // first unssign all users
1241 role_unassign_all(array('roleid'=>$roleid));
1243 // cleanup all references to this role, ignore errors
1244 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1245 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1246 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1247 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1248 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1249 $DB->delete_records('role_names', array('roleid'=>$roleid));
1250 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1252 // Get role record before it's deleted.
1253 $role = $DB->get_record('role', array('id'=>$roleid));
1255 // Finally delete the role itself.
1256 $DB->delete_records('role', array('id'=>$roleid));
1258 // Trigger event.
1259 $event = \core\event\role_deleted::create(
1260 array(
1261 'context' => context_system::instance(),
1262 'objectid' => $roleid,
1263 'other' =>
1264 array(
1265 'shortname' => $role->shortname,
1266 'description' => $role->description,
1267 'archetype' => $role->archetype
1271 $event->add_record_snapshot('role', $role);
1272 $event->trigger();
1274 // Reset any cache of this role, including MUC.
1275 accesslib_clear_role_cache($roleid);
1277 return true;
1281 * Function to write context specific overrides, or default capabilities.
1283 * NOTE: use $context->mark_dirty() after this
1285 * @param string $capability string name
1286 * @param int $permission CAP_ constants
1287 * @param int $roleid role id
1288 * @param int|context $contextid context id
1289 * @param bool $overwrite
1290 * @return bool always true or exception
1292 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1293 global $USER, $DB;
1295 if ($contextid instanceof context) {
1296 $context = $contextid;
1297 } else {
1298 $context = context::instance_by_id($contextid);
1301 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1302 unassign_capability($capability, $roleid, $context->id);
1303 return true;
1306 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1308 if ($existing and !$overwrite) { // We want to keep whatever is there already
1309 return true;
1312 $cap = new stdClass();
1313 $cap->contextid = $context->id;
1314 $cap->roleid = $roleid;
1315 $cap->capability = $capability;
1316 $cap->permission = $permission;
1317 $cap->timemodified = time();
1318 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1320 if ($existing) {
1321 $cap->id = $existing->id;
1322 $DB->update_record('role_capabilities', $cap);
1323 } else {
1324 if ($DB->record_exists('context', array('id'=>$context->id))) {
1325 $DB->insert_record('role_capabilities', $cap);
1329 // Reset any cache of this role, including MUC.
1330 accesslib_clear_role_cache($roleid);
1332 return true;
1336 * Unassign a capability from a role.
1338 * NOTE: use $context->mark_dirty() after this
1340 * @param string $capability the name of the capability
1341 * @param int $roleid the role id
1342 * @param int|context $contextid null means all contexts
1343 * @return boolean true or exception
1345 function unassign_capability($capability, $roleid, $contextid = null) {
1346 global $DB;
1348 if (!empty($contextid)) {
1349 if ($contextid instanceof context) {
1350 $context = $contextid;
1351 } else {
1352 $context = context::instance_by_id($contextid);
1354 // delete from context rel, if this is the last override in this context
1355 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1356 } else {
1357 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1360 // Reset any cache of this role, including MUC.
1361 accesslib_clear_role_cache($roleid);
1363 return true;
1367 * Get the roles that have a given capability assigned to it
1369 * This function does not resolve the actual permission of the capability.
1370 * It just checks for permissions and overrides.
1371 * Use get_roles_with_cap_in_context() if resolution is required.
1373 * @param string $capability capability name (string)
1374 * @param string $permission optional, the permission defined for this capability
1375 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1376 * @param stdClass $context null means any
1377 * @return array of role records
1379 function get_roles_with_capability($capability, $permission = null, $context = null) {
1380 global $DB;
1382 if ($context) {
1383 $contexts = $context->get_parent_context_ids(true);
1384 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1385 $contextsql = "AND rc.contextid $insql";
1386 } else {
1387 $params = array();
1388 $contextsql = '';
1391 if ($permission) {
1392 $permissionsql = " AND rc.permission = :permission";
1393 $params['permission'] = $permission;
1394 } else {
1395 $permissionsql = '';
1398 $sql = "SELECT r.*
1399 FROM {role} r
1400 WHERE r.id IN (SELECT rc.roleid
1401 FROM {role_capabilities} rc
1402 WHERE rc.capability = :capname
1403 $contextsql
1404 $permissionsql)";
1405 $params['capname'] = $capability;
1408 return $DB->get_records_sql($sql, $params);
1412 * This function makes a role-assignment (a role for a user in a particular context)
1414 * @param int $roleid the role of the id
1415 * @param int $userid userid
1416 * @param int|context $contextid id of the context
1417 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1418 * @param int $itemid id of enrolment/auth plugin
1419 * @param string $timemodified defaults to current time
1420 * @return int new/existing id of the assignment
1422 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1423 global $USER, $DB;
1425 // first of all detect if somebody is using old style parameters
1426 if ($contextid === 0 or is_numeric($component)) {
1427 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1430 // now validate all parameters
1431 if (empty($roleid)) {
1432 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1435 if (empty($userid)) {
1436 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1439 if ($itemid) {
1440 if (strpos($component, '_') === false) {
1441 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1443 } else {
1444 $itemid = 0;
1445 if ($component !== '' and strpos($component, '_') === false) {
1446 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1450 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1451 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1454 if ($contextid instanceof context) {
1455 $context = $contextid;
1456 } else {
1457 $context = context::instance_by_id($contextid, MUST_EXIST);
1460 if (!$timemodified) {
1461 $timemodified = time();
1464 // Check for existing entry
1465 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1467 if ($ras) {
1468 // role already assigned - this should not happen
1469 if (count($ras) > 1) {
1470 // very weird - remove all duplicates!
1471 $ra = array_shift($ras);
1472 foreach ($ras as $r) {
1473 $DB->delete_records('role_assignments', array('id'=>$r->id));
1475 } else {
1476 $ra = reset($ras);
1479 // actually there is no need to update, reset anything or trigger any event, so just return
1480 return $ra->id;
1483 // Create a new entry
1484 $ra = new stdClass();
1485 $ra->roleid = $roleid;
1486 $ra->contextid = $context->id;
1487 $ra->userid = $userid;
1488 $ra->component = $component;
1489 $ra->itemid = $itemid;
1490 $ra->timemodified = $timemodified;
1491 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1492 $ra->sortorder = 0;
1494 $ra->id = $DB->insert_record('role_assignments', $ra);
1496 // mark context as dirty - again expensive, but needed
1497 $context->mark_dirty();
1499 if (!empty($USER->id) && $USER->id == $userid) {
1500 // If the user is the current user, then do full reload of capabilities too.
1501 reload_all_capabilities();
1504 core_course_category::role_assignment_changed($roleid, $context);
1506 $event = \core\event\role_assigned::create(array(
1507 'context' => $context,
1508 'objectid' => $ra->roleid,
1509 'relateduserid' => $ra->userid,
1510 'other' => array(
1511 'id' => $ra->id,
1512 'component' => $ra->component,
1513 'itemid' => $ra->itemid
1516 $event->add_record_snapshot('role_assignments', $ra);
1517 $event->trigger();
1519 return $ra->id;
1523 * Removes one role assignment
1525 * @param int $roleid
1526 * @param int $userid
1527 * @param int $contextid
1528 * @param string $component
1529 * @param int $itemid
1530 * @return void
1532 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1533 // first make sure the params make sense
1534 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1535 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1538 if ($itemid) {
1539 if (strpos($component, '_') === false) {
1540 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1542 } else {
1543 $itemid = 0;
1544 if ($component !== '' and strpos($component, '_') === false) {
1545 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1549 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1553 * Removes multiple role assignments, parameters may contain:
1554 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1556 * @param array $params role assignment parameters
1557 * @param bool $subcontexts unassign in subcontexts too
1558 * @param bool $includemanual include manual role assignments too
1559 * @return void
1561 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1562 global $USER, $CFG, $DB;
1564 if (!$params) {
1565 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1568 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1569 foreach ($params as $key=>$value) {
1570 if (!in_array($key, $allowed)) {
1571 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1575 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1576 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1579 if ($includemanual) {
1580 if (!isset($params['component']) or $params['component'] === '') {
1581 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1585 if ($subcontexts) {
1586 if (empty($params['contextid'])) {
1587 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1591 $ras = $DB->get_records('role_assignments', $params);
1592 foreach($ras as $ra) {
1593 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1594 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1595 // this is a bit expensive but necessary
1596 $context->mark_dirty();
1597 // If the user is the current user, then do full reload of capabilities too.
1598 if (!empty($USER->id) && $USER->id == $ra->userid) {
1599 reload_all_capabilities();
1601 $event = \core\event\role_unassigned::create(array(
1602 'context' => $context,
1603 'objectid' => $ra->roleid,
1604 'relateduserid' => $ra->userid,
1605 'other' => array(
1606 'id' => $ra->id,
1607 'component' => $ra->component,
1608 'itemid' => $ra->itemid
1611 $event->add_record_snapshot('role_assignments', $ra);
1612 $event->trigger();
1613 core_course_category::role_assignment_changed($ra->roleid, $context);
1616 unset($ras);
1618 // process subcontexts
1619 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1620 if ($params['contextid'] instanceof context) {
1621 $context = $params['contextid'];
1622 } else {
1623 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1626 if ($context) {
1627 $contexts = $context->get_child_contexts();
1628 $mparams = $params;
1629 foreach($contexts as $context) {
1630 $mparams['contextid'] = $context->id;
1631 $ras = $DB->get_records('role_assignments', $mparams);
1632 foreach($ras as $ra) {
1633 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1634 // this is a bit expensive but necessary
1635 $context->mark_dirty();
1636 // If the user is the current user, then do full reload of capabilities too.
1637 if (!empty($USER->id) && $USER->id == $ra->userid) {
1638 reload_all_capabilities();
1640 $event = \core\event\role_unassigned::create(
1641 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1642 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1643 $event->add_record_snapshot('role_assignments', $ra);
1644 $event->trigger();
1645 core_course_category::role_assignment_changed($ra->roleid, $context);
1651 // do this once more for all manual role assignments
1652 if ($includemanual) {
1653 $params['component'] = '';
1654 role_unassign_all($params, $subcontexts, false);
1659 * Determines if a user is currently logged in
1661 * @category access
1663 * @return bool
1665 function isloggedin() {
1666 global $USER;
1668 return (!empty($USER->id));
1672 * Determines if a user is logged in as real guest user with username 'guest'.
1674 * @category access
1676 * @param int|object $user mixed user object or id, $USER if not specified
1677 * @return bool true if user is the real guest user, false if not logged in or other user
1679 function isguestuser($user = null) {
1680 global $USER, $DB, $CFG;
1682 // make sure we have the user id cached in config table, because we are going to use it a lot
1683 if (empty($CFG->siteguest)) {
1684 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1685 // guest does not exist yet, weird
1686 return false;
1688 set_config('siteguest', $guestid);
1690 if ($user === null) {
1691 $user = $USER;
1694 if ($user === null) {
1695 // happens when setting the $USER
1696 return false;
1698 } else if (is_numeric($user)) {
1699 return ($CFG->siteguest == $user);
1701 } else if (is_object($user)) {
1702 if (empty($user->id)) {
1703 return false; // not logged in means is not be guest
1704 } else {
1705 return ($CFG->siteguest == $user->id);
1708 } else {
1709 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1714 * Does user have a (temporary or real) guest access to course?
1716 * @category access
1718 * @param context $context
1719 * @param stdClass|int $user
1720 * @return bool
1722 function is_guest(context $context, $user = null) {
1723 global $USER;
1725 // first find the course context
1726 $coursecontext = $context->get_course_context();
1728 // make sure there is a real user specified
1729 if ($user === null) {
1730 $userid = isset($USER->id) ? $USER->id : 0;
1731 } else {
1732 $userid = is_object($user) ? $user->id : $user;
1735 if (isguestuser($userid)) {
1736 // can not inspect or be enrolled
1737 return true;
1740 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1741 // viewing users appear out of nowhere, they are neither guests nor participants
1742 return false;
1745 // consider only real active enrolments here
1746 if (is_enrolled($coursecontext, $user, '', true)) {
1747 return false;
1750 return true;
1754 * Returns true if the user has moodle/course:view capability in the course,
1755 * this is intended for admins, managers (aka small admins), inspectors, etc.
1757 * @category access
1759 * @param context $context
1760 * @param int|stdClass $user if null $USER is used
1761 * @param string $withcapability extra capability name
1762 * @return bool
1764 function is_viewing(context $context, $user = null, $withcapability = '') {
1765 // first find the course context
1766 $coursecontext = $context->get_course_context();
1768 if (isguestuser($user)) {
1769 // can not inspect
1770 return false;
1773 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1774 // admins are allowed to inspect courses
1775 return false;
1778 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1779 // site admins always have the capability, but the enrolment above blocks
1780 return false;
1783 return true;
1787 * Returns true if the user is able to access the course.
1789 * This function is in no way, shape, or form a substitute for require_login.
1790 * It should only be used in circumstances where it is not possible to call require_login
1791 * such as the navigation.
1793 * This function checks many of the methods of access to a course such as the view
1794 * capability, enrollments, and guest access. It also makes use of the cache
1795 * generated by require_login for guest access.
1797 * The flags within the $USER object that are used here should NEVER be used outside
1798 * of this function can_access_course and require_login. Doing so WILL break future
1799 * versions.
1801 * @param stdClass $course record
1802 * @param stdClass|int|null $user user record or id, current user if null
1803 * @param string $withcapability Check for this capability as well.
1804 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1805 * @return boolean Returns true if the user is able to access the course
1807 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
1808 global $DB, $USER;
1810 // this function originally accepted $coursecontext parameter
1811 if ($course instanceof context) {
1812 if ($course instanceof context_course) {
1813 debugging('deprecated context parameter, please use $course record');
1814 $coursecontext = $course;
1815 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
1816 } else {
1817 debugging('Invalid context parameter, please use $course record');
1818 return false;
1820 } else {
1821 $coursecontext = context_course::instance($course->id);
1824 if (!isset($USER->id)) {
1825 // should never happen
1826 $USER->id = 0;
1827 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
1830 // make sure there is a user specified
1831 if ($user === null) {
1832 $userid = $USER->id;
1833 } else {
1834 $userid = is_object($user) ? $user->id : $user;
1836 unset($user);
1838 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
1839 return false;
1842 if ($userid == $USER->id) {
1843 if (!empty($USER->access['rsw'][$coursecontext->path])) {
1844 // the fact that somebody switched role means they can access the course no matter to what role they switched
1845 return true;
1849 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
1850 return false;
1853 if (is_viewing($coursecontext, $userid)) {
1854 return true;
1857 if ($userid != $USER->id) {
1858 // for performance reasons we do not verify temporary guest access for other users, sorry...
1859 return is_enrolled($coursecontext, $userid, '', $onlyactive);
1862 // === from here we deal only with $USER ===
1864 $coursecontext->reload_if_dirty();
1866 if (isset($USER->enrol['enrolled'][$course->id])) {
1867 if ($USER->enrol['enrolled'][$course->id] > time()) {
1868 return true;
1871 if (isset($USER->enrol['tempguest'][$course->id])) {
1872 if ($USER->enrol['tempguest'][$course->id] > time()) {
1873 return true;
1877 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
1878 return true;
1881 // if not enrolled try to gain temporary guest access
1882 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
1883 $enrols = enrol_get_plugins(true);
1884 foreach($instances as $instance) {
1885 if (!isset($enrols[$instance->enrol])) {
1886 continue;
1888 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
1889 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
1890 if ($until !== false and $until > time()) {
1891 $USER->enrol['tempguest'][$course->id] = $until;
1892 return true;
1895 if (isset($USER->enrol['tempguest'][$course->id])) {
1896 unset($USER->enrol['tempguest'][$course->id]);
1897 remove_temp_course_roles($coursecontext);
1900 return false;
1904 * Loads the capability definitions for the component (from file).
1906 * Loads the capability definitions for the component (from file). If no
1907 * capabilities are defined for the component, we simply return an empty array.
1909 * @access private
1910 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
1911 * @return array array of capabilities
1913 function load_capability_def($component) {
1914 $defpath = core_component::get_component_directory($component).'/db/access.php';
1916 $capabilities = array();
1917 if (file_exists($defpath)) {
1918 require($defpath);
1919 if (!empty(${$component.'_capabilities'})) {
1920 // BC capability array name
1921 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
1922 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
1923 $capabilities = ${$component.'_capabilities'};
1927 return $capabilities;
1931 * Gets the capabilities that have been cached in the database for this component.
1933 * @access private
1934 * @param string $component - examples: 'moodle', 'mod_forum'
1935 * @return array array of capabilities
1937 function get_cached_capabilities($component = 'moodle') {
1938 global $DB;
1939 $caps = get_all_capabilities();
1940 $componentcaps = array();
1941 foreach ($caps as $cap) {
1942 if ($cap['component'] == $component) {
1943 $componentcaps[] = (object) $cap;
1946 return $componentcaps;
1950 * Returns default capabilities for given role archetype.
1952 * @param string $archetype role archetype
1953 * @return array
1955 function get_default_capabilities($archetype) {
1956 global $DB;
1958 if (!$archetype) {
1959 return array();
1962 $alldefs = array();
1963 $defaults = array();
1964 $components = array();
1965 $allcaps = get_all_capabilities();
1967 foreach ($allcaps as $cap) {
1968 if (!in_array($cap['component'], $components)) {
1969 $components[] = $cap['component'];
1970 $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
1973 foreach($alldefs as $name=>$def) {
1974 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
1975 if (isset($def['archetypes'])) {
1976 if (isset($def['archetypes'][$archetype])) {
1977 $defaults[$name] = $def['archetypes'][$archetype];
1979 // 'legacy' is for backward compatibility with 1.9 access.php
1980 } else {
1981 if (isset($def['legacy'][$archetype])) {
1982 $defaults[$name] = $def['legacy'][$archetype];
1987 return $defaults;
1991 * Return default roles that can be assigned, overridden or switched
1992 * by give role archetype.
1994 * @param string $type assign|override|switch|view
1995 * @param string $archetype
1996 * @return array of role ids
1998 function get_default_role_archetype_allows($type, $archetype) {
1999 global $DB;
2001 if (empty($archetype)) {
2002 return array();
2005 $roles = $DB->get_records('role');
2006 $archetypemap = array();
2007 foreach ($roles as $role) {
2008 if ($role->archetype) {
2009 $archetypemap[$role->archetype][$role->id] = $role->id;
2013 $defaults = array(
2014 'assign' => array(
2015 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2016 'coursecreator' => array(),
2017 'editingteacher' => array('teacher', 'student'),
2018 'teacher' => array(),
2019 'student' => array(),
2020 'guest' => array(),
2021 'user' => array(),
2022 'frontpage' => array(),
2024 'override' => array(
2025 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2026 'coursecreator' => array(),
2027 'editingteacher' => array('teacher', 'student', 'guest'),
2028 'teacher' => array(),
2029 'student' => array(),
2030 'guest' => array(),
2031 'user' => array(),
2032 'frontpage' => array(),
2034 'switch' => array(
2035 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2036 'coursecreator' => array(),
2037 'editingteacher' => array('teacher', 'student', 'guest'),
2038 'teacher' => array('student', 'guest'),
2039 'student' => array(),
2040 'guest' => array(),
2041 'user' => array(),
2042 'frontpage' => array(),
2044 'view' => array(
2045 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2046 'coursecreator' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2047 'editingteacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2048 'teacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2049 'student' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2050 'guest' => array(),
2051 'user' => array(),
2052 'frontpage' => array(),
2056 if (!isset($defaults[$type][$archetype])) {
2057 debugging("Unknown type '$type'' or archetype '$archetype''");
2058 return array();
2061 $return = array();
2062 foreach ($defaults[$type][$archetype] as $at) {
2063 if (isset($archetypemap[$at])) {
2064 foreach ($archetypemap[$at] as $roleid) {
2065 $return[$roleid] = $roleid;
2070 return $return;
2074 * Reset role capabilities to default according to selected role archetype.
2075 * If no archetype selected, removes all capabilities.
2077 * This applies to capabilities that are assigned to the role (that you could
2078 * edit in the 'define roles' interface), and not to any capability overrides
2079 * in different locations.
2081 * @param int $roleid ID of role to reset capabilities for
2083 function reset_role_capabilities($roleid) {
2084 global $DB;
2086 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2087 $defaultcaps = get_default_capabilities($role->archetype);
2089 $systemcontext = context_system::instance();
2091 $DB->delete_records('role_capabilities',
2092 array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2094 foreach($defaultcaps as $cap=>$permission) {
2095 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2098 // Reset any cache of this role, including MUC.
2099 accesslib_clear_role_cache($roleid);
2101 // Mark the system context dirty.
2102 context_system::instance()->mark_dirty();
2106 * Updates the capabilities table with the component capability definitions.
2107 * If no parameters are given, the function updates the core moodle
2108 * capabilities.
2110 * Note that the absence of the db/access.php capabilities definition file
2111 * will cause any stored capabilities for the component to be removed from
2112 * the database.
2114 * @access private
2115 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2116 * @return boolean true if success, exception in case of any problems
2118 function update_capabilities($component = 'moodle') {
2119 global $DB, $OUTPUT;
2121 $storedcaps = array();
2123 $filecaps = load_capability_def($component);
2124 foreach($filecaps as $capname=>$unused) {
2125 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2126 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2130 // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2131 // So ensure our updating is based on fresh data.
2132 cache::make('core', 'capabilities')->delete('core_capabilities');
2134 $cachedcaps = get_cached_capabilities($component);
2135 if ($cachedcaps) {
2136 foreach ($cachedcaps as $cachedcap) {
2137 array_push($storedcaps, $cachedcap->name);
2138 // update risk bitmasks and context levels in existing capabilities if needed
2139 if (array_key_exists($cachedcap->name, $filecaps)) {
2140 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2141 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2143 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2144 $updatecap = new stdClass();
2145 $updatecap->id = $cachedcap->id;
2146 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2147 $DB->update_record('capabilities', $updatecap);
2149 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2150 $updatecap = new stdClass();
2151 $updatecap->id = $cachedcap->id;
2152 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2153 $DB->update_record('capabilities', $updatecap);
2156 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2157 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2159 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2160 $updatecap = new stdClass();
2161 $updatecap->id = $cachedcap->id;
2162 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2163 $DB->update_record('capabilities', $updatecap);
2169 // Flush the cached again, as we have changed DB.
2170 cache::make('core', 'capabilities')->delete('core_capabilities');
2172 // Are there new capabilities in the file definition?
2173 $newcaps = array();
2175 foreach ($filecaps as $filecap => $def) {
2176 if (!$storedcaps ||
2177 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2178 if (!array_key_exists('riskbitmask', $def)) {
2179 $def['riskbitmask'] = 0; // no risk if not specified
2181 $newcaps[$filecap] = $def;
2184 // Add new capabilities to the stored definition.
2185 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2186 foreach ($newcaps as $capname => $capdef) {
2187 $capability = new stdClass();
2188 $capability->name = $capname;
2189 $capability->captype = $capdef['captype'];
2190 $capability->contextlevel = $capdef['contextlevel'];
2191 $capability->component = $component;
2192 $capability->riskbitmask = $capdef['riskbitmask'];
2194 $DB->insert_record('capabilities', $capability, false);
2196 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2197 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2198 foreach ($rolecapabilities as $rolecapability){
2199 //assign_capability will update rather than insert if capability exists
2200 if (!assign_capability($capname, $rolecapability->permission,
2201 $rolecapability->roleid, $rolecapability->contextid, true)){
2202 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2206 // we ignore archetype key if we have cloned permissions
2207 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2208 assign_legacy_capabilities($capname, $capdef['archetypes']);
2209 // 'legacy' is for backward compatibility with 1.9 access.php
2210 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2211 assign_legacy_capabilities($capname, $capdef['legacy']);
2214 // Are there any capabilities that have been removed from the file
2215 // definition that we need to delete from the stored capabilities and
2216 // role assignments?
2217 capabilities_cleanup($component, $filecaps);
2219 // reset static caches
2220 accesslib_clear_all_caches(false);
2222 // Flush the cached again, as we have changed DB.
2223 cache::make('core', 'capabilities')->delete('core_capabilities');
2225 return true;
2229 * Deletes cached capabilities that are no longer needed by the component.
2230 * Also unassigns these capabilities from any roles that have them.
2231 * NOTE: this function is called from lib/db/upgrade.php
2233 * @access private
2234 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2235 * @param array $newcapdef array of the new capability definitions that will be
2236 * compared with the cached capabilities
2237 * @return int number of deprecated capabilities that have been removed
2239 function capabilities_cleanup($component, $newcapdef = null) {
2240 global $DB;
2242 $removedcount = 0;
2244 if ($cachedcaps = get_cached_capabilities($component)) {
2245 foreach ($cachedcaps as $cachedcap) {
2246 if (empty($newcapdef) ||
2247 array_key_exists($cachedcap->name, $newcapdef) === false) {
2249 // Remove from capabilities cache.
2250 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2251 $removedcount++;
2252 // Delete from roles.
2253 if ($roles = get_roles_with_capability($cachedcap->name)) {
2254 foreach($roles as $role) {
2255 if (!unassign_capability($cachedcap->name, $role->id)) {
2256 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2260 } // End if.
2263 if ($removedcount) {
2264 cache::make('core', 'capabilities')->delete('core_capabilities');
2266 return $removedcount;
2270 * Returns an array of all the known types of risk
2271 * The array keys can be used, for example as CSS class names, or in calls to
2272 * print_risk_icon. The values are the corresponding RISK_ constants.
2274 * @return array all the known types of risk.
2276 function get_all_risks() {
2277 return array(
2278 'riskmanagetrust' => RISK_MANAGETRUST,
2279 'riskconfig' => RISK_CONFIG,
2280 'riskxss' => RISK_XSS,
2281 'riskpersonal' => RISK_PERSONAL,
2282 'riskspam' => RISK_SPAM,
2283 'riskdataloss' => RISK_DATALOSS,
2288 * Return a link to moodle docs for a given capability name
2290 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2291 * @return string the human-readable capability name as a link to Moodle Docs.
2293 function get_capability_docs_link($capability) {
2294 $url = get_docs_url('Capabilities/' . $capability->name);
2295 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2299 * This function pulls out all the resolved capabilities (overrides and
2300 * defaults) of a role used in capability overrides in contexts at a given
2301 * context.
2303 * @param int $roleid
2304 * @param context $context
2305 * @param string $cap capability, optional, defaults to ''
2306 * @return array Array of capabilities
2308 function role_context_capabilities($roleid, context $context, $cap = '') {
2309 global $DB;
2311 $contexts = $context->get_parent_context_ids(true);
2312 $contexts = '('.implode(',', $contexts).')';
2314 $params = array($roleid);
2316 if ($cap) {
2317 $search = " AND rc.capability = ? ";
2318 $params[] = $cap;
2319 } else {
2320 $search = '';
2323 $sql = "SELECT rc.*
2324 FROM {role_capabilities} rc, {context} c
2325 WHERE rc.contextid in $contexts
2326 AND rc.roleid = ?
2327 AND rc.contextid = c.id $search
2328 ORDER BY c.contextlevel DESC, rc.capability DESC";
2330 $capabilities = array();
2332 if ($records = $DB->get_records_sql($sql, $params)) {
2333 // We are traversing via reverse order.
2334 foreach ($records as $record) {
2335 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2336 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2337 $capabilities[$record->capability] = $record->permission;
2341 return $capabilities;
2345 * Constructs array with contextids as first parameter and context paths,
2346 * in both cases bottom top including self.
2348 * @access private
2349 * @param context $context
2350 * @return array
2352 function get_context_info_list(context $context) {
2353 $contextids = explode('/', ltrim($context->path, '/'));
2354 $contextpaths = array();
2355 $contextids2 = $contextids;
2356 while ($contextids2) {
2357 $contextpaths[] = '/' . implode('/', $contextids2);
2358 array_pop($contextids2);
2360 return array($contextids, $contextpaths);
2364 * Check if context is the front page context or a context inside it
2366 * Returns true if this context is the front page context, or a context inside it,
2367 * otherwise false.
2369 * @param context $context a context object.
2370 * @return bool
2372 function is_inside_frontpage(context $context) {
2373 $frontpagecontext = context_course::instance(SITEID);
2374 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2378 * Returns capability information (cached)
2380 * @param string $capabilityname
2381 * @return stdClass or null if capability not found
2383 function get_capability_info($capabilityname) {
2384 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2386 $caps = get_all_capabilities();
2388 if (!isset($caps[$capabilityname])) {
2389 return null;
2392 return (object) $caps[$capabilityname];
2396 * Returns all capabilitiy records, preferably from MUC and not database.
2398 * @return array All capability records indexed by capability name
2400 function get_all_capabilities() {
2401 global $DB;
2402 $cache = cache::make('core', 'capabilities');
2403 if (!$allcaps = $cache->get('core_capabilities')) {
2404 $rs = $DB->get_recordset('capabilities');
2405 $allcaps = array();
2406 foreach ($rs as $capability) {
2407 $capability->riskbitmask = (int) $capability->riskbitmask;
2408 $allcaps[$capability->name] = (array) $capability;
2410 $rs->close();
2411 $cache->set('core_capabilities', $allcaps);
2413 return $allcaps;
2417 * Returns the human-readable, translated version of the capability.
2418 * Basically a big switch statement.
2420 * @param string $capabilityname e.g. mod/choice:readresponses
2421 * @return string
2423 function get_capability_string($capabilityname) {
2425 // Typical capability name is 'plugintype/pluginname:capabilityname'
2426 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2428 if ($type === 'moodle') {
2429 $component = 'core_role';
2430 } else if ($type === 'quizreport') {
2431 //ugly hack!!
2432 $component = 'quiz_'.$name;
2433 } else {
2434 $component = $type.'_'.$name;
2437 $stringname = $name.':'.$capname;
2439 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2440 return get_string($stringname, $component);
2443 $dir = core_component::get_component_directory($component);
2444 if (!file_exists($dir)) {
2445 // plugin broken or does not exist, do not bother with printing of debug message
2446 return $capabilityname.' ???';
2449 // something is wrong in plugin, better print debug
2450 return get_string($stringname, $component);
2454 * This gets the mod/block/course/core etc strings.
2456 * @param string $component
2457 * @param int $contextlevel
2458 * @return string|bool String is success, false if failed
2460 function get_component_string($component, $contextlevel) {
2462 if ($component === 'moodle' or $component === 'core') {
2463 switch ($contextlevel) {
2464 // TODO MDL-46123: this should probably use context level names instead
2465 case CONTEXT_SYSTEM: return get_string('coresystem');
2466 case CONTEXT_USER: return get_string('users');
2467 case CONTEXT_COURSECAT: return get_string('categories');
2468 case CONTEXT_COURSE: return get_string('course');
2469 case CONTEXT_MODULE: return get_string('activities');
2470 case CONTEXT_BLOCK: return get_string('block');
2471 default: print_error('unknowncontext');
2475 list($type, $name) = core_component::normalize_component($component);
2476 $dir = core_component::get_plugin_directory($type, $name);
2477 if (!file_exists($dir)) {
2478 // plugin not installed, bad luck, there is no way to find the name
2479 return $component.' ???';
2482 switch ($type) {
2483 // TODO MDL-46123: this is really hacky and should be improved.
2484 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2485 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2486 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2487 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2488 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2489 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2490 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2491 case 'mod':
2492 if (get_string_manager()->string_exists('pluginname', $component)) {
2493 return get_string('activity').': '.get_string('pluginname', $component);
2494 } else {
2495 return get_string('activity').': '.get_string('modulename', $component);
2497 default: return get_string('pluginname', $component);
2502 * Gets the list of roles assigned to this context and up (parents)
2503 * from the aggregation of:
2504 * a) the list of roles that are visible on user profile page and participants page (profileroles setting) and;
2505 * b) if applicable, those roles that are assigned in the context.
2507 * @param context $context
2508 * @return array
2510 function get_profile_roles(context $context) {
2511 global $CFG, $DB;
2512 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2513 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2514 if (has_capability('moodle/role:assign', $context)) {
2515 $rolesinscope = array_keys(get_all_roles($context));
2516 } else {
2517 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2520 if (empty($rolesinscope)) {
2521 return [];
2524 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2525 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2526 $params = array_merge($params, $cparams);
2528 if ($coursecontext = $context->get_course_context(false)) {
2529 $params['coursecontext'] = $coursecontext->id;
2530 } else {
2531 $params['coursecontext'] = 0;
2534 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2535 FROM {role_assignments} ra, {role} r
2536 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2537 WHERE r.id = ra.roleid
2538 AND ra.contextid $contextlist
2539 AND r.id $rallowed
2540 ORDER BY r.sortorder ASC";
2542 return $DB->get_records_sql($sql, $params);
2546 * Gets the list of roles assigned to this context and up (parents)
2548 * @param context $context
2549 * @param boolean $includeparents, false means without parents.
2550 * @return array
2552 function get_roles_used_in_context(context $context, $includeparents = true) {
2553 global $DB;
2555 if ($includeparents === true) {
2556 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2557 } else {
2558 list($contextlist, $params) = $DB->get_in_or_equal($context->id, SQL_PARAMS_NAMED, 'cl');
2561 if ($coursecontext = $context->get_course_context(false)) {
2562 $params['coursecontext'] = $coursecontext->id;
2563 } else {
2564 $params['coursecontext'] = 0;
2567 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2568 FROM {role_assignments} ra, {role} r
2569 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2570 WHERE r.id = ra.roleid
2571 AND ra.contextid $contextlist
2572 ORDER BY r.sortorder ASC";
2574 return $DB->get_records_sql($sql, $params);
2578 * This function is used to print roles column in user profile page.
2579 * It is using the CFG->profileroles to limit the list to only interesting roles.
2580 * (The permission tab has full details of user role assignments.)
2582 * @param int $userid
2583 * @param int $courseid
2584 * @return string
2586 function get_user_roles_in_course($userid, $courseid) {
2587 global $CFG, $DB;
2588 if ($courseid == SITEID) {
2589 $context = context_system::instance();
2590 } else {
2591 $context = context_course::instance($courseid);
2593 // If the current user can assign roles, then they can see all roles on the profile and participants page,
2594 // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2595 if (has_capability('moodle/role:assign', $context)) {
2596 $rolesinscope = array_keys(get_all_roles($context));
2597 } else {
2598 $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2600 if (empty($rolesinscope)) {
2601 return '';
2604 list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2605 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2606 $params = array_merge($params, $cparams);
2608 if ($coursecontext = $context->get_course_context(false)) {
2609 $params['coursecontext'] = $coursecontext->id;
2610 } else {
2611 $params['coursecontext'] = 0;
2614 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2615 FROM {role_assignments} ra, {role} r
2616 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2617 WHERE r.id = ra.roleid
2618 AND ra.contextid $contextlist
2619 AND r.id $rallowed
2620 AND ra.userid = :userid
2621 ORDER BY r.sortorder ASC";
2622 $params['userid'] = $userid;
2624 $rolestring = '';
2626 if ($roles = $DB->get_records_sql($sql, $params)) {
2627 $viewableroles = get_viewable_roles($context, $userid);
2629 $rolenames = array();
2630 foreach ($roles as $roleid => $unused) {
2631 if (isset($viewableroles[$roleid])) {
2632 $url = new moodle_url('/user/index.php', ['contextid' => $context->id, 'roleid' => $roleid]);
2633 $rolenames[] = '<a href="' . $url . '">' . $viewableroles[$roleid] . '</a>';
2636 $rolestring = implode(',', $rolenames);
2639 return $rolestring;
2643 * Checks if a user can assign users to a particular role in this context
2645 * @param context $context
2646 * @param int $targetroleid - the id of the role you want to assign users to
2647 * @return boolean
2649 function user_can_assign(context $context, $targetroleid) {
2650 global $DB;
2652 // First check to see if the user is a site administrator.
2653 if (is_siteadmin()) {
2654 return true;
2657 // Check if user has override capability.
2658 // If not return false.
2659 if (!has_capability('moodle/role:assign', $context)) {
2660 return false;
2662 // pull out all active roles of this user from this context(or above)
2663 if ($userroles = get_user_roles($context)) {
2664 foreach ($userroles as $userrole) {
2665 // if any in the role_allow_override table, then it's ok
2666 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2667 return true;
2672 return false;
2676 * Returns all site roles in correct sort order.
2678 * Note: this method does not localise role names or descriptions,
2679 * use role_get_names() if you need role names.
2681 * @param context $context optional context for course role name aliases
2682 * @return array of role records with optional coursealias property
2684 function get_all_roles(context $context = null) {
2685 global $DB;
2687 if (!$context or !$coursecontext = $context->get_course_context(false)) {
2688 $coursecontext = null;
2691 if ($coursecontext) {
2692 $sql = "SELECT r.*, rn.name AS coursealias
2693 FROM {role} r
2694 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2695 ORDER BY r.sortorder ASC";
2696 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
2698 } else {
2699 return $DB->get_records('role', array(), 'sortorder ASC');
2704 * Returns roles of a specified archetype
2706 * @param string $archetype
2707 * @return array of full role records
2709 function get_archetype_roles($archetype) {
2710 global $DB;
2711 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2715 * Gets all the user roles assigned in this context, or higher contexts for a list of users.
2717 * If you try using the combination $userids = [], $checkparentcontexts = true then this is likely
2718 * to cause an out-of-memory error on large Moodle sites, so this combination is deprecated and
2719 * outputs a warning, even though it is the default.
2721 * @param context $context
2722 * @param array $userids. An empty list means fetch all role assignments for the context.
2723 * @param bool $checkparentcontexts defaults to true
2724 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2725 * @return array
2727 function get_users_roles(context $context, $userids = [], $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2728 global $DB;
2730 if (!$userids && $checkparentcontexts) {
2731 debugging('Please do not call get_users_roles() with $checkparentcontexts = true ' .
2732 'and $userids array not set. This combination causes large Moodle sites ' .
2733 'with lots of site-wide role assignemnts to run out of memory.', DEBUG_DEVELOPER);
2736 if ($checkparentcontexts) {
2737 $contextids = $context->get_parent_context_ids();
2738 } else {
2739 $contextids = array();
2741 $contextids[] = $context->id;
2743 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
2745 // If userids was passed as an empty array, we fetch all role assignments for the course.
2746 if (empty($userids)) {
2747 $useridlist = ' IS NOT NULL ';
2748 $uparams = [];
2749 } else {
2750 list($useridlist, $uparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'uids');
2753 $sql = "SELECT ra.*, r.name, r.shortname, ra.userid
2754 FROM {role_assignments} ra, {role} r, {context} c
2755 WHERE ra.userid $useridlist
2756 AND ra.roleid = r.id
2757 AND ra.contextid = c.id
2758 AND ra.contextid $contextids
2759 ORDER BY $order";
2761 $all = $DB->get_records_sql($sql , array_merge($params, $uparams));
2763 // Return results grouped by userid.
2764 $result = [];
2765 foreach ($all as $id => $record) {
2766 if (!isset($result[$record->userid])) {
2767 $result[$record->userid] = [];
2769 $result[$record->userid][$record->id] = $record;
2772 // Make sure all requested users are included in the result, even if they had no role assignments.
2773 foreach ($userids as $id) {
2774 if (!isset($result[$id])) {
2775 $result[$id] = [];
2779 return $result;
2784 * Gets all the user roles assigned in this context, or higher contexts
2785 * this is mainly used when checking if a user can assign a role, or overriding a role
2786 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2787 * allow_override tables
2789 * @param context $context
2790 * @param int $userid
2791 * @param bool $checkparentcontexts defaults to true
2792 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2793 * @return array
2795 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2796 global $USER, $DB;
2798 if (empty($userid)) {
2799 if (empty($USER->id)) {
2800 return array();
2802 $userid = $USER->id;
2805 if ($checkparentcontexts) {
2806 $contextids = $context->get_parent_context_ids();
2807 } else {
2808 $contextids = array();
2810 $contextids[] = $context->id;
2812 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2814 array_unshift($params, $userid);
2816 $sql = "SELECT ra.*, r.name, r.shortname
2817 FROM {role_assignments} ra, {role} r, {context} c
2818 WHERE ra.userid = ?
2819 AND ra.roleid = r.id
2820 AND ra.contextid = c.id
2821 AND ra.contextid $contextids
2822 ORDER BY $order";
2824 return $DB->get_records_sql($sql ,$params);
2828 * Like get_user_roles, but adds in the authenticated user role, and the front
2829 * page roles, if applicable.
2831 * @param context $context the context.
2832 * @param int $userid optional. Defaults to $USER->id
2833 * @return array of objects with fields ->userid, ->contextid and ->roleid.
2835 function get_user_roles_with_special(context $context, $userid = 0) {
2836 global $CFG, $USER;
2838 if (empty($userid)) {
2839 if (empty($USER->id)) {
2840 return array();
2842 $userid = $USER->id;
2845 $ras = get_user_roles($context, $userid);
2847 // Add front-page role if relevant.
2848 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2849 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
2850 is_inside_frontpage($context);
2851 if ($defaultfrontpageroleid && $isfrontpage) {
2852 $frontpagecontext = context_course::instance(SITEID);
2853 $ra = new stdClass();
2854 $ra->userid = $userid;
2855 $ra->contextid = $frontpagecontext->id;
2856 $ra->roleid = $defaultfrontpageroleid;
2857 $ras[] = $ra;
2860 // Add authenticated user role if relevant.
2861 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2862 if ($defaultuserroleid && !isguestuser($userid)) {
2863 $systemcontext = context_system::instance();
2864 $ra = new stdClass();
2865 $ra->userid = $userid;
2866 $ra->contextid = $systemcontext->id;
2867 $ra->roleid = $defaultuserroleid;
2868 $ras[] = $ra;
2871 return $ras;
2875 * Creates a record in the role_allow_override table
2877 * @param int $fromroleid source roleid
2878 * @param int $targetroleid target roleid
2879 * @return void
2881 function core_role_set_override_allowed($fromroleid, $targetroleid) {
2882 global $DB;
2884 $record = new stdClass();
2885 $record->roleid = $fromroleid;
2886 $record->allowoverride = $targetroleid;
2887 $DB->insert_record('role_allow_override', $record);
2891 * Creates a record in the role_allow_assign table
2893 * @param int $fromroleid source roleid
2894 * @param int $targetroleid target roleid
2895 * @return void
2897 function core_role_set_assign_allowed($fromroleid, $targetroleid) {
2898 global $DB;
2900 $record = new stdClass();
2901 $record->roleid = $fromroleid;
2902 $record->allowassign = $targetroleid;
2903 $DB->insert_record('role_allow_assign', $record);
2907 * Creates a record in the role_allow_switch table
2909 * @param int $fromroleid source roleid
2910 * @param int $targetroleid target roleid
2911 * @return void
2913 function core_role_set_switch_allowed($fromroleid, $targetroleid) {
2914 global $DB;
2916 $record = new stdClass();
2917 $record->roleid = $fromroleid;
2918 $record->allowswitch = $targetroleid;
2919 $DB->insert_record('role_allow_switch', $record);
2923 * Creates a record in the role_allow_view table
2925 * @param int $fromroleid source roleid
2926 * @param int $targetroleid target roleid
2927 * @return void
2929 function core_role_set_view_allowed($fromroleid, $targetroleid) {
2930 global $DB;
2932 $record = new stdClass();
2933 $record->roleid = $fromroleid;
2934 $record->allowview = $targetroleid;
2935 $DB->insert_record('role_allow_view', $record);
2939 * Gets a list of roles that this user can assign in this context
2941 * @param context $context the context.
2942 * @param int $rolenamedisplay the type of role name to display. One of the
2943 * ROLENAME_X constants. Default ROLENAME_ALIAS.
2944 * @param bool $withusercounts if true, count the number of users with each role.
2945 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
2946 * @return array if $withusercounts is false, then an array $roleid => $rolename.
2947 * if $withusercounts is true, returns a list of three arrays,
2948 * $rolenames, $rolecounts, and $nameswithcounts.
2950 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
2951 global $USER, $DB;
2953 // make sure there is a real user specified
2954 if ($user === null) {
2955 $userid = isset($USER->id) ? $USER->id : 0;
2956 } else {
2957 $userid = is_object($user) ? $user->id : $user;
2960 if (!has_capability('moodle/role:assign', $context, $userid)) {
2961 if ($withusercounts) {
2962 return array(array(), array(), array());
2963 } else {
2964 return array();
2968 $params = array();
2969 $extrafields = '';
2971 if ($withusercounts) {
2972 $extrafields = ', (SELECT count(u.id)
2973 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
2974 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
2975 ) AS usercount';
2976 $params['conid'] = $context->id;
2979 if (is_siteadmin($userid)) {
2980 // show all roles allowed in this context to admins
2981 $assignrestriction = "";
2982 } else {
2983 $parents = $context->get_parent_context_ids(true);
2984 $contexts = implode(',' , $parents);
2985 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
2986 FROM {role_allow_assign} raa
2987 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
2988 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
2989 ) ar ON ar.id = r.id";
2990 $params['userid'] = $userid;
2992 $params['contextlevel'] = $context->contextlevel;
2994 if ($coursecontext = $context->get_course_context(false)) {
2995 $params['coursecontext'] = $coursecontext->id;
2996 } else {
2997 $params['coursecontext'] = 0; // no course aliases
2998 $coursecontext = null;
3000 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3001 FROM {role} r
3002 $assignrestriction
3003 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3004 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3005 ORDER BY r.sortorder ASC";
3006 $roles = $DB->get_records_sql($sql, $params);
3008 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3010 if (!$withusercounts) {
3011 return $rolenames;
3014 $rolecounts = array();
3015 $nameswithcounts = array();
3016 foreach ($roles as $role) {
3017 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3018 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3020 return array($rolenames, $rolecounts, $nameswithcounts);
3024 * Gets a list of roles that this user can switch to in a context
3026 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3027 * This function just process the contents of the role_allow_switch table. You also need to
3028 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3030 * @param context $context a context.
3031 * @return array an array $roleid => $rolename.
3033 function get_switchable_roles(context $context) {
3034 global $USER, $DB;
3036 // You can't switch roles without this capability.
3037 if (!has_capability('moodle/role:switchroles', $context)) {
3038 return [];
3041 $params = array();
3042 $extrajoins = '';
3043 $extrawhere = '';
3044 if (!is_siteadmin()) {
3045 // Admins are allowed to switch to any role with.
3046 // Others are subject to the additional constraint that the switch-to role must be allowed by
3047 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3048 $parents = $context->get_parent_context_ids(true);
3049 $contexts = implode(',' , $parents);
3051 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3052 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3053 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3054 $params['userid'] = $USER->id;
3057 if ($coursecontext = $context->get_course_context(false)) {
3058 $params['coursecontext'] = $coursecontext->id;
3059 } else {
3060 $params['coursecontext'] = 0; // no course aliases
3061 $coursecontext = null;
3064 $query = "
3065 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3066 FROM (SELECT DISTINCT rc.roleid
3067 FROM {role_capabilities} rc
3068 $extrajoins
3069 $extrawhere) idlist
3070 JOIN {role} r ON r.id = idlist.roleid
3071 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3072 ORDER BY r.sortorder";
3073 $roles = $DB->get_records_sql($query, $params);
3075 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3079 * Gets a list of roles that this user can view in a context
3081 * @param context $context a context.
3082 * @param int $userid id of user.
3083 * @return array an array $roleid => $rolename.
3085 function get_viewable_roles(context $context, $userid = null) {
3086 global $USER, $DB;
3088 if ($userid == null) {
3089 $userid = $USER->id;
3092 $params = array();
3093 $extrajoins = '';
3094 $extrawhere = '';
3095 if (!is_siteadmin()) {
3096 // Admins are allowed to view any role.
3097 // Others are subject to the additional constraint that the view role must be allowed by
3098 // 'role_allow_view' for some role they have assigned in this context or any parent.
3099 $contexts = $context->get_parent_context_ids(true);
3100 list($insql, $inparams) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED);
3102 $extrajoins = "JOIN {role_allow_view} ras ON ras.allowview = r.id
3103 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3104 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid $insql";
3106 $params += $inparams;
3107 $params['userid'] = $userid;
3110 if ($coursecontext = $context->get_course_context(false)) {
3111 $params['coursecontext'] = $coursecontext->id;
3112 } else {
3113 $params['coursecontext'] = 0; // No course aliases.
3114 $coursecontext = null;
3117 $query = "
3118 SELECT r.id, r.name, r.shortname, rn.name AS coursealias, r.sortorder
3119 FROM {role} r
3120 $extrajoins
3121 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3122 $extrawhere
3123 GROUP BY r.id, r.name, r.shortname, rn.name, r.sortorder
3124 ORDER BY r.sortorder";
3125 $roles = $DB->get_records_sql($query, $params);
3127 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3131 * Gets a list of roles that this user can override in this context.
3133 * @param context $context the context.
3134 * @param int $rolenamedisplay the type of role name to display. One of the
3135 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3136 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3137 * @return array if $withcounts is false, then an array $roleid => $rolename.
3138 * if $withusercounts is true, returns a list of three arrays,
3139 * $rolenames, $rolecounts, and $nameswithcounts.
3141 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3142 global $USER, $DB;
3144 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3145 if ($withcounts) {
3146 return array(array(), array(), array());
3147 } else {
3148 return array();
3152 $parents = $context->get_parent_context_ids(true);
3153 $contexts = implode(',' , $parents);
3155 $params = array();
3156 $extrafields = '';
3158 $params['userid'] = $USER->id;
3159 if ($withcounts) {
3160 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3161 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3162 $params['conid'] = $context->id;
3165 if ($coursecontext = $context->get_course_context(false)) {
3166 $params['coursecontext'] = $coursecontext->id;
3167 } else {
3168 $params['coursecontext'] = 0; // no course aliases
3169 $coursecontext = null;
3172 if (is_siteadmin()) {
3173 // show all roles to admins
3174 $roles = $DB->get_records_sql("
3175 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3176 FROM {role} ro
3177 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3178 ORDER BY ro.sortorder ASC", $params);
3180 } else {
3181 $roles = $DB->get_records_sql("
3182 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3183 FROM {role} ro
3184 JOIN (SELECT DISTINCT r.id
3185 FROM {role} r
3186 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3187 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3188 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3189 ) inline_view ON ro.id = inline_view.id
3190 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3191 ORDER BY ro.sortorder ASC", $params);
3194 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3196 if (!$withcounts) {
3197 return $rolenames;
3200 $rolecounts = array();
3201 $nameswithcounts = array();
3202 foreach ($roles as $role) {
3203 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3204 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3206 return array($rolenames, $rolecounts, $nameswithcounts);
3210 * Create a role menu suitable for default role selection in enrol plugins.
3212 * @package core_enrol
3214 * @param context $context
3215 * @param int $addroleid current or default role - always added to list
3216 * @return array roleid=>localised role name
3218 function get_default_enrol_roles(context $context, $addroleid = null) {
3219 global $DB;
3221 $params = array('contextlevel'=>CONTEXT_COURSE);
3223 if ($coursecontext = $context->get_course_context(false)) {
3224 $params['coursecontext'] = $coursecontext->id;
3225 } else {
3226 $params['coursecontext'] = 0; // no course names
3227 $coursecontext = null;
3230 if ($addroleid) {
3231 $addrole = "OR r.id = :addroleid";
3232 $params['addroleid'] = $addroleid;
3233 } else {
3234 $addrole = "";
3237 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3238 FROM {role} r
3239 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3240 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3241 WHERE rcl.id IS NOT NULL $addrole
3242 ORDER BY sortorder DESC";
3244 $roles = $DB->get_records_sql($sql, $params);
3246 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3250 * Return context levels where this role is assignable.
3252 * @param integer $roleid the id of a role.
3253 * @return array list of the context levels at which this role may be assigned.
3255 function get_role_contextlevels($roleid) {
3256 global $DB;
3257 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3258 'contextlevel', 'id,contextlevel');
3262 * Return roles suitable for assignment at the specified context level.
3264 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3266 * @param integer $contextlevel a contextlevel.
3267 * @return array list of role ids that are assignable at this context level.
3269 function get_roles_for_contextlevels($contextlevel) {
3270 global $DB;
3271 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3272 '', 'id,roleid');
3276 * Returns default context levels where roles can be assigned.
3278 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3279 * from the array returned by get_role_archetypes();
3280 * @return array list of the context levels at which this type of role may be assigned by default.
3282 function get_default_contextlevels($rolearchetype) {
3283 static $defaults = array(
3284 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3285 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3286 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3287 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3288 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3289 'guest' => array(),
3290 'user' => array(),
3291 'frontpage' => array());
3293 if (isset($defaults[$rolearchetype])) {
3294 return $defaults[$rolearchetype];
3295 } else {
3296 return array();
3301 * Set the context levels at which a particular role can be assigned.
3302 * Throws exceptions in case of error.
3304 * @param integer $roleid the id of a role.
3305 * @param array $contextlevels the context levels at which this role should be assignable,
3306 * duplicate levels are removed.
3307 * @return void
3309 function set_role_contextlevels($roleid, array $contextlevels) {
3310 global $DB;
3311 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3312 $rcl = new stdClass();
3313 $rcl->roleid = $roleid;
3314 $contextlevels = array_unique($contextlevels);
3315 foreach ($contextlevels as $level) {
3316 $rcl->contextlevel = $level;
3317 $DB->insert_record('role_context_levels', $rcl, false, true);
3322 * Who has this capability in this context?
3324 * This can be a very expensive call - use sparingly and keep
3325 * the results if you are going to need them again soon.
3327 * Note if $fields is empty this function attempts to get u.*
3328 * which can get rather large - and has a serious perf impact
3329 * on some DBs.
3331 * @param context $context
3332 * @param string|array $capability - capability name(s)
3333 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3334 * @param string $sort - the sort order. Default is lastaccess time.
3335 * @param mixed $limitfrom - number of records to skip (offset)
3336 * @param mixed $limitnum - number of records to fetch
3337 * @param string|array $groups - single group or array of groups - only return
3338 * users who are in one of these group(s).
3339 * @param string|array $exceptions - list of users to exclude, comma separated or array
3340 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3341 * @param bool $view_ignored - use get_enrolled_sql() instead
3342 * @param bool $useviewallgroups if $groups is set the return users who
3343 * have capability both $capability and moodle/site:accessallgroups
3344 * in this context, as well as users who have $capability and who are
3345 * in $groups.
3346 * @return array of user records
3348 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3349 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3350 global $CFG, $DB;
3352 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3353 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3355 $ctxids = trim($context->path, '/');
3356 $ctxids = str_replace('/', ',', $ctxids);
3358 // Context is the frontpage
3359 $iscoursepage = false; // coursepage other than fp
3360 $isfrontpage = false;
3361 if ($context->contextlevel == CONTEXT_COURSE) {
3362 if ($context->instanceid == SITEID) {
3363 $isfrontpage = true;
3364 } else {
3365 $iscoursepage = true;
3368 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3370 $caps = (array)$capability;
3372 // construct list of context paths bottom-->top
3373 list($contextids, $paths) = get_context_info_list($context);
3375 // we need to find out all roles that have these capabilities either in definition or in overrides
3376 $defs = array();
3377 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3378 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3379 $params = array_merge($params, $params2);
3380 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3381 FROM {role_capabilities} rc
3382 JOIN {context} ctx on rc.contextid = ctx.id
3383 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3385 $rcs = $DB->get_records_sql($sql, $params);
3386 foreach ($rcs as $rc) {
3387 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3390 // go through the permissions bottom-->top direction to evaluate the current permission,
3391 // first one wins (prohibit is an exception that always wins)
3392 $access = array();
3393 foreach ($caps as $cap) {
3394 foreach ($paths as $path) {
3395 if (empty($defs[$cap][$path])) {
3396 continue;
3398 foreach($defs[$cap][$path] as $roleid => $perm) {
3399 if ($perm == CAP_PROHIBIT) {
3400 $access[$cap][$roleid] = CAP_PROHIBIT;
3401 continue;
3403 if (!isset($access[$cap][$roleid])) {
3404 $access[$cap][$roleid] = (int)$perm;
3410 // make lists of roles that are needed and prohibited in this context
3411 $needed = array(); // one of these is enough
3412 $prohibited = array(); // must not have any of these
3413 foreach ($caps as $cap) {
3414 if (empty($access[$cap])) {
3415 continue;
3417 foreach ($access[$cap] as $roleid => $perm) {
3418 if ($perm == CAP_PROHIBIT) {
3419 unset($needed[$cap][$roleid]);
3420 $prohibited[$cap][$roleid] = true;
3421 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3422 $needed[$cap][$roleid] = true;
3425 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3426 // easy, nobody has the permission
3427 unset($needed[$cap]);
3428 unset($prohibited[$cap]);
3429 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3430 // everybody is disqualified on the frontpage
3431 unset($needed[$cap]);
3432 unset($prohibited[$cap]);
3434 if (empty($prohibited[$cap])) {
3435 unset($prohibited[$cap]);
3439 if (empty($needed)) {
3440 // there can not be anybody if no roles match this request
3441 return array();
3444 if (empty($prohibited)) {
3445 // we can compact the needed roles
3446 $n = array();
3447 foreach ($needed as $cap) {
3448 foreach ($cap as $roleid=>$unused) {
3449 $n[$roleid] = true;
3452 $needed = array('any'=>$n);
3453 unset($n);
3456 // ***** Set up default fields ******
3457 if (empty($fields)) {
3458 if ($iscoursepage) {
3459 $fields = 'u.*, ul.timeaccess AS lastaccess';
3460 } else {
3461 $fields = 'u.*';
3463 } else {
3464 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3465 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3469 // Set up default sort
3470 if (empty($sort)) { // default to course lastaccess or just lastaccess
3471 if ($iscoursepage) {
3472 $sort = 'ul.timeaccess';
3473 } else {
3474 $sort = 'u.lastaccess';
3478 // Prepare query clauses
3479 $wherecond = array();
3480 $params = array();
3481 $joins = array();
3483 // User lastaccess JOIN
3484 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3485 // user_lastaccess is not required MDL-13810
3486 } else {
3487 if ($iscoursepage) {
3488 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3489 } else {
3490 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3494 // We never return deleted users or guest account.
3495 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3496 $params['guestid'] = $CFG->siteguest;
3498 // Groups
3499 if ($groups) {
3500 $groups = (array)$groups;
3501 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3502 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3503 $params = array_merge($params, $grpparams);
3505 if ($useviewallgroups) {
3506 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3507 if (!empty($viewallgroupsusers)) {
3508 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3509 } else {
3510 $wherecond[] = "($grouptest)";
3512 } else {
3513 $wherecond[] = "($grouptest)";
3517 // User exceptions
3518 if (!empty($exceptions)) {
3519 $exceptions = (array)$exceptions;
3520 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3521 $params = array_merge($params, $exparams);
3522 $wherecond[] = "u.id $exsql";
3525 // now add the needed and prohibited roles conditions as joins
3526 if (!empty($needed['any'])) {
3527 // simple case - there are no prohibits involved
3528 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3529 // everybody
3530 } else {
3531 $joins[] = "JOIN (SELECT DISTINCT userid
3532 FROM {role_assignments}
3533 WHERE contextid IN ($ctxids)
3534 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3535 ) ra ON ra.userid = u.id";
3537 } else {
3538 $unions = array();
3539 $everybody = false;
3540 foreach ($needed as $cap=>$unused) {
3541 if (empty($prohibited[$cap])) {
3542 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3543 $everybody = true;
3544 break;
3545 } else {
3546 $unions[] = "SELECT userid
3547 FROM {role_assignments}
3548 WHERE contextid IN ($ctxids)
3549 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3551 } else {
3552 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3553 // nobody can have this cap because it is prevented in default roles
3554 continue;
3556 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3557 // everybody except the prohibitted - hiding does not matter
3558 $unions[] = "SELECT id AS userid
3559 FROM {user}
3560 WHERE id NOT IN (SELECT userid
3561 FROM {role_assignments}
3562 WHERE contextid IN ($ctxids)
3563 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3565 } else {
3566 $unions[] = "SELECT userid
3567 FROM {role_assignments}
3568 WHERE contextid IN ($ctxids) AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3569 AND userid NOT IN (
3570 SELECT userid
3571 FROM {role_assignments}
3572 WHERE contextid IN ($ctxids)
3573 AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . ")
3578 if (!$everybody) {
3579 if ($unions) {
3580 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3581 } else {
3582 // only prohibits found - nobody can be matched
3583 $wherecond[] = "1 = 2";
3588 // Collect WHERE conditions and needed joins
3589 $where = implode(' AND ', $wherecond);
3590 if ($where !== '') {
3591 $where = 'WHERE ' . $where;
3593 $joins = implode("\n", $joins);
3595 // Ok, let's get the users!
3596 $sql = "SELECT $fields
3597 FROM {user} u
3598 $joins
3599 $where
3600 ORDER BY $sort";
3602 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3606 * Re-sort a users array based on a sorting policy
3608 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3609 * based on a sorting policy. This is to support the odd practice of
3610 * sorting teachers by 'authority', where authority was "lowest id of the role
3611 * assignment".
3613 * Will execute 1 database query. Only suitable for small numbers of users, as it
3614 * uses an u.id IN() clause.
3616 * Notes about the sorting criteria.
3618 * As a default, we cannot rely on role.sortorder because then
3619 * admins/coursecreators will always win. That is why the sane
3620 * rule "is locality matters most", with sortorder as 2nd
3621 * consideration.
3623 * If you want role.sortorder, use the 'sortorder' policy, and
3624 * name explicitly what roles you want to cover. It's probably
3625 * a good idea to see what roles have the capabilities you want
3626 * (array_diff() them against roiles that have 'can-do-anything'
3627 * to weed out admin-ish roles. Or fetch a list of roles from
3628 * variables like $CFG->coursecontact .
3630 * @param array $users Users array, keyed on userid
3631 * @param context $context
3632 * @param array $roles ids of the roles to include, optional
3633 * @param string $sortpolicy defaults to locality, more about
3634 * @return array sorted copy of the array
3636 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3637 global $DB;
3639 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3640 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3641 if (empty($roles)) {
3642 $roleswhere = '';
3643 } else {
3644 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3647 $sql = "SELECT ra.userid
3648 FROM {role_assignments} ra
3649 JOIN {role} r
3650 ON ra.roleid=r.id
3651 JOIN {context} ctx
3652 ON ra.contextid=ctx.id
3653 WHERE $userswhere
3654 $contextwhere
3655 $roleswhere";
3657 // Default 'locality' policy -- read PHPDoc notes
3658 // about sort policies...
3659 $orderby = 'ORDER BY '
3660 .'ctx.depth DESC, ' /* locality wins */
3661 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3662 .'ra.id'; /* role assignment order tie-breaker */
3663 if ($sortpolicy === 'sortorder') {
3664 $orderby = 'ORDER BY '
3665 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3666 .'ra.id'; /* role assignment order tie-breaker */
3669 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3670 $sortedusers = array();
3671 $seen = array();
3673 foreach ($sortedids as $id) {
3674 // Avoid duplicates
3675 if (isset($seen[$id])) {
3676 continue;
3678 $seen[$id] = true;
3680 // assign
3681 $sortedusers[$id] = $users[$id];
3683 return $sortedusers;
3687 * Gets all the users assigned this role in this context or higher
3689 * Note that moodle is based on capabilities and it is usually better
3690 * to check permissions than to check role ids as the capabilities
3691 * system is more flexible. If you really need, you can to use this
3692 * function but consider has_capability() as a possible substitute.
3694 * All $sort fields are added into $fields if not present there yet.
3696 * If $roleid is an array or is empty (all roles) you need to set $fields
3697 * (and $sort by extension) params according to it, as the first field
3698 * returned by the database should be unique (ra.id is the best candidate).
3700 * @param int $roleid (can also be an array of ints!)
3701 * @param context $context
3702 * @param bool $parent if true, get list of users assigned in higher context too
3703 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3704 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3705 * null => use default sort from users_order_by_sql.
3706 * @param bool $all true means all, false means limit to enrolled users
3707 * @param string $group defaults to ''
3708 * @param mixed $limitfrom defaults to ''
3709 * @param mixed $limitnum defaults to ''
3710 * @param string $extrawheretest defaults to ''
3711 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3712 * @return array
3714 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3715 $sort = null, $all = true, $group = '',
3716 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3717 global $DB;
3719 if (empty($fields)) {
3720 $allnames = get_all_user_name_fields(true, 'u');
3721 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
3722 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3723 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3724 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3725 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3728 // Prevent wrong function uses.
3729 if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
3730 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
3731 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
3733 if (!empty($roleid)) {
3734 // Solving partially the issue when specifying multiple roles.
3735 $users = array();
3736 foreach ($roleid as $id) {
3737 // Ignoring duplicated keys keeping the first user appearance.
3738 $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
3739 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
3741 return $users;
3745 $parentcontexts = '';
3746 if ($parent) {
3747 $parentcontexts = substr($context->path, 1); // kill leading slash
3748 $parentcontexts = str_replace('/', ',', $parentcontexts);
3749 if ($parentcontexts !== '') {
3750 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3754 if ($roleid) {
3755 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
3756 $roleselect = "AND ra.roleid $rids";
3757 } else {
3758 $params = array();
3759 $roleselect = '';
3762 if ($coursecontext = $context->get_course_context(false)) {
3763 $params['coursecontext'] = $coursecontext->id;
3764 } else {
3765 $params['coursecontext'] = 0;
3768 if ($group) {
3769 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3770 $groupselect = " AND gm.groupid = :groupid ";
3771 $params['groupid'] = $group;
3772 } else {
3773 $groupjoin = '';
3774 $groupselect = '';
3777 $params['contextid'] = $context->id;
3779 if ($extrawheretest) {
3780 $extrawheretest = ' AND ' . $extrawheretest;
3783 if ($whereorsortparams) {
3784 $params = array_merge($params, $whereorsortparams);
3787 if (!$sort) {
3788 list($sort, $sortparams) = users_order_by_sql('u');
3789 $params = array_merge($params, $sortparams);
3792 // Adding the fields from $sort that are not present in $fields.
3793 $sortarray = preg_split('/,\s*/', $sort);
3794 $fieldsarray = preg_split('/,\s*/', $fields);
3796 // Discarding aliases from the fields.
3797 $fieldnames = array();
3798 foreach ($fieldsarray as $key => $field) {
3799 list($fieldnames[$key]) = explode(' ', $field);
3802 $addedfields = array();
3803 foreach ($sortarray as $sortfield) {
3804 // Throw away any additional arguments to the sort (e.g. ASC/DESC).
3805 list($sortfield) = explode(' ', $sortfield);
3806 list($tableprefix) = explode('.', $sortfield);
3807 $fieldpresent = false;
3808 foreach ($fieldnames as $fieldname) {
3809 if ($fieldname === $sortfield || $fieldname === $tableprefix.'.*') {
3810 $fieldpresent = true;
3811 break;
3815 if (!$fieldpresent) {
3816 $fieldsarray[] = $sortfield;
3817 $addedfields[] = $sortfield;
3821 $fields = implode(', ', $fieldsarray);
3822 if (!empty($addedfields)) {
3823 $addedfields = implode(', ', $addedfields);
3824 debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
3827 if ($all === null) {
3828 // Previously null was used to indicate that parameter was not used.
3829 $all = true;
3831 if (!$all and $coursecontext) {
3832 // Do not use get_enrolled_sql() here for performance reasons.
3833 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
3834 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
3835 $params['ecourseid'] = $coursecontext->instanceid;
3836 } else {
3837 $ejoin = "";
3840 $sql = "SELECT DISTINCT $fields, ra.roleid
3841 FROM {role_assignments} ra
3842 JOIN {user} u ON u.id = ra.userid
3843 JOIN {role} r ON ra.roleid = r.id
3844 $ejoin
3845 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3846 $groupjoin
3847 WHERE (ra.contextid = :contextid $parentcontexts)
3848 $roleselect
3849 $groupselect
3850 $extrawheretest
3851 ORDER BY $sort"; // join now so that we can just use fullname() later
3853 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3857 * Counts all the users assigned this role in this context or higher
3859 * @param int|array $roleid either int or an array of ints
3860 * @param context $context
3861 * @param bool $parent if true, get list of users assigned in higher context too
3862 * @return int Returns the result count
3864 function count_role_users($roleid, context $context, $parent = false) {
3865 global $DB;
3867 if ($parent) {
3868 if ($contexts = $context->get_parent_context_ids()) {
3869 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3870 } else {
3871 $parentcontexts = '';
3873 } else {
3874 $parentcontexts = '';
3877 if ($roleid) {
3878 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3879 $roleselect = "AND r.roleid $rids";
3880 } else {
3881 $params = array();
3882 $roleselect = '';
3885 array_unshift($params, $context->id);
3887 $sql = "SELECT COUNT(DISTINCT u.id)
3888 FROM {role_assignments} r
3889 JOIN {user} u ON u.id = r.userid
3890 WHERE (r.contextid = ? $parentcontexts)
3891 $roleselect
3892 AND u.deleted = 0";
3894 return $DB->count_records_sql($sql, $params);
3898 * This function gets the list of courses that this user has a particular capability in.
3900 * It is now reasonably efficient, but bear in mind that if there are users who have the capability
3901 * everywhere, it may return an array of all courses.
3903 * @param string $capability Capability in question
3904 * @param int $userid User ID or null for current user
3905 * @param bool $doanything True if 'doanything' is permitted (default)
3906 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3907 * otherwise use a comma-separated list of the fields you require, not including id.
3908 * Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
3909 * @param string $orderby If set, use a comma-separated list of fields from course
3910 * table with sql modifiers (DESC) if needed
3911 * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
3912 * @return array|bool Array of courses, if none found false is returned.
3914 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '',
3915 $limit = 0) {
3916 global $DB, $USER;
3918 // Default to current user.
3919 if (!$userid) {
3920 $userid = $USER->id;
3923 if ($doanything && is_siteadmin($userid)) {
3924 // If the user is a site admin and $doanything is enabled then there is no need to restrict
3925 // the list of courses.
3926 $contextlimitsql = '';
3927 $contextlimitparams = [];
3928 } else {
3929 // Gets SQL to limit contexts ('x' table) to those where the user has this capability.
3930 list ($contextlimitsql, $contextlimitparams) = \core\access\get_user_capability_course_helper::get_sql(
3931 $userid, $capability);
3932 if (!$contextlimitsql) {
3933 // If the does not have this capability in any context, return false without querying.
3934 return false;
3937 $contextlimitsql = 'WHERE' . $contextlimitsql;
3940 // Convert fields list and ordering
3941 $fieldlist = '';
3942 if ($fieldsexceptid) {
3943 $fields = array_map('trim', explode(',', $fieldsexceptid));
3944 foreach($fields as $field) {
3945 // Context fields have a different alias.
3946 if (strpos($field, 'ctx') === 0) {
3947 switch($field) {
3948 case 'ctxlevel' :
3949 $realfield = 'contextlevel';
3950 break;
3951 case 'ctxinstance' :
3952 $realfield = 'instanceid';
3953 break;
3954 default:
3955 $realfield = substr($field, 3);
3956 break;
3958 $fieldlist .= ',x.' . $realfield . ' AS ' . $field;
3959 } else {
3960 $fieldlist .= ',c.'.$field;
3964 if ($orderby) {
3965 $fields = explode(',', $orderby);
3966 $orderby = '';
3967 foreach($fields as $field) {
3968 if ($orderby) {
3969 $orderby .= ',';
3971 $orderby .= 'c.'.$field;
3973 $orderby = 'ORDER BY '.$orderby;
3976 $courses = array();
3977 $rs = $DB->get_recordset_sql("
3978 SELECT c.id $fieldlist
3979 FROM {course} c
3980 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
3981 $contextlimitsql
3982 $orderby", array_merge([CONTEXT_COURSE], $contextlimitparams));
3983 foreach ($rs as $course) {
3984 $courses[] = $course;
3985 $limit--;
3986 if ($limit == 0) {
3987 break;
3990 $rs->close();
3991 return empty($courses) ? false : $courses;
3995 * Switches the current user to another role for the current session and only
3996 * in the given context.
3998 * The caller *must* check
3999 * - that this op is allowed
4000 * - that the requested role can be switched to in this context (use get_switchable_roles)
4001 * - that the requested role is NOT $CFG->defaultuserroleid
4003 * To "unswitch" pass 0 as the roleid.
4005 * This function *will* modify $USER->access - beware
4007 * @param integer $roleid the role to switch to.
4008 * @param context $context the context in which to perform the switch.
4009 * @return bool success or failure.
4011 function role_switch($roleid, context $context) {
4012 global $USER;
4014 // Add the ghost RA to $USER->access as $USER->access['rsw'][$path] = $roleid.
4015 // To un-switch just unset($USER->access['rsw'][$path]).
4017 // Note: it is not possible to switch to roles that do not have course:view
4019 if (!isset($USER->access)) {
4020 load_all_capabilities();
4023 // Add the switch RA
4024 if ($roleid == 0) {
4025 unset($USER->access['rsw'][$context->path]);
4026 return true;
4029 $USER->access['rsw'][$context->path] = $roleid;
4031 return true;
4035 * Checks if the user has switched roles within the given course.
4037 * Note: You can only switch roles within the course, hence it takes a course id
4038 * rather than a context. On that note Petr volunteered to implement this across
4039 * all other contexts, all requests for this should be forwarded to him ;)
4041 * @param int $courseid The id of the course to check
4042 * @return bool True if the user has switched roles within the course.
4044 function is_role_switched($courseid) {
4045 global $USER;
4046 $context = context_course::instance($courseid, MUST_EXIST);
4047 return (!empty($USER->access['rsw'][$context->path]));
4051 * Get any role that has an override on exact context
4053 * @param context $context The context to check
4054 * @return array An array of roles
4056 function get_roles_with_override_on_context(context $context) {
4057 global $DB;
4059 return $DB->get_records_sql("SELECT r.*
4060 FROM {role_capabilities} rc, {role} r
4061 WHERE rc.roleid = r.id AND rc.contextid = ?",
4062 array($context->id));
4066 * Get all capabilities for this role on this context (overrides)
4068 * @param stdClass $role
4069 * @param context $context
4070 * @return array
4072 function get_capabilities_from_role_on_context($role, context $context) {
4073 global $DB;
4075 return $DB->get_records_sql("SELECT *
4076 FROM {role_capabilities}
4077 WHERE contextid = ? AND roleid = ?",
4078 array($context->id, $role->id));
4082 * Find all user assignment of users for this role, on this context
4084 * @param stdClass $role
4085 * @param context $context
4086 * @return array
4088 function get_users_from_role_on_context($role, context $context) {
4089 global $DB;
4091 return $DB->get_records_sql("SELECT *
4092 FROM {role_assignments}
4093 WHERE contextid = ? AND roleid = ?",
4094 array($context->id, $role->id));
4098 * Simple function returning a boolean true if user has roles
4099 * in context or parent contexts, otherwise false.
4101 * @param int $userid
4102 * @param int $roleid
4103 * @param int $contextid empty means any context
4104 * @return bool
4106 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4107 global $DB;
4109 if ($contextid) {
4110 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4111 return false;
4113 $parents = $context->get_parent_context_ids(true);
4114 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4115 $params['userid'] = $userid;
4116 $params['roleid'] = $roleid;
4118 $sql = "SELECT COUNT(ra.id)
4119 FROM {role_assignments} ra
4120 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4122 $count = $DB->get_field_sql($sql, $params);
4123 return ($count > 0);
4125 } else {
4126 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4131 * Get localised role name or alias if exists and format the text.
4133 * @param stdClass $role role object
4134 * - optional 'coursealias' property should be included for performance reasons if course context used
4135 * - description property is not required here
4136 * @param context|bool $context empty means system context
4137 * @param int $rolenamedisplay type of role name
4138 * @return string localised role name or course role name alias
4140 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4141 global $DB;
4143 if ($rolenamedisplay == ROLENAME_SHORT) {
4144 return $role->shortname;
4147 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4148 $coursecontext = null;
4151 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4152 $role = clone($role); // Do not modify parameters.
4153 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4154 $role->coursealias = $r->name;
4155 } else {
4156 $role->coursealias = null;
4160 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4161 if ($coursecontext) {
4162 return $role->coursealias;
4163 } else {
4164 return null;
4168 if (trim($role->name) !== '') {
4169 // For filtering always use context where was the thing defined - system for roles here.
4170 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4172 } else {
4173 // Empty role->name means we want to see localised role name based on shortname,
4174 // only default roles are supposed to be localised.
4175 switch ($role->shortname) {
4176 case 'manager': $original = get_string('manager', 'role'); break;
4177 case 'coursecreator': $original = get_string('coursecreators'); break;
4178 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4179 case 'teacher': $original = get_string('noneditingteacher'); break;
4180 case 'student': $original = get_string('defaultcoursestudent'); break;
4181 case 'guest': $original = get_string('guest'); break;
4182 case 'user': $original = get_string('authenticateduser'); break;
4183 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4184 // We should not get here, the role UI should require the name for custom roles!
4185 default: $original = $role->shortname; break;
4189 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4190 return $original;
4193 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4194 return "$original ($role->shortname)";
4197 if ($rolenamedisplay == ROLENAME_ALIAS) {
4198 if ($coursecontext and trim($role->coursealias) !== '') {
4199 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4200 } else {
4201 return $original;
4205 if ($rolenamedisplay == ROLENAME_BOTH) {
4206 if ($coursecontext and trim($role->coursealias) !== '') {
4207 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4208 } else {
4209 return $original;
4213 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4217 * Returns localised role description if available.
4218 * If the name is empty it tries to find the default role name using
4219 * hardcoded list of default role names or other methods in the future.
4221 * @param stdClass $role
4222 * @return string localised role name
4224 function role_get_description(stdClass $role) {
4225 if (!html_is_blank($role->description)) {
4226 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4229 switch ($role->shortname) {
4230 case 'manager': return get_string('managerdescription', 'role');
4231 case 'coursecreator': return get_string('coursecreatorsdescription');
4232 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4233 case 'teacher': return get_string('noneditingteacherdescription');
4234 case 'student': return get_string('defaultcoursestudentdescription');
4235 case 'guest': return get_string('guestdescription');
4236 case 'user': return get_string('authenticateduserdescription');
4237 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4238 default: return '';
4243 * Get all the localised role names for a context.
4245 * In new installs default roles have empty names, this function
4246 * add localised role names using current language pack.
4248 * @param context $context the context, null means system context
4249 * @param array of role objects with a ->localname field containing the context-specific role name.
4250 * @param int $rolenamedisplay
4251 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4252 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4254 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4255 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4259 * Prepare list of roles for display, apply aliases and localise default role names.
4261 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4262 * @param context $context the context, null means system context
4263 * @param int $rolenamedisplay
4264 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4265 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4267 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4268 global $DB;
4270 if (empty($roleoptions)) {
4271 return array();
4274 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4275 $coursecontext = null;
4278 // We usually need all role columns...
4279 $first = reset($roleoptions);
4280 if ($returnmenu === null) {
4281 $returnmenu = !is_object($first);
4284 if (!is_object($first) or !property_exists($first, 'shortname')) {
4285 $allroles = get_all_roles($context);
4286 foreach ($roleoptions as $rid => $unused) {
4287 $roleoptions[$rid] = $allroles[$rid];
4291 // Inject coursealias if necessary.
4292 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4293 $first = reset($roleoptions);
4294 if (!property_exists($first, 'coursealias')) {
4295 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4296 foreach ($aliasnames as $alias) {
4297 if (isset($roleoptions[$alias->roleid])) {
4298 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4304 // Add localname property.
4305 foreach ($roleoptions as $rid => $role) {
4306 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4309 if (!$returnmenu) {
4310 return $roleoptions;
4313 $menu = array();
4314 foreach ($roleoptions as $rid => $role) {
4315 $menu[$rid] = $role->localname;
4318 return $menu;
4322 * Aids in detecting if a new line is required when reading a new capability
4324 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4325 * when we read in a new capability.
4326 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4327 * but when we are in grade, all reports/import/export capabilities should be together
4329 * @param string $cap component string a
4330 * @param string $comp component string b
4331 * @param int $contextlevel
4332 * @return bool whether 2 component are in different "sections"
4334 function component_level_changed($cap, $comp, $contextlevel) {
4336 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4337 $compsa = explode('/', $cap->component);
4338 $compsb = explode('/', $comp);
4340 // list of system reports
4341 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4342 return false;
4345 // we are in gradebook, still
4346 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4347 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4348 return false;
4351 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4352 return false;
4356 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4360 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4361 * and return an array of roleids in order.
4363 * @param array $allroles array of roles, as returned by get_all_roles();
4364 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4366 function fix_role_sortorder($allroles) {
4367 global $DB;
4369 $rolesort = array();
4370 $i = 0;
4371 foreach ($allroles as $role) {
4372 $rolesort[$i] = $role->id;
4373 if ($role->sortorder != $i) {
4374 $r = new stdClass();
4375 $r->id = $role->id;
4376 $r->sortorder = $i;
4377 $DB->update_record('role', $r);
4378 $allroles[$role->id]->sortorder = $i;
4380 $i++;
4382 return $rolesort;
4386 * Switch the sort order of two roles (used in admin/roles/manage.php).
4388 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4389 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4390 * @return boolean success or failure
4392 function switch_roles($first, $second) {
4393 global $DB;
4394 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4395 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4396 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4397 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4398 return $result;
4402 * Duplicates all the base definitions of a role
4404 * @param stdClass $sourcerole role to copy from
4405 * @param int $targetrole id of role to copy to
4407 function role_cap_duplicate($sourcerole, $targetrole) {
4408 global $DB;
4410 $systemcontext = context_system::instance();
4411 $caps = $DB->get_records_sql("SELECT *
4412 FROM {role_capabilities}
4413 WHERE roleid = ? AND contextid = ?",
4414 array($sourcerole->id, $systemcontext->id));
4415 // adding capabilities
4416 foreach ($caps as $cap) {
4417 unset($cap->id);
4418 $cap->roleid = $targetrole;
4419 $DB->insert_record('role_capabilities', $cap);
4422 // Reset any cache of this role, including MUC.
4423 accesslib_clear_role_cache($targetrole);
4427 * Returns two lists, this can be used to find out if user has capability.
4428 * Having any needed role and no forbidden role in this context means
4429 * user has this capability in this context.
4430 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4432 * @param stdClass $context
4433 * @param string $capability
4434 * @return array($neededroles, $forbiddenroles)
4436 function get_roles_with_cap_in_context($context, $capability) {
4437 global $DB;
4439 $ctxids = trim($context->path, '/'); // kill leading slash
4440 $ctxids = str_replace('/', ',', $ctxids);
4442 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4443 FROM {role_capabilities} rc
4444 JOIN {context} ctx ON ctx.id = rc.contextid
4445 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4446 ORDER BY rc.roleid ASC, ctx.depth DESC";
4447 $params = array('cap'=>$capability);
4449 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4450 // no cap definitions --> no capability
4451 return array(array(), array());
4454 $forbidden = array();
4455 $needed = array();
4456 foreach($capdefs as $def) {
4457 if (isset($forbidden[$def->roleid])) {
4458 continue;
4460 if ($def->permission == CAP_PROHIBIT) {
4461 $forbidden[$def->roleid] = $def->roleid;
4462 unset($needed[$def->roleid]);
4463 continue;
4465 if (!isset($needed[$def->roleid])) {
4466 if ($def->permission == CAP_ALLOW) {
4467 $needed[$def->roleid] = true;
4468 } else if ($def->permission == CAP_PREVENT) {
4469 $needed[$def->roleid] = false;
4473 unset($capdefs);
4475 // remove all those roles not allowing
4476 foreach($needed as $key=>$value) {
4477 if (!$value) {
4478 unset($needed[$key]);
4479 } else {
4480 $needed[$key] = $key;
4484 return array($needed, $forbidden);
4488 * Returns an array of role IDs that have ALL of the the supplied capabilities
4489 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4491 * @param stdClass $context
4492 * @param array $capabilities An array of capabilities
4493 * @return array of roles with all of the required capabilities
4495 function get_roles_with_caps_in_context($context, $capabilities) {
4496 $neededarr = array();
4497 $forbiddenarr = array();
4498 foreach($capabilities as $caprequired) {
4499 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4502 $rolesthatcanrate = array();
4503 if (!empty($neededarr)) {
4504 foreach ($neededarr as $needed) {
4505 if (empty($rolesthatcanrate)) {
4506 $rolesthatcanrate = $needed;
4507 } else {
4508 //only want roles that have all caps
4509 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4513 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4514 foreach ($forbiddenarr as $forbidden) {
4515 //remove any roles that are forbidden any of the caps
4516 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4519 return $rolesthatcanrate;
4523 * Returns an array of role names that have ALL of the the supplied capabilities
4524 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4526 * @param stdClass $context
4527 * @param array $capabilities An array of capabilities
4528 * @return array of roles with all of the required capabilities
4530 function get_role_names_with_caps_in_context($context, $capabilities) {
4531 global $DB;
4533 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4534 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4536 $roles = array();
4537 foreach ($rolesthatcanrate as $r) {
4538 $roles[$r] = $allroles[$r];
4541 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4545 * This function verifies the prohibit comes from this context
4546 * and there are no more prohibits in parent contexts.
4548 * @param int $roleid
4549 * @param context $context
4550 * @param string $capability name
4551 * @return bool
4553 function prohibit_is_removable($roleid, context $context, $capability) {
4554 global $DB;
4556 $ctxids = trim($context->path, '/'); // kill leading slash
4557 $ctxids = str_replace('/', ',', $ctxids);
4559 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4561 $sql = "SELECT ctx.id
4562 FROM {role_capabilities} rc
4563 JOIN {context} ctx ON ctx.id = rc.contextid
4564 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4565 ORDER BY ctx.depth DESC";
4567 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4568 // no prohibits == nothing to remove
4569 return true;
4572 if (count($prohibits) > 1) {
4573 // more prohibits can not be removed
4574 return false;
4577 return !empty($prohibits[$context->id]);
4581 * More user friendly role permission changing,
4582 * it should produce as few overrides as possible.
4584 * @param int $roleid
4585 * @param stdClass $context
4586 * @param string $capname capability name
4587 * @param int $permission
4588 * @return void
4590 function role_change_permission($roleid, $context, $capname, $permission) {
4591 global $DB;
4593 if ($permission == CAP_INHERIT) {
4594 unassign_capability($capname, $roleid, $context->id);
4595 $context->mark_dirty();
4596 return;
4599 $ctxids = trim($context->path, '/'); // kill leading slash
4600 $ctxids = str_replace('/', ',', $ctxids);
4602 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4604 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4605 FROM {role_capabilities} rc
4606 JOIN {context} ctx ON ctx.id = rc.contextid
4607 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4608 ORDER BY ctx.depth DESC";
4610 if ($existing = $DB->get_records_sql($sql, $params)) {
4611 foreach($existing as $e) {
4612 if ($e->permission == CAP_PROHIBIT) {
4613 // prohibit can not be overridden, no point in changing anything
4614 return;
4617 $lowest = array_shift($existing);
4618 if ($lowest->permission == $permission) {
4619 // permission already set in this context or parent - nothing to do
4620 return;
4622 if ($existing) {
4623 $parent = array_shift($existing);
4624 if ($parent->permission == $permission) {
4625 // permission already set in parent context or parent - just unset in this context
4626 // we do this because we want as few overrides as possible for performance reasons
4627 unassign_capability($capname, $roleid, $context->id);
4628 $context->mark_dirty();
4629 return;
4633 } else {
4634 if ($permission == CAP_PREVENT) {
4635 // nothing means role does not have permission
4636 return;
4640 // assign the needed capability
4641 assign_capability($capname, $permission, $roleid, $context->id, true);
4643 // force cap reloading
4644 $context->mark_dirty();
4649 * Basic moodle context abstraction class.
4651 * Google confirms that no other important framework is using "context" class,
4652 * we could use something else like mcontext or moodle_context, but we need to type
4653 * this very often which would be annoying and it would take too much space...
4655 * This class is derived from stdClass for backwards compatibility with
4656 * odl $context record that was returned from DML $DB->get_record()
4658 * @package core_access
4659 * @category access
4660 * @copyright Petr Skoda {@link http://skodak.org}
4661 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4662 * @since Moodle 2.2
4664 * @property-read int $id context id
4665 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4666 * @property-read int $instanceid id of related instance in each context
4667 * @property-read string $path path to context, starts with system context
4668 * @property-read int $depth
4670 abstract class context extends stdClass implements IteratorAggregate {
4673 * The context id
4674 * Can be accessed publicly through $context->id
4675 * @var int
4677 protected $_id;
4680 * The context level
4681 * Can be accessed publicly through $context->contextlevel
4682 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4684 protected $_contextlevel;
4687 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4688 * Can be accessed publicly through $context->instanceid
4689 * @var int
4691 protected $_instanceid;
4694 * The path to the context always starting from the system context
4695 * Can be accessed publicly through $context->path
4696 * @var string
4698 protected $_path;
4701 * The depth of the context in relation to parent contexts
4702 * Can be accessed publicly through $context->depth
4703 * @var int
4705 protected $_depth;
4708 * @var array Context caching info
4710 private static $cache_contextsbyid = array();
4713 * @var array Context caching info
4715 private static $cache_contexts = array();
4718 * Context count
4719 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4720 * @var int
4722 protected static $cache_count = 0;
4725 * @var array Context caching info
4727 protected static $cache_preloaded = array();
4730 * @var context_system The system context once initialised
4732 protected static $systemcontext = null;
4735 * Resets the cache to remove all data.
4736 * @static
4738 protected static function reset_caches() {
4739 self::$cache_contextsbyid = array();
4740 self::$cache_contexts = array();
4741 self::$cache_count = 0;
4742 self::$cache_preloaded = array();
4744 self::$systemcontext = null;
4748 * Adds a context to the cache. If the cache is full, discards a batch of
4749 * older entries.
4751 * @static
4752 * @param context $context New context to add
4753 * @return void
4755 protected static function cache_add(context $context) {
4756 if (isset(self::$cache_contextsbyid[$context->id])) {
4757 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4758 return;
4761 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4762 $i = 0;
4763 foreach(self::$cache_contextsbyid as $ctx) {
4764 $i++;
4765 if ($i <= 100) {
4766 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4767 continue;
4769 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4770 // we remove oldest third of the contexts to make room for more contexts
4771 break;
4773 unset(self::$cache_contextsbyid[$ctx->id]);
4774 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4775 self::$cache_count--;
4779 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4780 self::$cache_contextsbyid[$context->id] = $context;
4781 self::$cache_count++;
4785 * Removes a context from the cache.
4787 * @static
4788 * @param context $context Context object to remove
4789 * @return void
4791 protected static function cache_remove(context $context) {
4792 if (!isset(self::$cache_contextsbyid[$context->id])) {
4793 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4794 return;
4796 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4797 unset(self::$cache_contextsbyid[$context->id]);
4799 self::$cache_count--;
4801 if (self::$cache_count < 0) {
4802 self::$cache_count = 0;
4807 * Gets a context from the cache.
4809 * @static
4810 * @param int $contextlevel Context level
4811 * @param int $instance Instance ID
4812 * @return context|bool Context or false if not in cache
4814 protected static function cache_get($contextlevel, $instance) {
4815 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4816 return self::$cache_contexts[$contextlevel][$instance];
4818 return false;
4822 * Gets a context from the cache based on its id.
4824 * @static
4825 * @param int $id Context ID
4826 * @return context|bool Context or false if not in cache
4828 protected static function cache_get_by_id($id) {
4829 if (isset(self::$cache_contextsbyid[$id])) {
4830 return self::$cache_contextsbyid[$id];
4832 return false;
4836 * Preloads context information from db record and strips the cached info.
4838 * @static
4839 * @param stdClass $rec
4840 * @return void (modifies $rec)
4842 protected static function preload_from_record(stdClass $rec) {
4843 if (empty($rec->ctxid) or empty($rec->ctxlevel) or !isset($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
4844 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4845 return;
4848 // note: in PHP5 the objects are passed by reference, no need to return $rec
4849 $record = new stdClass();
4850 $record->id = $rec->ctxid; unset($rec->ctxid);
4851 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
4852 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
4853 $record->path = $rec->ctxpath; unset($rec->ctxpath);
4854 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
4856 return context::create_instance_from_record($record);
4860 // ====== magic methods =======
4863 * Magic setter method, we do not want anybody to modify properties from the outside
4864 * @param string $name
4865 * @param mixed $value
4867 public function __set($name, $value) {
4868 debugging('Can not change context instance properties!');
4872 * Magic method getter, redirects to read only values.
4873 * @param string $name
4874 * @return mixed
4876 public function __get($name) {
4877 switch ($name) {
4878 case 'id': return $this->_id;
4879 case 'contextlevel': return $this->_contextlevel;
4880 case 'instanceid': return $this->_instanceid;
4881 case 'path': return $this->_path;
4882 case 'depth': return $this->_depth;
4884 default:
4885 debugging('Invalid context property accessed! '.$name);
4886 return null;
4891 * Full support for isset on our magic read only properties.
4892 * @param string $name
4893 * @return bool
4895 public function __isset($name) {
4896 switch ($name) {
4897 case 'id': return isset($this->_id);
4898 case 'contextlevel': return isset($this->_contextlevel);
4899 case 'instanceid': return isset($this->_instanceid);
4900 case 'path': return isset($this->_path);
4901 case 'depth': return isset($this->_depth);
4903 default: return false;
4909 * ALl properties are read only, sorry.
4910 * @param string $name
4912 public function __unset($name) {
4913 debugging('Can not unset context instance properties!');
4916 // ====== implementing method from interface IteratorAggregate ======
4919 * Create an iterator because magic vars can't be seen by 'foreach'.
4921 * Now we can convert context object to array using convert_to_array(),
4922 * and feed it properly to json_encode().
4924 public function getIterator() {
4925 $ret = array(
4926 'id' => $this->id,
4927 'contextlevel' => $this->contextlevel,
4928 'instanceid' => $this->instanceid,
4929 'path' => $this->path,
4930 'depth' => $this->depth
4932 return new ArrayIterator($ret);
4935 // ====== general context methods ======
4938 * Constructor is protected so that devs are forced to
4939 * use context_xxx::instance() or context::instance_by_id().
4941 * @param stdClass $record
4943 protected function __construct(stdClass $record) {
4944 $this->_id = (int)$record->id;
4945 $this->_contextlevel = (int)$record->contextlevel;
4946 $this->_instanceid = $record->instanceid;
4947 $this->_path = $record->path;
4948 $this->_depth = $record->depth;
4952 * This function is also used to work around 'protected' keyword problems in context_helper.
4953 * @static
4954 * @param stdClass $record
4955 * @return context instance
4957 protected static function create_instance_from_record(stdClass $record) {
4958 $classname = context_helper::get_class_for_level($record->contextlevel);
4960 if ($context = context::cache_get_by_id($record->id)) {
4961 return $context;
4964 $context = new $classname($record);
4965 context::cache_add($context);
4967 return $context;
4971 * Copy prepared new contexts from temp table to context table,
4972 * we do this in db specific way for perf reasons only.
4973 * @static
4975 protected static function merge_context_temp_table() {
4976 global $DB;
4978 /* MDL-11347:
4979 * - mysql does not allow to use FROM in UPDATE statements
4980 * - using two tables after UPDATE works in mysql, but might give unexpected
4981 * results in pg 8 (depends on configuration)
4982 * - using table alias in UPDATE does not work in pg < 8.2
4984 * Different code for each database - mostly for performance reasons
4987 $dbfamily = $DB->get_dbfamily();
4988 if ($dbfamily == 'mysql') {
4989 $updatesql = "UPDATE {context} ct, {context_temp} temp
4990 SET ct.path = temp.path,
4991 ct.depth = temp.depth
4992 WHERE ct.id = temp.id";
4993 } else if ($dbfamily == 'oracle') {
4994 $updatesql = "UPDATE {context} ct
4995 SET (ct.path, ct.depth) =
4996 (SELECT temp.path, temp.depth
4997 FROM {context_temp} temp
4998 WHERE temp.id=ct.id)
4999 WHERE EXISTS (SELECT 'x'
5000 FROM {context_temp} temp
5001 WHERE temp.id = ct.id)";
5002 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5003 $updatesql = "UPDATE {context}
5004 SET path = temp.path,
5005 depth = temp.depth
5006 FROM {context_temp} temp
5007 WHERE temp.id={context}.id";
5008 } else {
5009 // sqlite and others
5010 $updatesql = "UPDATE {context}
5011 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5012 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5013 WHERE id IN (SELECT id FROM {context_temp})";
5016 $DB->execute($updatesql);
5020 * Get a context instance as an object, from a given context id.
5022 * @static
5023 * @param int $id context id
5024 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5025 * MUST_EXIST means throw exception if no record found
5026 * @return context|bool the context object or false if not found
5028 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5029 global $DB;
5031 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5032 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5033 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5036 if ($id == SYSCONTEXTID) {
5037 return context_system::instance(0, $strictness);
5040 if (is_array($id) or is_object($id) or empty($id)) {
5041 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5044 if ($context = context::cache_get_by_id($id)) {
5045 return $context;
5048 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5049 return context::create_instance_from_record($record);
5052 return false;
5056 * Update context info after moving context in the tree structure.
5058 * @param context $newparent
5059 * @return void
5061 public function update_moved(context $newparent) {
5062 global $DB;
5064 $frompath = $this->_path;
5065 $newpath = $newparent->path . '/' . $this->_id;
5067 $trans = $DB->start_delegated_transaction();
5069 $this->mark_dirty();
5071 $setdepth = '';
5072 if (($newparent->depth +1) != $this->_depth) {
5073 $diff = $newparent->depth - $this->_depth + 1;
5074 $setdepth = ", depth = depth + $diff";
5076 $sql = "UPDATE {context}
5077 SET path = ?
5078 $setdepth
5079 WHERE id = ?";
5080 $params = array($newpath, $this->_id);
5081 $DB->execute($sql, $params);
5083 $this->_path = $newpath;
5084 $this->_depth = $newparent->depth + 1;
5086 $sql = "UPDATE {context}
5087 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5088 $setdepth
5089 WHERE path LIKE ?";
5090 $params = array($newpath, "{$frompath}/%");
5091 $DB->execute($sql, $params);
5093 $this->mark_dirty();
5095 context::reset_caches();
5097 $trans->allow_commit();
5101 * Remove all context path info and optionally rebuild it.
5103 * @param bool $rebuild
5104 * @return void
5106 public function reset_paths($rebuild = true) {
5107 global $DB;
5109 if ($this->_path) {
5110 $this->mark_dirty();
5112 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5113 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5114 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5115 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5116 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5117 $this->_depth = 0;
5118 $this->_path = null;
5121 if ($rebuild) {
5122 context_helper::build_all_paths(false);
5125 context::reset_caches();
5129 * Delete all data linked to content, do not delete the context record itself
5131 public function delete_content() {
5132 global $CFG, $DB;
5134 blocks_delete_all_for_context($this->_id);
5135 filter_delete_all_for_context($this->_id);
5137 require_once($CFG->dirroot . '/comment/lib.php');
5138 comment::delete_comments(array('contextid'=>$this->_id));
5140 require_once($CFG->dirroot.'/rating/lib.php');
5141 $delopt = new stdclass();
5142 $delopt->contextid = $this->_id;
5143 $rm = new rating_manager();
5144 $rm->delete_ratings($delopt);
5146 // delete all files attached to this context
5147 $fs = get_file_storage();
5148 $fs->delete_area_files($this->_id);
5150 // Delete all repository instances attached to this context.
5151 require_once($CFG->dirroot . '/repository/lib.php');
5152 repository::delete_all_for_context($this->_id);
5154 // delete all advanced grading data attached to this context
5155 require_once($CFG->dirroot.'/grade/grading/lib.php');
5156 grading_manager::delete_all_for_context($this->_id);
5158 $ids = $DB->get_fieldset_select('role_capabilities', 'DISTINCT roleid', 'contextid = ?', array($this->_id));
5160 // now delete stuff from role related tables, role_unassign_all
5161 // and unenrol should be called earlier to do proper cleanup
5162 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5163 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5164 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5166 if ($ids) {
5167 // Reset any cache of these roles, including MUC.
5168 accesslib_clear_role_cache($ids);
5173 * Delete the context content and the context record itself
5175 public function delete() {
5176 global $DB;
5178 if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5179 throw new coding_exception('Cannot delete system context');
5182 // double check the context still exists
5183 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5184 context::cache_remove($this);
5185 return;
5188 $this->delete_content();
5189 $DB->delete_records('context', array('id'=>$this->_id));
5190 // purge static context cache if entry present
5191 context::cache_remove($this);
5193 // do not mark dirty contexts if parents unknown
5194 if (!is_null($this->_path) and $this->_depth > 0) {
5195 $this->mark_dirty();
5199 // ====== context level related methods ======
5202 * Utility method for context creation
5204 * @static
5205 * @param int $contextlevel
5206 * @param int $instanceid
5207 * @param string $parentpath
5208 * @return stdClass context record
5210 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5211 global $DB;
5213 $record = new stdClass();
5214 $record->contextlevel = $contextlevel;
5215 $record->instanceid = $instanceid;
5216 $record->depth = 0;
5217 $record->path = null; //not known before insert
5219 $record->id = $DB->insert_record('context', $record);
5221 // now add path if known - it can be added later
5222 if (!is_null($parentpath)) {
5223 $record->path = $parentpath.'/'.$record->id;
5224 $record->depth = substr_count($record->path, '/');
5225 $DB->update_record('context', $record);
5228 return $record;
5232 * Returns human readable context identifier.
5234 * @param boolean $withprefix whether to prefix the name of the context with the
5235 * type of context, e.g. User, Course, Forum, etc.
5236 * @param boolean $short whether to use the short name of the thing. Only applies
5237 * to course contexts
5238 * @return string the human readable context name.
5240 public function get_context_name($withprefix = true, $short = false) {
5241 // must be implemented in all context levels
5242 throw new coding_exception('can not get name of abstract context');
5246 * Returns the most relevant URL for this context.
5248 * @return moodle_url
5250 public abstract function get_url();
5253 * Returns array of relevant context capability records.
5255 * @return array
5257 public abstract function get_capabilities();
5260 * Recursive function which, given a context, find all its children context ids.
5262 * For course category contexts it will return immediate children and all subcategory contexts.
5263 * It will NOT recurse into courses or subcategories categories.
5264 * If you want to do that, call it on the returned courses/categories.
5266 * When called for a course context, it will return the modules and blocks
5267 * displayed in the course page and blocks displayed on the module pages.
5269 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5270 * contexts ;-)
5272 * @return array Array of child records
5274 public function get_child_contexts() {
5275 global $DB;
5277 if (empty($this->_path) or empty($this->_depth)) {
5278 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5279 return array();
5282 $sql = "SELECT ctx.*
5283 FROM {context} ctx
5284 WHERE ctx.path LIKE ?";
5285 $params = array($this->_path.'/%');
5286 $records = $DB->get_records_sql($sql, $params);
5288 $result = array();
5289 foreach ($records as $record) {
5290 $result[$record->id] = context::create_instance_from_record($record);
5293 return $result;
5297 * Returns parent contexts of this context in reversed order, i.e. parent first,
5298 * then grand parent, etc.
5300 * @param bool $includeself tre means include self too
5301 * @return array of context instances
5303 public function get_parent_contexts($includeself = false) {
5304 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5305 return array();
5308 $result = array();
5309 foreach ($contextids as $contextid) {
5310 $parent = context::instance_by_id($contextid, MUST_EXIST);
5311 $result[$parent->id] = $parent;
5314 return $result;
5318 * Returns parent contexts of this context in reversed order, i.e. parent first,
5319 * then grand parent, etc.
5321 * @param bool $includeself tre means include self too
5322 * @return array of context ids
5324 public function get_parent_context_ids($includeself = false) {
5325 if (empty($this->_path)) {
5326 return array();
5329 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5330 $parentcontexts = explode('/', $parentcontexts);
5331 if (!$includeself) {
5332 array_pop($parentcontexts); // and remove its own id
5335 return array_reverse($parentcontexts);
5339 * Returns parent context
5341 * @return context
5343 public function get_parent_context() {
5344 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5345 return false;
5348 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5349 $parentcontexts = explode('/', $parentcontexts);
5350 array_pop($parentcontexts); // self
5351 $contextid = array_pop($parentcontexts); // immediate parent
5353 return context::instance_by_id($contextid, MUST_EXIST);
5357 * Is this context part of any course? If yes return course context.
5359 * @param bool $strict true means throw exception if not found, false means return false if not found
5360 * @return context_course context of the enclosing course, null if not found or exception
5362 public function get_course_context($strict = true) {
5363 if ($strict) {
5364 throw new coding_exception('Context does not belong to any course.');
5365 } else {
5366 return false;
5371 * Returns sql necessary for purging of stale context instances.
5373 * @static
5374 * @return string cleanup SQL
5376 protected static function get_cleanup_sql() {
5377 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5381 * Rebuild context paths and depths at context level.
5383 * @static
5384 * @param bool $force
5385 * @return void
5387 protected static function build_paths($force) {
5388 throw new coding_exception('build_paths() method must be implemented in all context levels');
5392 * Create missing context instances at given level
5394 * @static
5395 * @return void
5397 protected static function create_level_instances() {
5398 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5402 * Reset all cached permissions and definitions if the necessary.
5403 * @return void
5405 public function reload_if_dirty() {
5406 global $ACCESSLIB_PRIVATE, $USER;
5408 // Load dirty contexts list if needed
5409 if (CLI_SCRIPT) {
5410 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5411 // we do not load dirty flags in CLI and cron
5412 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5414 } else {
5415 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5416 if (!isset($USER->access['time'])) {
5417 // nothing was loaded yet, we do not need to check dirty contexts now
5418 return;
5420 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5421 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5425 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5426 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5427 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5428 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5429 reload_all_capabilities();
5430 break;
5436 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5438 public function mark_dirty() {
5439 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5441 if (during_initial_install()) {
5442 return;
5445 // only if it is a non-empty string
5446 if (is_string($this->_path) && $this->_path !== '') {
5447 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5448 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5449 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5450 } else {
5451 if (CLI_SCRIPT) {
5452 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5453 } else {
5454 if (isset($USER->access['time'])) {
5455 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5456 } else {
5457 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5459 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5468 * Context maintenance and helper methods.
5470 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5471 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5472 * level implementation from the rest of code, the code completion returns what developers need.
5474 * Thank you Tim Hunt for helping me with this nasty trick.
5476 * @package core_access
5477 * @category access
5478 * @copyright Petr Skoda {@link http://skodak.org}
5479 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5480 * @since Moodle 2.2
5482 class context_helper extends context {
5485 * @var array An array mapping context levels to classes
5487 private static $alllevels;
5490 * Instance does not make sense here, only static use
5492 protected function __construct() {
5496 * Reset internal context levels array.
5498 public static function reset_levels() {
5499 self::$alllevels = null;
5503 * Initialise context levels, call before using self::$alllevels.
5505 private static function init_levels() {
5506 global $CFG;
5508 if (isset(self::$alllevels)) {
5509 return;
5511 self::$alllevels = array(
5512 CONTEXT_SYSTEM => 'context_system',
5513 CONTEXT_USER => 'context_user',
5514 CONTEXT_COURSECAT => 'context_coursecat',
5515 CONTEXT_COURSE => 'context_course',
5516 CONTEXT_MODULE => 'context_module',
5517 CONTEXT_BLOCK => 'context_block',
5520 if (empty($CFG->custom_context_classes)) {
5521 return;
5524 $levels = $CFG->custom_context_classes;
5525 if (!is_array($levels)) {
5526 $levels = @unserialize($levels);
5528 if (!is_array($levels)) {
5529 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
5530 return;
5533 // Unsupported custom levels, use with care!!!
5534 foreach ($levels as $level => $classname) {
5535 self::$alllevels[$level] = $classname;
5537 ksort(self::$alllevels);
5541 * Returns a class name of the context level class
5543 * @static
5544 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5545 * @return string class name of the context class
5547 public static function get_class_for_level($contextlevel) {
5548 self::init_levels();
5549 if (isset(self::$alllevels[$contextlevel])) {
5550 return self::$alllevels[$contextlevel];
5551 } else {
5552 throw new coding_exception('Invalid context level specified');
5557 * Returns a list of all context levels
5559 * @static
5560 * @return array int=>string (level=>level class name)
5562 public static function get_all_levels() {
5563 self::init_levels();
5564 return self::$alllevels;
5568 * Remove stale contexts that belonged to deleted instances.
5569 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5571 * @static
5572 * @return void
5574 public static function cleanup_instances() {
5575 global $DB;
5576 self::init_levels();
5578 $sqls = array();
5579 foreach (self::$alllevels as $level=>$classname) {
5580 $sqls[] = $classname::get_cleanup_sql();
5583 $sql = implode(" UNION ", $sqls);
5585 // it is probably better to use transactions, it might be faster too
5586 $transaction = $DB->start_delegated_transaction();
5588 $rs = $DB->get_recordset_sql($sql);
5589 foreach ($rs as $record) {
5590 $context = context::create_instance_from_record($record);
5591 $context->delete();
5593 $rs->close();
5595 $transaction->allow_commit();
5599 * Create all context instances at the given level and above.
5601 * @static
5602 * @param int $contextlevel null means all levels
5603 * @param bool $buildpaths
5604 * @return void
5606 public static function create_instances($contextlevel = null, $buildpaths = true) {
5607 self::init_levels();
5608 foreach (self::$alllevels as $level=>$classname) {
5609 if ($contextlevel and $level > $contextlevel) {
5610 // skip potential sub-contexts
5611 continue;
5613 $classname::create_level_instances();
5614 if ($buildpaths) {
5615 $classname::build_paths(false);
5621 * Rebuild paths and depths in all context levels.
5623 * @static
5624 * @param bool $force false means add missing only
5625 * @return void
5627 public static function build_all_paths($force = false) {
5628 self::init_levels();
5629 foreach (self::$alllevels as $classname) {
5630 $classname::build_paths($force);
5633 // reset static course cache - it might have incorrect cached data
5634 accesslib_clear_all_caches(true);
5638 * Resets the cache to remove all data.
5639 * @static
5641 public static function reset_caches() {
5642 context::reset_caches();
5646 * Returns all fields necessary for context preloading from user $rec.
5648 * This helps with performance when dealing with hundreds of contexts.
5650 * @static
5651 * @param string $tablealias context table alias in the query
5652 * @return array (table.column=>alias, ...)
5654 public static function get_preload_record_columns($tablealias) {
5655 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5659 * Returns all fields necessary for context preloading from user $rec.
5661 * This helps with performance when dealing with hundreds of contexts.
5663 * @static
5664 * @param string $tablealias context table alias in the query
5665 * @return string
5667 public static function get_preload_record_columns_sql($tablealias) {
5668 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5672 * Preloads context information from db record and strips the cached info.
5674 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5676 * @static
5677 * @param stdClass $rec
5678 * @return void (modifies $rec)
5680 public static function preload_from_record(stdClass $rec) {
5681 context::preload_from_record($rec);
5685 * Preload all contexts instances from course.
5687 * To be used if you expect multiple queries for course activities...
5689 * @static
5690 * @param int $courseid
5692 public static function preload_course($courseid) {
5693 // Users can call this multiple times without doing any harm
5694 if (isset(context::$cache_preloaded[$courseid])) {
5695 return;
5697 $coursecontext = context_course::instance($courseid);
5698 $coursecontext->get_child_contexts();
5700 context::$cache_preloaded[$courseid] = true;
5704 * Delete context instance
5706 * @static
5707 * @param int $contextlevel
5708 * @param int $instanceid
5709 * @return void
5711 public static function delete_instance($contextlevel, $instanceid) {
5712 global $DB;
5714 // double check the context still exists
5715 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5716 $context = context::create_instance_from_record($record);
5717 $context->delete();
5718 } else {
5719 // we should try to purge the cache anyway
5724 * Returns the name of specified context level
5726 * @static
5727 * @param int $contextlevel
5728 * @return string name of the context level
5730 public static function get_level_name($contextlevel) {
5731 $classname = context_helper::get_class_for_level($contextlevel);
5732 return $classname::get_level_name();
5736 * not used
5738 public function get_url() {
5742 * not used
5744 public function get_capabilities() {
5750 * System context class
5752 * @package core_access
5753 * @category access
5754 * @copyright Petr Skoda {@link http://skodak.org}
5755 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5756 * @since Moodle 2.2
5758 class context_system extends context {
5760 * Please use context_system::instance() if you need the instance of context.
5762 * @param stdClass $record
5764 protected function __construct(stdClass $record) {
5765 parent::__construct($record);
5766 if ($record->contextlevel != CONTEXT_SYSTEM) {
5767 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5772 * Returns human readable context level name.
5774 * @static
5775 * @return string the human readable context level name.
5777 public static function get_level_name() {
5778 return get_string('coresystem');
5782 * Returns human readable context identifier.
5784 * @param boolean $withprefix does not apply to system context
5785 * @param boolean $short does not apply to system context
5786 * @return string the human readable context name.
5788 public function get_context_name($withprefix = true, $short = false) {
5789 return self::get_level_name();
5793 * Returns the most relevant URL for this context.
5795 * @return moodle_url
5797 public function get_url() {
5798 return new moodle_url('/');
5802 * Returns array of relevant context capability records.
5804 * @return array
5806 public function get_capabilities() {
5807 global $DB;
5809 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5811 $params = array();
5812 $sql = "SELECT *
5813 FROM {capabilities}";
5815 return $DB->get_records_sql($sql.' '.$sort, $params);
5819 * Create missing context instances at system context
5820 * @static
5822 protected static function create_level_instances() {
5823 // nothing to do here, the system context is created automatically in installer
5824 self::instance(0);
5828 * Returns system context instance.
5830 * @static
5831 * @param int $instanceid should be 0
5832 * @param int $strictness
5833 * @param bool $cache
5834 * @return context_system context instance
5836 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
5837 global $DB;
5839 if ($instanceid != 0) {
5840 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5843 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5844 if (!isset(context::$systemcontext)) {
5845 $record = new stdClass();
5846 $record->id = SYSCONTEXTID;
5847 $record->contextlevel = CONTEXT_SYSTEM;
5848 $record->instanceid = 0;
5849 $record->path = '/'.SYSCONTEXTID;
5850 $record->depth = 1;
5851 context::$systemcontext = new context_system($record);
5853 return context::$systemcontext;
5857 try {
5858 // We ignore the strictness completely because system context must exist except during install.
5859 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5860 } catch (dml_exception $e) {
5861 //table or record does not exist
5862 if (!during_initial_install()) {
5863 // do not mess with system context after install, it simply must exist
5864 throw $e;
5866 $record = null;
5869 if (!$record) {
5870 $record = new stdClass();
5871 $record->contextlevel = CONTEXT_SYSTEM;
5872 $record->instanceid = 0;
5873 $record->depth = 1;
5874 $record->path = null; //not known before insert
5876 try {
5877 if ($DB->count_records('context')) {
5878 // contexts already exist, this is very weird, system must be first!!!
5879 return null;
5881 if (defined('SYSCONTEXTID')) {
5882 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5883 $record->id = SYSCONTEXTID;
5884 $DB->import_record('context', $record);
5885 $DB->get_manager()->reset_sequence('context');
5886 } else {
5887 $record->id = $DB->insert_record('context', $record);
5889 } catch (dml_exception $e) {
5890 // can not create context - table does not exist yet, sorry
5891 return null;
5895 if ($record->instanceid != 0) {
5896 // this is very weird, somebody must be messing with context table
5897 debugging('Invalid system context 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);
5907 if (!defined('SYSCONTEXTID')) {
5908 define('SYSCONTEXTID', $record->id);
5911 context::$systemcontext = new context_system($record);
5912 return context::$systemcontext;
5916 * Returns all site contexts except the system context, DO NOT call on production servers!!
5918 * Contexts are not cached.
5920 * @return array
5922 public function get_child_contexts() {
5923 global $DB;
5925 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
5927 // Just get all the contexts except for CONTEXT_SYSTEM level
5928 // and hope we don't OOM in the process - don't cache
5929 $sql = "SELECT c.*
5930 FROM {context} c
5931 WHERE contextlevel > ".CONTEXT_SYSTEM;
5932 $records = $DB->get_records_sql($sql);
5934 $result = array();
5935 foreach ($records as $record) {
5936 $result[$record->id] = context::create_instance_from_record($record);
5939 return $result;
5943 * Returns sql necessary for purging of stale context instances.
5945 * @static
5946 * @return string cleanup SQL
5948 protected static function get_cleanup_sql() {
5949 $sql = "
5950 SELECT c.*
5951 FROM {context} c
5952 WHERE 1=2
5955 return $sql;
5959 * Rebuild context paths and depths at system context level.
5961 * @static
5962 * @param bool $force
5964 protected static function build_paths($force) {
5965 global $DB;
5967 /* note: ignore $force here, we always do full test of system context */
5969 // exactly one record must exist
5970 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5972 if ($record->instanceid != 0) {
5973 debugging('Invalid system context detected');
5976 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
5977 debugging('Invalid SYSCONTEXTID detected');
5980 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5981 // fix path if necessary, initial install or path reset
5982 $record->depth = 1;
5983 $record->path = '/'.$record->id;
5984 $DB->update_record('context', $record);
5991 * User context class
5993 * @package core_access
5994 * @category access
5995 * @copyright Petr Skoda {@link http://skodak.org}
5996 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5997 * @since Moodle 2.2
5999 class context_user extends context {
6001 * Please use context_user::instance($userid) if you need the instance of context.
6002 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6004 * @param stdClass $record
6006 protected function __construct(stdClass $record) {
6007 parent::__construct($record);
6008 if ($record->contextlevel != CONTEXT_USER) {
6009 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6014 * Returns human readable context level name.
6016 * @static
6017 * @return string the human readable context level name.
6019 public static function get_level_name() {
6020 return get_string('user');
6024 * Returns human readable context identifier.
6026 * @param boolean $withprefix whether to prefix the name of the context with User
6027 * @param boolean $short does not apply to user context
6028 * @return string the human readable context name.
6030 public function get_context_name($withprefix = true, $short = false) {
6031 global $DB;
6033 $name = '';
6034 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6035 if ($withprefix){
6036 $name = get_string('user').': ';
6038 $name .= fullname($user);
6040 return $name;
6044 * Returns the most relevant URL for this context.
6046 * @return moodle_url
6048 public function get_url() {
6049 global $COURSE;
6051 if ($COURSE->id == SITEID) {
6052 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6053 } else {
6054 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6056 return $url;
6060 * Returns array of relevant context capability records.
6062 * @return array
6064 public function get_capabilities() {
6065 global $DB;
6067 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6069 $extracaps = array('moodle/grade:viewall');
6070 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6071 $sql = "SELECT *
6072 FROM {capabilities}
6073 WHERE contextlevel = ".CONTEXT_USER."
6074 OR name $extra";
6076 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6080 * Returns user context instance.
6082 * @static
6083 * @param int $userid id from {user} table
6084 * @param int $strictness
6085 * @return context_user context instance
6087 public static function instance($userid, $strictness = MUST_EXIST) {
6088 global $DB;
6090 if ($context = context::cache_get(CONTEXT_USER, $userid)) {
6091 return $context;
6094 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER, 'instanceid' => $userid))) {
6095 if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6096 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6100 if ($record) {
6101 $context = new context_user($record);
6102 context::cache_add($context);
6103 return $context;
6106 return false;
6110 * Create missing context instances at user context level
6111 * @static
6113 protected static function create_level_instances() {
6114 global $DB;
6116 $sql = "SELECT ".CONTEXT_USER.", u.id
6117 FROM {user} u
6118 WHERE u.deleted = 0
6119 AND NOT EXISTS (SELECT 'x'
6120 FROM {context} cx
6121 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6122 $contextdata = $DB->get_recordset_sql($sql);
6123 foreach ($contextdata as $context) {
6124 context::insert_context_record(CONTEXT_USER, $context->id, null);
6126 $contextdata->close();
6130 * Returns sql necessary for purging of stale context instances.
6132 * @static
6133 * @return string cleanup SQL
6135 protected static function get_cleanup_sql() {
6136 $sql = "
6137 SELECT c.*
6138 FROM {context} c
6139 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6140 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6143 return $sql;
6147 * Rebuild context paths and depths at user context level.
6149 * @static
6150 * @param bool $force
6152 protected static function build_paths($force) {
6153 global $DB;
6155 // First update normal users.
6156 $path = $DB->sql_concat('?', 'id');
6157 $pathstart = '/' . SYSCONTEXTID . '/';
6158 $params = array($pathstart);
6160 if ($force) {
6161 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6162 $params[] = $pathstart;
6163 } else {
6164 $where = "depth = 0 OR path IS NULL";
6167 $sql = "UPDATE {context}
6168 SET depth = 2,
6169 path = {$path}
6170 WHERE contextlevel = " . CONTEXT_USER . "
6171 AND ($where)";
6172 $DB->execute($sql, $params);
6178 * Course category context class
6180 * @package core_access
6181 * @category access
6182 * @copyright Petr Skoda {@link http://skodak.org}
6183 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6184 * @since Moodle 2.2
6186 class context_coursecat extends context {
6188 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6189 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6191 * @param stdClass $record
6193 protected function __construct(stdClass $record) {
6194 parent::__construct($record);
6195 if ($record->contextlevel != CONTEXT_COURSECAT) {
6196 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6201 * Returns human readable context level name.
6203 * @static
6204 * @return string the human readable context level name.
6206 public static function get_level_name() {
6207 return get_string('category');
6211 * Returns human readable context identifier.
6213 * @param boolean $withprefix whether to prefix the name of the context with Category
6214 * @param boolean $short does not apply to course categories
6215 * @return string the human readable context name.
6217 public function get_context_name($withprefix = true, $short = false) {
6218 global $DB;
6220 $name = '';
6221 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6222 if ($withprefix){
6223 $name = get_string('category').': ';
6225 $name .= format_string($category->name, true, array('context' => $this));
6227 return $name;
6231 * Returns the most relevant URL for this context.
6233 * @return moodle_url
6235 public function get_url() {
6236 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6240 * Returns array of relevant context capability records.
6242 * @return array
6244 public function get_capabilities() {
6245 global $DB;
6247 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6249 $params = array();
6250 $sql = "SELECT *
6251 FROM {capabilities}
6252 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6254 return $DB->get_records_sql($sql.' '.$sort, $params);
6258 * Returns course category context instance.
6260 * @static
6261 * @param int $categoryid id from {course_categories} table
6262 * @param int $strictness
6263 * @return context_coursecat context instance
6265 public static function instance($categoryid, $strictness = MUST_EXIST) {
6266 global $DB;
6268 if ($context = context::cache_get(CONTEXT_COURSECAT, $categoryid)) {
6269 return $context;
6272 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT, 'instanceid' => $categoryid))) {
6273 if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6274 if ($category->parent) {
6275 $parentcontext = context_coursecat::instance($category->parent);
6276 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6277 } else {
6278 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6283 if ($record) {
6284 $context = new context_coursecat($record);
6285 context::cache_add($context);
6286 return $context;
6289 return false;
6293 * Returns immediate child contexts of category and all subcategories,
6294 * children of subcategories and courses are not returned.
6296 * @return array
6298 public function get_child_contexts() {
6299 global $DB;
6301 if (empty($this->_path) or empty($this->_depth)) {
6302 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6303 return array();
6306 $sql = "SELECT ctx.*
6307 FROM {context} ctx
6308 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6309 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6310 $records = $DB->get_records_sql($sql, $params);
6312 $result = array();
6313 foreach ($records as $record) {
6314 $result[$record->id] = context::create_instance_from_record($record);
6317 return $result;
6321 * Create missing context instances at course category context level
6322 * @static
6324 protected static function create_level_instances() {
6325 global $DB;
6327 $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6328 FROM {course_categories} cc
6329 WHERE NOT EXISTS (SELECT 'x'
6330 FROM {context} cx
6331 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6332 $contextdata = $DB->get_recordset_sql($sql);
6333 foreach ($contextdata as $context) {
6334 context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6336 $contextdata->close();
6340 * Returns sql necessary for purging of stale context instances.
6342 * @static
6343 * @return string cleanup SQL
6345 protected static function get_cleanup_sql() {
6346 $sql = "
6347 SELECT c.*
6348 FROM {context} c
6349 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6350 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6353 return $sql;
6357 * Rebuild context paths and depths at course category context level.
6359 * @static
6360 * @param bool $force
6362 protected static function build_paths($force) {
6363 global $DB;
6365 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6366 if ($force) {
6367 $ctxemptyclause = $emptyclause = '';
6368 } else {
6369 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6370 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6373 $base = '/'.SYSCONTEXTID;
6375 // Normal top level categories
6376 $sql = "UPDATE {context}
6377 SET depth=2,
6378 path=".$DB->sql_concat("'$base/'", 'id')."
6379 WHERE contextlevel=".CONTEXT_COURSECAT."
6380 AND EXISTS (SELECT 'x'
6381 FROM {course_categories} cc
6382 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6383 $emptyclause";
6384 $DB->execute($sql);
6386 // Deeper categories - one query per depthlevel
6387 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6388 for ($n=2; $n<=$maxdepth; $n++) {
6389 $sql = "INSERT INTO {context_temp} (id, path, depth)
6390 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6391 FROM {context} ctx
6392 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6393 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6394 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6395 $ctxemptyclause";
6396 $trans = $DB->start_delegated_transaction();
6397 $DB->delete_records('context_temp');
6398 $DB->execute($sql);
6399 context::merge_context_temp_table();
6400 $DB->delete_records('context_temp');
6401 $trans->allow_commit();
6410 * Course context class
6412 * @package core_access
6413 * @category access
6414 * @copyright Petr Skoda {@link http://skodak.org}
6415 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6416 * @since Moodle 2.2
6418 class context_course extends context {
6420 * Please use context_course::instance($courseid) if you need the instance of context.
6421 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6423 * @param stdClass $record
6425 protected function __construct(stdClass $record) {
6426 parent::__construct($record);
6427 if ($record->contextlevel != CONTEXT_COURSE) {
6428 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6433 * Returns human readable context level name.
6435 * @static
6436 * @return string the human readable context level name.
6438 public static function get_level_name() {
6439 return get_string('course');
6443 * Returns human readable context identifier.
6445 * @param boolean $withprefix whether to prefix the name of the context with Course
6446 * @param boolean $short whether to use the short name of the thing.
6447 * @return string the human readable context name.
6449 public function get_context_name($withprefix = true, $short = false) {
6450 global $DB;
6452 $name = '';
6453 if ($this->_instanceid == SITEID) {
6454 $name = get_string('frontpage', 'admin');
6455 } else {
6456 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6457 if ($withprefix){
6458 $name = get_string('course').': ';
6460 if ($short){
6461 $name .= format_string($course->shortname, true, array('context' => $this));
6462 } else {
6463 $name .= format_string(get_course_display_name_for_list($course));
6467 return $name;
6471 * Returns the most relevant URL for this context.
6473 * @return moodle_url
6475 public function get_url() {
6476 if ($this->_instanceid != SITEID) {
6477 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6480 return new moodle_url('/');
6484 * Returns array of relevant context capability records.
6486 * @return array
6488 public function get_capabilities() {
6489 global $DB;
6491 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6493 $params = array();
6494 $sql = "SELECT *
6495 FROM {capabilities}
6496 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6498 return $DB->get_records_sql($sql.' '.$sort, $params);
6502 * Is this context part of any course? If yes return course context.
6504 * @param bool $strict true means throw exception if not found, false means return false if not found
6505 * @return context_course context of the enclosing course, null if not found or exception
6507 public function get_course_context($strict = true) {
6508 return $this;
6512 * Returns course context instance.
6514 * @static
6515 * @param int $courseid id from {course} table
6516 * @param int $strictness
6517 * @return context_course context instance
6519 public static function instance($courseid, $strictness = MUST_EXIST) {
6520 global $DB;
6522 if ($context = context::cache_get(CONTEXT_COURSE, $courseid)) {
6523 return $context;
6526 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $courseid))) {
6527 if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
6528 if ($course->category) {
6529 $parentcontext = context_coursecat::instance($course->category);
6530 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6531 } else {
6532 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6537 if ($record) {
6538 $context = new context_course($record);
6539 context::cache_add($context);
6540 return $context;
6543 return false;
6547 * Create missing context instances at course context level
6548 * @static
6550 protected static function create_level_instances() {
6551 global $DB;
6553 $sql = "SELECT ".CONTEXT_COURSE.", c.id
6554 FROM {course} c
6555 WHERE NOT EXISTS (SELECT 'x'
6556 FROM {context} cx
6557 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6558 $contextdata = $DB->get_recordset_sql($sql);
6559 foreach ($contextdata as $context) {
6560 context::insert_context_record(CONTEXT_COURSE, $context->id, null);
6562 $contextdata->close();
6566 * Returns sql necessary for purging of stale context instances.
6568 * @static
6569 * @return string cleanup SQL
6571 protected static function get_cleanup_sql() {
6572 $sql = "
6573 SELECT c.*
6574 FROM {context} c
6575 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6576 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6579 return $sql;
6583 * Rebuild context paths and depths at course context level.
6585 * @static
6586 * @param bool $force
6588 protected static function build_paths($force) {
6589 global $DB;
6591 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6592 if ($force) {
6593 $ctxemptyclause = $emptyclause = '';
6594 } else {
6595 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6596 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6599 $base = '/'.SYSCONTEXTID;
6601 // Standard frontpage
6602 $sql = "UPDATE {context}
6603 SET depth = 2,
6604 path = ".$DB->sql_concat("'$base/'", 'id')."
6605 WHERE contextlevel = ".CONTEXT_COURSE."
6606 AND EXISTS (SELECT 'x'
6607 FROM {course} c
6608 WHERE c.id = {context}.instanceid AND c.category = 0)
6609 $emptyclause";
6610 $DB->execute($sql);
6612 // standard courses
6613 $sql = "INSERT INTO {context_temp} (id, path, depth)
6614 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6615 FROM {context} ctx
6616 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6617 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6618 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6619 $ctxemptyclause";
6620 $trans = $DB->start_delegated_transaction();
6621 $DB->delete_records('context_temp');
6622 $DB->execute($sql);
6623 context::merge_context_temp_table();
6624 $DB->delete_records('context_temp');
6625 $trans->allow_commit();
6632 * Course module context class
6634 * @package core_access
6635 * @category access
6636 * @copyright Petr Skoda {@link http://skodak.org}
6637 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6638 * @since Moodle 2.2
6640 class context_module extends context {
6642 * Please use context_module::instance($cmid) if you need the instance of context.
6643 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6645 * @param stdClass $record
6647 protected function __construct(stdClass $record) {
6648 parent::__construct($record);
6649 if ($record->contextlevel != CONTEXT_MODULE) {
6650 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6655 * Returns human readable context level name.
6657 * @static
6658 * @return string the human readable context level name.
6660 public static function get_level_name() {
6661 return get_string('activitymodule');
6665 * Returns human readable context identifier.
6667 * @param boolean $withprefix whether to prefix the name of the context with the
6668 * module name, e.g. Forum, Glossary, etc.
6669 * @param boolean $short does not apply to module context
6670 * @return string the human readable context name.
6672 public function get_context_name($withprefix = true, $short = false) {
6673 global $DB;
6675 $name = '';
6676 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6677 FROM {course_modules} cm
6678 JOIN {modules} md ON md.id = cm.module
6679 WHERE cm.id = ?", array($this->_instanceid))) {
6680 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6681 if ($withprefix){
6682 $name = get_string('modulename', $cm->modname).': ';
6684 $name .= format_string($mod->name, true, array('context' => $this));
6687 return $name;
6691 * Returns the most relevant URL for this context.
6693 * @return moodle_url
6695 public function get_url() {
6696 global $DB;
6698 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6699 FROM {course_modules} cm
6700 JOIN {modules} md ON md.id = cm.module
6701 WHERE cm.id = ?", array($this->_instanceid))) {
6702 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6705 return new moodle_url('/');
6709 * Returns array of relevant context capability records.
6711 * @return array
6713 public function get_capabilities() {
6714 global $DB, $CFG;
6716 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6718 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6719 $module = $DB->get_record('modules', array('id'=>$cm->module));
6721 $subcaps = array();
6722 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6723 if (file_exists($subpluginsfile)) {
6724 $subplugins = array(); // should be redefined in the file
6725 include($subpluginsfile);
6726 if (!empty($subplugins)) {
6727 foreach (array_keys($subplugins) as $subplugintype) {
6728 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
6729 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6735 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6736 $extracaps = array();
6737 if (file_exists($modfile)) {
6738 include_once($modfile);
6739 $modfunction = $module->name.'_get_extra_capabilities';
6740 if (function_exists($modfunction)) {
6741 $extracaps = $modfunction();
6745 $extracaps = array_merge($subcaps, $extracaps);
6746 $extra = '';
6747 list($extra, $params) = $DB->get_in_or_equal(
6748 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
6749 if (!empty($extra)) {
6750 $extra = "OR name $extra";
6752 $sql = "SELECT *
6753 FROM {capabilities}
6754 WHERE (contextlevel = ".CONTEXT_MODULE."
6755 AND (component = :component OR component = 'moodle'))
6756 $extra";
6757 $params['component'] = "mod_$module->name";
6759 return $DB->get_records_sql($sql.' '.$sort, $params);
6763 * Is this context part of any course? If yes return course context.
6765 * @param bool $strict true means throw exception if not found, false means return false if not found
6766 * @return context_course context of the enclosing course, null if not found or exception
6768 public function get_course_context($strict = true) {
6769 return $this->get_parent_context();
6773 * Returns module context instance.
6775 * @static
6776 * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
6777 * @param int $strictness
6778 * @return context_module context instance
6780 public static function instance($cmid, $strictness = MUST_EXIST) {
6781 global $DB;
6783 if ($context = context::cache_get(CONTEXT_MODULE, $cmid)) {
6784 return $context;
6787 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE, 'instanceid' => $cmid))) {
6788 if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
6789 $parentcontext = context_course::instance($cm->course);
6790 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
6794 if ($record) {
6795 $context = new context_module($record);
6796 context::cache_add($context);
6797 return $context;
6800 return false;
6804 * Create missing context instances at module context level
6805 * @static
6807 protected static function create_level_instances() {
6808 global $DB;
6810 $sql = "SELECT ".CONTEXT_MODULE.", cm.id
6811 FROM {course_modules} cm
6812 WHERE NOT EXISTS (SELECT 'x'
6813 FROM {context} cx
6814 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
6815 $contextdata = $DB->get_recordset_sql($sql);
6816 foreach ($contextdata as $context) {
6817 context::insert_context_record(CONTEXT_MODULE, $context->id, null);
6819 $contextdata->close();
6823 * Returns sql necessary for purging of stale context instances.
6825 * @static
6826 * @return string cleanup SQL
6828 protected static function get_cleanup_sql() {
6829 $sql = "
6830 SELECT c.*
6831 FROM {context} c
6832 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6833 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
6836 return $sql;
6840 * Rebuild context paths and depths at module context level.
6842 * @static
6843 * @param bool $force
6845 protected static function build_paths($force) {
6846 global $DB;
6848 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
6849 if ($force) {
6850 $ctxemptyclause = '';
6851 } else {
6852 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6855 $sql = "INSERT INTO {context_temp} (id, path, depth)
6856 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6857 FROM {context} ctx
6858 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
6859 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
6860 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6861 $ctxemptyclause";
6862 $trans = $DB->start_delegated_transaction();
6863 $DB->delete_records('context_temp');
6864 $DB->execute($sql);
6865 context::merge_context_temp_table();
6866 $DB->delete_records('context_temp');
6867 $trans->allow_commit();
6874 * Block context class
6876 * @package core_access
6877 * @category access
6878 * @copyright Petr Skoda {@link http://skodak.org}
6879 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6880 * @since Moodle 2.2
6882 class context_block extends context {
6884 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6885 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6887 * @param stdClass $record
6889 protected function __construct(stdClass $record) {
6890 parent::__construct($record);
6891 if ($record->contextlevel != CONTEXT_BLOCK) {
6892 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6897 * Returns human readable context level name.
6899 * @static
6900 * @return string the human readable context level name.
6902 public static function get_level_name() {
6903 return get_string('block');
6907 * Returns human readable context identifier.
6909 * @param boolean $withprefix whether to prefix the name of the context with Block
6910 * @param boolean $short does not apply to block context
6911 * @return string the human readable context name.
6913 public function get_context_name($withprefix = true, $short = false) {
6914 global $DB, $CFG;
6916 $name = '';
6917 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
6918 global $CFG;
6919 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
6920 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
6921 $blockname = "block_$blockinstance->blockname";
6922 if ($blockobject = new $blockname()) {
6923 if ($withprefix){
6924 $name = get_string('block').': ';
6926 $name .= $blockobject->title;
6930 return $name;
6934 * Returns the most relevant URL for this context.
6936 * @return moodle_url
6938 public function get_url() {
6939 $parentcontexts = $this->get_parent_context();
6940 return $parentcontexts->get_url();
6944 * Returns array of relevant context capability records.
6946 * @return array
6948 public function get_capabilities() {
6949 global $DB;
6951 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6953 $params = array();
6954 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
6956 $extra = '';
6957 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
6958 if ($extracaps) {
6959 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6960 $extra = "OR name $extra";
6963 $sql = "SELECT *
6964 FROM {capabilities}
6965 WHERE (contextlevel = ".CONTEXT_BLOCK."
6966 AND component = :component)
6967 $extra";
6968 $params['component'] = 'block_' . $bi->blockname;
6970 return $DB->get_records_sql($sql.' '.$sort, $params);
6974 * Is this context part of any course? If yes return course context.
6976 * @param bool $strict true means throw exception if not found, false means return false if not found
6977 * @return context_course context of the enclosing course, null if not found or exception
6979 public function get_course_context($strict = true) {
6980 $parentcontext = $this->get_parent_context();
6981 return $parentcontext->get_course_context($strict);
6985 * Returns block context instance.
6987 * @static
6988 * @param int $blockinstanceid id from {block_instances} table.
6989 * @param int $strictness
6990 * @return context_block context instance
6992 public static function instance($blockinstanceid, $strictness = MUST_EXIST) {
6993 global $DB;
6995 if ($context = context::cache_get(CONTEXT_BLOCK, $blockinstanceid)) {
6996 return $context;
6999 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $blockinstanceid))) {
7000 if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
7001 $parentcontext = context::instance_by_id($bi->parentcontextid);
7002 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7006 if ($record) {
7007 $context = new context_block($record);
7008 context::cache_add($context);
7009 return $context;
7012 return false;
7016 * Block do not have child contexts...
7017 * @return array
7019 public function get_child_contexts() {
7020 return array();
7024 * Create missing context instances at block context level
7025 * @static
7027 protected static function create_level_instances() {
7028 global $DB;
7030 $sql = "SELECT ".CONTEXT_BLOCK.", bi.id
7031 FROM {block_instances} bi
7032 WHERE NOT EXISTS (SELECT 'x'
7033 FROM {context} cx
7034 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7035 $contextdata = $DB->get_recordset_sql($sql);
7036 foreach ($contextdata as $context) {
7037 context::insert_context_record(CONTEXT_BLOCK, $context->id, null);
7039 $contextdata->close();
7043 * Returns sql necessary for purging of stale context instances.
7045 * @static
7046 * @return string cleanup SQL
7048 protected static function get_cleanup_sql() {
7049 $sql = "
7050 SELECT c.*
7051 FROM {context} c
7052 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7053 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7056 return $sql;
7060 * Rebuild context paths and depths at block context level.
7062 * @static
7063 * @param bool $force
7065 protected static function build_paths($force) {
7066 global $DB;
7068 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7069 if ($force) {
7070 $ctxemptyclause = '';
7071 } else {
7072 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7075 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7076 $sql = "INSERT INTO {context_temp} (id, path, depth)
7077 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7078 FROM {context} ctx
7079 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7080 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7081 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7082 $ctxemptyclause";
7083 $trans = $DB->start_delegated_transaction();
7084 $DB->delete_records('context_temp');
7085 $DB->execute($sql);
7086 context::merge_context_temp_table();
7087 $DB->delete_records('context_temp');
7088 $trans->allow_commit();
7094 // ============== DEPRECATED FUNCTIONS ==========================================
7095 // Old context related functions were deprecated in 2.0, it is recommended
7096 // to use context classes in new code. Old function can be used when
7097 // creating patches that are supposed to be backported to older stable branches.
7098 // These deprecated functions will not be removed in near future,
7099 // before removing devs will be warned with a debugging message first,
7100 // then we will add error message and only after that we can remove the functions
7101 // completely.
7104 * Runs get_records select on context table and returns the result
7105 * Does get_records_select on the context table, and returns the results ordered
7106 * by contextlevel, and then the natural sort order within each level.
7107 * for the purpose of $select, you need to know that the context table has been
7108 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7110 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7111 * @param array $params any parameters required by $select.
7112 * @return array the requested context records.
7114 function get_sorted_contexts($select, $params = array()) {
7116 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7118 global $DB;
7119 if ($select) {
7120 $select = 'WHERE ' . $select;
7122 return $DB->get_records_sql("
7123 SELECT ctx.*
7124 FROM {context} ctx
7125 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7126 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7127 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7128 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7129 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7130 $select
7131 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7132 ", $params);
7136 * Given context and array of users, returns array of users whose enrolment status is suspended,
7137 * or enrolment has expired or has not started. Also removes those users from the given array
7139 * @param context $context context in which suspended users should be extracted.
7140 * @param array $users list of users.
7141 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7142 * @return array list of suspended users.
7144 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7145 global $DB;
7147 // Get active enrolled users.
7148 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7149 $activeusers = $DB->get_records_sql($sql, $params);
7151 // Move suspended users to a separate array & remove from the initial one.
7152 $susers = array();
7153 if (sizeof($activeusers)) {
7154 foreach ($users as $userid => $user) {
7155 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7156 $susers[$userid] = $user;
7157 unset($users[$userid]);
7161 return $susers;
7165 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7166 * or enrolment has expired or not started.
7168 * @param context $context context in which user enrolment is checked.
7169 * @param bool $usecache Enable or disable (default) the request cache
7170 * @return array list of suspended user id's.
7172 function get_suspended_userids(context $context, $usecache = false) {
7173 global $DB;
7175 if ($usecache) {
7176 $cache = cache::make('core', 'suspended_userids');
7177 $susers = $cache->get($context->id);
7178 if ($susers !== false) {
7179 return $susers;
7183 $coursecontext = $context->get_course_context();
7184 $susers = array();
7186 // Front page users are always enrolled, so suspended list is empty.
7187 if ($coursecontext->instanceid != SITEID) {
7188 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7189 $susers = $DB->get_fieldset_sql($sql, $params);
7190 $susers = array_combine($susers, $susers);
7193 // Cache results for the remainder of this request.
7194 if ($usecache) {
7195 $cache->set($context->id, $susers);
7198 return $susers;
7202 * Gets sql for finding users with capability in the given context
7204 * @param context $context
7205 * @param string|array $capability Capability name or array of names.
7206 * If an array is provided then this is the equivalent of a logical 'OR',
7207 * i.e. the user needs to have one of these capabilities.
7208 * @return array($sql, $params)
7210 function get_with_capability_sql(context $context, $capability) {
7211 static $i = 0;
7212 $i++;
7213 $prefix = 'cu' . $i . '_';
7215 $capjoin = get_with_capability_join($context, $capability, $prefix . 'u.id');
7217 $sql = "SELECT DISTINCT {$prefix}u.id
7218 FROM {user} {$prefix}u
7219 $capjoin->joins
7220 WHERE {$prefix}u.deleted = 0 AND $capjoin->wheres";
7222 return array($sql, $capjoin->params);
7226 * Gets sql joins for finding users with capability in the given context
7228 * @param context $context Context for the join
7229 * @param string|array $capability Capability name or array of names.
7230 * If an array is provided then this is the equivalent of a logical 'OR',
7231 * i.e. the user needs to have one of these capabilities.
7232 * @param string $useridcolumn e.g. 'u.id'
7233 * @return \core\dml\sql_join Contains joins, wheres, params
7235 function get_with_capability_join(context $context, $capability, $useridcolumn) {
7236 global $DB, $CFG;
7238 // Use unique prefix just in case somebody makes some SQL magic with the result.
7239 static $i = 0;
7240 $i++;
7241 $prefix = 'eu' . $i . '_';
7243 // First find the course context.
7244 $coursecontext = $context->get_course_context();
7246 $isfrontpage = ($coursecontext->instanceid == SITEID);
7248 $joins = array();
7249 $wheres = array();
7250 $params = array();
7252 list($contextids, $contextpaths) = get_context_info_list($context);
7254 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
7256 list($incaps, $capsparams) = $DB->get_in_or_equal($capability, SQL_PARAMS_NAMED, 'cap');
7258 $defs = array();
7259 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
7260 FROM {role_capabilities} rc
7261 JOIN {context} ctx on rc.contextid = ctx.id
7262 WHERE rc.contextid $incontexts AND rc.capability $incaps";
7263 $rcs = $DB->get_records_sql($sql, array_merge($cparams, $capsparams));
7264 foreach ($rcs as $rc) {
7265 $defs[$rc->path][$rc->roleid] = $rc->permission;
7268 $access = array();
7269 if (!empty($defs)) {
7270 foreach ($contextpaths as $path) {
7271 if (empty($defs[$path])) {
7272 continue;
7274 foreach ($defs[$path] as $roleid => $perm) {
7275 if ($perm == CAP_PROHIBIT) {
7276 $access[$roleid] = CAP_PROHIBIT;
7277 continue;
7279 if (!isset($access[$roleid])) {
7280 $access[$roleid] = (int) $perm;
7286 unset($defs);
7288 // Make lists of roles that are needed and prohibited.
7289 $needed = array(); // One of these is enough.
7290 $prohibited = array(); // Must not have any of these.
7291 foreach ($access as $roleid => $perm) {
7292 if ($perm == CAP_PROHIBIT) {
7293 unset($needed[$roleid]);
7294 $prohibited[$roleid] = true;
7295 } else {
7296 if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
7297 $needed[$roleid] = true;
7302 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
7303 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
7305 $nobody = false;
7307 if ($isfrontpage) {
7308 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
7309 $nobody = true;
7310 } else {
7311 if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
7312 // Everybody not having prohibit has the capability.
7313 $needed = array();
7314 } else {
7315 if (empty($needed)) {
7316 $nobody = true;
7320 } else {
7321 if (!empty($prohibited[$defaultuserroleid])) {
7322 $nobody = true;
7323 } else {
7324 if (!empty($needed[$defaultuserroleid])) {
7325 // Everybody not having prohibit has the capability.
7326 $needed = array();
7327 } else {
7328 if (empty($needed)) {
7329 $nobody = true;
7335 if ($nobody) {
7336 // Nobody can match so return some SQL that does not return any results.
7337 $wheres[] = "1 = 2";
7339 } else {
7341 if ($needed) {
7342 $ctxids = implode(',', $contextids);
7343 $roleids = implode(',', array_keys($needed));
7344 $joins[] = "JOIN {role_assignments} {$prefix}ra3
7345 ON ({$prefix}ra3.userid = $useridcolumn
7346 AND {$prefix}ra3.roleid IN ($roleids)
7347 AND {$prefix}ra3.contextid IN ($ctxids))";
7350 if ($prohibited) {
7351 $ctxids = implode(',', $contextids);
7352 $roleids = implode(',', array_keys($prohibited));
7353 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4
7354 ON ({$prefix}ra4.userid = $useridcolumn
7355 AND {$prefix}ra4.roleid IN ($roleids)
7356 AND {$prefix}ra4.contextid IN ($ctxids))";
7357 $wheres[] = "{$prefix}ra4.id IS NULL";
7362 $wheres[] = "$useridcolumn <> :{$prefix}guestid";
7363 $params["{$prefix}guestid"] = $CFG->siteguest;
7365 $joins = implode("\n", $joins);
7366 $wheres = "(" . implode(" AND ", $wheres) . ")";
7368 return new \core\dml\sql_join($joins, $wheres, $params);