MDL-35701 respect case of external column names in enrol_database
[moodle.git] / lib / accesslib.php
blob2163435043da3a309fe93342e3ee8764bc7db091
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_access_sitewide()
60 * - load_course_context()
61 * - load_role_access_by_context()
62 * - etc.
64 * <b>Name conventions</b>
66 * "ctx" means context
68 * <b>accessdata</b>
70 * Access control data is held in the "accessdata" array
71 * which - for the logged-in user, will be in $USER->access
73 * For other users can be generated and passed around (but may also be cached
74 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser).
76 * $accessdata is a multidimensional array, holding
77 * role assignments (RAs), role-capabilities-perm sets
78 * (role defs) and a list of courses we have loaded
79 * data for.
81 * Things are keyed on "contextpaths" (the path field of
82 * the context table) for fast walking up/down the tree.
83 * <code>
84 * $accessdata['ra'][$contextpath] = array($roleid=>$roleid)
85 * [$contextpath] = array($roleid=>$roleid)
86 * [$contextpath] = array($roleid=>$roleid)
87 * </code>
89 * Role definitions are stored like this
90 * (no cap merge is done - so it's compact)
92 * <code>
93 * $accessdata['rdef']["$contextpath:$roleid"]['mod/forum:viewpost'] = 1
94 * ['mod/forum:editallpost'] = -1
95 * ['mod/forum:startdiscussion'] = -1000
96 * </code>
98 * See how has_capability_in_accessdata() walks up the tree.
100 * First we only load rdef and ra down to the course level, but not below.
101 * This keeps accessdata small and compact. Below-the-course ra/rdef
102 * are loaded as needed. We keep track of which courses we have loaded ra/rdef in
103 * <code>
104 * $accessdata['loaded'] = array($courseid1=>1, $courseid2=>1)
105 * </code>
107 * <b>Stale accessdata</b>
109 * For the logged-in user, accessdata is long-lived.
111 * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
112 * context paths affected by changes. Any check at-or-below
113 * a dirty context will trigger a transparent reload of accessdata.
115 * Changes at the system level will force the reload for everyone.
117 * <b>Default role caps</b>
118 * The default role assignment is not in the DB, so we
119 * add it manually to accessdata.
121 * This means that functions that work directly off the
122 * DB need to ensure that the default role caps
123 * are dealt with appropriately.
125 * @package core_access
126 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
127 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
130 defined('MOODLE_INTERNAL') || die();
132 /** No capability change */
133 define('CAP_INHERIT', 0);
134 /** Allow permission, overrides CAP_PREVENT defined in parent contexts */
135 define('CAP_ALLOW', 1);
136 /** Prevent permission, overrides CAP_ALLOW defined in parent contexts */
137 define('CAP_PREVENT', -1);
138 /** Prohibit permission, overrides everything in current and child contexts */
139 define('CAP_PROHIBIT', -1000);
141 /** System context level - only one instance in every system */
142 define('CONTEXT_SYSTEM', 10);
143 /** User context level - one instance for each user describing what others can do to user */
144 define('CONTEXT_USER', 30);
145 /** Course category context level - one instance for each category */
146 define('CONTEXT_COURSECAT', 40);
147 /** Course context level - one instances for each course */
148 define('CONTEXT_COURSE', 50);
149 /** Course module context level - one instance for each course module */
150 define('CONTEXT_MODULE', 70);
152 * Block context level - one instance for each block, sticky blocks are tricky
153 * because ppl think they should be able to override them at lower contexts.
154 * Any other context level instance can be parent of block context.
156 define('CONTEXT_BLOCK', 80);
158 /** Capability allow management of trusts - NOT IMPLEMENTED YET - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
159 define('RISK_MANAGETRUST', 0x0001);
160 /** Capability allows changes in system configuration - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
161 define('RISK_CONFIG', 0x0002);
162 /** Capability allows user to add scripted content - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
163 define('RISK_XSS', 0x0004);
164 /** Capability allows access to personal user information - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
165 define('RISK_PERSONAL', 0x0008);
166 /** Capability allows users to add content others may see - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
167 define('RISK_SPAM', 0x0010);
168 /** capability allows mass delete of data belonging to other users - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
169 define('RISK_DATALOSS', 0x0020);
171 /** rolename displays - the name as defined in the role definition, localised if name empty */
172 define('ROLENAME_ORIGINAL', 0);
173 /** rolename displays - the name as defined by a role alias at the course level, falls back to ROLENAME_ORIGINAL if alias not present */
174 define('ROLENAME_ALIAS', 1);
175 /** rolename displays - Both, like this: Role alias (Original) */
176 define('ROLENAME_BOTH', 2);
177 /** rolename displays - the name as defined in the role definition and the shortname in brackets */
178 define('ROLENAME_ORIGINALANDSHORT', 3);
179 /** rolename displays - the name as defined by a role alias, in raw form suitable for editing */
180 define('ROLENAME_ALIAS_RAW', 4);
181 /** rolename displays - the name is simply short role name */
182 define('ROLENAME_SHORT', 5);
184 if (!defined('CONTEXT_CACHE_MAX_SIZE')) {
185 /** maximum size of context cache - it is possible to tweak this config.php or in any script before inclusion of context.php */
186 define('CONTEXT_CACHE_MAX_SIZE', 2500);
190 * Although this looks like a global variable, it isn't really.
192 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
193 * It is used to cache various bits of data between function calls for performance reasons.
194 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
195 * as methods of a class, instead of functions.
197 * @access private
198 * @global stdClass $ACCESSLIB_PRIVATE
199 * @name $ACCESSLIB_PRIVATE
201 global $ACCESSLIB_PRIVATE;
202 $ACCESSLIB_PRIVATE = new stdClass();
203 $ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache, loaded from DB once per page
204 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
205 $ACCESSLIB_PRIVATE->rolepermissions = array(); // role permissions cache - helps a lot with mem usage
206 $ACCESSLIB_PRIVATE->capabilities = null; // detailed information about the capabilities
209 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
211 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
212 * accesslib's private caches. You need to do this before setting up test data,
213 * and also at the end of the tests.
215 * @access private
216 * @return void
218 function accesslib_clear_all_caches_for_unit_testing() {
219 global $USER;
220 if (!PHPUNIT_TEST) {
221 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
224 accesslib_clear_all_caches(true);
226 unset($USER->access);
230 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
232 * This reset does not touch global $USER.
234 * @access private
235 * @param bool $resetcontexts
236 * @return void
238 function accesslib_clear_all_caches($resetcontexts) {
239 global $ACCESSLIB_PRIVATE;
241 $ACCESSLIB_PRIVATE->dirtycontexts = null;
242 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
243 $ACCESSLIB_PRIVATE->rolepermissions = array();
244 $ACCESSLIB_PRIVATE->capabilities = null;
246 if ($resetcontexts) {
247 context_helper::reset_caches();
252 * Gets the accessdata for role "sitewide" (system down to course)
254 * @access private
255 * @param int $roleid
256 * @return array
258 function get_role_access($roleid) {
259 global $DB, $ACCESSLIB_PRIVATE;
261 /* Get it in 1 DB query...
262 * - relevant role caps at the root and down
263 * to the course level - but not below
266 //TODO: MUC - this could be cached in shared memory to speed up first page loading, web crawlers, etc.
268 $accessdata = get_empty_accessdata();
270 $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
273 // Overrides for the role IN ANY CONTEXTS
274 // down to COURSE - not below -
276 $sql = "SELECT ctx.path,
277 rc.capability, rc.permission
278 FROM {context} ctx
279 JOIN {role_capabilities} rc ON rc.contextid = ctx.id
280 LEFT JOIN {context} cctx
281 ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
282 WHERE rc.roleid = ? AND cctx.id IS NULL";
283 $params = array($roleid);
285 // we need extra caching in CLI scripts and cron
286 $rs = $DB->get_recordset_sql($sql, $params);
287 foreach ($rs as $rd) {
288 $k = "{$rd->path}:{$roleid}";
289 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
291 $rs->close();
293 // share the role definitions
294 foreach ($accessdata['rdef'] as $k=>$unused) {
295 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
296 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
298 $accessdata['rdef_count']++;
299 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
302 return $accessdata;
306 * Get the default guest role, this is used for guest account,
307 * search engine spiders, etc.
309 * @return stdClass role record
311 function get_guest_role() {
312 global $CFG, $DB;
314 if (empty($CFG->guestroleid)) {
315 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
316 $guestrole = array_shift($roles); // Pick the first one
317 set_config('guestroleid', $guestrole->id);
318 return $guestrole;
319 } else {
320 debugging('Can not find any guest role!');
321 return false;
323 } else {
324 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
325 return $guestrole;
326 } else {
327 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
328 set_config('guestroleid', '');
329 return get_guest_role();
335 * Check whether a user has a particular capability in a given context.
337 * For example:
338 * $context = context_module::instance($cm->id);
339 * has_capability('mod/forum:replypost', $context)
341 * By default checks the capabilities of the current user, but you can pass a
342 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
344 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
345 * or capabilities with XSS, config or data loss risks.
347 * @category access
349 * @param string $capability the name of the capability to check. For example mod/forum:view
350 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
351 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
352 * @param boolean $doanything If false, ignores effect of admin role assignment
353 * @return boolean true if the user has this capability. Otherwise false.
355 function has_capability($capability, context $context, $user = null, $doanything = true) {
356 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
358 if (during_initial_install()) {
359 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cli/install.php" or $SCRIPT === "/$CFG->admin/cli/install_database.php") {
360 // we are in an installer - roles can not work yet
361 return true;
362 } else {
363 return false;
367 if (strpos($capability, 'moodle/legacy:') === 0) {
368 throw new coding_exception('Legacy capabilities can not be used any more!');
371 if (!is_bool($doanything)) {
372 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
375 // capability must exist
376 if (!$capinfo = get_capability_info($capability)) {
377 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
378 return false;
381 if (!isset($USER->id)) {
382 // should never happen
383 $USER->id = 0;
386 // make sure there is a real user specified
387 if ($user === null) {
388 $userid = $USER->id;
389 } else {
390 $userid = is_object($user) ? $user->id : $user;
393 // make sure forcelogin cuts off not-logged-in users if enabled
394 if (!empty($CFG->forcelogin) and $userid == 0) {
395 return false;
398 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
399 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
400 if (isguestuser($userid) or $userid == 0) {
401 return false;
405 // somehow make sure the user is not deleted and actually exists
406 if ($userid != 0) {
407 if ($userid == $USER->id and isset($USER->deleted)) {
408 // this prevents one query per page, it is a bit of cheating,
409 // but hopefully session is terminated properly once user is deleted
410 if ($USER->deleted) {
411 return false;
413 } else {
414 if (!context_user::instance($userid, IGNORE_MISSING)) {
415 // no user context == invalid userid
416 return false;
421 // context path/depth must be valid
422 if (empty($context->path) or $context->depth == 0) {
423 // this should not happen often, each upgrade tries to rebuild the context paths
424 debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()');
425 if (is_siteadmin($userid)) {
426 return true;
427 } else {
428 return false;
432 // Find out if user is admin - it is not possible to override the doanything in any way
433 // and it is not possible to switch to admin role either.
434 if ($doanything) {
435 if (is_siteadmin($userid)) {
436 if ($userid != $USER->id) {
437 return true;
439 // make sure switchrole is not used in this context
440 if (empty($USER->access['rsw'])) {
441 return true;
443 $parts = explode('/', trim($context->path, '/'));
444 $path = '';
445 $switched = false;
446 foreach ($parts as $part) {
447 $path .= '/' . $part;
448 if (!empty($USER->access['rsw'][$path])) {
449 $switched = true;
450 break;
453 if (!$switched) {
454 return true;
456 //ok, admin switched role in this context, let's use normal access control rules
460 // Careful check for staleness...
461 $context->reload_if_dirty();
463 if ($USER->id == $userid) {
464 if (!isset($USER->access)) {
465 load_all_capabilities();
467 $access =& $USER->access;
469 } else {
470 // make sure user accessdata is really loaded
471 get_user_accessdata($userid, true);
472 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
476 // Load accessdata for below-the-course context if necessary,
477 // all contexts at and above all courses are already loaded
478 if ($context->contextlevel != CONTEXT_COURSE and $coursecontext = $context->get_course_context(false)) {
479 load_course_context($userid, $coursecontext, $access);
482 return has_capability_in_accessdata($capability, $context, $access);
486 * Check if the user has any one of several capabilities from a list.
488 * This is just a utility method that calls has_capability in a loop. Try to put
489 * the capabilities that most users are likely to have first in the list for best
490 * performance.
492 * @category access
493 * @see has_capability()
495 * @param array $capabilities an array of capability names.
496 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
497 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
498 * @param boolean $doanything If false, ignore effect of admin role assignment
499 * @return boolean true if the user has any of these capabilities. Otherwise false.
501 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
502 foreach ($capabilities as $capability) {
503 if (has_capability($capability, $context, $user, $doanything)) {
504 return true;
507 return false;
511 * Check if the user has all the capabilities in a list.
513 * This is just a utility method that calls has_capability in a loop. Try to put
514 * the capabilities that fewest users are likely to have first in the list for best
515 * performance.
517 * @category access
518 * @see has_capability()
520 * @param array $capabilities an array of capability names.
521 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
522 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
523 * @param boolean $doanything If false, ignore effect of admin role assignment
524 * @return boolean true if the user has all of these capabilities. Otherwise false.
526 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
527 foreach ($capabilities as $capability) {
528 if (!has_capability($capability, $context, $user, $doanything)) {
529 return false;
532 return true;
536 * Check if the user is an admin at the site level.
538 * Please note that use of proper capabilities is always encouraged,
539 * this function is supposed to be used from core or for temporary hacks.
541 * @category access
543 * @param int|stdClass $user_or_id user id or user object
544 * @return bool true if user is one of the administrators, false otherwise
546 function is_siteadmin($user_or_id = null) {
547 global $CFG, $USER;
549 if ($user_or_id === null) {
550 $user_or_id = $USER;
553 if (empty($user_or_id)) {
554 return false;
556 if (!empty($user_or_id->id)) {
557 $userid = $user_or_id->id;
558 } else {
559 $userid = $user_or_id;
562 $siteadmins = explode(',', $CFG->siteadmins);
563 return in_array($userid, $siteadmins);
567 * Returns true if user has at least one role assign
568 * of 'coursecontact' role (is potentially listed in some course descriptions).
570 * @param int $userid
571 * @return bool
573 function has_coursecontact_role($userid) {
574 global $DB, $CFG;
576 if (empty($CFG->coursecontact)) {
577 return false;
579 $sql = "SELECT 1
580 FROM {role_assignments}
581 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
582 return $DB->record_exists_sql($sql, array('userid'=>$userid));
586 * Does the user have a capability to do something?
588 * Walk the accessdata array and return true/false.
589 * Deals with prohibits, role switching, aggregating
590 * capabilities, etc.
592 * The main feature of here is being FAST and with no
593 * side effects.
595 * Notes:
597 * Switch Role merges with default role
598 * ------------------------------------
599 * If you are a teacher in course X, you have at least
600 * teacher-in-X + defaultloggedinuser-sitewide. So in the
601 * course you'll have techer+defaultloggedinuser.
602 * We try to mimic that in switchrole.
604 * Permission evaluation
605 * ---------------------
606 * Originally there was an extremely complicated way
607 * to determine the user access that dealt with
608 * "locality" or role assignments and role overrides.
609 * Now we simply evaluate access for each role separately
610 * and then verify if user has at least one role with allow
611 * and at the same time no role with prohibit.
613 * @access private
614 * @param string $capability
615 * @param context $context
616 * @param array $accessdata
617 * @return bool
619 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
620 global $CFG;
622 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
623 $path = $context->path;
624 $paths = array($path);
625 while($path = rtrim($path, '0123456789')) {
626 $path = rtrim($path, '/');
627 if ($path === '') {
628 break;
630 $paths[] = $path;
633 $roles = array();
634 $switchedrole = false;
636 // Find out if role switched
637 if (!empty($accessdata['rsw'])) {
638 // From the bottom up...
639 foreach ($paths as $path) {
640 if (isset($accessdata['rsw'][$path])) {
641 // Found a switchrole assignment - check for that role _plus_ the default user role
642 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
643 $switchedrole = true;
644 break;
649 if (!$switchedrole) {
650 // get all users roles in this context and above
651 foreach ($paths as $path) {
652 if (isset($accessdata['ra'][$path])) {
653 foreach ($accessdata['ra'][$path] as $roleid) {
654 $roles[$roleid] = null;
660 // Now find out what access is given to each role, going bottom-->up direction
661 $allowed = false;
662 foreach ($roles as $roleid => $ignored) {
663 foreach ($paths as $path) {
664 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
665 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
666 if ($perm === CAP_PROHIBIT) {
667 // any CAP_PROHIBIT found means no permission for the user
668 return false;
670 if (is_null($roles[$roleid])) {
671 $roles[$roleid] = $perm;
675 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
676 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
679 return $allowed;
683 * A convenience function that tests has_capability, and displays an error if
684 * the user does not have that capability.
686 * NOTE before Moodle 2.0, this function attempted to make an appropriate
687 * require_login call before checking the capability. This is no longer the case.
688 * You must call require_login (or one of its variants) if you want to check the
689 * user is logged in, before you call this function.
691 * @see has_capability()
693 * @param string $capability the name of the capability to check. For example mod/forum:view
694 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
695 * @param int $userid A user id. By default (null) checks the permissions of the current user.
696 * @param bool $doanything If false, ignore effect of admin role assignment
697 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
698 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
699 * @return void terminates with an error if the user does not have the given capability.
701 function require_capability($capability, context $context, $userid = null, $doanything = true,
702 $errormessage = 'nopermissions', $stringfile = '') {
703 if (!has_capability($capability, $context, $userid, $doanything)) {
704 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
709 * Return a nested array showing role assignments
710 * all relevant role capabilities for the user at
711 * site/course_category/course levels
713 * We do _not_ delve deeper than courses because the number of
714 * overrides at the module/block levels can be HUGE.
716 * [ra] => [/path][roleid]=roleid
717 * [rdef] => [/path:roleid][capability]=permission
719 * @access private
720 * @param int $userid - the id of the user
721 * @return array access info array
723 function get_user_access_sitewide($userid) {
724 global $CFG, $DB, $ACCESSLIB_PRIVATE;
726 /* Get in a few cheap DB queries...
727 * - role assignments
728 * - relevant role caps
729 * - above and within this user's RAs
730 * - below this user's RAs - limited to course level
733 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
734 $raparents = array();
735 $accessdata = get_empty_accessdata();
737 // start with the default role
738 if (!empty($CFG->defaultuserroleid)) {
739 $syscontext = context_system::instance();
740 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
741 $raparents[$CFG->defaultuserroleid][$syscontext->id] = $syscontext->id;
744 // load the "default frontpage role"
745 if (!empty($CFG->defaultfrontpageroleid)) {
746 $frontpagecontext = context_course::instance(get_site()->id);
747 if ($frontpagecontext->path) {
748 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
749 $raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->id] = $frontpagecontext->id;
753 // preload every assigned role at and above course context
754 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
755 FROM {role_assignments} ra
756 JOIN {context} ctx
757 ON ctx.id = ra.contextid
758 LEFT JOIN {block_instances} bi
759 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
760 LEFT JOIN {context} bpctx
761 ON (bpctx.id = bi.parentcontextid)
762 WHERE ra.userid = :userid
763 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")";
764 $params = array('userid'=>$userid);
765 $rs = $DB->get_recordset_sql($sql, $params);
766 foreach ($rs as $ra) {
767 // RAs leafs are arrays to support multi-role assignments...
768 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
769 $raparents[$ra->roleid][$ra->contextid] = $ra->contextid;
771 $rs->close();
773 if (empty($raparents)) {
774 return $accessdata;
777 // now get overrides of interesting roles in all interesting child contexts
778 // hopefully we will not run out of SQL limits here,
779 // users would have to have very many roles at/above course context...
780 $sqls = array();
781 $params = array();
783 static $cp = 0;
784 foreach ($raparents as $roleid=>$ras) {
785 $cp++;
786 list($sqlcids, $cids) = $DB->get_in_or_equal($ras, SQL_PARAMS_NAMED, 'c'.$cp.'_');
787 $params = array_merge($params, $cids);
788 $params['r'.$cp] = $roleid;
789 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
790 FROM {role_capabilities} rc
791 JOIN {context} ctx
792 ON (ctx.id = rc.contextid)
793 JOIN {context} pctx
794 ON (pctx.id $sqlcids
795 AND (ctx.id = pctx.id
796 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
797 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
798 LEFT JOIN {block_instances} bi
799 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
800 LEFT JOIN {context} bpctx
801 ON (bpctx.id = bi.parentcontextid)
802 WHERE rc.roleid = :r{$cp}
803 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")
807 // fixed capability order is necessary for rdef dedupe
808 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
810 foreach ($rs as $rd) {
811 $k = $rd->path.':'.$rd->roleid;
812 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
814 $rs->close();
816 // share the role definitions
817 foreach ($accessdata['rdef'] as $k=>$unused) {
818 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
819 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
821 $accessdata['rdef_count']++;
822 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
825 return $accessdata;
829 * Add to the access ctrl array the data needed by a user for a given course.
831 * This function injects all course related access info into the accessdata array.
833 * @access private
834 * @param int $userid the id of the user
835 * @param context_course $coursecontext course context
836 * @param array $accessdata accessdata array (modified)
837 * @return void modifies $accessdata parameter
839 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
840 global $DB, $CFG, $ACCESSLIB_PRIVATE;
842 if (empty($coursecontext->path)) {
843 // weird, this should not happen
844 return;
847 if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
848 // already loaded, great!
849 return;
852 $roles = array();
854 if (empty($userid)) {
855 if (!empty($CFG->notloggedinroleid)) {
856 $roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
859 } else if (isguestuser($userid)) {
860 if ($guestrole = get_guest_role()) {
861 $roles[$guestrole->id] = $guestrole->id;
864 } else {
865 // Interesting role assignments at, above and below the course context
866 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
867 $params['userid'] = $userid;
868 $params['children'] = $coursecontext->path."/%";
869 $sql = "SELECT ra.*, ctx.path
870 FROM {role_assignments} ra
871 JOIN {context} ctx ON ra.contextid = ctx.id
872 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
873 $rs = $DB->get_recordset_sql($sql, $params);
875 // add missing role definitions
876 foreach ($rs as $ra) {
877 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
878 $roles[$ra->roleid] = $ra->roleid;
880 $rs->close();
882 // add the "default frontpage role" when on the frontpage
883 if (!empty($CFG->defaultfrontpageroleid)) {
884 $frontpagecontext = context_course::instance(get_site()->id);
885 if ($frontpagecontext->id == $coursecontext->id) {
886 $roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
890 // do not forget the default role
891 if (!empty($CFG->defaultuserroleid)) {
892 $roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
896 if (!$roles) {
897 // weird, default roles must be missing...
898 $accessdata['loaded'][$coursecontext->instanceid] = 1;
899 return;
902 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
903 $params = array('c'=>$coursecontext->id);
904 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
905 $params = array_merge($params, $rparams);
906 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
907 $params = array_merge($params, $rparams);
909 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
910 FROM {role_capabilities} rc
911 JOIN {context} ctx
912 ON (ctx.id = rc.contextid)
913 JOIN {context} cctx
914 ON (cctx.id = :c
915 AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
916 WHERE rc.roleid $roleids
917 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
918 $rs = $DB->get_recordset_sql($sql, $params);
920 $newrdefs = array();
921 foreach ($rs as $rd) {
922 $k = $rd->path.':'.$rd->roleid;
923 if (isset($accessdata['rdef'][$k])) {
924 continue;
926 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
928 $rs->close();
930 // share new role definitions
931 foreach ($newrdefs as $k=>$unused) {
932 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
933 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
935 $accessdata['rdef_count']++;
936 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
939 $accessdata['loaded'][$coursecontext->instanceid] = 1;
941 // we want to deduplicate the USER->access from time to time, this looks like a good place,
942 // because we have to do it before the end of session
943 dedupe_user_access();
947 * Add to the access ctrl array the data needed by a role for a given context.
949 * The data is added in the rdef key.
950 * This role-centric function is useful for role_switching
951 * and temporary course roles.
953 * @access private
954 * @param int $roleid the id of the user
955 * @param context $context needs path!
956 * @param array $accessdata accessdata array (is modified)
957 * @return array
959 function load_role_access_by_context($roleid, context $context, &$accessdata) {
960 global $DB, $ACCESSLIB_PRIVATE;
962 /* Get the relevant rolecaps into rdef
963 * - relevant role caps
964 * - at ctx and above
965 * - below this ctx
968 if (empty($context->path)) {
969 // weird, this should not happen
970 return;
973 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
974 $params['roleid'] = $roleid;
975 $params['childpath'] = $context->path.'/%';
977 $sql = "SELECT ctx.path, rc.capability, rc.permission
978 FROM {role_capabilities} rc
979 JOIN {context} ctx ON (rc.contextid = ctx.id)
980 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
981 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
982 $rs = $DB->get_recordset_sql($sql, $params);
984 $newrdefs = array();
985 foreach ($rs as $rd) {
986 $k = $rd->path.':'.$roleid;
987 if (isset($accessdata['rdef'][$k])) {
988 continue;
990 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
992 $rs->close();
994 // share new role definitions
995 foreach ($newrdefs as $k=>$unused) {
996 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
997 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
999 $accessdata['rdef_count']++;
1000 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1005 * Returns empty accessdata structure.
1007 * @access private
1008 * @return array empt accessdata
1010 function get_empty_accessdata() {
1011 $accessdata = array(); // named list
1012 $accessdata['ra'] = array();
1013 $accessdata['rdef'] = array();
1014 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
1015 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
1016 $accessdata['loaded'] = array(); // loaded course contexts
1017 $accessdata['time'] = time();
1018 $accessdata['rsw'] = array();
1020 return $accessdata;
1024 * Get accessdata for a given user.
1026 * @access private
1027 * @param int $userid
1028 * @param bool $preloadonly true means do not return access array
1029 * @return array accessdata
1031 function get_user_accessdata($userid, $preloadonly=false) {
1032 global $CFG, $ACCESSLIB_PRIVATE, $USER;
1034 if (!empty($USER->acces['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1035 // share rdef from USER session with rolepermissions cache in order to conserve memory
1036 foreach($USER->acces['rdef'] as $k=>$v) {
1037 $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->acces['rdef'][$k];
1039 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->acces;
1042 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
1043 if (empty($userid)) {
1044 if (!empty($CFG->notloggedinroleid)) {
1045 $accessdata = get_role_access($CFG->notloggedinroleid);
1046 } else {
1047 // weird
1048 return get_empty_accessdata();
1051 } else if (isguestuser($userid)) {
1052 if ($guestrole = get_guest_role()) {
1053 $accessdata = get_role_access($guestrole->id);
1054 } else {
1055 //weird
1056 return get_empty_accessdata();
1059 } else {
1060 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1063 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1066 if ($preloadonly) {
1067 return;
1068 } else {
1069 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1074 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1075 * this function looks for contexts with the same overrides and shares them.
1077 * @access private
1078 * @return void
1080 function dedupe_user_access() {
1081 global $USER;
1083 if (CLI_SCRIPT) {
1084 // no session in CLI --> no compression necessary
1085 return;
1088 if (empty($USER->access['rdef_count'])) {
1089 // weird, this should not happen
1090 return;
1093 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1094 if ($USER->access['rdef_count'] - $USER->access['rdef_lcc'] > 10) {
1095 // do not compress after each change, wait till there is more stuff to be done
1096 return;
1099 $hashmap = array();
1100 foreach ($USER->access['rdef'] as $k=>$def) {
1101 $hash = sha1(serialize($def));
1102 if (isset($hashmap[$hash])) {
1103 $USER->access['rdef'][$k] =& $hashmap[$hash];
1104 } else {
1105 $hashmap[$hash] =& $USER->access['rdef'][$k];
1109 $USER->access['rdef_lcc'] = $USER->access['rdef_count'];
1113 * A convenience function to completely load all the capabilities
1114 * for the current user. It is called from has_capability() and functions change permissions.
1116 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1117 * @see check_enrolment_plugins()
1119 * @access private
1120 * @return void
1122 function load_all_capabilities() {
1123 global $USER;
1125 // roles not installed yet - we are in the middle of installation
1126 if (during_initial_install()) {
1127 return;
1130 if (!isset($USER->id)) {
1131 // this should not happen
1132 $USER->id = 0;
1135 unset($USER->access);
1136 $USER->access = get_user_accessdata($USER->id);
1138 // deduplicate the overrides to minimize session size
1139 dedupe_user_access();
1141 // Clear to force a refresh
1142 unset($USER->mycourses);
1144 // init/reset internal enrol caches - active course enrolments and temp access
1145 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1149 * A convenience function to completely reload all the capabilities
1150 * for the current user when roles have been updated in a relevant
1151 * context -- but PRESERVING switchroles and loginas.
1152 * This function resets all accesslib and context caches.
1154 * That is - completely transparent to the user.
1156 * Note: reloads $USER->access completely.
1158 * @access private
1159 * @return void
1161 function reload_all_capabilities() {
1162 global $USER, $DB, $ACCESSLIB_PRIVATE;
1164 // copy switchroles
1165 $sw = array();
1166 if (!empty($USER->access['rsw'])) {
1167 $sw = $USER->access['rsw'];
1170 accesslib_clear_all_caches(true);
1171 unset($USER->access);
1172 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
1174 load_all_capabilities();
1176 foreach ($sw as $path => $roleid) {
1177 if ($record = $DB->get_record('context', array('path'=>$path))) {
1178 $context = context::instance_by_id($record->id);
1179 role_switch($roleid, $context);
1185 * Adds a temp role to current USER->access array.
1187 * Useful for the "temporary guest" access we grant to logged-in users.
1188 * This is useful for enrol plugins only.
1190 * @since 2.2
1191 * @param context_course $coursecontext
1192 * @param int $roleid
1193 * @return void
1195 function load_temp_course_role(context_course $coursecontext, $roleid) {
1196 global $USER, $SITE;
1198 if (empty($roleid)) {
1199 debugging('invalid role specified in load_temp_course_role()');
1200 return;
1203 if ($coursecontext->instanceid == $SITE->id) {
1204 debugging('Can not use temp roles on the frontpage');
1205 return;
1208 if (!isset($USER->access)) {
1209 load_all_capabilities();
1212 $coursecontext->reload_if_dirty();
1214 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1215 return;
1218 // load course stuff first
1219 load_course_context($USER->id, $coursecontext, $USER->access);
1221 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1223 load_role_access_by_context($roleid, $coursecontext, $USER->access);
1227 * Removes any extra guest roles from current USER->access array.
1228 * This is useful for enrol plugins only.
1230 * @since 2.2
1231 * @param context_course $coursecontext
1232 * @return void
1234 function remove_temp_course_roles(context_course $coursecontext) {
1235 global $DB, $USER, $SITE;
1237 if ($coursecontext->instanceid == $SITE->id) {
1238 debugging('Can not use temp roles on the frontpage');
1239 return;
1242 if (empty($USER->access['ra'][$coursecontext->path])) {
1243 //no roles here, weird
1244 return;
1247 $sql = "SELECT DISTINCT ra.roleid AS id
1248 FROM {role_assignments} ra
1249 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1250 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1252 $USER->access['ra'][$coursecontext->path] = array();
1253 foreach($ras as $r) {
1254 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1259 * Returns array of all role archetypes.
1261 * @return array
1263 function get_role_archetypes() {
1264 return array(
1265 'manager' => 'manager',
1266 'coursecreator' => 'coursecreator',
1267 'editingteacher' => 'editingteacher',
1268 'teacher' => 'teacher',
1269 'student' => 'student',
1270 'guest' => 'guest',
1271 'user' => 'user',
1272 'frontpage' => 'frontpage'
1277 * Assign the defaults found in this capability definition to roles that have
1278 * the corresponding legacy capabilities assigned to them.
1280 * @param string $capability
1281 * @param array $legacyperms an array in the format (example):
1282 * 'guest' => CAP_PREVENT,
1283 * 'student' => CAP_ALLOW,
1284 * 'teacher' => CAP_ALLOW,
1285 * 'editingteacher' => CAP_ALLOW,
1286 * 'coursecreator' => CAP_ALLOW,
1287 * 'manager' => CAP_ALLOW
1288 * @return boolean success or failure.
1290 function assign_legacy_capabilities($capability, $legacyperms) {
1292 $archetypes = get_role_archetypes();
1294 foreach ($legacyperms as $type => $perm) {
1296 $systemcontext = context_system::instance();
1297 if ($type === 'admin') {
1298 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1299 $type = 'manager';
1302 if (!array_key_exists($type, $archetypes)) {
1303 print_error('invalidlegacy', '', '', $type);
1306 if ($roles = get_archetype_roles($type)) {
1307 foreach ($roles as $role) {
1308 // Assign a site level capability.
1309 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1310 return false;
1315 return true;
1319 * Verify capability risks.
1321 * @param stdClass $capability a capability - a row from the capabilities table.
1322 * @return boolean whether this capability is safe - that is, whether people with the
1323 * safeoverrides capability should be allowed to change it.
1325 function is_safe_capability($capability) {
1326 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1330 * Get the local override (if any) for a given capability in a role in a context
1332 * @param int $roleid
1333 * @param int $contextid
1334 * @param string $capability
1335 * @return stdClass local capability override
1337 function get_local_override($roleid, $contextid, $capability) {
1338 global $DB;
1339 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1343 * Returns context instance plus related course and cm instances
1345 * @param int $contextid
1346 * @return array of ($context, $course, $cm)
1348 function get_context_info_array($contextid) {
1349 global $DB;
1351 $context = context::instance_by_id($contextid, MUST_EXIST);
1352 $course = null;
1353 $cm = null;
1355 if ($context->contextlevel == CONTEXT_COURSE) {
1356 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1358 } else if ($context->contextlevel == CONTEXT_MODULE) {
1359 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1360 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1362 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1363 $parent = $context->get_parent_context();
1365 if ($parent->contextlevel == CONTEXT_COURSE) {
1366 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1367 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1368 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1369 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1373 return array($context, $course, $cm);
1377 * Function that creates a role
1379 * @param string $name role name
1380 * @param string $shortname role short name
1381 * @param string $description role description
1382 * @param string $archetype
1383 * @return int id or dml_exception
1385 function create_role($name, $shortname, $description, $archetype = '') {
1386 global $DB;
1388 if (strpos($archetype, 'moodle/legacy:') !== false) {
1389 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1392 // verify role archetype actually exists
1393 $archetypes = get_role_archetypes();
1394 if (empty($archetypes[$archetype])) {
1395 $archetype = '';
1398 // Insert the role record.
1399 $role = new stdClass();
1400 $role->name = $name;
1401 $role->shortname = $shortname;
1402 $role->description = $description;
1403 $role->archetype = $archetype;
1405 //find free sortorder number
1406 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1407 if (empty($role->sortorder)) {
1408 $role->sortorder = 1;
1410 $id = $DB->insert_record('role', $role);
1412 return $id;
1416 * Function that deletes a role and cleanups up after it
1418 * @param int $roleid id of role to delete
1419 * @return bool always true
1421 function delete_role($roleid) {
1422 global $DB;
1424 // first unssign all users
1425 role_unassign_all(array('roleid'=>$roleid));
1427 // cleanup all references to this role, ignore errors
1428 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1429 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1430 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1431 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1432 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1433 $DB->delete_records('role_names', array('roleid'=>$roleid));
1434 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1436 // finally delete the role itself
1437 // get this before the name is gone for logging
1438 $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
1440 $DB->delete_records('role', array('id'=>$roleid));
1442 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
1444 return true;
1448 * Function to write context specific overrides, or default capabilities.
1450 * NOTE: use $context->mark_dirty() after this
1452 * @param string $capability string name
1453 * @param int $permission CAP_ constants
1454 * @param int $roleid role id
1455 * @param int|context $contextid context id
1456 * @param bool $overwrite
1457 * @return bool always true or exception
1459 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1460 global $USER, $DB;
1462 if ($contextid instanceof context) {
1463 $context = $contextid;
1464 } else {
1465 $context = context::instance_by_id($contextid);
1468 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1469 unassign_capability($capability, $roleid, $context->id);
1470 return true;
1473 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1475 if ($existing and !$overwrite) { // We want to keep whatever is there already
1476 return true;
1479 $cap = new stdClass();
1480 $cap->contextid = $context->id;
1481 $cap->roleid = $roleid;
1482 $cap->capability = $capability;
1483 $cap->permission = $permission;
1484 $cap->timemodified = time();
1485 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1487 if ($existing) {
1488 $cap->id = $existing->id;
1489 $DB->update_record('role_capabilities', $cap);
1490 } else {
1491 if ($DB->record_exists('context', array('id'=>$context->id))) {
1492 $DB->insert_record('role_capabilities', $cap);
1495 return true;
1499 * Unassign a capability from a role.
1501 * NOTE: use $context->mark_dirty() after this
1503 * @param string $capability the name of the capability
1504 * @param int $roleid the role id
1505 * @param int|context $contextid null means all contexts
1506 * @return boolean true or exception
1508 function unassign_capability($capability, $roleid, $contextid = null) {
1509 global $DB;
1511 if (!empty($contextid)) {
1512 if ($contextid instanceof context) {
1513 $context = $contextid;
1514 } else {
1515 $context = context::instance_by_id($contextid);
1517 // delete from context rel, if this is the last override in this context
1518 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1519 } else {
1520 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1522 return true;
1526 * Get the roles that have a given capability assigned to it
1528 * This function does not resolve the actual permission of the capability.
1529 * It just checks for permissions and overrides.
1530 * Use get_roles_with_cap_in_context() if resolution is required.
1532 * @param string $capability capability name (string)
1533 * @param string $permission optional, the permission defined for this capability
1534 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1535 * @param stdClass $context null means any
1536 * @return array of role records
1538 function get_roles_with_capability($capability, $permission = null, $context = null) {
1539 global $DB;
1541 if ($context) {
1542 $contexts = $context->get_parent_context_ids(true);
1543 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1544 $contextsql = "AND rc.contextid $insql";
1545 } else {
1546 $params = array();
1547 $contextsql = '';
1550 if ($permission) {
1551 $permissionsql = " AND rc.permission = :permission";
1552 $params['permission'] = $permission;
1553 } else {
1554 $permissionsql = '';
1557 $sql = "SELECT r.*
1558 FROM {role} r
1559 WHERE r.id IN (SELECT rc.roleid
1560 FROM {role_capabilities} rc
1561 WHERE rc.capability = :capname
1562 $contextsql
1563 $permissionsql)";
1564 $params['capname'] = $capability;
1567 return $DB->get_records_sql($sql, $params);
1571 * This function makes a role-assignment (a role for a user in a particular context)
1573 * @param int $roleid the role of the id
1574 * @param int $userid userid
1575 * @param int|context $contextid id of the context
1576 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1577 * @param int $itemid id of enrolment/auth plugin
1578 * @param string $timemodified defaults to current time
1579 * @return int new/existing id of the assignment
1581 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1582 global $USER, $DB;
1584 // first of all detect if somebody is using old style parameters
1585 if ($contextid === 0 or is_numeric($component)) {
1586 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1589 // now validate all parameters
1590 if (empty($roleid)) {
1591 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1594 if (empty($userid)) {
1595 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1598 if ($itemid) {
1599 if (strpos($component, '_') === false) {
1600 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1602 } else {
1603 $itemid = 0;
1604 if ($component !== '' and strpos($component, '_') === false) {
1605 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1609 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1610 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1613 if ($contextid instanceof context) {
1614 $context = $contextid;
1615 } else {
1616 $context = context::instance_by_id($contextid, MUST_EXIST);
1619 if (!$timemodified) {
1620 $timemodified = time();
1623 // Check for existing entry
1624 // TODO: Revisit this sql_empty() use once Oracle bindings are improved. MDL-29765
1625 $component = ($component === '') ? $DB->sql_empty() : $component;
1626 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1628 if ($ras) {
1629 // role already assigned - this should not happen
1630 if (count($ras) > 1) {
1631 // very weird - remove all duplicates!
1632 $ra = array_shift($ras);
1633 foreach ($ras as $r) {
1634 $DB->delete_records('role_assignments', array('id'=>$r->id));
1636 } else {
1637 $ra = reset($ras);
1640 // actually there is no need to update, reset anything or trigger any event, so just return
1641 return $ra->id;
1644 // Create a new entry
1645 $ra = new stdClass();
1646 $ra->roleid = $roleid;
1647 $ra->contextid = $context->id;
1648 $ra->userid = $userid;
1649 $ra->component = $component;
1650 $ra->itemid = $itemid;
1651 $ra->timemodified = $timemodified;
1652 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1654 $ra->id = $DB->insert_record('role_assignments', $ra);
1656 // mark context as dirty - again expensive, but needed
1657 $context->mark_dirty();
1659 if (!empty($USER->id) && $USER->id == $userid) {
1660 // If the user is the current user, then do full reload of capabilities too.
1661 reload_all_capabilities();
1664 events_trigger('role_assigned', $ra);
1666 return $ra->id;
1670 * Removes one role assignment
1672 * @param int $roleid
1673 * @param int $userid
1674 * @param int|context $contextid
1675 * @param string $component
1676 * @param int $itemid
1677 * @return void
1679 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1680 // first make sure the params make sense
1681 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1682 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1685 if ($itemid) {
1686 if (strpos($component, '_') === false) {
1687 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1689 } else {
1690 $itemid = 0;
1691 if ($component !== '' and strpos($component, '_') === false) {
1692 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1696 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1700 * Removes multiple role assignments, parameters may contain:
1701 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1703 * @param array $params role assignment parameters
1704 * @param bool $subcontexts unassign in subcontexts too
1705 * @param bool $includemanual include manual role assignments too
1706 * @return void
1708 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1709 global $USER, $CFG, $DB;
1711 if (!$params) {
1712 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1715 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1716 foreach ($params as $key=>$value) {
1717 if (!in_array($key, $allowed)) {
1718 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1722 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1723 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1726 if ($includemanual) {
1727 if (!isset($params['component']) or $params['component'] === '') {
1728 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1732 if ($subcontexts) {
1733 if (empty($params['contextid'])) {
1734 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1738 // TODO: Revisit this sql_empty() use once Oracle bindings are improved. MDL-29765
1739 if (isset($params['component'])) {
1740 $params['component'] = ($params['component'] === '') ? $DB->sql_empty() : $params['component'];
1742 $ras = $DB->get_records('role_assignments', $params);
1743 foreach($ras as $ra) {
1744 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1745 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1746 // this is a bit expensive but necessary
1747 $context->mark_dirty();
1748 // If the user is the current user, then do full reload of capabilities too.
1749 if (!empty($USER->id) && $USER->id == $ra->userid) {
1750 reload_all_capabilities();
1753 events_trigger('role_unassigned', $ra);
1755 unset($ras);
1757 // process subcontexts
1758 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1759 if ($params['contextid'] instanceof context) {
1760 $context = $params['contextid'];
1761 } else {
1762 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1765 if ($context) {
1766 $contexts = $context->get_child_contexts();
1767 $mparams = $params;
1768 foreach($contexts as $context) {
1769 $mparams['contextid'] = $context->id;
1770 $ras = $DB->get_records('role_assignments', $mparams);
1771 foreach($ras as $ra) {
1772 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1773 // this is a bit expensive but necessary
1774 $context->mark_dirty();
1775 // If the user is the current user, then do full reload of capabilities too.
1776 if (!empty($USER->id) && $USER->id == $ra->userid) {
1777 reload_all_capabilities();
1779 events_trigger('role_unassigned', $ra);
1785 // do this once more for all manual role assignments
1786 if ($includemanual) {
1787 $params['component'] = '';
1788 role_unassign_all($params, $subcontexts, false);
1793 * Determines if a user is currently logged in
1795 * @category access
1797 * @return bool
1799 function isloggedin() {
1800 global $USER;
1802 return (!empty($USER->id));
1806 * Determines if a user is logged in as real guest user with username 'guest'.
1808 * @category access
1810 * @param int|object $user mixed user object or id, $USER if not specified
1811 * @return bool true if user is the real guest user, false if not logged in or other user
1813 function isguestuser($user = null) {
1814 global $USER, $DB, $CFG;
1816 // make sure we have the user id cached in config table, because we are going to use it a lot
1817 if (empty($CFG->siteguest)) {
1818 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1819 // guest does not exist yet, weird
1820 return false;
1822 set_config('siteguest', $guestid);
1824 if ($user === null) {
1825 $user = $USER;
1828 if ($user === null) {
1829 // happens when setting the $USER
1830 return false;
1832 } else if (is_numeric($user)) {
1833 return ($CFG->siteguest == $user);
1835 } else if (is_object($user)) {
1836 if (empty($user->id)) {
1837 return false; // not logged in means is not be guest
1838 } else {
1839 return ($CFG->siteguest == $user->id);
1842 } else {
1843 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1848 * Does user have a (temporary or real) guest access to course?
1850 * @category access
1852 * @param context $context
1853 * @param stdClass|int $user
1854 * @return bool
1856 function is_guest(context $context, $user = null) {
1857 global $USER;
1859 // first find the course context
1860 $coursecontext = $context->get_course_context();
1862 // make sure there is a real user specified
1863 if ($user === null) {
1864 $userid = isset($USER->id) ? $USER->id : 0;
1865 } else {
1866 $userid = is_object($user) ? $user->id : $user;
1869 if (isguestuser($userid)) {
1870 // can not inspect or be enrolled
1871 return true;
1874 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1875 // viewing users appear out of nowhere, they are neither guests nor participants
1876 return false;
1879 // consider only real active enrolments here
1880 if (is_enrolled($coursecontext, $user, '', true)) {
1881 return false;
1884 return true;
1888 * Returns true if the user has moodle/course:view capability in the course,
1889 * this is intended for admins, managers (aka small admins), inspectors, etc.
1891 * @category access
1893 * @param context $context
1894 * @param int|stdClass $user if null $USER is used
1895 * @param string $withcapability extra capability name
1896 * @return bool
1898 function is_viewing(context $context, $user = null, $withcapability = '') {
1899 // first find the course context
1900 $coursecontext = $context->get_course_context();
1902 if (isguestuser($user)) {
1903 // can not inspect
1904 return false;
1907 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1908 // admins are allowed to inspect courses
1909 return false;
1912 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1913 // site admins always have the capability, but the enrolment above blocks
1914 return false;
1917 return true;
1921 * Returns true if user is enrolled (is participating) in course
1922 * this is intended for students and teachers.
1924 * Since 2.2 the result for active enrolments and current user are cached.
1926 * @package core_enrol
1927 * @category access
1929 * @param context $context
1930 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1931 * @param string $withcapability extra capability name
1932 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1933 * @return bool
1935 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1936 global $USER, $DB;
1938 // first find the course context
1939 $coursecontext = $context->get_course_context();
1941 // make sure there is a real user specified
1942 if ($user === null) {
1943 $userid = isset($USER->id) ? $USER->id : 0;
1944 } else {
1945 $userid = is_object($user) ? $user->id : $user;
1948 if (empty($userid)) {
1949 // not-logged-in!
1950 return false;
1951 } else if (isguestuser($userid)) {
1952 // guest account can not be enrolled anywhere
1953 return false;
1956 if ($coursecontext->instanceid == SITEID) {
1957 // everybody participates on frontpage
1958 } else {
1959 // try cached info first - the enrolled flag is set only when active enrolment present
1960 if ($USER->id == $userid) {
1961 $coursecontext->reload_if_dirty();
1962 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1963 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
1964 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1965 return false;
1967 return true;
1972 if ($onlyactive) {
1973 // look for active enrolments only
1974 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1976 if ($until === false) {
1977 return false;
1980 if ($USER->id == $userid) {
1981 if ($until == 0) {
1982 $until = ENROL_MAX_TIMESTAMP;
1984 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
1985 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
1986 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
1987 remove_temp_course_roles($coursecontext);
1991 } else {
1992 // any enrolment is good for us here, even outdated, disabled or inactive
1993 $sql = "SELECT 'x'
1994 FROM {user_enrolments} ue
1995 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1996 JOIN {user} u ON u.id = ue.userid
1997 WHERE ue.userid = :userid AND u.deleted = 0";
1998 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
1999 if (!$DB->record_exists_sql($sql, $params)) {
2000 return false;
2005 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2006 return false;
2009 return true;
2013 * Returns true if the user is able to access the course.
2015 * This function is in no way, shape, or form a substitute for require_login.
2016 * It should only be used in circumstances where it is not possible to call require_login
2017 * such as the navigation.
2019 * This function checks many of the methods of access to a course such as the view
2020 * capability, enrollments, and guest access. It also makes use of the cache
2021 * generated by require_login for guest access.
2023 * The flags within the $USER object that are used here should NEVER be used outside
2024 * of this function can_access_course and require_login. Doing so WILL break future
2025 * versions.
2027 * @param stdClass $course record
2028 * @param stdClass|int|null $user user record or id, current user if null
2029 * @param string $withcapability Check for this capability as well.
2030 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2031 * @return boolean Returns true if the user is able to access the course
2033 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
2034 global $DB, $USER;
2036 // this function originally accepted $coursecontext parameter
2037 if ($course instanceof context) {
2038 if ($course instanceof context_course) {
2039 debugging('deprecated context parameter, please use $course record');
2040 $coursecontext = $course;
2041 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2042 } else {
2043 debugging('Invalid context parameter, please use $course record');
2044 return false;
2046 } else {
2047 $coursecontext = context_course::instance($course->id);
2050 if (!isset($USER->id)) {
2051 // should never happen
2052 $USER->id = 0;
2055 // make sure there is a user specified
2056 if ($user === null) {
2057 $userid = $USER->id;
2058 } else {
2059 $userid = is_object($user) ? $user->id : $user;
2061 unset($user);
2063 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2064 return false;
2067 if ($userid == $USER->id) {
2068 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2069 // the fact that somebody switched role means they can access the course no matter to what role they switched
2070 return true;
2074 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2075 return false;
2078 if (is_viewing($coursecontext, $userid)) {
2079 return true;
2082 if ($userid != $USER->id) {
2083 // for performance reasons we do not verify temporary guest access for other users, sorry...
2084 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2087 // === from here we deal only with $USER ===
2089 $coursecontext->reload_if_dirty();
2091 if (isset($USER->enrol['enrolled'][$course->id])) {
2092 if ($USER->enrol['enrolled'][$course->id] > time()) {
2093 return true;
2096 if (isset($USER->enrol['tempguest'][$course->id])) {
2097 if ($USER->enrol['tempguest'][$course->id] > time()) {
2098 return true;
2102 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2103 return true;
2106 // if not enrolled try to gain temporary guest access
2107 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2108 $enrols = enrol_get_plugins(true);
2109 foreach($instances as $instance) {
2110 if (!isset($enrols[$instance->enrol])) {
2111 continue;
2113 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2114 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2115 if ($until !== false and $until > time()) {
2116 $USER->enrol['tempguest'][$course->id] = $until;
2117 return true;
2120 if (isset($USER->enrol['tempguest'][$course->id])) {
2121 unset($USER->enrol['tempguest'][$course->id]);
2122 remove_temp_course_roles($coursecontext);
2125 return false;
2129 * Returns array with sql code and parameters returning all ids
2130 * of users enrolled into course.
2132 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2134 * @package core_enrol
2135 * @category access
2137 * @param context $context
2138 * @param string $withcapability
2139 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2140 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2141 * @return array list($sql, $params)
2143 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2144 global $DB, $CFG;
2146 // use unique prefix just in case somebody makes some SQL magic with the result
2147 static $i = 0;
2148 $i++;
2149 $prefix = 'eu'.$i.'_';
2151 // first find the course context
2152 $coursecontext = $context->get_course_context();
2154 $isfrontpage = ($coursecontext->instanceid == SITEID);
2156 $joins = array();
2157 $wheres = array();
2158 $params = array();
2160 list($contextids, $contextpaths) = get_context_info_list($context);
2162 // get all relevant capability info for all roles
2163 if ($withcapability) {
2164 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2165 $cparams['cap'] = $withcapability;
2167 $defs = array();
2168 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2169 FROM {role_capabilities} rc
2170 JOIN {context} ctx on rc.contextid = ctx.id
2171 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2172 $rcs = $DB->get_records_sql($sql, $cparams);
2173 foreach ($rcs as $rc) {
2174 $defs[$rc->path][$rc->roleid] = $rc->permission;
2177 $access = array();
2178 if (!empty($defs)) {
2179 foreach ($contextpaths as $path) {
2180 if (empty($defs[$path])) {
2181 continue;
2183 foreach($defs[$path] as $roleid => $perm) {
2184 if ($perm == CAP_PROHIBIT) {
2185 $access[$roleid] = CAP_PROHIBIT;
2186 continue;
2188 if (!isset($access[$roleid])) {
2189 $access[$roleid] = (int)$perm;
2195 unset($defs);
2197 // make lists of roles that are needed and prohibited
2198 $needed = array(); // one of these is enough
2199 $prohibited = array(); // must not have any of these
2200 foreach ($access as $roleid => $perm) {
2201 if ($perm == CAP_PROHIBIT) {
2202 unset($needed[$roleid]);
2203 $prohibited[$roleid] = true;
2204 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2205 $needed[$roleid] = true;
2209 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2210 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2212 $nobody = false;
2214 if ($isfrontpage) {
2215 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2216 $nobody = true;
2217 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2218 // everybody not having prohibit has the capability
2219 $needed = array();
2220 } else if (empty($needed)) {
2221 $nobody = true;
2223 } else {
2224 if (!empty($prohibited[$defaultuserroleid])) {
2225 $nobody = true;
2226 } else if (!empty($needed[$defaultuserroleid])) {
2227 // everybody not having prohibit has the capability
2228 $needed = array();
2229 } else if (empty($needed)) {
2230 $nobody = true;
2234 if ($nobody) {
2235 // nobody can match so return some SQL that does not return any results
2236 $wheres[] = "1 = 2";
2238 } else {
2240 if ($needed) {
2241 $ctxids = implode(',', $contextids);
2242 $roleids = implode(',', array_keys($needed));
2243 $joins[] = "JOIN {role_assignments} {$prefix}ra3 ON ({$prefix}ra3.userid = {$prefix}u.id AND {$prefix}ra3.roleid IN ($roleids) AND {$prefix}ra3.contextid IN ($ctxids))";
2246 if ($prohibited) {
2247 $ctxids = implode(',', $contextids);
2248 $roleids = implode(',', array_keys($prohibited));
2249 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4 ON ({$prefix}ra4.userid = {$prefix}u.id AND {$prefix}ra4.roleid IN ($roleids) AND {$prefix}ra4.contextid IN ($ctxids))";
2250 $wheres[] = "{$prefix}ra4.id IS NULL";
2253 if ($groupid) {
2254 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2255 $params["{$prefix}gmid"] = $groupid;
2259 } else {
2260 if ($groupid) {
2261 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2262 $params["{$prefix}gmid"] = $groupid;
2266 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2267 $params["{$prefix}guestid"] = $CFG->siteguest;
2269 if ($isfrontpage) {
2270 // all users are "enrolled" on the frontpage
2271 } else {
2272 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2273 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2274 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2276 if ($onlyactive) {
2277 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2278 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2279 $now = round(time(), -2); // rounding helps caching in DB
2280 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2281 $prefix.'active'=>ENROL_USER_ACTIVE,
2282 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2286 $joins = implode("\n", $joins);
2287 $wheres = "WHERE ".implode(" AND ", $wheres);
2289 $sql = "SELECT DISTINCT {$prefix}u.id
2290 FROM {user} {$prefix}u
2291 $joins
2292 $wheres";
2294 return array($sql, $params);
2298 * Returns list of users enrolled into course.
2300 * @package core_enrol
2301 * @category access
2303 * @param context $context
2304 * @param string $withcapability
2305 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2306 * @param string $userfields requested user record fields
2307 * @param string $orderby
2308 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2309 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2310 * @return array of user records
2312 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = '', $limitfrom = 0, $limitnum = 0) {
2313 global $DB;
2315 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2316 $sql = "SELECT $userfields
2317 FROM {user} u
2318 JOIN ($esql) je ON je.id = u.id
2319 WHERE u.deleted = 0";
2321 if ($orderby) {
2322 $sql = "$sql ORDER BY $orderby";
2323 } else {
2324 $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
2327 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2331 * Counts list of users enrolled into course (as per above function)
2333 * @package core_enrol
2334 * @category access
2336 * @param context $context
2337 * @param string $withcapability
2338 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2339 * @return array of user records
2341 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0) {
2342 global $DB;
2344 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2345 $sql = "SELECT count(u.id)
2346 FROM {user} u
2347 JOIN ($esql) je ON je.id = u.id
2348 WHERE u.deleted = 0";
2350 return $DB->count_records_sql($sql, $params);
2354 * Loads the capability definitions for the component (from file).
2356 * Loads the capability definitions for the component (from file). If no
2357 * capabilities are defined for the component, we simply return an empty array.
2359 * @access private
2360 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2361 * @return array array of capabilities
2363 function load_capability_def($component) {
2364 $defpath = get_component_directory($component).'/db/access.php';
2366 $capabilities = array();
2367 if (file_exists($defpath)) {
2368 require($defpath);
2369 if (!empty(${$component.'_capabilities'})) {
2370 // BC capability array name
2371 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2372 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2373 $capabilities = ${$component.'_capabilities'};
2377 return $capabilities;
2381 * Gets the capabilities that have been cached in the database for this component.
2383 * @access private
2384 * @param string $component - examples: 'moodle', 'mod_forum'
2385 * @return array array of capabilities
2387 function get_cached_capabilities($component = 'moodle') {
2388 global $DB;
2389 return $DB->get_records('capabilities', array('component'=>$component));
2393 * Returns default capabilities for given role archetype.
2395 * @param string $archetype role archetype
2396 * @return array
2398 function get_default_capabilities($archetype) {
2399 global $DB;
2401 if (!$archetype) {
2402 return array();
2405 $alldefs = array();
2406 $defaults = array();
2407 $components = array();
2408 $allcaps = $DB->get_records('capabilities');
2410 foreach ($allcaps as $cap) {
2411 if (!in_array($cap->component, $components)) {
2412 $components[] = $cap->component;
2413 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2416 foreach($alldefs as $name=>$def) {
2417 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2418 if (isset($def['archetypes'])) {
2419 if (isset($def['archetypes'][$archetype])) {
2420 $defaults[$name] = $def['archetypes'][$archetype];
2422 // 'legacy' is for backward compatibility with 1.9 access.php
2423 } else {
2424 if (isset($def['legacy'][$archetype])) {
2425 $defaults[$name] = $def['legacy'][$archetype];
2430 return $defaults;
2434 * Reset role capabilities to default according to selected role archetype.
2435 * If no archetype selected, removes all capabilities.
2437 * @param int $roleid
2438 * @return void
2440 function reset_role_capabilities($roleid) {
2441 global $DB;
2443 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2444 $defaultcaps = get_default_capabilities($role->archetype);
2446 $systemcontext = context_system::instance();
2448 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2450 foreach($defaultcaps as $cap=>$permission) {
2451 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2456 * Updates the capabilities table with the component capability definitions.
2457 * If no parameters are given, the function updates the core moodle
2458 * capabilities.
2460 * Note that the absence of the db/access.php capabilities definition file
2461 * will cause any stored capabilities for the component to be removed from
2462 * the database.
2464 * @access private
2465 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2466 * @return boolean true if success, exception in case of any problems
2468 function update_capabilities($component = 'moodle') {
2469 global $DB, $OUTPUT;
2471 $storedcaps = array();
2473 $filecaps = load_capability_def($component);
2474 foreach($filecaps as $capname=>$unused) {
2475 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2476 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2480 $cachedcaps = get_cached_capabilities($component);
2481 if ($cachedcaps) {
2482 foreach ($cachedcaps as $cachedcap) {
2483 array_push($storedcaps, $cachedcap->name);
2484 // update risk bitmasks and context levels in existing capabilities if needed
2485 if (array_key_exists($cachedcap->name, $filecaps)) {
2486 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2487 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2489 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2490 $updatecap = new stdClass();
2491 $updatecap->id = $cachedcap->id;
2492 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2493 $DB->update_record('capabilities', $updatecap);
2495 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2496 $updatecap = new stdClass();
2497 $updatecap->id = $cachedcap->id;
2498 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2499 $DB->update_record('capabilities', $updatecap);
2502 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2503 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2505 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2506 $updatecap = new stdClass();
2507 $updatecap->id = $cachedcap->id;
2508 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2509 $DB->update_record('capabilities', $updatecap);
2515 // Are there new capabilities in the file definition?
2516 $newcaps = array();
2518 foreach ($filecaps as $filecap => $def) {
2519 if (!$storedcaps ||
2520 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2521 if (!array_key_exists('riskbitmask', $def)) {
2522 $def['riskbitmask'] = 0; // no risk if not specified
2524 $newcaps[$filecap] = $def;
2527 // Add new capabilities to the stored definition.
2528 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2529 foreach ($newcaps as $capname => $capdef) {
2530 $capability = new stdClass();
2531 $capability->name = $capname;
2532 $capability->captype = $capdef['captype'];
2533 $capability->contextlevel = $capdef['contextlevel'];
2534 $capability->component = $component;
2535 $capability->riskbitmask = $capdef['riskbitmask'];
2537 $DB->insert_record('capabilities', $capability, false);
2539 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2540 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2541 foreach ($rolecapabilities as $rolecapability){
2542 //assign_capability will update rather than insert if capability exists
2543 if (!assign_capability($capname, $rolecapability->permission,
2544 $rolecapability->roleid, $rolecapability->contextid, true)){
2545 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2549 // we ignore archetype key if we have cloned permissions
2550 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2551 assign_legacy_capabilities($capname, $capdef['archetypes']);
2552 // 'legacy' is for backward compatibility with 1.9 access.php
2553 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2554 assign_legacy_capabilities($capname, $capdef['legacy']);
2557 // Are there any capabilities that have been removed from the file
2558 // definition that we need to delete from the stored capabilities and
2559 // role assignments?
2560 capabilities_cleanup($component, $filecaps);
2562 // reset static caches
2563 accesslib_clear_all_caches(false);
2565 return true;
2569 * Deletes cached capabilities that are no longer needed by the component.
2570 * Also unassigns these capabilities from any roles that have them.
2572 * @access private
2573 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2574 * @param array $newcapdef array of the new capability definitions that will be
2575 * compared with the cached capabilities
2576 * @return int number of deprecated capabilities that have been removed
2578 function capabilities_cleanup($component, $newcapdef = null) {
2579 global $DB;
2581 $removedcount = 0;
2583 if ($cachedcaps = get_cached_capabilities($component)) {
2584 foreach ($cachedcaps as $cachedcap) {
2585 if (empty($newcapdef) ||
2586 array_key_exists($cachedcap->name, $newcapdef) === false) {
2588 // Remove from capabilities cache.
2589 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2590 $removedcount++;
2591 // Delete from roles.
2592 if ($roles = get_roles_with_capability($cachedcap->name)) {
2593 foreach($roles as $role) {
2594 if (!unassign_capability($cachedcap->name, $role->id)) {
2595 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2599 } // End if.
2602 return $removedcount;
2606 * Returns an array of all the known types of risk
2607 * The array keys can be used, for example as CSS class names, or in calls to
2608 * print_risk_icon. The values are the corresponding RISK_ constants.
2610 * @return array all the known types of risk.
2612 function get_all_risks() {
2613 return array(
2614 'riskmanagetrust' => RISK_MANAGETRUST,
2615 'riskconfig' => RISK_CONFIG,
2616 'riskxss' => RISK_XSS,
2617 'riskpersonal' => RISK_PERSONAL,
2618 'riskspam' => RISK_SPAM,
2619 'riskdataloss' => RISK_DATALOSS,
2624 * Return a link to moodle docs for a given capability name
2626 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2627 * @return string the human-readable capability name as a link to Moodle Docs.
2629 function get_capability_docs_link($capability) {
2630 $url = get_docs_url('Capabilities/' . $capability->name);
2631 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2635 * This function pulls out all the resolved capabilities (overrides and
2636 * defaults) of a role used in capability overrides in contexts at a given
2637 * context.
2639 * @param int $roleid
2640 * @param context $context
2641 * @param string $cap capability, optional, defaults to ''
2642 * @return array Array of capabilities
2644 function role_context_capabilities($roleid, context $context, $cap = '') {
2645 global $DB;
2647 $contexts = $context->get_parent_context_ids(true);
2648 $contexts = '('.implode(',', $contexts).')';
2650 $params = array($roleid);
2652 if ($cap) {
2653 $search = " AND rc.capability = ? ";
2654 $params[] = $cap;
2655 } else {
2656 $search = '';
2659 $sql = "SELECT rc.*
2660 FROM {role_capabilities} rc, {context} c
2661 WHERE rc.contextid in $contexts
2662 AND rc.roleid = ?
2663 AND rc.contextid = c.id $search
2664 ORDER BY c.contextlevel DESC, rc.capability DESC";
2666 $capabilities = array();
2668 if ($records = $DB->get_records_sql($sql, $params)) {
2669 // We are traversing via reverse order.
2670 foreach ($records as $record) {
2671 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2672 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2673 $capabilities[$record->capability] = $record->permission;
2677 return $capabilities;
2681 * Constructs array with contextids as first parameter and context paths,
2682 * in both cases bottom top including self.
2684 * @access private
2685 * @param context $context
2686 * @return array
2688 function get_context_info_list(context $context) {
2689 $contextids = explode('/', ltrim($context->path, '/'));
2690 $contextpaths = array();
2691 $contextids2 = $contextids;
2692 while ($contextids2) {
2693 $contextpaths[] = '/' . implode('/', $contextids2);
2694 array_pop($contextids2);
2696 return array($contextids, $contextpaths);
2700 * Check if context is the front page context or a context inside it
2702 * Returns true if this context is the front page context, or a context inside it,
2703 * otherwise false.
2705 * @param context $context a context object.
2706 * @return bool
2708 function is_inside_frontpage(context $context) {
2709 $frontpagecontext = context_course::instance(SITEID);
2710 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2714 * Returns capability information (cached)
2716 * @param string $capabilityname
2717 * @return stdClass or null if capability not found
2719 function get_capability_info($capabilityname) {
2720 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2722 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2724 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2725 $ACCESSLIB_PRIVATE->capabilities = array();
2726 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2727 foreach ($caps as $cap) {
2728 $capname = $cap->name;
2729 unset($cap->id);
2730 unset($cap->name);
2731 $cap->riskbitmask = (int)$cap->riskbitmask;
2732 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2736 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2740 * Returns the human-readable, translated version of the capability.
2741 * Basically a big switch statement.
2743 * @param string $capabilityname e.g. mod/choice:readresponses
2744 * @return string
2746 function get_capability_string($capabilityname) {
2748 // Typical capability name is 'plugintype/pluginname:capabilityname'
2749 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2751 if ($type === 'moodle') {
2752 $component = 'core_role';
2753 } else if ($type === 'quizreport') {
2754 //ugly hack!!
2755 $component = 'quiz_'.$name;
2756 } else {
2757 $component = $type.'_'.$name;
2760 $stringname = $name.':'.$capname;
2762 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2763 return get_string($stringname, $component);
2766 $dir = get_component_directory($component);
2767 if (!file_exists($dir)) {
2768 // plugin broken or does not exist, do not bother with printing of debug message
2769 return $capabilityname.' ???';
2772 // something is wrong in plugin, better print debug
2773 return get_string($stringname, $component);
2777 * This gets the mod/block/course/core etc strings.
2779 * @param string $component
2780 * @param int $contextlevel
2781 * @return string|bool String is success, false if failed
2783 function get_component_string($component, $contextlevel) {
2785 if ($component === 'moodle' or $component === 'core') {
2786 switch ($contextlevel) {
2787 // TODO: this should probably use context level names instead
2788 case CONTEXT_SYSTEM: return get_string('coresystem');
2789 case CONTEXT_USER: return get_string('users');
2790 case CONTEXT_COURSECAT: return get_string('categories');
2791 case CONTEXT_COURSE: return get_string('course');
2792 case CONTEXT_MODULE: return get_string('activities');
2793 case CONTEXT_BLOCK: return get_string('block');
2794 default: print_error('unknowncontext');
2798 list($type, $name) = normalize_component($component);
2799 $dir = get_plugin_directory($type, $name);
2800 if (!file_exists($dir)) {
2801 // plugin not installed, bad luck, there is no way to find the name
2802 return $component.' ???';
2805 switch ($type) {
2806 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2807 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2808 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2809 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2810 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2811 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2812 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2813 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2814 case 'mod':
2815 if (get_string_manager()->string_exists('pluginname', $component)) {
2816 return get_string('activity').': '.get_string('pluginname', $component);
2817 } else {
2818 return get_string('activity').': '.get_string('modulename', $component);
2820 default: return get_string('pluginname', $component);
2825 * Gets the list of roles assigned to this context and up (parents)
2826 * from the list of roles that are visible on user profile page
2827 * and participants page.
2829 * @param context $context
2830 * @return array
2832 function get_profile_roles(context $context) {
2833 global $CFG, $DB;
2835 if (empty($CFG->profileroles)) {
2836 return array();
2839 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2840 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2841 $params = array_merge($params, $cparams);
2843 if ($coursecontext = $context->get_course_context(false)) {
2844 $params['coursecontext'] = $coursecontext->id;
2845 } else {
2846 $params['coursecontext'] = 0;
2849 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2850 FROM {role_assignments} ra, {role} r
2851 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2852 WHERE r.id = ra.roleid
2853 AND ra.contextid $contextlist
2854 AND r.id $rallowed
2855 ORDER BY r.sortorder ASC";
2857 return $DB->get_records_sql($sql, $params);
2861 * Gets the list of roles assigned to this context and up (parents)
2863 * @param context $context
2864 * @return array
2866 function get_roles_used_in_context(context $context) {
2867 global $DB;
2869 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2871 if ($coursecontext = $context->get_course_context(false)) {
2872 $params['coursecontext'] = $coursecontext->id;
2873 } else {
2874 $params['coursecontext'] = 0;
2877 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2878 FROM {role_assignments} ra, {role} r
2879 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2880 WHERE r.id = ra.roleid
2881 AND ra.contextid $contextlist
2882 ORDER BY r.sortorder ASC";
2884 return $DB->get_records_sql($sql, $params);
2888 * This function is used to print roles column in user profile page.
2889 * It is using the CFG->profileroles to limit the list to only interesting roles.
2890 * (The permission tab has full details of user role assignments.)
2892 * @param int $userid
2893 * @param int $courseid
2894 * @return string
2896 function get_user_roles_in_course($userid, $courseid) {
2897 global $CFG, $DB;
2899 if (empty($CFG->profileroles)) {
2900 return '';
2903 if ($courseid == SITEID) {
2904 $context = context_system::instance();
2905 } else {
2906 $context = context_course::instance($courseid);
2909 if (empty($CFG->profileroles)) {
2910 return array();
2913 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2914 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2915 $params = array_merge($params, $cparams);
2917 if ($coursecontext = $context->get_course_context(false)) {
2918 $params['coursecontext'] = $coursecontext->id;
2919 } else {
2920 $params['coursecontext'] = 0;
2923 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2924 FROM {role_assignments} ra, {role} r
2925 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2926 WHERE r.id = ra.roleid
2927 AND ra.contextid $contextlist
2928 AND r.id $rallowed
2929 AND ra.userid = :userid
2930 ORDER BY r.sortorder ASC";
2931 $params['userid'] = $userid;
2933 $rolestring = '';
2935 if ($roles = $DB->get_records_sql($sql, $params)) {
2936 $rolenames = role_fix_names($roles, $context, ROLENAME_ALIAS, true); // Substitute aliases
2938 foreach ($rolenames as $roleid => $rolename) {
2939 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
2941 $rolestring = implode(',', $rolenames);
2944 return $rolestring;
2948 * Checks if a user can assign users to a particular role in this context
2950 * @param context $context
2951 * @param int $targetroleid - the id of the role you want to assign users to
2952 * @return boolean
2954 function user_can_assign(context $context, $targetroleid) {
2955 global $DB;
2957 // first check if user has override capability
2958 // if not return false;
2959 if (!has_capability('moodle/role:assign', $context)) {
2960 return false;
2962 // pull out all active roles of this user from this context(or above)
2963 if ($userroles = get_user_roles($context)) {
2964 foreach ($userroles as $userrole) {
2965 // if any in the role_allow_override table, then it's ok
2966 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2967 return true;
2972 return false;
2976 * Returns all site roles in correct sort order.
2978 * @param context $context optional context for course role name aliases
2979 * @return array of role records with optional coursealias property
2981 function get_all_roles(context $context = null) {
2982 global $DB;
2984 if (!$context or !$coursecontext = $context->get_course_context(false)) {
2985 $coursecontext = null;
2988 if ($coursecontext) {
2989 $sql = "SELECT r.*, rn.name AS coursealias
2990 FROM {role} r
2991 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2992 ORDER BY r.sortorder ASC";
2993 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
2995 } else {
2996 return $DB->get_records('role', array(), 'sortorder ASC');
3001 * Returns roles of a specified archetype
3003 * @param string $archetype
3004 * @return array of full role records
3006 function get_archetype_roles($archetype) {
3007 global $DB;
3008 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
3012 * Gets all the user roles assigned in this context, or higher contexts
3013 * this is mainly used when checking if a user can assign a role, or overriding a role
3014 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3015 * allow_override tables
3017 * @param context $context
3018 * @param int $userid
3019 * @param bool $checkparentcontexts defaults to true
3020 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
3021 * @return array
3023 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
3024 global $USER, $DB;
3026 if (empty($userid)) {
3027 if (empty($USER->id)) {
3028 return array();
3030 $userid = $USER->id;
3033 if ($checkparentcontexts) {
3034 $contextids = $context->get_parent_context_ids();
3035 } else {
3036 $contextids = array();
3038 $contextids[] = $context->id;
3040 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3042 array_unshift($params, $userid);
3044 $sql = "SELECT ra.*, r.name, r.shortname
3045 FROM {role_assignments} ra, {role} r, {context} c
3046 WHERE ra.userid = ?
3047 AND ra.roleid = r.id
3048 AND ra.contextid = c.id
3049 AND ra.contextid $contextids
3050 ORDER BY $order";
3052 return $DB->get_records_sql($sql ,$params);
3056 * Like get_user_roles, but adds in the authenticated user role, and the front
3057 * page roles, if applicable.
3059 * @param context $context the context.
3060 * @param int $userid optional. Defaults to $USER->id
3061 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3063 function get_user_roles_with_special(context $context, $userid = 0) {
3064 global $CFG, $USER;
3066 if (empty($userid)) {
3067 if (empty($USER->id)) {
3068 return array();
3070 $userid = $USER->id;
3073 $ras = get_user_roles($context, $userid);
3075 // Add front-page role if relevant.
3076 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3077 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3078 is_inside_frontpage($context);
3079 if ($defaultfrontpageroleid && $isfrontpage) {
3080 $frontpagecontext = context_course::instance(SITEID);
3081 $ra = new stdClass();
3082 $ra->userid = $userid;
3083 $ra->contextid = $frontpagecontext->id;
3084 $ra->roleid = $defaultfrontpageroleid;
3085 $ras[] = $ra;
3088 // Add authenticated user role if relevant.
3089 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3090 if ($defaultuserroleid && !isguestuser($userid)) {
3091 $systemcontext = context_system::instance();
3092 $ra = new stdClass();
3093 $ra->userid = $userid;
3094 $ra->contextid = $systemcontext->id;
3095 $ra->roleid = $defaultuserroleid;
3096 $ras[] = $ra;
3099 return $ras;
3103 * Creates a record in the role_allow_override table
3105 * @param int $sroleid source roleid
3106 * @param int $troleid target roleid
3107 * @return void
3109 function allow_override($sroleid, $troleid) {
3110 global $DB;
3112 $record = new stdClass();
3113 $record->roleid = $sroleid;
3114 $record->allowoverride = $troleid;
3115 $DB->insert_record('role_allow_override', $record);
3119 * Creates a record in the role_allow_assign table
3121 * @param int $fromroleid source roleid
3122 * @param int $targetroleid target roleid
3123 * @return void
3125 function allow_assign($fromroleid, $targetroleid) {
3126 global $DB;
3128 $record = new stdClass();
3129 $record->roleid = $fromroleid;
3130 $record->allowassign = $targetroleid;
3131 $DB->insert_record('role_allow_assign', $record);
3135 * Creates a record in the role_allow_switch table
3137 * @param int $fromroleid source roleid
3138 * @param int $targetroleid target roleid
3139 * @return void
3141 function allow_switch($fromroleid, $targetroleid) {
3142 global $DB;
3144 $record = new stdClass();
3145 $record->roleid = $fromroleid;
3146 $record->allowswitch = $targetroleid;
3147 $DB->insert_record('role_allow_switch', $record);
3151 * Gets a list of roles that this user can assign in this context
3153 * @param context $context the context.
3154 * @param int $rolenamedisplay the type of role name to display. One of the
3155 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3156 * @param bool $withusercounts if true, count the number of users with each role.
3157 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3158 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3159 * if $withusercounts is true, returns a list of three arrays,
3160 * $rolenames, $rolecounts, and $nameswithcounts.
3162 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3163 global $USER, $DB;
3165 // make sure there is a real user specified
3166 if ($user === null) {
3167 $userid = isset($USER->id) ? $USER->id : 0;
3168 } else {
3169 $userid = is_object($user) ? $user->id : $user;
3172 if (!has_capability('moodle/role:assign', $context, $userid)) {
3173 if ($withusercounts) {
3174 return array(array(), array(), array());
3175 } else {
3176 return array();
3180 $params = array();
3181 $extrafields = '';
3183 if ($withusercounts) {
3184 $extrafields = ', (SELECT count(u.id)
3185 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3186 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3187 ) AS usercount';
3188 $params['conid'] = $context->id;
3191 if (is_siteadmin($userid)) {
3192 // show all roles allowed in this context to admins
3193 $assignrestriction = "";
3194 } else {
3195 $parents = $context->get_parent_context_ids(true);
3196 $contexts = implode(',' , $parents);
3197 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3198 FROM {role_allow_assign} raa
3199 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3200 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3201 ) ar ON ar.id = r.id";
3202 $params['userid'] = $userid;
3204 $params['contextlevel'] = $context->contextlevel;
3206 if ($coursecontext = $context->get_course_context(false)) {
3207 $params['coursecontext'] = $coursecontext->id;
3208 } else {
3209 $params['coursecontext'] = 0; // no course aliases
3210 $coursecontext = null;
3212 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3213 FROM {role} r
3214 $assignrestriction
3215 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3216 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3217 ORDER BY r.sortorder ASC";
3218 $roles = $DB->get_records_sql($sql, $params);
3220 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3222 if (!$withusercounts) {
3223 return $rolenames;
3226 $rolecounts = array();
3227 $nameswithcounts = array();
3228 foreach ($roles as $role) {
3229 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3230 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3232 return array($rolenames, $rolecounts, $nameswithcounts);
3236 * Gets a list of roles that this user can switch to in a context
3238 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3239 * This function just process the contents of the role_allow_switch table. You also need to
3240 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3242 * @param context $context a context.
3243 * @return array an array $roleid => $rolename.
3245 function get_switchable_roles(context $context) {
3246 global $USER, $DB;
3248 $params = array();
3249 $extrajoins = '';
3250 $extrawhere = '';
3251 if (!is_siteadmin()) {
3252 // Admins are allowed to switch to any role with.
3253 // Others are subject to the additional constraint that the switch-to role must be allowed by
3254 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3255 $parents = $context->get_parent_context_ids(true);
3256 $contexts = implode(',' , $parents);
3258 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3259 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3260 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3261 $params['userid'] = $USER->id;
3264 if ($coursecontext = $context->get_course_context(false)) {
3265 $params['coursecontext'] = $coursecontext->id;
3266 } else {
3267 $params['coursecontext'] = 0; // no course aliases
3268 $coursecontext = null;
3271 $query = "
3272 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3273 FROM (SELECT DISTINCT rc.roleid
3274 FROM {role_capabilities} rc
3275 $extrajoins
3276 $extrawhere) idlist
3277 JOIN {role} r ON r.id = idlist.roleid
3278 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3279 ORDER BY r.sortorder";
3280 $roles = $DB->get_records_sql($query, $params);
3282 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3286 * Gets a list of roles that this user can override in this context.
3288 * @param context $context the context.
3289 * @param int $rolenamedisplay the type of role name to display. One of the
3290 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3291 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3292 * @return array if $withcounts is false, then an array $roleid => $rolename.
3293 * if $withusercounts is true, returns a list of three arrays,
3294 * $rolenames, $rolecounts, and $nameswithcounts.
3296 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3297 global $USER, $DB;
3299 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3300 if ($withcounts) {
3301 return array(array(), array(), array());
3302 } else {
3303 return array();
3307 $parents = $context->get_parent_context_ids(true);
3308 $contexts = implode(',' , $parents);
3310 $params = array();
3311 $extrafields = '';
3313 $params['userid'] = $USER->id;
3314 if ($withcounts) {
3315 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3316 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3317 $params['conid'] = $context->id;
3320 if ($coursecontext = $context->get_course_context(false)) {
3321 $params['coursecontext'] = $coursecontext->id;
3322 } else {
3323 $params['coursecontext'] = 0; // no course aliases
3324 $coursecontext = null;
3327 if (is_siteadmin()) {
3328 // show all roles to admins
3329 $roles = $DB->get_records_sql("
3330 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3331 FROM {role} ro
3332 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3333 ORDER BY ro.sortorder ASC", $params);
3335 } else {
3336 $roles = $DB->get_records_sql("
3337 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3338 FROM {role} ro
3339 JOIN (SELECT DISTINCT r.id
3340 FROM {role} r
3341 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3342 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3343 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3344 ) inline_view ON ro.id = inline_view.id
3345 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3346 ORDER BY ro.sortorder ASC", $params);
3349 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3351 if (!$withcounts) {
3352 return $rolenames;
3355 $rolecounts = array();
3356 $nameswithcounts = array();
3357 foreach ($roles as $role) {
3358 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3359 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3361 return array($rolenames, $rolecounts, $nameswithcounts);
3365 * Create a role menu suitable for default role selection in enrol plugins.
3367 * @package core_enrol
3369 * @param context $context
3370 * @param int $addroleid current or default role - always added to list
3371 * @return array roleid=>localised role name
3373 function get_default_enrol_roles(context $context, $addroleid = null) {
3374 global $DB;
3376 $params = array('contextlevel'=>CONTEXT_COURSE);
3378 if ($coursecontext = $context->get_course_context(false)) {
3379 $params['coursecontext'] = $coursecontext->id;
3380 } else {
3381 $params['coursecontext'] = 0; // no course names
3382 $coursecontext = null;
3385 if ($addroleid) {
3386 $addrole = "OR r.id = :addroleid";
3387 $params['addroleid'] = $addroleid;
3388 } else {
3389 $addrole = "";
3392 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3393 FROM {role} r
3394 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3395 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3396 WHERE rcl.id IS NOT NULL $addrole
3397 ORDER BY sortorder DESC";
3399 $roles = $DB->get_records_sql($sql, $params);
3401 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3405 * Return context levels where this role is assignable.
3407 * @param integer $roleid the id of a role.
3408 * @return array list of the context levels at which this role may be assigned.
3410 function get_role_contextlevels($roleid) {
3411 global $DB;
3412 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3413 'contextlevel', 'id,contextlevel');
3417 * Return roles suitable for assignment at the specified context level.
3419 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3421 * @param integer $contextlevel a contextlevel.
3422 * @return array list of role ids that are assignable at this context level.
3424 function get_roles_for_contextlevels($contextlevel) {
3425 global $DB;
3426 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3427 '', 'id,roleid');
3431 * Returns default context levels where roles can be assigned.
3433 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3434 * from the array returned by get_role_archetypes();
3435 * @return array list of the context levels at which this type of role may be assigned by default.
3437 function get_default_contextlevels($rolearchetype) {
3438 static $defaults = array(
3439 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3440 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3441 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3442 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3443 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3444 'guest' => array(),
3445 'user' => array(),
3446 'frontpage' => array());
3448 if (isset($defaults[$rolearchetype])) {
3449 return $defaults[$rolearchetype];
3450 } else {
3451 return array();
3456 * Set the context levels at which a particular role can be assigned.
3457 * Throws exceptions in case of error.
3459 * @param integer $roleid the id of a role.
3460 * @param array $contextlevels the context levels at which this role should be assignable,
3461 * duplicate levels are removed.
3462 * @return void
3464 function set_role_contextlevels($roleid, array $contextlevels) {
3465 global $DB;
3466 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3467 $rcl = new stdClass();
3468 $rcl->roleid = $roleid;
3469 $contextlevels = array_unique($contextlevels);
3470 foreach ($contextlevels as $level) {
3471 $rcl->contextlevel = $level;
3472 $DB->insert_record('role_context_levels', $rcl, false, true);
3477 * Who has this capability in this context?
3479 * This can be a very expensive call - use sparingly and keep
3480 * the results if you are going to need them again soon.
3482 * Note if $fields is empty this function attempts to get u.*
3483 * which can get rather large - and has a serious perf impact
3484 * on some DBs.
3486 * @param context $context
3487 * @param string|array $capability - capability name(s)
3488 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3489 * @param string $sort - the sort order. Default is lastaccess time.
3490 * @param mixed $limitfrom - number of records to skip (offset)
3491 * @param mixed $limitnum - number of records to fetch
3492 * @param string|array $groups - single group or array of groups - only return
3493 * users who are in one of these group(s).
3494 * @param string|array $exceptions - list of users to exclude, comma separated or array
3495 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3496 * @param bool $view_ignored - use get_enrolled_sql() instead
3497 * @param bool $useviewallgroups if $groups is set the return users who
3498 * have capability both $capability and moodle/site:accessallgroups
3499 * in this context, as well as users who have $capability and who are
3500 * in $groups.
3501 * @return array of user records
3503 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3504 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3505 global $CFG, $DB;
3507 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3508 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3510 $ctxids = trim($context->path, '/');
3511 $ctxids = str_replace('/', ',', $ctxids);
3513 // Context is the frontpage
3514 $iscoursepage = false; // coursepage other than fp
3515 $isfrontpage = false;
3516 if ($context->contextlevel == CONTEXT_COURSE) {
3517 if ($context->instanceid == SITEID) {
3518 $isfrontpage = true;
3519 } else {
3520 $iscoursepage = true;
3523 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3525 $caps = (array)$capability;
3527 // construct list of context paths bottom-->top
3528 list($contextids, $paths) = get_context_info_list($context);
3530 // we need to find out all roles that have these capabilities either in definition or in overrides
3531 $defs = array();
3532 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3533 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3534 $params = array_merge($params, $params2);
3535 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3536 FROM {role_capabilities} rc
3537 JOIN {context} ctx on rc.contextid = ctx.id
3538 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3540 $rcs = $DB->get_records_sql($sql, $params);
3541 foreach ($rcs as $rc) {
3542 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3545 // go through the permissions bottom-->top direction to evaluate the current permission,
3546 // first one wins (prohibit is an exception that always wins)
3547 $access = array();
3548 foreach ($caps as $cap) {
3549 foreach ($paths as $path) {
3550 if (empty($defs[$cap][$path])) {
3551 continue;
3553 foreach($defs[$cap][$path] as $roleid => $perm) {
3554 if ($perm == CAP_PROHIBIT) {
3555 $access[$cap][$roleid] = CAP_PROHIBIT;
3556 continue;
3558 if (!isset($access[$cap][$roleid])) {
3559 $access[$cap][$roleid] = (int)$perm;
3565 // make lists of roles that are needed and prohibited in this context
3566 $needed = array(); // one of these is enough
3567 $prohibited = array(); // must not have any of these
3568 foreach ($caps as $cap) {
3569 if (empty($access[$cap])) {
3570 continue;
3572 foreach ($access[$cap] as $roleid => $perm) {
3573 if ($perm == CAP_PROHIBIT) {
3574 unset($needed[$cap][$roleid]);
3575 $prohibited[$cap][$roleid] = true;
3576 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3577 $needed[$cap][$roleid] = true;
3580 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3581 // easy, nobody has the permission
3582 unset($needed[$cap]);
3583 unset($prohibited[$cap]);
3584 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3585 // everybody is disqualified on the frontpage
3586 unset($needed[$cap]);
3587 unset($prohibited[$cap]);
3589 if (empty($prohibited[$cap])) {
3590 unset($prohibited[$cap]);
3594 if (empty($needed)) {
3595 // there can not be anybody if no roles match this request
3596 return array();
3599 if (empty($prohibited)) {
3600 // we can compact the needed roles
3601 $n = array();
3602 foreach ($needed as $cap) {
3603 foreach ($cap as $roleid=>$unused) {
3604 $n[$roleid] = true;
3607 $needed = array('any'=>$n);
3608 unset($n);
3611 // ***** Set up default fields ******
3612 if (empty($fields)) {
3613 if ($iscoursepage) {
3614 $fields = 'u.*, ul.timeaccess AS lastaccess';
3615 } else {
3616 $fields = 'u.*';
3618 } else {
3619 if (debugging('', DEBUG_DEVELOPER) && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3620 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3624 // Set up default sort
3625 if (empty($sort)) { // default to course lastaccess or just lastaccess
3626 if ($iscoursepage) {
3627 $sort = 'ul.timeaccess';
3628 } else {
3629 $sort = 'u.lastaccess';
3633 // Prepare query clauses
3634 $wherecond = array();
3635 $params = array();
3636 $joins = array();
3638 // User lastaccess JOIN
3639 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3640 // user_lastaccess is not required MDL-13810
3641 } else {
3642 if ($iscoursepage) {
3643 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3644 } else {
3645 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3649 // We never return deleted users or guest account.
3650 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3651 $params['guestid'] = $CFG->siteguest;
3653 // Groups
3654 if ($groups) {
3655 $groups = (array)$groups;
3656 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3657 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3658 $params = array_merge($params, $grpparams);
3660 if ($useviewallgroups) {
3661 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3662 if (!empty($viewallgroupsusers)) {
3663 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3664 } else {
3665 $wherecond[] = "($grouptest)";
3667 } else {
3668 $wherecond[] = "($grouptest)";
3672 // User exceptions
3673 if (!empty($exceptions)) {
3674 $exceptions = (array)$exceptions;
3675 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3676 $params = array_merge($params, $exparams);
3677 $wherecond[] = "u.id $exsql";
3680 // now add the needed and prohibited roles conditions as joins
3681 if (!empty($needed['any'])) {
3682 // simple case - there are no prohibits involved
3683 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3684 // everybody
3685 } else {
3686 $joins[] = "JOIN (SELECT DISTINCT userid
3687 FROM {role_assignments}
3688 WHERE contextid IN ($ctxids)
3689 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3690 ) ra ON ra.userid = u.id";
3692 } else {
3693 $unions = array();
3694 $everybody = false;
3695 foreach ($needed as $cap=>$unused) {
3696 if (empty($prohibited[$cap])) {
3697 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3698 $everybody = true;
3699 break;
3700 } else {
3701 $unions[] = "SELECT userid
3702 FROM {role_assignments}
3703 WHERE contextid IN ($ctxids)
3704 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3706 } else {
3707 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3708 // nobody can have this cap because it is prevented in default roles
3709 continue;
3711 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3712 // everybody except the prohibitted - hiding does not matter
3713 $unions[] = "SELECT id AS userid
3714 FROM {user}
3715 WHERE id NOT IN (SELECT userid
3716 FROM {role_assignments}
3717 WHERE contextid IN ($ctxids)
3718 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3720 } else {
3721 $unions[] = "SELECT userid
3722 FROM {role_assignments}
3723 WHERE contextid IN ($ctxids)
3724 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3725 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3729 if (!$everybody) {
3730 if ($unions) {
3731 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3732 } else {
3733 // only prohibits found - nobody can be matched
3734 $wherecond[] = "1 = 2";
3739 // Collect WHERE conditions and needed joins
3740 $where = implode(' AND ', $wherecond);
3741 if ($where !== '') {
3742 $where = 'WHERE ' . $where;
3744 $joins = implode("\n", $joins);
3746 // Ok, let's get the users!
3747 $sql = "SELECT $fields
3748 FROM {user} u
3749 $joins
3750 $where
3751 ORDER BY $sort";
3753 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3757 * Re-sort a users array based on a sorting policy
3759 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3760 * based on a sorting policy. This is to support the odd practice of
3761 * sorting teachers by 'authority', where authority was "lowest id of the role
3762 * assignment".
3764 * Will execute 1 database query. Only suitable for small numbers of users, as it
3765 * uses an u.id IN() clause.
3767 * Notes about the sorting criteria.
3769 * As a default, we cannot rely on role.sortorder because then
3770 * admins/coursecreators will always win. That is why the sane
3771 * rule "is locality matters most", with sortorder as 2nd
3772 * consideration.
3774 * If you want role.sortorder, use the 'sortorder' policy, and
3775 * name explicitly what roles you want to cover. It's probably
3776 * a good idea to see what roles have the capabilities you want
3777 * (array_diff() them against roiles that have 'can-do-anything'
3778 * to weed out admin-ish roles. Or fetch a list of roles from
3779 * variables like $CFG->coursecontact .
3781 * @param array $users Users array, keyed on userid
3782 * @param context $context
3783 * @param array $roles ids of the roles to include, optional
3784 * @param string $sortpolicy defaults to locality, more about
3785 * @return array sorted copy of the array
3787 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3788 global $DB;
3790 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3791 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3792 if (empty($roles)) {
3793 $roleswhere = '';
3794 } else {
3795 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3798 $sql = "SELECT ra.userid
3799 FROM {role_assignments} ra
3800 JOIN {role} r
3801 ON ra.roleid=r.id
3802 JOIN {context} ctx
3803 ON ra.contextid=ctx.id
3804 WHERE $userswhere
3805 $contextwhere
3806 $roleswhere";
3808 // Default 'locality' policy -- read PHPDoc notes
3809 // about sort policies...
3810 $orderby = 'ORDER BY '
3811 .'ctx.depth DESC, ' /* locality wins */
3812 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3813 .'ra.id'; /* role assignment order tie-breaker */
3814 if ($sortpolicy === 'sortorder') {
3815 $orderby = 'ORDER BY '
3816 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3817 .'ra.id'; /* role assignment order tie-breaker */
3820 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3821 $sortedusers = array();
3822 $seen = array();
3824 foreach ($sortedids as $id) {
3825 // Avoid duplicates
3826 if (isset($seen[$id])) {
3827 continue;
3829 $seen[$id] = true;
3831 // assign
3832 $sortedusers[$id] = $users[$id];
3834 return $sortedusers;
3838 * Gets all the users assigned this role in this context or higher
3840 * @param int $roleid (can also be an array of ints!)
3841 * @param context $context
3842 * @param bool $parent if true, get list of users assigned in higher context too
3843 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3844 * @param string $sort sort from user (u.) , role assignment (ra) or role (r.)
3845 * @param bool $gethidden_ignored use enrolments instead
3846 * @param string $group defaults to ''
3847 * @param mixed $limitfrom defaults to ''
3848 * @param mixed $limitnum defaults to ''
3849 * @param string $extrawheretest defaults to ''
3850 * @param string|array $whereparams defaults to ''
3851 * @return array
3853 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3854 $sort = 'u.lastname, u.firstname', $gethidden_ignored = null, $group = '',
3855 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereparams = array()) {
3856 global $DB;
3858 if (empty($fields)) {
3859 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3860 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3861 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3862 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3863 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3866 $parentcontexts = '';
3867 if ($parent) {
3868 $parentcontexts = substr($context->path, 1); // kill leading slash
3869 $parentcontexts = str_replace('/', ',', $parentcontexts);
3870 if ($parentcontexts !== '') {
3871 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3875 if ($roleid) {
3876 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
3877 $roleselect = "AND ra.roleid $rids";
3878 } else {
3879 $params = array();
3880 $roleselect = '';
3883 if ($coursecontext = $context->get_course_context(false)) {
3884 $params['coursecontext'] = $coursecontext->id;
3885 } else {
3886 $params['coursecontext'] = 0;
3889 if ($group) {
3890 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3891 $groupselect = " AND gm.groupid = :groupid ";
3892 $params['groupid'] = $group;
3893 } else {
3894 $groupjoin = '';
3895 $groupselect = '';
3898 $params['contextid'] = $context->id;
3900 if ($extrawheretest) {
3901 $extrawheretest = ' AND ' . $extrawheretest;
3902 $params = array_merge($params, $whereparams);
3905 $sql = "SELECT DISTINCT $fields, ra.roleid
3906 FROM {role_assignments} ra
3907 JOIN {user} u ON u.id = ra.userid
3908 JOIN {role} r ON ra.roleid = r.id
3909 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3910 $groupjoin
3911 WHERE (ra.contextid = :contextid $parentcontexts)
3912 $roleselect
3913 $groupselect
3914 $extrawheretest
3915 ORDER BY $sort"; // join now so that we can just use fullname() later
3917 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3921 * Counts all the users assigned this role in this context or higher
3923 * @param int|array $roleid either int or an array of ints
3924 * @param context $context
3925 * @param bool $parent if true, get list of users assigned in higher context too
3926 * @return int Returns the result count
3928 function count_role_users($roleid, context $context, $parent = false) {
3929 global $DB;
3931 if ($parent) {
3932 if ($contexts = $context->get_parent_context_ids()) {
3933 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3934 } else {
3935 $parentcontexts = '';
3937 } else {
3938 $parentcontexts = '';
3941 if ($roleid) {
3942 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3943 $roleselect = "AND r.roleid $rids";
3944 } else {
3945 $params = array();
3946 $roleselect = '';
3949 array_unshift($params, $context->id);
3951 $sql = "SELECT COUNT(u.id)
3952 FROM {role_assignments} r
3953 JOIN {user} u ON u.id = r.userid
3954 WHERE (r.contextid = ? $parentcontexts)
3955 $roleselect
3956 AND u.deleted = 0";
3958 return $DB->count_records_sql($sql, $params);
3962 * This function gets the list of courses that this user has a particular capability in.
3963 * It is still not very efficient.
3965 * @param string $capability Capability in question
3966 * @param int $userid User ID or null for current user
3967 * @param bool $doanything True if 'doanything' is permitted (default)
3968 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3969 * otherwise use a comma-separated list of the fields you require, not including id
3970 * @param string $orderby If set, use a comma-separated list of fields from course
3971 * table with sql modifiers (DESC) if needed
3972 * @return array Array of courses, may have zero entries. Or false if query failed.
3974 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
3975 global $DB;
3977 // Convert fields list and ordering
3978 $fieldlist = '';
3979 if ($fieldsexceptid) {
3980 $fields = explode(',', $fieldsexceptid);
3981 foreach($fields as $field) {
3982 $fieldlist .= ',c.'.$field;
3985 if ($orderby) {
3986 $fields = explode(',', $orderby);
3987 $orderby = '';
3988 foreach($fields as $field) {
3989 if ($orderby) {
3990 $orderby .= ',';
3992 $orderby .= 'c.'.$field;
3994 $orderby = 'ORDER BY '.$orderby;
3997 // Obtain a list of everything relevant about all courses including context.
3998 // Note the result can be used directly as a context (we are going to), the course
3999 // fields are just appended.
4001 $contextpreload = context_helper::get_preload_record_columns_sql('x');
4003 $courses = array();
4004 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
4005 FROM {course} c
4006 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
4007 $orderby");
4008 // Check capability for each course in turn
4009 foreach ($rs as $course) {
4010 context_helper::preload_from_record($course);
4011 $context = context_course::instance($course->id);
4012 if (has_capability($capability, $context, $userid, $doanything)) {
4013 // We've got the capability. Make the record look like a course record
4014 // and store it
4015 $courses[] = $course;
4018 $rs->close();
4019 return empty($courses) ? false : $courses;
4023 * This function finds the roles assigned directly to this context only
4024 * i.e. no roles in parent contexts
4026 * @param context $context
4027 * @return array
4029 function get_roles_on_exact_context(context $context) {
4030 global $DB;
4032 return $DB->get_records_sql("SELECT r.*
4033 FROM {role_assignments} ra, {role} r
4034 WHERE ra.roleid = r.id AND ra.contextid = ?",
4035 array($context->id));
4039 * Switches the current user to another role for the current session and only
4040 * in the given context.
4042 * The caller *must* check
4043 * - that this op is allowed
4044 * - that the requested role can be switched to in this context (use get_switchable_roles)
4045 * - that the requested role is NOT $CFG->defaultuserroleid
4047 * To "unswitch" pass 0 as the roleid.
4049 * This function *will* modify $USER->access - beware
4051 * @param integer $roleid the role to switch to.
4052 * @param context $context the context in which to perform the switch.
4053 * @return bool success or failure.
4055 function role_switch($roleid, context $context) {
4056 global $USER;
4059 // Plan of action
4061 // - Add the ghost RA to $USER->access
4062 // as $USER->access['rsw'][$path] = $roleid
4064 // - Make sure $USER->access['rdef'] has the roledefs
4065 // it needs to honour the switcherole
4067 // Roledefs will get loaded "deep" here - down to the last child
4068 // context. Note that
4070 // - When visiting subcontexts, our selective accessdata loading
4071 // will still work fine - though those ra/rdefs will be ignored
4072 // appropriately while the switch is in place
4074 // - If a switcherole happens at a category with tons of courses
4075 // (that have many overrides for switched-to role), the session
4076 // will get... quite large. Sometimes you just can't win.
4078 // To un-switch just unset($USER->access['rsw'][$path])
4080 // Note: it is not possible to switch to roles that do not have course:view
4082 if (!isset($USER->access)) {
4083 load_all_capabilities();
4087 // Add the switch RA
4088 if ($roleid == 0) {
4089 unset($USER->access['rsw'][$context->path]);
4090 return true;
4093 $USER->access['rsw'][$context->path] = $roleid;
4095 // Load roledefs
4096 load_role_access_by_context($roleid, $context, $USER->access);
4098 return true;
4102 * Checks if the user has switched roles within the given course.
4104 * Note: You can only switch roles within the course, hence it takes a course id
4105 * rather than a context. On that note Petr volunteered to implement this across
4106 * all other contexts, all requests for this should be forwarded to him ;)
4108 * @param int $courseid The id of the course to check
4109 * @return bool True if the user has switched roles within the course.
4111 function is_role_switched($courseid) {
4112 global $USER;
4113 $context = context_course::instance($courseid, MUST_EXIST);
4114 return (!empty($USER->access['rsw'][$context->path]));
4118 * Get any role that has an override on exact context
4120 * @param context $context The context to check
4121 * @return array An array of roles
4123 function get_roles_with_override_on_context(context $context) {
4124 global $DB;
4126 return $DB->get_records_sql("SELECT r.*
4127 FROM {role_capabilities} rc, {role} r
4128 WHERE rc.roleid = r.id AND rc.contextid = ?",
4129 array($context->id));
4133 * Get all capabilities for this role on this context (overrides)
4135 * @param stdClass $role
4136 * @param context $context
4137 * @return array
4139 function get_capabilities_from_role_on_context($role, context $context) {
4140 global $DB;
4142 return $DB->get_records_sql("SELECT *
4143 FROM {role_capabilities}
4144 WHERE contextid = ? AND roleid = ?",
4145 array($context->id, $role->id));
4149 * Find out which roles has assignment on this context
4151 * @param context $context
4152 * @return array
4155 function get_roles_with_assignment_on_context(context $context) {
4156 global $DB;
4158 return $DB->get_records_sql("SELECT r.*
4159 FROM {role_assignments} ra, {role} r
4160 WHERE ra.roleid = r.id AND ra.contextid = ?",
4161 array($context->id));
4165 * Find all user assignment of users for this role, on this context
4167 * @param stdClass $role
4168 * @param context $context
4169 * @return array
4171 function get_users_from_role_on_context($role, context $context) {
4172 global $DB;
4174 return $DB->get_records_sql("SELECT *
4175 FROM {role_assignments}
4176 WHERE contextid = ? AND roleid = ?",
4177 array($context->id, $role->id));
4181 * Simple function returning a boolean true if user has roles
4182 * in context or parent contexts, otherwise false.
4184 * @param int $userid
4185 * @param int $roleid
4186 * @param int $contextid empty means any context
4187 * @return bool
4189 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4190 global $DB;
4192 if ($contextid) {
4193 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4194 return false;
4196 $parents = $context->get_parent_context_ids(true);
4197 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4198 $params['userid'] = $userid;
4199 $params['roleid'] = $roleid;
4201 $sql = "SELECT COUNT(ra.id)
4202 FROM {role_assignments} ra
4203 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4205 $count = $DB->get_field_sql($sql, $params);
4206 return ($count > 0);
4208 } else {
4209 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4214 * Get role name or alias if exists and format the text.
4216 * @param stdClass $role role object
4217 * - optional 'coursealias' property should be included for performance reasons if course context used
4218 * - description property is not required here
4219 * @param context|bool $context empty means system context
4220 * @param int $rolenamedisplay type of role name
4221 * @return string localised role name or course role name alias
4223 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4224 global $DB;
4226 if ($rolenamedisplay == ROLENAME_SHORT) {
4227 return $role->shortname;
4230 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4231 $coursecontext = null;
4234 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4235 $role = clone($role); // Do not modify parameters.
4236 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4237 $role->coursealias = $r->name;
4238 } else {
4239 $role->coursealias = null;
4243 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4244 if ($coursecontext) {
4245 return $role->coursealias;
4246 } else {
4247 return null;
4251 if (trim($role->name) !== '') {
4252 // For filtering always use context where was the thing defined - system for roles here.
4253 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4255 } else {
4256 // Empty role->name means we want to see localised role name based on shortname,
4257 // only default roles are supposed to be localised.
4258 switch ($role->shortname) {
4259 case 'manager': $original = get_string('manager', 'role'); break;
4260 case 'coursecreator': $original = get_string('coursecreators'); break;
4261 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4262 case 'teacher': $original = get_string('noneditingteacher'); break;
4263 case 'student': $original = get_string('defaultcoursestudent'); break;
4264 case 'guest': $original = get_string('guest'); break;
4265 case 'user': $original = get_string('authenticateduser'); break;
4266 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4267 // We should not get here, the role UI should require the name for custom roles!
4268 default: $original = $role->shortname; break;
4272 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4273 return $original;
4276 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4277 return "$original ($role->shortname)";
4280 if ($rolenamedisplay == ROLENAME_ALIAS) {
4281 if ($coursecontext and trim($role->coursealias) !== '') {
4282 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4283 } else {
4284 return $original;
4288 if ($rolenamedisplay == ROLENAME_BOTH) {
4289 if ($coursecontext and trim($role->coursealias) !== '') {
4290 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4291 } else {
4292 return $original;
4296 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4300 * Returns localised role description if available.
4301 * If the name is empty it tries to find the default role name using
4302 * hardcoded list of default role names or other methods in the future.
4304 * @param stdClass $role
4305 * @return string localised role name
4307 function role_get_description(stdClass $role) {
4308 if (!html_is_blank($role->description)) {
4309 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4312 switch ($role->shortname) {
4313 case 'manager': return get_string('managerdescription', 'role');
4314 case 'coursecreator': return get_string('coursecreatorsdescription');
4315 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4316 case 'teacher': return get_string('noneditingteacherdescription');
4317 case 'student': return get_string('defaultcoursestudentdescription');
4318 case 'guest': return get_string('guestdescription');
4319 case 'user': return get_string('authenticateduserdescription');
4320 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4321 default: return '';
4326 * Get all the localised role names for a context.
4327 * @param context $context the context
4328 * @param array of role objects with a ->localname field containing the context-specific role name.
4330 function role_get_names(context $context) {
4331 return role_fix_names(get_all_roles(), $context);
4335 * Prepare list of roles for display, apply aliases and format text
4337 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4338 * @param context|bool $context a context
4339 * @param int $rolenamedisplay
4340 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4341 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4343 function role_fix_names($roleoptions, $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4344 global $DB;
4346 if (empty($roleoptions)) {
4347 return array();
4350 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4351 $coursecontext = null;
4354 // We usually need all role columns...
4355 $first = reset($roleoptions);
4356 if ($returnmenu === null) {
4357 $returnmenu = !is_object($first);
4360 if (!is_object($first) or !property_exists($first, 'shortname')) {
4361 $allroles = get_all_roles($context);
4362 foreach ($roleoptions as $rid => $unused) {
4363 $roleoptions[$rid] = $allroles[$rid];
4367 // Inject coursealias if necessary.
4368 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4369 $first = reset($roleoptions);
4370 if (!property_exists($first, 'coursealias')) {
4371 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4372 foreach ($aliasnames as $alias) {
4373 if (isset($roleoptions[$alias->roleid])) {
4374 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4380 // Add localname property.
4381 foreach ($roleoptions as $rid => $role) {
4382 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4385 if (!$returnmenu) {
4386 return $roleoptions;
4389 $menu = array();
4390 foreach ($roleoptions as $rid => $role) {
4391 $menu[$rid] = $role->localname;
4394 return $menu;
4398 * Aids in detecting if a new line is required when reading a new capability
4400 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4401 * when we read in a new capability.
4402 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4403 * but when we are in grade, all reports/import/export capabilities should be together
4405 * @param string $cap component string a
4406 * @param string $comp component string b
4407 * @param int $contextlevel
4408 * @return bool whether 2 component are in different "sections"
4410 function component_level_changed($cap, $comp, $contextlevel) {
4412 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4413 $compsa = explode('/', $cap->component);
4414 $compsb = explode('/', $comp);
4416 // list of system reports
4417 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4418 return false;
4421 // we are in gradebook, still
4422 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4423 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4424 return false;
4427 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4428 return false;
4432 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4436 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4437 * and return an array of roleids in order.
4439 * @param array $allroles array of roles, as returned by get_all_roles();
4440 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4442 function fix_role_sortorder($allroles) {
4443 global $DB;
4445 $rolesort = array();
4446 $i = 0;
4447 foreach ($allroles as $role) {
4448 $rolesort[$i] = $role->id;
4449 if ($role->sortorder != $i) {
4450 $r = new stdClass();
4451 $r->id = $role->id;
4452 $r->sortorder = $i;
4453 $DB->update_record('role', $r);
4454 $allroles[$role->id]->sortorder = $i;
4456 $i++;
4458 return $rolesort;
4462 * Switch the sort order of two roles (used in admin/roles/manage.php).
4464 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4465 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4466 * @return boolean success or failure
4468 function switch_roles($first, $second) {
4469 global $DB;
4470 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4471 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4472 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4473 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4474 return $result;
4478 * Duplicates all the base definitions of a role
4480 * @param stdClass $sourcerole role to copy from
4481 * @param int $targetrole id of role to copy to
4483 function role_cap_duplicate($sourcerole, $targetrole) {
4484 global $DB;
4486 $systemcontext = context_system::instance();
4487 $caps = $DB->get_records_sql("SELECT *
4488 FROM {role_capabilities}
4489 WHERE roleid = ? AND contextid = ?",
4490 array($sourcerole->id, $systemcontext->id));
4491 // adding capabilities
4492 foreach ($caps as $cap) {
4493 unset($cap->id);
4494 $cap->roleid = $targetrole;
4495 $DB->insert_record('role_capabilities', $cap);
4500 * Returns two lists, this can be used to find out if user has capability.
4501 * Having any needed role and no forbidden role in this context means
4502 * user has this capability in this context.
4503 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4505 * @param stdClass $context
4506 * @param string $capability
4507 * @return array($neededroles, $forbiddenroles)
4509 function get_roles_with_cap_in_context($context, $capability) {
4510 global $DB;
4512 $ctxids = trim($context->path, '/'); // kill leading slash
4513 $ctxids = str_replace('/', ',', $ctxids);
4515 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4516 FROM {role_capabilities} rc
4517 JOIN {context} ctx ON ctx.id = rc.contextid
4518 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4519 ORDER BY rc.roleid ASC, ctx.depth DESC";
4520 $params = array('cap'=>$capability);
4522 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4523 // no cap definitions --> no capability
4524 return array(array(), array());
4527 $forbidden = array();
4528 $needed = array();
4529 foreach($capdefs as $def) {
4530 if (isset($forbidden[$def->roleid])) {
4531 continue;
4533 if ($def->permission == CAP_PROHIBIT) {
4534 $forbidden[$def->roleid] = $def->roleid;
4535 unset($needed[$def->roleid]);
4536 continue;
4538 if (!isset($needed[$def->roleid])) {
4539 if ($def->permission == CAP_ALLOW) {
4540 $needed[$def->roleid] = true;
4541 } else if ($def->permission == CAP_PREVENT) {
4542 $needed[$def->roleid] = false;
4546 unset($capdefs);
4548 // remove all those roles not allowing
4549 foreach($needed as $key=>$value) {
4550 if (!$value) {
4551 unset($needed[$key]);
4552 } else {
4553 $needed[$key] = $key;
4557 return array($needed, $forbidden);
4561 * Returns an array of role IDs that have ALL of the the supplied capabilities
4562 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4564 * @param stdClass $context
4565 * @param array $capabilities An array of capabilities
4566 * @return array of roles with all of the required capabilities
4568 function get_roles_with_caps_in_context($context, $capabilities) {
4569 $neededarr = array();
4570 $forbiddenarr = array();
4571 foreach($capabilities as $caprequired) {
4572 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4575 $rolesthatcanrate = array();
4576 if (!empty($neededarr)) {
4577 foreach ($neededarr as $needed) {
4578 if (empty($rolesthatcanrate)) {
4579 $rolesthatcanrate = $needed;
4580 } else {
4581 //only want roles that have all caps
4582 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4586 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4587 foreach ($forbiddenarr as $forbidden) {
4588 //remove any roles that are forbidden any of the caps
4589 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4592 return $rolesthatcanrate;
4596 * Returns an array of role names that have ALL of the the supplied capabilities
4597 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4599 * @param stdClass $context
4600 * @param array $capabilities An array of capabilities
4601 * @return array of roles with all of the required capabilities
4603 function get_role_names_with_caps_in_context($context, $capabilities) {
4604 global $DB;
4606 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4607 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4609 $roles = array();
4610 foreach ($rolesthatcanrate as $r) {
4611 $roles[$r] = $allroles[$r];
4614 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4618 * This function verifies the prohibit comes from this context
4619 * and there are no more prohibits in parent contexts.
4621 * @param int $roleid
4622 * @param context $context
4623 * @param string $capability name
4624 * @return bool
4626 function prohibit_is_removable($roleid, context $context, $capability) {
4627 global $DB;
4629 $ctxids = trim($context->path, '/'); // kill leading slash
4630 $ctxids = str_replace('/', ',', $ctxids);
4632 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4634 $sql = "SELECT ctx.id
4635 FROM {role_capabilities} rc
4636 JOIN {context} ctx ON ctx.id = rc.contextid
4637 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4638 ORDER BY ctx.depth DESC";
4640 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4641 // no prohibits == nothing to remove
4642 return true;
4645 if (count($prohibits) > 1) {
4646 // more prohibits can not be removed
4647 return false;
4650 return !empty($prohibits[$context->id]);
4654 * More user friendly role permission changing,
4655 * it should produce as few overrides as possible.
4657 * @param int $roleid
4658 * @param stdClass $context
4659 * @param string $capname capability name
4660 * @param int $permission
4661 * @return void
4663 function role_change_permission($roleid, $context, $capname, $permission) {
4664 global $DB;
4666 if ($permission == CAP_INHERIT) {
4667 unassign_capability($capname, $roleid, $context->id);
4668 $context->mark_dirty();
4669 return;
4672 $ctxids = trim($context->path, '/'); // kill leading slash
4673 $ctxids = str_replace('/', ',', $ctxids);
4675 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4677 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4678 FROM {role_capabilities} rc
4679 JOIN {context} ctx ON ctx.id = rc.contextid
4680 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4681 ORDER BY ctx.depth DESC";
4683 if ($existing = $DB->get_records_sql($sql, $params)) {
4684 foreach($existing as $e) {
4685 if ($e->permission == CAP_PROHIBIT) {
4686 // prohibit can not be overridden, no point in changing anything
4687 return;
4690 $lowest = array_shift($existing);
4691 if ($lowest->permission == $permission) {
4692 // permission already set in this context or parent - nothing to do
4693 return;
4695 if ($existing) {
4696 $parent = array_shift($existing);
4697 if ($parent->permission == $permission) {
4698 // permission already set in parent context or parent - just unset in this context
4699 // we do this because we want as few overrides as possible for performance reasons
4700 unassign_capability($capname, $roleid, $context->id);
4701 $context->mark_dirty();
4702 return;
4706 } else {
4707 if ($permission == CAP_PREVENT) {
4708 // nothing means role does not have permission
4709 return;
4713 // assign the needed capability
4714 assign_capability($capname, $permission, $roleid, $context->id, true);
4716 // force cap reloading
4717 $context->mark_dirty();
4722 * Basic moodle context abstraction class.
4724 * Google confirms that no other important framework is using "context" class,
4725 * we could use something else like mcontext or moodle_context, but we need to type
4726 * this very often which would be annoying and it would take too much space...
4728 * This class is derived from stdClass for backwards compatibility with
4729 * odl $context record that was returned from DML $DB->get_record()
4731 * @package core_access
4732 * @category access
4733 * @copyright Petr Skoda {@link http://skodak.org}
4734 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4735 * @since 2.2
4737 * @property-read int $id context id
4738 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4739 * @property-read int $instanceid id of related instance in each context
4740 * @property-read string $path path to context, starts with system context
4741 * @property-read int $depth
4743 abstract class context extends stdClass implements IteratorAggregate {
4746 * The context id
4747 * Can be accessed publicly through $context->id
4748 * @var int
4750 protected $_id;
4753 * The context level
4754 * Can be accessed publicly through $context->contextlevel
4755 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4757 protected $_contextlevel;
4760 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4761 * Can be accessed publicly through $context->instanceid
4762 * @var int
4764 protected $_instanceid;
4767 * The path to the context always starting from the system context
4768 * Can be accessed publicly through $context->path
4769 * @var string
4771 protected $_path;
4774 * The depth of the context in relation to parent contexts
4775 * Can be accessed publicly through $context->depth
4776 * @var int
4778 protected $_depth;
4781 * @var array Context caching info
4783 private static $cache_contextsbyid = array();
4786 * @var array Context caching info
4788 private static $cache_contexts = array();
4791 * Context count
4792 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4793 * @var int
4795 protected static $cache_count = 0;
4798 * @var array Context caching info
4800 protected static $cache_preloaded = array();
4803 * @var context_system The system context once initialised
4805 protected static $systemcontext = null;
4808 * Resets the cache to remove all data.
4809 * @static
4811 protected static function reset_caches() {
4812 self::$cache_contextsbyid = array();
4813 self::$cache_contexts = array();
4814 self::$cache_count = 0;
4815 self::$cache_preloaded = array();
4817 self::$systemcontext = null;
4821 * Adds a context to the cache. If the cache is full, discards a batch of
4822 * older entries.
4824 * @static
4825 * @param context $context New context to add
4826 * @return void
4828 protected static function cache_add(context $context) {
4829 if (isset(self::$cache_contextsbyid[$context->id])) {
4830 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4831 return;
4834 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4835 $i = 0;
4836 foreach(self::$cache_contextsbyid as $ctx) {
4837 $i++;
4838 if ($i <= 100) {
4839 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4840 continue;
4842 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4843 // we remove oldest third of the contexts to make room for more contexts
4844 break;
4846 unset(self::$cache_contextsbyid[$ctx->id]);
4847 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4848 self::$cache_count--;
4852 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4853 self::$cache_contextsbyid[$context->id] = $context;
4854 self::$cache_count++;
4858 * Removes a context from the cache.
4860 * @static
4861 * @param context $context Context object to remove
4862 * @return void
4864 protected static function cache_remove(context $context) {
4865 if (!isset(self::$cache_contextsbyid[$context->id])) {
4866 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4867 return;
4869 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4870 unset(self::$cache_contextsbyid[$context->id]);
4872 self::$cache_count--;
4874 if (self::$cache_count < 0) {
4875 self::$cache_count = 0;
4880 * Gets a context from the cache.
4882 * @static
4883 * @param int $contextlevel Context level
4884 * @param int $instance Instance ID
4885 * @return context|bool Context or false if not in cache
4887 protected static function cache_get($contextlevel, $instance) {
4888 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4889 return self::$cache_contexts[$contextlevel][$instance];
4891 return false;
4895 * Gets a context from the cache based on its id.
4897 * @static
4898 * @param int $id Context ID
4899 * @return context|bool Context or false if not in cache
4901 protected static function cache_get_by_id($id) {
4902 if (isset(self::$cache_contextsbyid[$id])) {
4903 return self::$cache_contextsbyid[$id];
4905 return false;
4909 * Preloads context information from db record and strips the cached info.
4911 * @static
4912 * @param stdClass $rec
4913 * @return void (modifies $rec)
4915 protected static function preload_from_record(stdClass $rec) {
4916 if (empty($rec->ctxid) or empty($rec->ctxlevel) or empty($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
4917 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4918 return;
4921 // note: in PHP5 the objects are passed by reference, no need to return $rec
4922 $record = new stdClass();
4923 $record->id = $rec->ctxid; unset($rec->ctxid);
4924 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
4925 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
4926 $record->path = $rec->ctxpath; unset($rec->ctxpath);
4927 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
4929 return context::create_instance_from_record($record);
4933 // ====== magic methods =======
4936 * Magic setter method, we do not want anybody to modify properties from the outside
4937 * @param string $name
4938 * @param mixed $value
4940 public function __set($name, $value) {
4941 debugging('Can not change context instance properties!');
4945 * Magic method getter, redirects to read only values.
4946 * @param string $name
4947 * @return mixed
4949 public function __get($name) {
4950 switch ($name) {
4951 case 'id': return $this->_id;
4952 case 'contextlevel': return $this->_contextlevel;
4953 case 'instanceid': return $this->_instanceid;
4954 case 'path': return $this->_path;
4955 case 'depth': return $this->_depth;
4957 default:
4958 debugging('Invalid context property accessed! '.$name);
4959 return null;
4964 * Full support for isset on our magic read only properties.
4965 * @param string $name
4966 * @return bool
4968 public function __isset($name) {
4969 switch ($name) {
4970 case 'id': return isset($this->_id);
4971 case 'contextlevel': return isset($this->_contextlevel);
4972 case 'instanceid': return isset($this->_instanceid);
4973 case 'path': return isset($this->_path);
4974 case 'depth': return isset($this->_depth);
4976 default: return false;
4982 * ALl properties are read only, sorry.
4983 * @param string $name
4985 public function __unset($name) {
4986 debugging('Can not unset context instance properties!');
4989 // ====== implementing method from interface IteratorAggregate ======
4992 * Create an iterator because magic vars can't be seen by 'foreach'.
4994 * Now we can convert context object to array using convert_to_array(),
4995 * and feed it properly to json_encode().
4997 public function getIterator() {
4998 $ret = array(
4999 'id' => $this->id,
5000 'contextlevel' => $this->contextlevel,
5001 'instanceid' => $this->instanceid,
5002 'path' => $this->path,
5003 'depth' => $this->depth
5005 return new ArrayIterator($ret);
5008 // ====== general context methods ======
5011 * Constructor is protected so that devs are forced to
5012 * use context_xxx::instance() or context::instance_by_id().
5014 * @param stdClass $record
5016 protected function __construct(stdClass $record) {
5017 $this->_id = $record->id;
5018 $this->_contextlevel = (int)$record->contextlevel;
5019 $this->_instanceid = $record->instanceid;
5020 $this->_path = $record->path;
5021 $this->_depth = $record->depth;
5025 * This function is also used to work around 'protected' keyword problems in context_helper.
5026 * @static
5027 * @param stdClass $record
5028 * @return context instance
5030 protected static function create_instance_from_record(stdClass $record) {
5031 $classname = context_helper::get_class_for_level($record->contextlevel);
5033 if ($context = context::cache_get_by_id($record->id)) {
5034 return $context;
5037 $context = new $classname($record);
5038 context::cache_add($context);
5040 return $context;
5044 * Copy prepared new contexts from temp table to context table,
5045 * we do this in db specific way for perf reasons only.
5046 * @static
5048 protected static function merge_context_temp_table() {
5049 global $DB;
5051 /* MDL-11347:
5052 * - mysql does not allow to use FROM in UPDATE statements
5053 * - using two tables after UPDATE works in mysql, but might give unexpected
5054 * results in pg 8 (depends on configuration)
5055 * - using table alias in UPDATE does not work in pg < 8.2
5057 * Different code for each database - mostly for performance reasons
5060 $dbfamily = $DB->get_dbfamily();
5061 if ($dbfamily == 'mysql') {
5062 $updatesql = "UPDATE {context} ct, {context_temp} temp
5063 SET ct.path = temp.path,
5064 ct.depth = temp.depth
5065 WHERE ct.id = temp.id";
5066 } else if ($dbfamily == 'oracle') {
5067 $updatesql = "UPDATE {context} ct
5068 SET (ct.path, ct.depth) =
5069 (SELECT temp.path, temp.depth
5070 FROM {context_temp} temp
5071 WHERE temp.id=ct.id)
5072 WHERE EXISTS (SELECT 'x'
5073 FROM {context_temp} temp
5074 WHERE temp.id = ct.id)";
5075 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5076 $updatesql = "UPDATE {context}
5077 SET path = temp.path,
5078 depth = temp.depth
5079 FROM {context_temp} temp
5080 WHERE temp.id={context}.id";
5081 } else {
5082 // sqlite and others
5083 $updatesql = "UPDATE {context}
5084 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5085 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5086 WHERE id IN (SELECT id FROM {context_temp})";
5089 $DB->execute($updatesql);
5093 * Get a context instance as an object, from a given context id.
5095 * @static
5096 * @param int $id context id
5097 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5098 * MUST_EXIST means throw exception if no record found
5099 * @return context|bool the context object or false if not found
5101 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5102 global $DB;
5104 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5105 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5106 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5109 if ($id == SYSCONTEXTID) {
5110 return context_system::instance(0, $strictness);
5113 if (is_array($id) or is_object($id) or empty($id)) {
5114 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5117 if ($context = context::cache_get_by_id($id)) {
5118 return $context;
5121 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5122 return context::create_instance_from_record($record);
5125 return false;
5129 * Update context info after moving context in the tree structure.
5131 * @param context $newparent
5132 * @return void
5134 public function update_moved(context $newparent) {
5135 global $DB;
5137 $frompath = $this->_path;
5138 $newpath = $newparent->path . '/' . $this->_id;
5140 $trans = $DB->start_delegated_transaction();
5142 $this->mark_dirty();
5144 $setdepth = '';
5145 if (($newparent->depth +1) != $this->_depth) {
5146 $diff = $newparent->depth - $this->_depth + 1;
5147 $setdepth = ", depth = depth + $diff";
5149 $sql = "UPDATE {context}
5150 SET path = ?
5151 $setdepth
5152 WHERE id = ?";
5153 $params = array($newpath, $this->_id);
5154 $DB->execute($sql, $params);
5156 $this->_path = $newpath;
5157 $this->_depth = $newparent->depth + 1;
5159 $sql = "UPDATE {context}
5160 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5161 $setdepth
5162 WHERE path LIKE ?";
5163 $params = array($newpath, "{$frompath}/%");
5164 $DB->execute($sql, $params);
5166 $this->mark_dirty();
5168 context::reset_caches();
5170 $trans->allow_commit();
5174 * Remove all context path info and optionally rebuild it.
5176 * @param bool $rebuild
5177 * @return void
5179 public function reset_paths($rebuild = true) {
5180 global $DB;
5182 if ($this->_path) {
5183 $this->mark_dirty();
5185 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5186 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5187 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5188 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5189 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5190 $this->_depth = 0;
5191 $this->_path = null;
5194 if ($rebuild) {
5195 context_helper::build_all_paths(false);
5198 context::reset_caches();
5202 * Delete all data linked to content, do not delete the context record itself
5204 public function delete_content() {
5205 global $CFG, $DB;
5207 blocks_delete_all_for_context($this->_id);
5208 filter_delete_all_for_context($this->_id);
5210 require_once($CFG->dirroot . '/comment/lib.php');
5211 comment::delete_comments(array('contextid'=>$this->_id));
5213 require_once($CFG->dirroot.'/rating/lib.php');
5214 $delopt = new stdclass();
5215 $delopt->contextid = $this->_id;
5216 $rm = new rating_manager();
5217 $rm->delete_ratings($delopt);
5219 // delete all files attached to this context
5220 $fs = get_file_storage();
5221 $fs->delete_area_files($this->_id);
5223 // delete all advanced grading data attached to this context
5224 require_once($CFG->dirroot.'/grade/grading/lib.php');
5225 grading_manager::delete_all_for_context($this->_id);
5227 // now delete stuff from role related tables, role_unassign_all
5228 // and unenrol should be called earlier to do proper cleanup
5229 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5230 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5231 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5235 * Delete the context content and the context record itself
5237 public function delete() {
5238 global $DB;
5240 // double check the context still exists
5241 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5242 context::cache_remove($this);
5243 return;
5246 $this->delete_content();
5247 $DB->delete_records('context', array('id'=>$this->_id));
5248 // purge static context cache if entry present
5249 context::cache_remove($this);
5251 // do not mark dirty contexts if parents unknown
5252 if (!is_null($this->_path) and $this->_depth > 0) {
5253 $this->mark_dirty();
5257 // ====== context level related methods ======
5260 * Utility method for context creation
5262 * @static
5263 * @param int $contextlevel
5264 * @param int $instanceid
5265 * @param string $parentpath
5266 * @return stdClass context record
5268 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5269 global $DB;
5271 $record = new stdClass();
5272 $record->contextlevel = $contextlevel;
5273 $record->instanceid = $instanceid;
5274 $record->depth = 0;
5275 $record->path = null; //not known before insert
5277 $record->id = $DB->insert_record('context', $record);
5279 // now add path if known - it can be added later
5280 if (!is_null($parentpath)) {
5281 $record->path = $parentpath.'/'.$record->id;
5282 $record->depth = substr_count($record->path, '/');
5283 $DB->update_record('context', $record);
5286 return $record;
5290 * Returns human readable context identifier.
5292 * @param boolean $withprefix whether to prefix the name of the context with the
5293 * type of context, e.g. User, Course, Forum, etc.
5294 * @param boolean $short whether to use the short name of the thing. Only applies
5295 * to course contexts
5296 * @return string the human readable context name.
5298 public function get_context_name($withprefix = true, $short = false) {
5299 // must be implemented in all context levels
5300 throw new coding_exception('can not get name of abstract context');
5304 * Returns the most relevant URL for this context.
5306 * @return moodle_url
5308 public abstract function get_url();
5311 * Returns array of relevant context capability records.
5313 * @return array
5315 public abstract function get_capabilities();
5318 * Recursive function which, given a context, find all its children context ids.
5320 * For course category contexts it will return immediate children and all subcategory contexts.
5321 * It will NOT recurse into courses or subcategories categories.
5322 * If you want to do that, call it on the returned courses/categories.
5324 * When called for a course context, it will return the modules and blocks
5325 * displayed in the course page and blocks displayed on the module pages.
5327 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5328 * contexts ;-)
5330 * @return array Array of child records
5332 public function get_child_contexts() {
5333 global $DB;
5335 $sql = "SELECT ctx.*
5336 FROM {context} ctx
5337 WHERE ctx.path LIKE ?";
5338 $params = array($this->_path.'/%');
5339 $records = $DB->get_records_sql($sql, $params);
5341 $result = array();
5342 foreach ($records as $record) {
5343 $result[$record->id] = context::create_instance_from_record($record);
5346 return $result;
5350 * Returns parent contexts of this context in reversed order, i.e. parent first,
5351 * then grand parent, etc.
5353 * @param bool $includeself tre means include self too
5354 * @return array of context instances
5356 public function get_parent_contexts($includeself = false) {
5357 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5358 return array();
5361 $result = array();
5362 foreach ($contextids as $contextid) {
5363 $parent = context::instance_by_id($contextid, MUST_EXIST);
5364 $result[$parent->id] = $parent;
5367 return $result;
5371 * Returns parent contexts of this context in reversed order, i.e. parent first,
5372 * then grand parent, etc.
5374 * @param bool $includeself tre means include self too
5375 * @return array of context ids
5377 public function get_parent_context_ids($includeself = false) {
5378 if (empty($this->_path)) {
5379 return array();
5382 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5383 $parentcontexts = explode('/', $parentcontexts);
5384 if (!$includeself) {
5385 array_pop($parentcontexts); // and remove its own id
5388 return array_reverse($parentcontexts);
5392 * Returns parent context
5394 * @return context
5396 public function get_parent_context() {
5397 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5398 return false;
5401 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5402 $parentcontexts = explode('/', $parentcontexts);
5403 array_pop($parentcontexts); // self
5404 $contextid = array_pop($parentcontexts); // immediate parent
5406 return context::instance_by_id($contextid, MUST_EXIST);
5410 * Is this context part of any course? If yes return course context.
5412 * @param bool $strict true means throw exception if not found, false means return false if not found
5413 * @return course_context context of the enclosing course, null if not found or exception
5415 public function get_course_context($strict = true) {
5416 if ($strict) {
5417 throw new coding_exception('Context does not belong to any course.');
5418 } else {
5419 return false;
5424 * Returns sql necessary for purging of stale context instances.
5426 * @static
5427 * @return string cleanup SQL
5429 protected static function get_cleanup_sql() {
5430 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5434 * Rebuild context paths and depths at context level.
5436 * @static
5437 * @param bool $force
5438 * @return void
5440 protected static function build_paths($force) {
5441 throw new coding_exception('build_paths() method must be implemented in all context levels');
5445 * Create missing context instances at given level
5447 * @static
5448 * @return void
5450 protected static function create_level_instances() {
5451 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5455 * Reset all cached permissions and definitions if the necessary.
5456 * @return void
5458 public function reload_if_dirty() {
5459 global $ACCESSLIB_PRIVATE, $USER;
5461 // Load dirty contexts list if needed
5462 if (CLI_SCRIPT) {
5463 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5464 // we do not load dirty flags in CLI and cron
5465 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5467 } else {
5468 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5469 if (!isset($USER->access['time'])) {
5470 // nothing was loaded yet, we do not need to check dirty contexts now
5471 return;
5473 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5474 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5478 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5479 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5480 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5481 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5482 reload_all_capabilities();
5483 break;
5489 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5491 public function mark_dirty() {
5492 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5494 if (during_initial_install()) {
5495 return;
5498 // only if it is a non-empty string
5499 if (is_string($this->_path) && $this->_path !== '') {
5500 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5501 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5502 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5503 } else {
5504 if (CLI_SCRIPT) {
5505 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5506 } else {
5507 if (isset($USER->access['time'])) {
5508 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5509 } else {
5510 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5512 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5521 * Context maintenance and helper methods.
5523 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5524 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5525 * level implementation from the rest of code, the code completion returns what developers need.
5527 * Thank you Tim Hunt for helping me with this nasty trick.
5529 * @package core_access
5530 * @category access
5531 * @copyright Petr Skoda {@link http://skodak.org}
5532 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5533 * @since 2.2
5535 class context_helper extends context {
5538 * @var array An array mapping context levels to classes
5540 private static $alllevels = array(
5541 CONTEXT_SYSTEM => 'context_system',
5542 CONTEXT_USER => 'context_user',
5543 CONTEXT_COURSECAT => 'context_coursecat',
5544 CONTEXT_COURSE => 'context_course',
5545 CONTEXT_MODULE => 'context_module',
5546 CONTEXT_BLOCK => 'context_block',
5550 * Instance does not make sense here, only static use
5552 protected function __construct() {
5556 * Returns a class name of the context level class
5558 * @static
5559 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5560 * @return string class name of the context class
5562 public static function get_class_for_level($contextlevel) {
5563 if (isset(self::$alllevels[$contextlevel])) {
5564 return self::$alllevels[$contextlevel];
5565 } else {
5566 throw new coding_exception('Invalid context level specified');
5571 * Returns a list of all context levels
5573 * @static
5574 * @return array int=>string (level=>level class name)
5576 public static function get_all_levels() {
5577 return self::$alllevels;
5581 * Remove stale contexts that belonged to deleted instances.
5582 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5584 * @static
5585 * @return void
5587 public static function cleanup_instances() {
5588 global $DB;
5589 $sqls = array();
5590 foreach (self::$alllevels as $level=>$classname) {
5591 $sqls[] = $classname::get_cleanup_sql();
5594 $sql = implode(" UNION ", $sqls);
5596 // it is probably better to use transactions, it might be faster too
5597 $transaction = $DB->start_delegated_transaction();
5599 $rs = $DB->get_recordset_sql($sql);
5600 foreach ($rs as $record) {
5601 $context = context::create_instance_from_record($record);
5602 $context->delete();
5604 $rs->close();
5606 $transaction->allow_commit();
5610 * Create all context instances at the given level and above.
5612 * @static
5613 * @param int $contextlevel null means all levels
5614 * @param bool $buildpaths
5615 * @return void
5617 public static function create_instances($contextlevel = null, $buildpaths = true) {
5618 foreach (self::$alllevels as $level=>$classname) {
5619 if ($contextlevel and $level > $contextlevel) {
5620 // skip potential sub-contexts
5621 continue;
5623 $classname::create_level_instances();
5624 if ($buildpaths) {
5625 $classname::build_paths(false);
5631 * Rebuild paths and depths in all context levels.
5633 * @static
5634 * @param bool $force false means add missing only
5635 * @return void
5637 public static function build_all_paths($force = false) {
5638 foreach (self::$alllevels as $classname) {
5639 $classname::build_paths($force);
5642 // reset static course cache - it might have incorrect cached data
5643 accesslib_clear_all_caches(true);
5647 * Resets the cache to remove all data.
5648 * @static
5650 public static function reset_caches() {
5651 context::reset_caches();
5655 * Returns all fields necessary for context preloading from user $rec.
5657 * This helps with performance when dealing with hundreds of contexts.
5659 * @static
5660 * @param string $tablealias context table alias in the query
5661 * @return array (table.column=>alias, ...)
5663 public static function get_preload_record_columns($tablealias) {
5664 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5668 * Returns all fields necessary for context preloading from user $rec.
5670 * This helps with performance when dealing with hundreds of contexts.
5672 * @static
5673 * @param string $tablealias context table alias in the query
5674 * @return string
5676 public static function get_preload_record_columns_sql($tablealias) {
5677 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5681 * Preloads context information from db record and strips the cached info.
5683 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5685 * @static
5686 * @param stdClass $rec
5687 * @return void (modifies $rec)
5689 public static function preload_from_record(stdClass $rec) {
5690 context::preload_from_record($rec);
5694 * Preload all contexts instances from course.
5696 * To be used if you expect multiple queries for course activities...
5698 * @static
5699 * @param int $courseid
5701 public static function preload_course($courseid) {
5702 // Users can call this multiple times without doing any harm
5703 if (isset(context::$cache_preloaded[$courseid])) {
5704 return;
5706 $coursecontext = context_course::instance($courseid);
5707 $coursecontext->get_child_contexts();
5709 context::$cache_preloaded[$courseid] = true;
5713 * Delete context instance
5715 * @static
5716 * @param int $contextlevel
5717 * @param int $instanceid
5718 * @return void
5720 public static function delete_instance($contextlevel, $instanceid) {
5721 global $DB;
5723 // double check the context still exists
5724 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5725 $context = context::create_instance_from_record($record);
5726 $context->delete();
5727 } else {
5728 // we should try to purge the cache anyway
5733 * Returns the name of specified context level
5735 * @static
5736 * @param int $contextlevel
5737 * @return string name of the context level
5739 public static function get_level_name($contextlevel) {
5740 $classname = context_helper::get_class_for_level($contextlevel);
5741 return $classname::get_level_name();
5745 * not used
5747 public function get_url() {
5751 * not used
5753 public function get_capabilities() {
5759 * System context class
5761 * @package core_access
5762 * @category access
5763 * @copyright Petr Skoda {@link http://skodak.org}
5764 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5765 * @since 2.2
5767 class context_system extends context {
5769 * Please use context_system::instance() if you need the instance of context.
5771 * @param stdClass $record
5773 protected function __construct(stdClass $record) {
5774 parent::__construct($record);
5775 if ($record->contextlevel != CONTEXT_SYSTEM) {
5776 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5781 * Returns human readable context level name.
5783 * @static
5784 * @return string the human readable context level name.
5786 public static function get_level_name() {
5787 return get_string('coresystem');
5791 * Returns human readable context identifier.
5793 * @param boolean $withprefix does not apply to system context
5794 * @param boolean $short does not apply to system context
5795 * @return string the human readable context name.
5797 public function get_context_name($withprefix = true, $short = false) {
5798 return self::get_level_name();
5802 * Returns the most relevant URL for this context.
5804 * @return moodle_url
5806 public function get_url() {
5807 return new moodle_url('/');
5811 * Returns array of relevant context capability records.
5813 * @return array
5815 public function get_capabilities() {
5816 global $DB;
5818 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5820 $params = array();
5821 $sql = "SELECT *
5822 FROM {capabilities}";
5824 return $DB->get_records_sql($sql.' '.$sort, $params);
5828 * Create missing context instances at system context
5829 * @static
5831 protected static function create_level_instances() {
5832 // nothing to do here, the system context is created automatically in installer
5833 self::instance(0);
5837 * Returns system context instance.
5839 * @static
5840 * @param int $instanceid
5841 * @param int $strictness
5842 * @param bool $cache
5843 * @return context_system context instance
5845 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
5846 global $DB;
5848 if ($instanceid != 0) {
5849 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5852 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5853 if (!isset(context::$systemcontext)) {
5854 $record = new stdClass();
5855 $record->id = SYSCONTEXTID;
5856 $record->contextlevel = CONTEXT_SYSTEM;
5857 $record->instanceid = 0;
5858 $record->path = '/'.SYSCONTEXTID;
5859 $record->depth = 1;
5860 context::$systemcontext = new context_system($record);
5862 return context::$systemcontext;
5866 try {
5867 // we ignore the strictness completely because system context must except except during install
5868 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5869 } catch (dml_exception $e) {
5870 //table or record does not exist
5871 if (!during_initial_install()) {
5872 // do not mess with system context after install, it simply must exist
5873 throw $e;
5875 $record = null;
5878 if (!$record) {
5879 $record = new stdClass();
5880 $record->contextlevel = CONTEXT_SYSTEM;
5881 $record->instanceid = 0;
5882 $record->depth = 1;
5883 $record->path = null; //not known before insert
5885 try {
5886 if ($DB->count_records('context')) {
5887 // contexts already exist, this is very weird, system must be first!!!
5888 return null;
5890 if (defined('SYSCONTEXTID')) {
5891 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5892 $record->id = SYSCONTEXTID;
5893 $DB->import_record('context', $record);
5894 $DB->get_manager()->reset_sequence('context');
5895 } else {
5896 $record->id = $DB->insert_record('context', $record);
5898 } catch (dml_exception $e) {
5899 // can not create context - table does not exist yet, sorry
5900 return null;
5904 if ($record->instanceid != 0) {
5905 // this is very weird, somebody must be messing with context table
5906 debugging('Invalid system context detected');
5909 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5910 // fix path if necessary, initial install or path reset
5911 $record->depth = 1;
5912 $record->path = '/'.$record->id;
5913 $DB->update_record('context', $record);
5916 if (!defined('SYSCONTEXTID')) {
5917 define('SYSCONTEXTID', $record->id);
5920 context::$systemcontext = new context_system($record);
5921 return context::$systemcontext;
5925 * Returns all site contexts except the system context, DO NOT call on production servers!!
5927 * Contexts are not cached.
5929 * @return array
5931 public function get_child_contexts() {
5932 global $DB;
5934 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
5936 // Just get all the contexts except for CONTEXT_SYSTEM level
5937 // and hope we don't OOM in the process - don't cache
5938 $sql = "SELECT c.*
5939 FROM {context} c
5940 WHERE contextlevel > ".CONTEXT_SYSTEM;
5941 $records = $DB->get_records_sql($sql);
5943 $result = array();
5944 foreach ($records as $record) {
5945 $result[$record->id] = context::create_instance_from_record($record);
5948 return $result;
5952 * Returns sql necessary for purging of stale context instances.
5954 * @static
5955 * @return string cleanup SQL
5957 protected static function get_cleanup_sql() {
5958 $sql = "
5959 SELECT c.*
5960 FROM {context} c
5961 WHERE 1=2
5964 return $sql;
5968 * Rebuild context paths and depths at system context level.
5970 * @static
5971 * @param bool $force
5973 protected static function build_paths($force) {
5974 global $DB;
5976 /* note: ignore $force here, we always do full test of system context */
5978 // exactly one record must exist
5979 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5981 if ($record->instanceid != 0) {
5982 debugging('Invalid system context detected');
5985 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
5986 debugging('Invalid SYSCONTEXTID detected');
5989 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5990 // fix path if necessary, initial install or path reset
5991 $record->depth = 1;
5992 $record->path = '/'.$record->id;
5993 $DB->update_record('context', $record);
6000 * User context class
6002 * @package core_access
6003 * @category access
6004 * @copyright Petr Skoda {@link http://skodak.org}
6005 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6006 * @since 2.2
6008 class context_user extends context {
6010 * Please use context_user::instance($userid) if you need the instance of context.
6011 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6013 * @param stdClass $record
6015 protected function __construct(stdClass $record) {
6016 parent::__construct($record);
6017 if ($record->contextlevel != CONTEXT_USER) {
6018 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6023 * Returns human readable context level name.
6025 * @static
6026 * @return string the human readable context level name.
6028 public static function get_level_name() {
6029 return get_string('user');
6033 * Returns human readable context identifier.
6035 * @param boolean $withprefix whether to prefix the name of the context with User
6036 * @param boolean $short does not apply to user context
6037 * @return string the human readable context name.
6039 public function get_context_name($withprefix = true, $short = false) {
6040 global $DB;
6042 $name = '';
6043 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6044 if ($withprefix){
6045 $name = get_string('user').': ';
6047 $name .= fullname($user);
6049 return $name;
6053 * Returns the most relevant URL for this context.
6055 * @return moodle_url
6057 public function get_url() {
6058 global $COURSE;
6060 if ($COURSE->id == SITEID) {
6061 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6062 } else {
6063 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6065 return $url;
6069 * Returns array of relevant context capability records.
6071 * @return array
6073 public function get_capabilities() {
6074 global $DB;
6076 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6078 $extracaps = array('moodle/grade:viewall');
6079 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6080 $sql = "SELECT *
6081 FROM {capabilities}
6082 WHERE contextlevel = ".CONTEXT_USER."
6083 OR name $extra";
6085 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6089 * Returns user context instance.
6091 * @static
6092 * @param int $instanceid
6093 * @param int $strictness
6094 * @return context_user context instance
6096 public static function instance($instanceid, $strictness = MUST_EXIST) {
6097 global $DB;
6099 if ($context = context::cache_get(CONTEXT_USER, $instanceid)) {
6100 return $context;
6103 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_USER, 'instanceid'=>$instanceid))) {
6104 if ($user = $DB->get_record('user', array('id'=>$instanceid, 'deleted'=>0), 'id', $strictness)) {
6105 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6109 if ($record) {
6110 $context = new context_user($record);
6111 context::cache_add($context);
6112 return $context;
6115 return false;
6119 * Create missing context instances at user context level
6120 * @static
6122 protected static function create_level_instances() {
6123 global $DB;
6125 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6126 SELECT ".CONTEXT_USER.", u.id
6127 FROM {user} u
6128 WHERE u.deleted = 0
6129 AND NOT EXISTS (SELECT 'x'
6130 FROM {context} cx
6131 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6132 $DB->execute($sql);
6136 * Returns sql necessary for purging of stale context instances.
6138 * @static
6139 * @return string cleanup SQL
6141 protected static function get_cleanup_sql() {
6142 $sql = "
6143 SELECT c.*
6144 FROM {context} c
6145 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6146 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6149 return $sql;
6153 * Rebuild context paths and depths at user context level.
6155 * @static
6156 * @param bool $force
6158 protected static function build_paths($force) {
6159 global $DB;
6161 // First update normal users.
6162 $path = $DB->sql_concat('?', 'id');
6163 $pathstart = '/' . SYSCONTEXTID . '/';
6164 $params = array($pathstart);
6166 if ($force) {
6167 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6168 $params[] = $pathstart;
6169 } else {
6170 $where = "depth = 0 OR path IS NULL";
6173 $sql = "UPDATE {context}
6174 SET depth = 2,
6175 path = {$path}
6176 WHERE contextlevel = " . CONTEXT_USER . "
6177 AND ($where)";
6178 $DB->execute($sql, $params);
6184 * Course category context class
6186 * @package core_access
6187 * @category access
6188 * @copyright Petr Skoda {@link http://skodak.org}
6189 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6190 * @since 2.2
6192 class context_coursecat extends context {
6194 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6195 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6197 * @param stdClass $record
6199 protected function __construct(stdClass $record) {
6200 parent::__construct($record);
6201 if ($record->contextlevel != CONTEXT_COURSECAT) {
6202 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6207 * Returns human readable context level name.
6209 * @static
6210 * @return string the human readable context level name.
6212 public static function get_level_name() {
6213 return get_string('category');
6217 * Returns human readable context identifier.
6219 * @param boolean $withprefix whether to prefix the name of the context with Category
6220 * @param boolean $short does not apply to course categories
6221 * @return string the human readable context name.
6223 public function get_context_name($withprefix = true, $short = false) {
6224 global $DB;
6226 $name = '';
6227 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6228 if ($withprefix){
6229 $name = get_string('category').': ';
6231 $name .= format_string($category->name, true, array('context' => $this));
6233 return $name;
6237 * Returns the most relevant URL for this context.
6239 * @return moodle_url
6241 public function get_url() {
6242 return new moodle_url('/course/category.php', array('id'=>$this->_instanceid));
6246 * Returns array of relevant context capability records.
6248 * @return array
6250 public function get_capabilities() {
6251 global $DB;
6253 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6255 $params = array();
6256 $sql = "SELECT *
6257 FROM {capabilities}
6258 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6260 return $DB->get_records_sql($sql.' '.$sort, $params);
6264 * Returns course category context instance.
6266 * @static
6267 * @param int $instanceid
6268 * @param int $strictness
6269 * @return context_coursecat context instance
6271 public static function instance($instanceid, $strictness = MUST_EXIST) {
6272 global $DB;
6274 if ($context = context::cache_get(CONTEXT_COURSECAT, $instanceid)) {
6275 return $context;
6278 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSECAT, 'instanceid'=>$instanceid))) {
6279 if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), 'id,parent', $strictness)) {
6280 if ($category->parent) {
6281 $parentcontext = context_coursecat::instance($category->parent);
6282 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6283 } else {
6284 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6289 if ($record) {
6290 $context = new context_coursecat($record);
6291 context::cache_add($context);
6292 return $context;
6295 return false;
6299 * Returns immediate child contexts of category and all subcategories,
6300 * children of subcategories and courses are not returned.
6302 * @return array
6304 public function get_child_contexts() {
6305 global $DB;
6307 $sql = "SELECT ctx.*
6308 FROM {context} ctx
6309 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6310 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6311 $records = $DB->get_records_sql($sql, $params);
6313 $result = array();
6314 foreach ($records as $record) {
6315 $result[$record->id] = context::create_instance_from_record($record);
6318 return $result;
6322 * Create missing context instances at course category context level
6323 * @static
6325 protected static function create_level_instances() {
6326 global $DB;
6328 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6329 SELECT ".CONTEXT_COURSECAT.", cc.id
6330 FROM {course_categories} cc
6331 WHERE NOT EXISTS (SELECT 'x'
6332 FROM {context} cx
6333 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6334 $DB->execute($sql);
6338 * Returns sql necessary for purging of stale context instances.
6340 * @static
6341 * @return string cleanup SQL
6343 protected static function get_cleanup_sql() {
6344 $sql = "
6345 SELECT c.*
6346 FROM {context} c
6347 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6348 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6351 return $sql;
6355 * Rebuild context paths and depths at course category context level.
6357 * @static
6358 * @param bool $force
6360 protected static function build_paths($force) {
6361 global $DB;
6363 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6364 if ($force) {
6365 $ctxemptyclause = $emptyclause = '';
6366 } else {
6367 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6368 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6371 $base = '/'.SYSCONTEXTID;
6373 // Normal top level categories
6374 $sql = "UPDATE {context}
6375 SET depth=2,
6376 path=".$DB->sql_concat("'$base/'", 'id')."
6377 WHERE contextlevel=".CONTEXT_COURSECAT."
6378 AND EXISTS (SELECT 'x'
6379 FROM {course_categories} cc
6380 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6381 $emptyclause";
6382 $DB->execute($sql);
6384 // Deeper categories - one query per depthlevel
6385 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6386 for ($n=2; $n<=$maxdepth; $n++) {
6387 $sql = "INSERT INTO {context_temp} (id, path, depth)
6388 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6389 FROM {context} ctx
6390 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6391 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6392 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6393 $ctxemptyclause";
6394 $trans = $DB->start_delegated_transaction();
6395 $DB->delete_records('context_temp');
6396 $DB->execute($sql);
6397 context::merge_context_temp_table();
6398 $DB->delete_records('context_temp');
6399 $trans->allow_commit();
6408 * Course context class
6410 * @package core_access
6411 * @category access
6412 * @copyright Petr Skoda {@link http://skodak.org}
6413 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6414 * @since 2.2
6416 class context_course extends context {
6418 * Please use context_course::instance($courseid) if you need the instance of context.
6419 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6421 * @param stdClass $record
6423 protected function __construct(stdClass $record) {
6424 parent::__construct($record);
6425 if ($record->contextlevel != CONTEXT_COURSE) {
6426 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6431 * Returns human readable context level name.
6433 * @static
6434 * @return string the human readable context level name.
6436 public static function get_level_name() {
6437 return get_string('course');
6441 * Returns human readable context identifier.
6443 * @param boolean $withprefix whether to prefix the name of the context with Course
6444 * @param boolean $short whether to use the short name of the thing.
6445 * @return string the human readable context name.
6447 public function get_context_name($withprefix = true, $short = false) {
6448 global $DB;
6450 $name = '';
6451 if ($this->_instanceid == SITEID) {
6452 $name = get_string('frontpage', 'admin');
6453 } else {
6454 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6455 if ($withprefix){
6456 $name = get_string('course').': ';
6458 if ($short){
6459 $name .= format_string($course->shortname, true, array('context' => $this));
6460 } else {
6461 $name .= format_string(get_course_display_name_for_list($course));
6465 return $name;
6469 * Returns the most relevant URL for this context.
6471 * @return moodle_url
6473 public function get_url() {
6474 if ($this->_instanceid != SITEID) {
6475 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6478 return new moodle_url('/');
6482 * Returns array of relevant context capability records.
6484 * @return array
6486 public function get_capabilities() {
6487 global $DB;
6489 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6491 $params = array();
6492 $sql = "SELECT *
6493 FROM {capabilities}
6494 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6496 return $DB->get_records_sql($sql.' '.$sort, $params);
6500 * Is this context part of any course? If yes return course context.
6502 * @param bool $strict true means throw exception if not found, false means return false if not found
6503 * @return course_context context of the enclosing course, null if not found or exception
6505 public function get_course_context($strict = true) {
6506 return $this;
6510 * Returns course context instance.
6512 * @static
6513 * @param int $instanceid
6514 * @param int $strictness
6515 * @return context_course context instance
6517 public static function instance($instanceid, $strictness = MUST_EXIST) {
6518 global $DB;
6520 if ($context = context::cache_get(CONTEXT_COURSE, $instanceid)) {
6521 return $context;
6524 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$instanceid))) {
6525 if ($course = $DB->get_record('course', array('id'=>$instanceid), 'id,category', $strictness)) {
6526 if ($course->category) {
6527 $parentcontext = context_coursecat::instance($course->category);
6528 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6529 } else {
6530 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6535 if ($record) {
6536 $context = new context_course($record);
6537 context::cache_add($context);
6538 return $context;
6541 return false;
6545 * Create missing context instances at course context level
6546 * @static
6548 protected static function create_level_instances() {
6549 global $DB;
6551 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6552 SELECT ".CONTEXT_COURSE.", c.id
6553 FROM {course} c
6554 WHERE NOT EXISTS (SELECT 'x'
6555 FROM {context} cx
6556 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6557 $DB->execute($sql);
6561 * Returns sql necessary for purging of stale context instances.
6563 * @static
6564 * @return string cleanup SQL
6566 protected static function get_cleanup_sql() {
6567 $sql = "
6568 SELECT c.*
6569 FROM {context} c
6570 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6571 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6574 return $sql;
6578 * Rebuild context paths and depths at course context level.
6580 * @static
6581 * @param bool $force
6583 protected static function build_paths($force) {
6584 global $DB;
6586 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6587 if ($force) {
6588 $ctxemptyclause = $emptyclause = '';
6589 } else {
6590 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6591 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6594 $base = '/'.SYSCONTEXTID;
6596 // Standard frontpage
6597 $sql = "UPDATE {context}
6598 SET depth = 2,
6599 path = ".$DB->sql_concat("'$base/'", 'id')."
6600 WHERE contextlevel = ".CONTEXT_COURSE."
6601 AND EXISTS (SELECT 'x'
6602 FROM {course} c
6603 WHERE c.id = {context}.instanceid AND c.category = 0)
6604 $emptyclause";
6605 $DB->execute($sql);
6607 // standard courses
6608 $sql = "INSERT INTO {context_temp} (id, path, depth)
6609 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6610 FROM {context} ctx
6611 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6612 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6613 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6614 $ctxemptyclause";
6615 $trans = $DB->start_delegated_transaction();
6616 $DB->delete_records('context_temp');
6617 $DB->execute($sql);
6618 context::merge_context_temp_table();
6619 $DB->delete_records('context_temp');
6620 $trans->allow_commit();
6627 * Course module context class
6629 * @package core_access
6630 * @category access
6631 * @copyright Petr Skoda {@link http://skodak.org}
6632 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6633 * @since 2.2
6635 class context_module extends context {
6637 * Please use context_module::instance($cmid) if you need the instance of context.
6638 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6640 * @param stdClass $record
6642 protected function __construct(stdClass $record) {
6643 parent::__construct($record);
6644 if ($record->contextlevel != CONTEXT_MODULE) {
6645 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6650 * Returns human readable context level name.
6652 * @static
6653 * @return string the human readable context level name.
6655 public static function get_level_name() {
6656 return get_string('activitymodule');
6660 * Returns human readable context identifier.
6662 * @param boolean $withprefix whether to prefix the name of the context with the
6663 * module name, e.g. Forum, Glossary, etc.
6664 * @param boolean $short does not apply to module context
6665 * @return string the human readable context name.
6667 public function get_context_name($withprefix = true, $short = false) {
6668 global $DB;
6670 $name = '';
6671 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6672 FROM {course_modules} cm
6673 JOIN {modules} md ON md.id = cm.module
6674 WHERE cm.id = ?", array($this->_instanceid))) {
6675 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6676 if ($withprefix){
6677 $name = get_string('modulename', $cm->modname).': ';
6679 $name .= format_string($mod->name, true, array('context' => $this));
6682 return $name;
6686 * Returns the most relevant URL for this context.
6688 * @return moodle_url
6690 public function get_url() {
6691 global $DB;
6693 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6694 FROM {course_modules} cm
6695 JOIN {modules} md ON md.id = cm.module
6696 WHERE cm.id = ?", array($this->_instanceid))) {
6697 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6700 return new moodle_url('/');
6704 * Returns array of relevant context capability records.
6706 * @return array
6708 public function get_capabilities() {
6709 global $DB, $CFG;
6711 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6713 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6714 $module = $DB->get_record('modules', array('id'=>$cm->module));
6716 $subcaps = array();
6717 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6718 if (file_exists($subpluginsfile)) {
6719 $subplugins = array(); // should be redefined in the file
6720 include($subpluginsfile);
6721 if (!empty($subplugins)) {
6722 foreach (array_keys($subplugins) as $subplugintype) {
6723 foreach (array_keys(get_plugin_list($subplugintype)) as $subpluginname) {
6724 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6730 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6731 $extracaps = array();
6732 if (file_exists($modfile)) {
6733 include_once($modfile);
6734 $modfunction = $module->name.'_get_extra_capabilities';
6735 if (function_exists($modfunction)) {
6736 $extracaps = $modfunction();
6740 $extracaps = array_merge($subcaps, $extracaps);
6741 $extra = '';
6742 list($extra, $params) = $DB->get_in_or_equal(
6743 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
6744 if (!empty($extra)) {
6745 $extra = "OR name $extra";
6747 $sql = "SELECT *
6748 FROM {capabilities}
6749 WHERE (contextlevel = ".CONTEXT_MODULE."
6750 AND (component = :component OR component = 'moodle'))
6751 $extra";
6752 $params['component'] = "mod_$module->name";
6754 return $DB->get_records_sql($sql.' '.$sort, $params);
6758 * Is this context part of any course? If yes return course context.
6760 * @param bool $strict true means throw exception if not found, false means return false if not found
6761 * @return course_context context of the enclosing course, null if not found or exception
6763 public function get_course_context($strict = true) {
6764 return $this->get_parent_context();
6768 * Returns module context instance.
6770 * @static
6771 * @param int $instanceid
6772 * @param int $strictness
6773 * @return context_module context instance
6775 public static function instance($instanceid, $strictness = MUST_EXIST) {
6776 global $DB;
6778 if ($context = context::cache_get(CONTEXT_MODULE, $instanceid)) {
6779 return $context;
6782 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$instanceid))) {
6783 if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), 'id,course', $strictness)) {
6784 $parentcontext = context_course::instance($cm->course);
6785 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
6789 if ($record) {
6790 $context = new context_module($record);
6791 context::cache_add($context);
6792 return $context;
6795 return false;
6799 * Create missing context instances at module context level
6800 * @static
6802 protected static function create_level_instances() {
6803 global $DB;
6805 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6806 SELECT ".CONTEXT_MODULE.", cm.id
6807 FROM {course_modules} cm
6808 WHERE NOT EXISTS (SELECT 'x'
6809 FROM {context} cx
6810 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
6811 $DB->execute($sql);
6815 * Returns sql necessary for purging of stale context instances.
6817 * @static
6818 * @return string cleanup SQL
6820 protected static function get_cleanup_sql() {
6821 $sql = "
6822 SELECT c.*
6823 FROM {context} c
6824 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6825 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
6828 return $sql;
6832 * Rebuild context paths and depths at module context level.
6834 * @static
6835 * @param bool $force
6837 protected static function build_paths($force) {
6838 global $DB;
6840 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
6841 if ($force) {
6842 $ctxemptyclause = '';
6843 } else {
6844 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6847 $sql = "INSERT INTO {context_temp} (id, path, depth)
6848 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6849 FROM {context} ctx
6850 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
6851 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
6852 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6853 $ctxemptyclause";
6854 $trans = $DB->start_delegated_transaction();
6855 $DB->delete_records('context_temp');
6856 $DB->execute($sql);
6857 context::merge_context_temp_table();
6858 $DB->delete_records('context_temp');
6859 $trans->allow_commit();
6866 * Block context class
6868 * @package core_access
6869 * @category access
6870 * @copyright Petr Skoda {@link http://skodak.org}
6871 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6872 * @since 2.2
6874 class context_block extends context {
6876 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6877 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6879 * @param stdClass $record
6881 protected function __construct(stdClass $record) {
6882 parent::__construct($record);
6883 if ($record->contextlevel != CONTEXT_BLOCK) {
6884 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6889 * Returns human readable context level name.
6891 * @static
6892 * @return string the human readable context level name.
6894 public static function get_level_name() {
6895 return get_string('block');
6899 * Returns human readable context identifier.
6901 * @param boolean $withprefix whether to prefix the name of the context with Block
6902 * @param boolean $short does not apply to block context
6903 * @return string the human readable context name.
6905 public function get_context_name($withprefix = true, $short = false) {
6906 global $DB, $CFG;
6908 $name = '';
6909 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
6910 global $CFG;
6911 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
6912 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
6913 $blockname = "block_$blockinstance->blockname";
6914 if ($blockobject = new $blockname()) {
6915 if ($withprefix){
6916 $name = get_string('block').': ';
6918 $name .= $blockobject->title;
6922 return $name;
6926 * Returns the most relevant URL for this context.
6928 * @return moodle_url
6930 public function get_url() {
6931 $parentcontexts = $this->get_parent_context();
6932 return $parentcontexts->get_url();
6936 * Returns array of relevant context capability records.
6938 * @return array
6940 public function get_capabilities() {
6941 global $DB;
6943 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6945 $params = array();
6946 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
6948 $extra = '';
6949 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
6950 if ($extracaps) {
6951 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6952 $extra = "OR name $extra";
6955 $sql = "SELECT *
6956 FROM {capabilities}
6957 WHERE (contextlevel = ".CONTEXT_BLOCK."
6958 AND component = :component)
6959 $extra";
6960 $params['component'] = 'block_' . $bi->blockname;
6962 return $DB->get_records_sql($sql.' '.$sort, $params);
6966 * Is this context part of any course? If yes return course context.
6968 * @param bool $strict true means throw exception if not found, false means return false if not found
6969 * @return course_context context of the enclosing course, null if not found or exception
6971 public function get_course_context($strict = true) {
6972 $parentcontext = $this->get_parent_context();
6973 return $parentcontext->get_course_context($strict);
6977 * Returns block context instance.
6979 * @static
6980 * @param int $instanceid
6981 * @param int $strictness
6982 * @return context_block context instance
6984 public static function instance($instanceid, $strictness = MUST_EXIST) {
6985 global $DB;
6987 if ($context = context::cache_get(CONTEXT_BLOCK, $instanceid)) {
6988 return $context;
6991 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$instanceid))) {
6992 if ($bi = $DB->get_record('block_instances', array('id'=>$instanceid), 'id,parentcontextid', $strictness)) {
6993 $parentcontext = context::instance_by_id($bi->parentcontextid);
6994 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
6998 if ($record) {
6999 $context = new context_block($record);
7000 context::cache_add($context);
7001 return $context;
7004 return false;
7008 * Block do not have child contexts...
7009 * @return array
7011 public function get_child_contexts() {
7012 return array();
7016 * Create missing context instances at block context level
7017 * @static
7019 protected static function create_level_instances() {
7020 global $DB;
7022 $sql = "INSERT INTO {context} (contextlevel, instanceid)
7023 SELECT ".CONTEXT_BLOCK.", bi.id
7024 FROM {block_instances} bi
7025 WHERE NOT EXISTS (SELECT 'x'
7026 FROM {context} cx
7027 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7028 $DB->execute($sql);
7032 * Returns sql necessary for purging of stale context instances.
7034 * @static
7035 * @return string cleanup SQL
7037 protected static function get_cleanup_sql() {
7038 $sql = "
7039 SELECT c.*
7040 FROM {context} c
7041 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7042 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7045 return $sql;
7049 * Rebuild context paths and depths at block context level.
7051 * @static
7052 * @param bool $force
7054 protected static function build_paths($force) {
7055 global $DB;
7057 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7058 if ($force) {
7059 $ctxemptyclause = '';
7060 } else {
7061 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7064 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7065 $sql = "INSERT INTO {context_temp} (id, path, depth)
7066 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7067 FROM {context} ctx
7068 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7069 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7070 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7071 $ctxemptyclause";
7072 $trans = $DB->start_delegated_transaction();
7073 $DB->delete_records('context_temp');
7074 $DB->execute($sql);
7075 context::merge_context_temp_table();
7076 $DB->delete_records('context_temp');
7077 $trans->allow_commit();
7083 // ============== DEPRECATED FUNCTIONS ==========================================
7084 // Old context related functions were deprecated in 2.0, it is recommended
7085 // to use context classes in new code. Old function can be used when
7086 // creating patches that are supposed to be backported to older stable branches.
7087 // These deprecated functions will not be removed in near future,
7088 // before removing devs will be warned with a debugging message first,
7089 // then we will add error message and only after that we can remove the functions
7090 // completely.
7094 * Not available any more, use load_temp_course_role() instead.
7096 * @deprecated since 2.2
7097 * @param stdClass $context
7098 * @param int $roleid
7099 * @param array $accessdata
7100 * @return array
7102 function load_temp_role($context, $roleid, array $accessdata) {
7103 debugging('load_temp_role() is deprecated, please use load_temp_course_role() instead, temp role not loaded.');
7104 return $accessdata;
7108 * Not available any more, use remove_temp_course_roles() instead.
7110 * @deprecated since 2.2
7111 * @param stdClass $context
7112 * @param array $accessdata
7113 * @return array access data
7115 function remove_temp_roles($context, array $accessdata) {
7116 debugging('remove_temp_role() is deprecated, please use remove_temp_course_roles() instead.');
7117 return $accessdata;
7121 * Returns system context or null if can not be created yet.
7123 * @deprecated since 2.2, use context_system::instance()
7124 * @param bool $cache use caching
7125 * @return context system context (null if context table not created yet)
7127 function get_system_context($cache = true) {
7128 return context_system::instance(0, IGNORE_MISSING, $cache);
7132 * Get the context instance as an object. This function will create the
7133 * context instance if it does not exist yet.
7135 * @deprecated since 2.2, use context_course::instance() or other relevant class instead
7136 * @param integer $contextlevel The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
7137 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
7138 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
7139 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
7140 * MUST_EXIST means throw exception if no record or multiple records found
7141 * @return context The context object.
7143 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
7144 $instances = (array)$instance;
7145 $contexts = array();
7147 $classname = context_helper::get_class_for_level($contextlevel);
7149 // we do not load multiple contexts any more, PAGE should be responsible for any preloading
7150 foreach ($instances as $inst) {
7151 $contexts[$inst] = $classname::instance($inst, $strictness);
7154 if (is_array($instance)) {
7155 return $contexts;
7156 } else {
7157 return $contexts[$instance];
7162 * Get a context instance as an object, from a given context id.
7164 * @deprecated since 2.2, use context::instance_by_id($id) instead
7165 * @param int $id context id
7166 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
7167 * MUST_EXIST means throw exception if no record or multiple records found
7168 * @return context|bool the context object or false if not found.
7170 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
7171 return context::instance_by_id($id, $strictness);
7175 * Recursive function which, given a context, find all parent context ids,
7176 * and return the array in reverse order, i.e. parent first, then grand
7177 * parent, etc.
7179 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
7180 * @param context $context
7181 * @param bool $includeself optional, defaults to false
7182 * @return array
7184 function get_parent_contexts(context $context, $includeself = false) {
7185 return $context->get_parent_context_ids($includeself);
7189 * Return the id of the parent of this context, or false if there is no parent (only happens if this
7190 * is the site context.)
7192 * @deprecated since 2.2, use $context->get_parent_context() instead
7193 * @param context $context
7194 * @return integer the id of the parent context.
7196 function get_parent_contextid(context $context) {
7197 if ($parent = $context->get_parent_context()) {
7198 return $parent->id;
7199 } else {
7200 return false;
7205 * Recursive function which, given a context, find all its children context ids.
7207 * For course category contexts it will return immediate children only categories and courses.
7208 * It will NOT recurse into courses or child categories.
7209 * If you want to do that, call it on the returned courses/categories.
7211 * When called for a course context, it will return the modules and blocks
7212 * displayed in the course page.
7214 * If called on a user/course/module context it _will_ populate the cache with the appropriate
7215 * contexts ;-)
7217 * @deprecated since 2.2, use $context->get_child_contexts() instead
7218 * @param context $context
7219 * @return array Array of child records
7221 function get_child_contexts(context $context) {
7222 return $context->get_child_contexts();
7226 * Precreates all contexts including all parents
7228 * @deprecated since 2.2
7229 * @param int $contextlevel empty means all
7230 * @param bool $buildpaths update paths and depths
7231 * @return void
7233 function create_contexts($contextlevel = null, $buildpaths = true) {
7234 context_helper::create_instances($contextlevel, $buildpaths);
7238 * Remove stale context records
7240 * @deprecated since 2.2, use context_helper::cleanup_instances() instead
7241 * @return bool
7243 function cleanup_contexts() {
7244 context_helper::cleanup_instances();
7245 return true;
7249 * Populate context.path and context.depth where missing.
7251 * @deprecated since 2.2, use context_helper::build_all_paths() instead
7252 * @param bool $force force a complete rebuild of the path and depth fields, defaults to false
7253 * @return void
7255 function build_context_path($force = false) {
7256 context_helper::build_all_paths($force);
7260 * Rebuild all related context depth and path caches
7262 * @deprecated since 2.2
7263 * @param array $fixcontexts array of contexts, strongtyped
7264 * @return void
7266 function rebuild_contexts(array $fixcontexts) {
7267 foreach ($fixcontexts as $fixcontext) {
7268 $fixcontext->reset_paths(false);
7270 context_helper::build_all_paths(false);
7274 * Preloads all contexts relating to a course: course, modules. Block contexts
7275 * are no longer loaded here. The contexts for all the blocks on the current
7276 * page are now efficiently loaded by {@link block_manager::load_blocks()}.
7278 * @deprecated since 2.2
7279 * @param int $courseid Course ID
7280 * @return void
7282 function preload_course_contexts($courseid) {
7283 context_helper::preload_course($courseid);
7287 * Preloads context information together with instances.
7288 * Use context_instance_preload() to strip the context info from the record and cache the context instance.
7290 * @deprecated since 2.2
7291 * @param string $joinon for example 'u.id'
7292 * @param string $contextlevel context level of instance in $joinon
7293 * @param string $tablealias context table alias
7294 * @return array with two values - select and join part
7296 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
7297 $select = ", ".context_helper::get_preload_record_columns_sql($tablealias);
7298 $join = "LEFT JOIN {context} $tablealias ON ($tablealias.instanceid = $joinon AND $tablealias.contextlevel = $contextlevel)";
7299 return array($select, $join);
7303 * Preloads context information from db record and strips the cached info.
7304 * The db request has to contain both the $join and $select from context_instance_preload_sql()
7306 * @deprecated since 2.2
7307 * @param stdClass $rec
7308 * @return void (modifies $rec)
7310 function context_instance_preload(stdClass $rec) {
7311 context_helper::preload_from_record($rec);
7315 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
7317 * @deprecated since 2.2, use $context->mark_dirty() instead
7318 * @param string $path context path
7320 function mark_context_dirty($path) {
7321 global $CFG, $USER, $ACCESSLIB_PRIVATE;
7323 if (during_initial_install()) {
7324 return;
7327 // only if it is a non-empty string
7328 if (is_string($path) && $path !== '') {
7329 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+$CFG->sessiontimeout);
7330 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
7331 $ACCESSLIB_PRIVATE->dirtycontexts[$path] = 1;
7332 } else {
7333 if (CLI_SCRIPT) {
7334 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
7335 } else {
7336 if (isset($USER->access['time'])) {
7337 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
7338 } else {
7339 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
7341 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
7348 * Update the path field of the context and all dep. subcontexts that follow
7350 * Update the path field of the context and
7351 * all the dependent subcontexts that follow
7352 * the move.
7354 * The most important thing here is to be as
7355 * DB efficient as possible. This op can have a
7356 * massive impact in the DB.
7358 * @deprecated since 2.2
7359 * @param context $context context obj
7360 * @param context $newparent new parent obj
7361 * @return void
7363 function context_moved(context $context, context $newparent) {
7364 $context->update_moved($newparent);
7368 * Remove a context record and any dependent entries,
7369 * removes context from static context cache too
7371 * @deprecated since 2.2, use $context->delete_content() instead
7372 * @param int $contextlevel
7373 * @param int $instanceid
7374 * @param bool $deleterecord false means keep record for now
7375 * @return bool returns true or throws an exception
7377 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
7378 if ($deleterecord) {
7379 context_helper::delete_instance($contextlevel, $instanceid);
7380 } else {
7381 $classname = context_helper::get_class_for_level($contextlevel);
7382 if ($context = $classname::instance($instanceid, IGNORE_MISSING)) {
7383 $context->delete_content();
7387 return true;
7391 * Returns context level name
7393 * @deprecated since 2.2
7394 * @param integer $contextlevel $context->context level. One of the CONTEXT_... constants.
7395 * @return string the name for this type of context.
7397 function get_contextlevel_name($contextlevel) {
7398 return context_helper::get_level_name($contextlevel);
7402 * Prints human readable context identifier.
7404 * @deprecated since 2.2
7405 * @param context $context the context.
7406 * @param boolean $withprefix whether to prefix the name of the context with the
7407 * type of context, e.g. User, Course, Forum, etc.
7408 * @param boolean $short whether to user the short name of the thing. Only applies
7409 * to course contexts
7410 * @return string the human readable context name.
7412 function print_context_name(context $context, $withprefix = true, $short = false) {
7413 return $context->get_context_name($withprefix, $short);
7417 * Get a URL for a context, if there is a natural one. For example, for
7418 * CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
7419 * user profile page.
7421 * @deprecated since 2.2
7422 * @param context $context the context.
7423 * @return moodle_url
7425 function get_context_url(context $context) {
7426 return $context->get_url();
7430 * Is this context part of any course? if yes return course context,
7431 * if not return null or throw exception.
7433 * @deprecated since 2.2, use $context->get_course_context() instead
7434 * @param context $context
7435 * @return course_context context of the enclosing course, null if not found or exception
7437 function get_course_context(context $context) {
7438 return $context->get_course_context(true);
7442 * Returns current course id or null if outside of course based on context parameter.
7444 * @deprecated since 2.2, use $context->get_course_context instead
7445 * @param context $context
7446 * @return int|bool related course id or false
7448 function get_courseid_from_context(context $context) {
7449 if ($coursecontext = $context->get_course_context(false)) {
7450 return $coursecontext->instanceid;
7451 } else {
7452 return false;
7457 * Get an array of courses where cap requested is available
7458 * and user is enrolled, this can be relatively slow.
7460 * @deprecated since 2.2, use enrol_get_users_courses() instead
7461 * @param int $userid A user id. By default (null) checks the permissions of the current user.
7462 * @param string $cap - name of the capability
7463 * @param array $accessdata_ignored
7464 * @param bool $doanything_ignored
7465 * @param string $sort - sorting fields - prefix each fieldname with "c."
7466 * @param array $fields - additional fields you are interested in...
7467 * @param int $limit_ignored
7468 * @return array $courses - ordered array of course objects - see notes above
7470 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
7472 $courses = enrol_get_users_courses($userid, true, $fields, $sort);
7473 foreach ($courses as $id=>$course) {
7474 $context = context_course::instance($id);
7475 if (!has_capability($cap, $context, $userid)) {
7476 unset($courses[$id]);
7480 return $courses;
7484 * Extracts the relevant capabilities given a contextid.
7485 * All case based, example an instance of forum context.
7486 * Will fetch all forum related capabilities, while course contexts
7487 * Will fetch all capabilities
7489 * capabilities
7490 * `name` varchar(150) NOT NULL,
7491 * `captype` varchar(50) NOT NULL,
7492 * `contextlevel` int(10) NOT NULL,
7493 * `component` varchar(100) NOT NULL,
7495 * @deprecated since 2.2
7496 * @param context $context
7497 * @return array
7499 function fetch_context_capabilities(context $context) {
7500 return $context->get_capabilities();
7504 * Runs get_records select on context table and returns the result
7505 * Does get_records_select on the context table, and returns the results ordered
7506 * by contextlevel, and then the natural sort order within each level.
7507 * for the purpose of $select, you need to know that the context table has been
7508 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7510 * @deprecated since 2.2
7511 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7512 * @param array $params any parameters required by $select.
7513 * @return array the requested context records.
7515 function get_sorted_contexts($select, $params = array()) {
7517 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7519 global $DB;
7520 if ($select) {
7521 $select = 'WHERE ' . $select;
7523 return $DB->get_records_sql("
7524 SELECT ctx.*
7525 FROM {context} ctx
7526 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7527 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7528 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7529 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7530 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7531 $select
7532 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7533 ", $params);
7537 * This is really slow!!! do not use above course context level
7539 * @deprecated since 2.2
7540 * @param int $roleid
7541 * @param context $context
7542 * @return array
7544 function get_role_context_caps($roleid, context $context) {
7545 global $DB;
7547 //this is really slow!!!! - do not use above course context level!
7548 $result = array();
7549 $result[$context->id] = array();
7551 // first emulate the parent context capabilities merging into context
7552 $searchcontexts = array_reverse($context->get_parent_context_ids(true));
7553 foreach ($searchcontexts as $cid) {
7554 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7555 foreach ($capabilities as $cap) {
7556 if (!array_key_exists($cap->capability, $result[$context->id])) {
7557 $result[$context->id][$cap->capability] = 0;
7559 $result[$context->id][$cap->capability] += $cap->permission;
7564 // now go through the contexts below given context
7565 $searchcontexts = array_keys($context->get_child_contexts());
7566 foreach ($searchcontexts as $cid) {
7567 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7568 foreach ($capabilities as $cap) {
7569 if (!array_key_exists($cap->contextid, $result)) {
7570 $result[$cap->contextid] = array();
7572 $result[$cap->contextid][$cap->capability] = $cap->permission;
7577 return $result;
7581 * Gets a string for sql calls, searching for stuff in this context or above
7583 * NOTE: use $DB->get_in_or_equal($context->get_parent_context_ids()...
7585 * @deprecated since 2.2, $context->use get_parent_context_ids() instead
7586 * @param context $context
7587 * @return string
7589 function get_related_contexts_string(context $context) {
7591 if ($parents = $context->get_parent_context_ids()) {
7592 return (' IN ('.$context->id.','.implode(',', $parents).')');
7593 } else {
7594 return (' ='.$context->id);