MDL-39680 theme_bootstrapbase: Fixed footer alignment in less/moodle/debug.less
[moodle.git] / lib / accesslib.php
blobf9e4e71cfdde852cd0a53c79977b9453bde933be
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);
272 // Overrides for the role IN ANY CONTEXTS down to COURSE - not below -.
275 $sql = "SELECT ctx.path,
276 rc.capability, rc.permission
277 FROM {context} ctx
278 JOIN {role_capabilities} rc ON rc.contextid = ctx.id
279 LEFT JOIN {context} cctx
280 ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
281 WHERE rc.roleid = ? AND cctx.id IS NULL";
282 $params = array($roleid);
285 // Note: the commented out query is 100% accurate but slow, so let's cheat instead by hardcoding the blocks mess directly.
287 $sql = "SELECT COALESCE(ctx.path, bctx.path) AS path, rc.capability, rc.permission
288 FROM {role_capabilities} rc
289 LEFT JOIN {context} ctx ON (ctx.id = rc.contextid AND ctx.contextlevel <= ".CONTEXT_COURSE.")
290 LEFT JOIN ({context} bctx
291 JOIN {block_instances} bi ON (bi.id = bctx.instanceid)
292 JOIN {context} pctx ON (pctx.id = bi.parentcontextid AND pctx.contextlevel < ".CONTEXT_COURSE.")
293 ) ON (bctx.id = rc.contextid AND bctx.contextlevel = ".CONTEXT_BLOCK.")
294 WHERE rc.roleid = :roleid AND (ctx.id IS NOT NULL OR bctx.id IS NOT NULL)";
295 $params = array('roleid'=>$roleid);
297 // we need extra caching in CLI scripts and cron
298 $rs = $DB->get_recordset_sql($sql, $params);
299 foreach ($rs as $rd) {
300 $k = "{$rd->path}:{$roleid}";
301 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
303 $rs->close();
305 // share the role definitions
306 foreach ($accessdata['rdef'] as $k=>$unused) {
307 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
308 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
310 $accessdata['rdef_count']++;
311 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
314 return $accessdata;
318 * Get the default guest role, this is used for guest account,
319 * search engine spiders, etc.
321 * @return stdClass role record
323 function get_guest_role() {
324 global $CFG, $DB;
326 if (empty($CFG->guestroleid)) {
327 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
328 $guestrole = array_shift($roles); // Pick the first one
329 set_config('guestroleid', $guestrole->id);
330 return $guestrole;
331 } else {
332 debugging('Can not find any guest role!');
333 return false;
335 } else {
336 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
337 return $guestrole;
338 } else {
339 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
340 set_config('guestroleid', '');
341 return get_guest_role();
347 * Check whether a user has a particular capability in a given context.
349 * For example:
350 * $context = context_module::instance($cm->id);
351 * has_capability('mod/forum:replypost', $context)
353 * By default checks the capabilities of the current user, but you can pass a
354 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
356 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
357 * or capabilities with XSS, config or data loss risks.
359 * @category access
361 * @param string $capability the name of the capability to check. For example mod/forum:view
362 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
363 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
364 * @param boolean $doanything If false, ignores effect of admin role assignment
365 * @return boolean true if the user has this capability. Otherwise false.
367 function has_capability($capability, context $context, $user = null, $doanything = true) {
368 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
370 if (during_initial_install()) {
371 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cli/install.php" or $SCRIPT === "/$CFG->admin/cli/install_database.php") {
372 // we are in an installer - roles can not work yet
373 return true;
374 } else {
375 return false;
379 if (strpos($capability, 'moodle/legacy:') === 0) {
380 throw new coding_exception('Legacy capabilities can not be used any more!');
383 if (!is_bool($doanything)) {
384 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
387 // capability must exist
388 if (!$capinfo = get_capability_info($capability)) {
389 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
390 return false;
393 if (!isset($USER->id)) {
394 // should never happen
395 $USER->id = 0;
396 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER);
399 // make sure there is a real user specified
400 if ($user === null) {
401 $userid = $USER->id;
402 } else {
403 $userid = is_object($user) ? $user->id : $user;
406 // make sure forcelogin cuts off not-logged-in users if enabled
407 if (!empty($CFG->forcelogin) and $userid == 0) {
408 return false;
411 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
412 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
413 if (isguestuser($userid) or $userid == 0) {
414 return false;
418 // somehow make sure the user is not deleted and actually exists
419 if ($userid != 0) {
420 if ($userid == $USER->id and isset($USER->deleted)) {
421 // this prevents one query per page, it is a bit of cheating,
422 // but hopefully session is terminated properly once user is deleted
423 if ($USER->deleted) {
424 return false;
426 } else {
427 if (!context_user::instance($userid, IGNORE_MISSING)) {
428 // no user context == invalid userid
429 return false;
434 // context path/depth must be valid
435 if (empty($context->path) or $context->depth == 0) {
436 // this should not happen often, each upgrade tries to rebuild the context paths
437 debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()');
438 if (is_siteadmin($userid)) {
439 return true;
440 } else {
441 return false;
445 // Find out if user is admin - it is not possible to override the doanything in any way
446 // and it is not possible to switch to admin role either.
447 if ($doanything) {
448 if (is_siteadmin($userid)) {
449 if ($userid != $USER->id) {
450 return true;
452 // make sure switchrole is not used in this context
453 if (empty($USER->access['rsw'])) {
454 return true;
456 $parts = explode('/', trim($context->path, '/'));
457 $path = '';
458 $switched = false;
459 foreach ($parts as $part) {
460 $path .= '/' . $part;
461 if (!empty($USER->access['rsw'][$path])) {
462 $switched = true;
463 break;
466 if (!$switched) {
467 return true;
469 //ok, admin switched role in this context, let's use normal access control rules
473 // Careful check for staleness...
474 $context->reload_if_dirty();
476 if ($USER->id == $userid) {
477 if (!isset($USER->access)) {
478 load_all_capabilities();
480 $access =& $USER->access;
482 } else {
483 // make sure user accessdata is really loaded
484 get_user_accessdata($userid, true);
485 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
489 // Load accessdata for below-the-course context if necessary,
490 // all contexts at and above all courses are already loaded
491 if ($context->contextlevel != CONTEXT_COURSE and $coursecontext = $context->get_course_context(false)) {
492 load_course_context($userid, $coursecontext, $access);
495 return has_capability_in_accessdata($capability, $context, $access);
499 * Check if the user has any one of several capabilities from a list.
501 * This is just a utility method that calls has_capability in a loop. Try to put
502 * the capabilities that most users are likely to have first in the list for best
503 * performance.
505 * @category access
506 * @see has_capability()
508 * @param array $capabilities an array of capability names.
509 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
510 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
511 * @param boolean $doanything If false, ignore effect of admin role assignment
512 * @return boolean true if the user has any of these capabilities. Otherwise false.
514 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
515 foreach ($capabilities as $capability) {
516 if (has_capability($capability, $context, $user, $doanything)) {
517 return true;
520 return false;
524 * Check if the user has all the capabilities in a list.
526 * This is just a utility method that calls has_capability in a loop. Try to put
527 * the capabilities that fewest users are likely to have first in the list for best
528 * performance.
530 * @category access
531 * @see has_capability()
533 * @param array $capabilities an array of capability names.
534 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
535 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
536 * @param boolean $doanything If false, ignore effect of admin role assignment
537 * @return boolean true if the user has all of these capabilities. Otherwise false.
539 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
540 foreach ($capabilities as $capability) {
541 if (!has_capability($capability, $context, $user, $doanything)) {
542 return false;
545 return true;
549 * Check if the user is an admin at the site level.
551 * Please note that use of proper capabilities is always encouraged,
552 * this function is supposed to be used from core or for temporary hacks.
554 * @category access
556 * @param int|stdClass $user_or_id user id or user object
557 * @return bool true if user is one of the administrators, false otherwise
559 function is_siteadmin($user_or_id = null) {
560 global $CFG, $USER;
562 if ($user_or_id === null) {
563 $user_or_id = $USER;
566 if (empty($user_or_id)) {
567 return false;
569 if (!empty($user_or_id->id)) {
570 $userid = $user_or_id->id;
571 } else {
572 $userid = $user_or_id;
575 $siteadmins = explode(',', $CFG->siteadmins);
576 return in_array($userid, $siteadmins);
580 * Returns true if user has at least one role assign
581 * of 'coursecontact' role (is potentially listed in some course descriptions).
583 * @param int $userid
584 * @return bool
586 function has_coursecontact_role($userid) {
587 global $DB, $CFG;
589 if (empty($CFG->coursecontact)) {
590 return false;
592 $sql = "SELECT 1
593 FROM {role_assignments}
594 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
595 return $DB->record_exists_sql($sql, array('userid'=>$userid));
599 * Does the user have a capability to do something?
601 * Walk the accessdata array and return true/false.
602 * Deals with prohibits, role switching, aggregating
603 * capabilities, etc.
605 * The main feature of here is being FAST and with no
606 * side effects.
608 * Notes:
610 * Switch Role merges with default role
611 * ------------------------------------
612 * If you are a teacher in course X, you have at least
613 * teacher-in-X + defaultloggedinuser-sitewide. So in the
614 * course you'll have techer+defaultloggedinuser.
615 * We try to mimic that in switchrole.
617 * Permission evaluation
618 * ---------------------
619 * Originally there was an extremely complicated way
620 * to determine the user access that dealt with
621 * "locality" or role assignments and role overrides.
622 * Now we simply evaluate access for each role separately
623 * and then verify if user has at least one role with allow
624 * and at the same time no role with prohibit.
626 * @access private
627 * @param string $capability
628 * @param context $context
629 * @param array $accessdata
630 * @return bool
632 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
633 global $CFG;
635 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
636 $path = $context->path;
637 $paths = array($path);
638 while($path = rtrim($path, '0123456789')) {
639 $path = rtrim($path, '/');
640 if ($path === '') {
641 break;
643 $paths[] = $path;
646 $roles = array();
647 $switchedrole = false;
649 // Find out if role switched
650 if (!empty($accessdata['rsw'])) {
651 // From the bottom up...
652 foreach ($paths as $path) {
653 if (isset($accessdata['rsw'][$path])) {
654 // Found a switchrole assignment - check for that role _plus_ the default user role
655 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
656 $switchedrole = true;
657 break;
662 if (!$switchedrole) {
663 // get all users roles in this context and above
664 foreach ($paths as $path) {
665 if (isset($accessdata['ra'][$path])) {
666 foreach ($accessdata['ra'][$path] as $roleid) {
667 $roles[$roleid] = null;
673 // Now find out what access is given to each role, going bottom-->up direction
674 $allowed = false;
675 foreach ($roles as $roleid => $ignored) {
676 foreach ($paths as $path) {
677 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
678 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
679 if ($perm === CAP_PROHIBIT) {
680 // any CAP_PROHIBIT found means no permission for the user
681 return false;
683 if (is_null($roles[$roleid])) {
684 $roles[$roleid] = $perm;
688 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
689 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
692 return $allowed;
696 * A convenience function that tests has_capability, and displays an error if
697 * the user does not have that capability.
699 * NOTE before Moodle 2.0, this function attempted to make an appropriate
700 * require_login call before checking the capability. This is no longer the case.
701 * You must call require_login (or one of its variants) if you want to check the
702 * user is logged in, before you call this function.
704 * @see has_capability()
706 * @param string $capability the name of the capability to check. For example mod/forum:view
707 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
708 * @param int $userid A user id. By default (null) checks the permissions of the current user.
709 * @param bool $doanything If false, ignore effect of admin role assignment
710 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
711 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
712 * @return void terminates with an error if the user does not have the given capability.
714 function require_capability($capability, context $context, $userid = null, $doanything = true,
715 $errormessage = 'nopermissions', $stringfile = '') {
716 if (!has_capability($capability, $context, $userid, $doanything)) {
717 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
722 * Return a nested array showing role assignments
723 * all relevant role capabilities for the user at
724 * site/course_category/course levels
726 * We do _not_ delve deeper than courses because the number of
727 * overrides at the module/block levels can be HUGE.
729 * [ra] => [/path][roleid]=roleid
730 * [rdef] => [/path:roleid][capability]=permission
732 * @access private
733 * @param int $userid - the id of the user
734 * @return array access info array
736 function get_user_access_sitewide($userid) {
737 global $CFG, $DB, $ACCESSLIB_PRIVATE;
739 /* Get in a few cheap DB queries...
740 * - role assignments
741 * - relevant role caps
742 * - above and within this user's RAs
743 * - below this user's RAs - limited to course level
746 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
747 $raparents = array();
748 $accessdata = get_empty_accessdata();
750 // start with the default role
751 if (!empty($CFG->defaultuserroleid)) {
752 $syscontext = context_system::instance();
753 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
754 $raparents[$CFG->defaultuserroleid][$syscontext->id] = $syscontext->id;
757 // load the "default frontpage role"
758 if (!empty($CFG->defaultfrontpageroleid)) {
759 $frontpagecontext = context_course::instance(get_site()->id);
760 if ($frontpagecontext->path) {
761 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
762 $raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->id] = $frontpagecontext->id;
766 // preload every assigned role at and above course context
767 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
768 FROM {role_assignments} ra
769 JOIN {context} ctx
770 ON ctx.id = ra.contextid
771 LEFT JOIN {block_instances} bi
772 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
773 LEFT JOIN {context} bpctx
774 ON (bpctx.id = bi.parentcontextid)
775 WHERE ra.userid = :userid
776 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")";
777 $params = array('userid'=>$userid);
778 $rs = $DB->get_recordset_sql($sql, $params);
779 foreach ($rs as $ra) {
780 // RAs leafs are arrays to support multi-role assignments...
781 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
782 $raparents[$ra->roleid][$ra->contextid] = $ra->contextid;
784 $rs->close();
786 if (empty($raparents)) {
787 return $accessdata;
790 // now get overrides of interesting roles in all interesting child contexts
791 // hopefully we will not run out of SQL limits here,
792 // users would have to have very many roles at/above course context...
793 $sqls = array();
794 $params = array();
796 static $cp = 0;
797 foreach ($raparents as $roleid=>$ras) {
798 $cp++;
799 list($sqlcids, $cids) = $DB->get_in_or_equal($ras, SQL_PARAMS_NAMED, 'c'.$cp.'_');
800 $params = array_merge($params, $cids);
801 $params['r'.$cp] = $roleid;
802 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
803 FROM {role_capabilities} rc
804 JOIN {context} ctx
805 ON (ctx.id = rc.contextid)
806 JOIN {context} pctx
807 ON (pctx.id $sqlcids
808 AND (ctx.id = pctx.id
809 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
810 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
811 LEFT JOIN {block_instances} bi
812 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
813 LEFT JOIN {context} bpctx
814 ON (bpctx.id = bi.parentcontextid)
815 WHERE rc.roleid = :r{$cp}
816 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")
820 // fixed capability order is necessary for rdef dedupe
821 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
823 foreach ($rs as $rd) {
824 $k = $rd->path.':'.$rd->roleid;
825 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
827 $rs->close();
829 // share the role definitions
830 foreach ($accessdata['rdef'] as $k=>$unused) {
831 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
832 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
834 $accessdata['rdef_count']++;
835 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
838 return $accessdata;
842 * Add to the access ctrl array the data needed by a user for a given course.
844 * This function injects all course related access info into the accessdata array.
846 * @access private
847 * @param int $userid the id of the user
848 * @param context_course $coursecontext course context
849 * @param array $accessdata accessdata array (modified)
850 * @return void modifies $accessdata parameter
852 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
853 global $DB, $CFG, $ACCESSLIB_PRIVATE;
855 if (empty($coursecontext->path)) {
856 // weird, this should not happen
857 return;
860 if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
861 // already loaded, great!
862 return;
865 $roles = array();
867 if (empty($userid)) {
868 if (!empty($CFG->notloggedinroleid)) {
869 $roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
872 } else if (isguestuser($userid)) {
873 if ($guestrole = get_guest_role()) {
874 $roles[$guestrole->id] = $guestrole->id;
877 } else {
878 // Interesting role assignments at, above and below the course context
879 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
880 $params['userid'] = $userid;
881 $params['children'] = $coursecontext->path."/%";
882 $sql = "SELECT ra.*, ctx.path
883 FROM {role_assignments} ra
884 JOIN {context} ctx ON ra.contextid = ctx.id
885 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
886 $rs = $DB->get_recordset_sql($sql, $params);
888 // add missing role definitions
889 foreach ($rs as $ra) {
890 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
891 $roles[$ra->roleid] = $ra->roleid;
893 $rs->close();
895 // add the "default frontpage role" when on the frontpage
896 if (!empty($CFG->defaultfrontpageroleid)) {
897 $frontpagecontext = context_course::instance(get_site()->id);
898 if ($frontpagecontext->id == $coursecontext->id) {
899 $roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
903 // do not forget the default role
904 if (!empty($CFG->defaultuserroleid)) {
905 $roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
909 if (!$roles) {
910 // weird, default roles must be missing...
911 $accessdata['loaded'][$coursecontext->instanceid] = 1;
912 return;
915 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
916 $params = array('c'=>$coursecontext->id);
917 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
918 $params = array_merge($params, $rparams);
919 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
920 $params = array_merge($params, $rparams);
922 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
923 FROM {role_capabilities} rc
924 JOIN {context} ctx
925 ON (ctx.id = rc.contextid)
926 JOIN {context} cctx
927 ON (cctx.id = :c
928 AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
929 WHERE rc.roleid $roleids
930 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
931 $rs = $DB->get_recordset_sql($sql, $params);
933 $newrdefs = array();
934 foreach ($rs as $rd) {
935 $k = $rd->path.':'.$rd->roleid;
936 if (isset($accessdata['rdef'][$k])) {
937 continue;
939 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
941 $rs->close();
943 // share new role definitions
944 foreach ($newrdefs as $k=>$unused) {
945 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
946 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
948 $accessdata['rdef_count']++;
949 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
952 $accessdata['loaded'][$coursecontext->instanceid] = 1;
954 // we want to deduplicate the USER->access from time to time, this looks like a good place,
955 // because we have to do it before the end of session
956 dedupe_user_access();
960 * Add to the access ctrl array the data needed by a role for a given context.
962 * The data is added in the rdef key.
963 * This role-centric function is useful for role_switching
964 * and temporary course roles.
966 * @access private
967 * @param int $roleid the id of the user
968 * @param context $context needs path!
969 * @param array $accessdata accessdata array (is modified)
970 * @return array
972 function load_role_access_by_context($roleid, context $context, &$accessdata) {
973 global $DB, $ACCESSLIB_PRIVATE;
975 /* Get the relevant rolecaps into rdef
976 * - relevant role caps
977 * - at ctx and above
978 * - below this ctx
981 if (empty($context->path)) {
982 // weird, this should not happen
983 return;
986 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
987 $params['roleid'] = $roleid;
988 $params['childpath'] = $context->path.'/%';
990 $sql = "SELECT ctx.path, rc.capability, rc.permission
991 FROM {role_capabilities} rc
992 JOIN {context} ctx ON (rc.contextid = ctx.id)
993 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
994 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
995 $rs = $DB->get_recordset_sql($sql, $params);
997 $newrdefs = array();
998 foreach ($rs as $rd) {
999 $k = $rd->path.':'.$roleid;
1000 if (isset($accessdata['rdef'][$k])) {
1001 continue;
1003 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
1005 $rs->close();
1007 // share new role definitions
1008 foreach ($newrdefs as $k=>$unused) {
1009 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
1010 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
1012 $accessdata['rdef_count']++;
1013 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1018 * Returns empty accessdata structure.
1020 * @access private
1021 * @return array empt accessdata
1023 function get_empty_accessdata() {
1024 $accessdata = array(); // named list
1025 $accessdata['ra'] = array();
1026 $accessdata['rdef'] = array();
1027 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
1028 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
1029 $accessdata['loaded'] = array(); // loaded course contexts
1030 $accessdata['time'] = time();
1031 $accessdata['rsw'] = array();
1033 return $accessdata;
1037 * Get accessdata for a given user.
1039 * @access private
1040 * @param int $userid
1041 * @param bool $preloadonly true means do not return access array
1042 * @return array accessdata
1044 function get_user_accessdata($userid, $preloadonly=false) {
1045 global $CFG, $ACCESSLIB_PRIVATE, $USER;
1047 if (!empty($USER->acces['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1048 // share rdef from USER session with rolepermissions cache in order to conserve memory
1049 foreach($USER->acces['rdef'] as $k=>$v) {
1050 $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->acces['rdef'][$k];
1052 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->acces;
1055 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
1056 if (empty($userid)) {
1057 if (!empty($CFG->notloggedinroleid)) {
1058 $accessdata = get_role_access($CFG->notloggedinroleid);
1059 } else {
1060 // weird
1061 return get_empty_accessdata();
1064 } else if (isguestuser($userid)) {
1065 if ($guestrole = get_guest_role()) {
1066 $accessdata = get_role_access($guestrole->id);
1067 } else {
1068 //weird
1069 return get_empty_accessdata();
1072 } else {
1073 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1076 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1079 if ($preloadonly) {
1080 return;
1081 } else {
1082 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1087 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1088 * this function looks for contexts with the same overrides and shares them.
1090 * @access private
1091 * @return void
1093 function dedupe_user_access() {
1094 global $USER;
1096 if (CLI_SCRIPT) {
1097 // no session in CLI --> no compression necessary
1098 return;
1101 if (empty($USER->access['rdef_count'])) {
1102 // weird, this should not happen
1103 return;
1106 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1107 if ($USER->access['rdef_count'] - $USER->access['rdef_lcc'] > 10) {
1108 // do not compress after each change, wait till there is more stuff to be done
1109 return;
1112 $hashmap = array();
1113 foreach ($USER->access['rdef'] as $k=>$def) {
1114 $hash = sha1(serialize($def));
1115 if (isset($hashmap[$hash])) {
1116 $USER->access['rdef'][$k] =& $hashmap[$hash];
1117 } else {
1118 $hashmap[$hash] =& $USER->access['rdef'][$k];
1122 $USER->access['rdef_lcc'] = $USER->access['rdef_count'];
1126 * A convenience function to completely load all the capabilities
1127 * for the current user. It is called from has_capability() and functions change permissions.
1129 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1130 * @see check_enrolment_plugins()
1132 * @access private
1133 * @return void
1135 function load_all_capabilities() {
1136 global $USER;
1138 // roles not installed yet - we are in the middle of installation
1139 if (during_initial_install()) {
1140 return;
1143 if (!isset($USER->id)) {
1144 // this should not happen
1145 $USER->id = 0;
1148 unset($USER->access);
1149 $USER->access = get_user_accessdata($USER->id);
1151 // deduplicate the overrides to minimize session size
1152 dedupe_user_access();
1154 // Clear to force a refresh
1155 unset($USER->mycourses);
1157 // init/reset internal enrol caches - active course enrolments and temp access
1158 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1162 * A convenience function to completely reload all the capabilities
1163 * for the current user when roles have been updated in a relevant
1164 * context -- but PRESERVING switchroles and loginas.
1165 * This function resets all accesslib and context caches.
1167 * That is - completely transparent to the user.
1169 * Note: reloads $USER->access completely.
1171 * @access private
1172 * @return void
1174 function reload_all_capabilities() {
1175 global $USER, $DB, $ACCESSLIB_PRIVATE;
1177 // copy switchroles
1178 $sw = array();
1179 if (!empty($USER->access['rsw'])) {
1180 $sw = $USER->access['rsw'];
1183 accesslib_clear_all_caches(true);
1184 unset($USER->access);
1185 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
1187 load_all_capabilities();
1189 foreach ($sw as $path => $roleid) {
1190 if ($record = $DB->get_record('context', array('path'=>$path))) {
1191 $context = context::instance_by_id($record->id);
1192 role_switch($roleid, $context);
1198 * Adds a temp role to current USER->access array.
1200 * Useful for the "temporary guest" access we grant to logged-in users.
1201 * This is useful for enrol plugins only.
1203 * @since 2.2
1204 * @param context_course $coursecontext
1205 * @param int $roleid
1206 * @return void
1208 function load_temp_course_role(context_course $coursecontext, $roleid) {
1209 global $USER, $SITE;
1211 if (empty($roleid)) {
1212 debugging('invalid role specified in load_temp_course_role()');
1213 return;
1216 if ($coursecontext->instanceid == $SITE->id) {
1217 debugging('Can not use temp roles on the frontpage');
1218 return;
1221 if (!isset($USER->access)) {
1222 load_all_capabilities();
1225 $coursecontext->reload_if_dirty();
1227 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1228 return;
1231 // load course stuff first
1232 load_course_context($USER->id, $coursecontext, $USER->access);
1234 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1236 load_role_access_by_context($roleid, $coursecontext, $USER->access);
1240 * Removes any extra guest roles from current USER->access array.
1241 * This is useful for enrol plugins only.
1243 * @since 2.2
1244 * @param context_course $coursecontext
1245 * @return void
1247 function remove_temp_course_roles(context_course $coursecontext) {
1248 global $DB, $USER, $SITE;
1250 if ($coursecontext->instanceid == $SITE->id) {
1251 debugging('Can not use temp roles on the frontpage');
1252 return;
1255 if (empty($USER->access['ra'][$coursecontext->path])) {
1256 //no roles here, weird
1257 return;
1260 $sql = "SELECT DISTINCT ra.roleid AS id
1261 FROM {role_assignments} ra
1262 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1263 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1265 $USER->access['ra'][$coursecontext->path] = array();
1266 foreach($ras as $r) {
1267 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1272 * Returns array of all role archetypes.
1274 * @return array
1276 function get_role_archetypes() {
1277 return array(
1278 'manager' => 'manager',
1279 'coursecreator' => 'coursecreator',
1280 'editingteacher' => 'editingteacher',
1281 'teacher' => 'teacher',
1282 'student' => 'student',
1283 'guest' => 'guest',
1284 'user' => 'user',
1285 'frontpage' => 'frontpage'
1290 * Assign the defaults found in this capability definition to roles that have
1291 * the corresponding legacy capabilities assigned to them.
1293 * @param string $capability
1294 * @param array $legacyperms an array in the format (example):
1295 * 'guest' => CAP_PREVENT,
1296 * 'student' => CAP_ALLOW,
1297 * 'teacher' => CAP_ALLOW,
1298 * 'editingteacher' => CAP_ALLOW,
1299 * 'coursecreator' => CAP_ALLOW,
1300 * 'manager' => CAP_ALLOW
1301 * @return boolean success or failure.
1303 function assign_legacy_capabilities($capability, $legacyperms) {
1305 $archetypes = get_role_archetypes();
1307 foreach ($legacyperms as $type => $perm) {
1309 $systemcontext = context_system::instance();
1310 if ($type === 'admin') {
1311 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1312 $type = 'manager';
1315 if (!array_key_exists($type, $archetypes)) {
1316 print_error('invalidlegacy', '', '', $type);
1319 if ($roles = get_archetype_roles($type)) {
1320 foreach ($roles as $role) {
1321 // Assign a site level capability.
1322 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1323 return false;
1328 return true;
1332 * Verify capability risks.
1334 * @param stdClass $capability a capability - a row from the capabilities table.
1335 * @return boolean whether this capability is safe - that is, whether people with the
1336 * safeoverrides capability should be allowed to change it.
1338 function is_safe_capability($capability) {
1339 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1343 * Get the local override (if any) for a given capability in a role in a context
1345 * @param int $roleid
1346 * @param int $contextid
1347 * @param string $capability
1348 * @return stdClass local capability override
1350 function get_local_override($roleid, $contextid, $capability) {
1351 global $DB;
1352 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1356 * Returns context instance plus related course and cm instances
1358 * @param int $contextid
1359 * @return array of ($context, $course, $cm)
1361 function get_context_info_array($contextid) {
1362 global $DB;
1364 $context = context::instance_by_id($contextid, MUST_EXIST);
1365 $course = null;
1366 $cm = null;
1368 if ($context->contextlevel == CONTEXT_COURSE) {
1369 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1371 } else if ($context->contextlevel == CONTEXT_MODULE) {
1372 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1373 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1375 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1376 $parent = $context->get_parent_context();
1378 if ($parent->contextlevel == CONTEXT_COURSE) {
1379 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1380 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1381 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1382 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1386 return array($context, $course, $cm);
1390 * Function that creates a role
1392 * @param string $name role name
1393 * @param string $shortname role short name
1394 * @param string $description role description
1395 * @param string $archetype
1396 * @return int id or dml_exception
1398 function create_role($name, $shortname, $description, $archetype = '') {
1399 global $DB;
1401 if (strpos($archetype, 'moodle/legacy:') !== false) {
1402 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1405 // verify role archetype actually exists
1406 $archetypes = get_role_archetypes();
1407 if (empty($archetypes[$archetype])) {
1408 $archetype = '';
1411 // Insert the role record.
1412 $role = new stdClass();
1413 $role->name = $name;
1414 $role->shortname = $shortname;
1415 $role->description = $description;
1416 $role->archetype = $archetype;
1418 //find free sortorder number
1419 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1420 if (empty($role->sortorder)) {
1421 $role->sortorder = 1;
1423 $id = $DB->insert_record('role', $role);
1425 return $id;
1429 * Function that deletes a role and cleanups up after it
1431 * @param int $roleid id of role to delete
1432 * @return bool always true
1434 function delete_role($roleid) {
1435 global $DB;
1437 // first unssign all users
1438 role_unassign_all(array('roleid'=>$roleid));
1440 // cleanup all references to this role, ignore errors
1441 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1442 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1443 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1444 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1445 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1446 $DB->delete_records('role_names', array('roleid'=>$roleid));
1447 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1449 // finally delete the role itself
1450 // get this before the name is gone for logging
1451 $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
1453 $DB->delete_records('role', array('id'=>$roleid));
1455 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
1457 return true;
1461 * Function to write context specific overrides, or default capabilities.
1463 * NOTE: use $context->mark_dirty() after this
1465 * @param string $capability string name
1466 * @param int $permission CAP_ constants
1467 * @param int $roleid role id
1468 * @param int|context $contextid context id
1469 * @param bool $overwrite
1470 * @return bool always true or exception
1472 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1473 global $USER, $DB;
1475 if ($contextid instanceof context) {
1476 $context = $contextid;
1477 } else {
1478 $context = context::instance_by_id($contextid);
1481 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1482 unassign_capability($capability, $roleid, $context->id);
1483 return true;
1486 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1488 if ($existing and !$overwrite) { // We want to keep whatever is there already
1489 return true;
1492 $cap = new stdClass();
1493 $cap->contextid = $context->id;
1494 $cap->roleid = $roleid;
1495 $cap->capability = $capability;
1496 $cap->permission = $permission;
1497 $cap->timemodified = time();
1498 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1500 if ($existing) {
1501 $cap->id = $existing->id;
1502 $DB->update_record('role_capabilities', $cap);
1503 } else {
1504 if ($DB->record_exists('context', array('id'=>$context->id))) {
1505 $DB->insert_record('role_capabilities', $cap);
1508 return true;
1512 * Unassign a capability from a role.
1514 * NOTE: use $context->mark_dirty() after this
1516 * @param string $capability the name of the capability
1517 * @param int $roleid the role id
1518 * @param int|context $contextid null means all contexts
1519 * @return boolean true or exception
1521 function unassign_capability($capability, $roleid, $contextid = null) {
1522 global $DB;
1524 if (!empty($contextid)) {
1525 if ($contextid instanceof context) {
1526 $context = $contextid;
1527 } else {
1528 $context = context::instance_by_id($contextid);
1530 // delete from context rel, if this is the last override in this context
1531 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1532 } else {
1533 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1535 return true;
1539 * Get the roles that have a given capability assigned to it
1541 * This function does not resolve the actual permission of the capability.
1542 * It just checks for permissions and overrides.
1543 * Use get_roles_with_cap_in_context() if resolution is required.
1545 * @param string $capability capability name (string)
1546 * @param string $permission optional, the permission defined for this capability
1547 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1548 * @param stdClass $context null means any
1549 * @return array of role records
1551 function get_roles_with_capability($capability, $permission = null, $context = null) {
1552 global $DB;
1554 if ($context) {
1555 $contexts = $context->get_parent_context_ids(true);
1556 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1557 $contextsql = "AND rc.contextid $insql";
1558 } else {
1559 $params = array();
1560 $contextsql = '';
1563 if ($permission) {
1564 $permissionsql = " AND rc.permission = :permission";
1565 $params['permission'] = $permission;
1566 } else {
1567 $permissionsql = '';
1570 $sql = "SELECT r.*
1571 FROM {role} r
1572 WHERE r.id IN (SELECT rc.roleid
1573 FROM {role_capabilities} rc
1574 WHERE rc.capability = :capname
1575 $contextsql
1576 $permissionsql)";
1577 $params['capname'] = $capability;
1580 return $DB->get_records_sql($sql, $params);
1584 * This function makes a role-assignment (a role for a user in a particular context)
1586 * @param int $roleid the role of the id
1587 * @param int $userid userid
1588 * @param int|context $contextid id of the context
1589 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1590 * @param int $itemid id of enrolment/auth plugin
1591 * @param string $timemodified defaults to current time
1592 * @return int new/existing id of the assignment
1594 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1595 global $USER, $DB;
1597 // first of all detect if somebody is using old style parameters
1598 if ($contextid === 0 or is_numeric($component)) {
1599 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1602 // now validate all parameters
1603 if (empty($roleid)) {
1604 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1607 if (empty($userid)) {
1608 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1611 if ($itemid) {
1612 if (strpos($component, '_') === false) {
1613 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1615 } else {
1616 $itemid = 0;
1617 if ($component !== '' and strpos($component, '_') === false) {
1618 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1622 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1623 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1626 if ($contextid instanceof context) {
1627 $context = $contextid;
1628 } else {
1629 $context = context::instance_by_id($contextid, MUST_EXIST);
1632 if (!$timemodified) {
1633 $timemodified = time();
1636 // Check for existing entry
1637 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1639 if ($ras) {
1640 // role already assigned - this should not happen
1641 if (count($ras) > 1) {
1642 // very weird - remove all duplicates!
1643 $ra = array_shift($ras);
1644 foreach ($ras as $r) {
1645 $DB->delete_records('role_assignments', array('id'=>$r->id));
1647 } else {
1648 $ra = reset($ras);
1651 // actually there is no need to update, reset anything or trigger any event, so just return
1652 return $ra->id;
1655 // Create a new entry
1656 $ra = new stdClass();
1657 $ra->roleid = $roleid;
1658 $ra->contextid = $context->id;
1659 $ra->userid = $userid;
1660 $ra->component = $component;
1661 $ra->itemid = $itemid;
1662 $ra->timemodified = $timemodified;
1663 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1665 $ra->id = $DB->insert_record('role_assignments', $ra);
1667 // mark context as dirty - again expensive, but needed
1668 $context->mark_dirty();
1670 if (!empty($USER->id) && $USER->id == $userid) {
1671 // If the user is the current user, then do full reload of capabilities too.
1672 reload_all_capabilities();
1675 events_trigger('role_assigned', $ra);
1677 return $ra->id;
1681 * Removes one role assignment
1683 * @param int $roleid
1684 * @param int $userid
1685 * @param int|context $contextid
1686 * @param string $component
1687 * @param int $itemid
1688 * @return void
1690 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1691 // first make sure the params make sense
1692 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1693 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1696 if ($itemid) {
1697 if (strpos($component, '_') === false) {
1698 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1700 } else {
1701 $itemid = 0;
1702 if ($component !== '' and strpos($component, '_') === false) {
1703 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1707 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1711 * Removes multiple role assignments, parameters may contain:
1712 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1714 * @param array $params role assignment parameters
1715 * @param bool $subcontexts unassign in subcontexts too
1716 * @param bool $includemanual include manual role assignments too
1717 * @return void
1719 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1720 global $USER, $CFG, $DB;
1722 if (!$params) {
1723 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1726 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1727 foreach ($params as $key=>$value) {
1728 if (!in_array($key, $allowed)) {
1729 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1733 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1734 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1737 if ($includemanual) {
1738 if (!isset($params['component']) or $params['component'] === '') {
1739 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1743 if ($subcontexts) {
1744 if (empty($params['contextid'])) {
1745 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1749 $ras = $DB->get_records('role_assignments', $params);
1750 foreach($ras as $ra) {
1751 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1752 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1753 // this is a bit expensive but necessary
1754 $context->mark_dirty();
1755 // If the user is the current user, then do full reload of capabilities too.
1756 if (!empty($USER->id) && $USER->id == $ra->userid) {
1757 reload_all_capabilities();
1760 events_trigger('role_unassigned', $ra);
1762 unset($ras);
1764 // process subcontexts
1765 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1766 if ($params['contextid'] instanceof context) {
1767 $context = $params['contextid'];
1768 } else {
1769 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1772 if ($context) {
1773 $contexts = $context->get_child_contexts();
1774 $mparams = $params;
1775 foreach($contexts as $context) {
1776 $mparams['contextid'] = $context->id;
1777 $ras = $DB->get_records('role_assignments', $mparams);
1778 foreach($ras as $ra) {
1779 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1780 // this is a bit expensive but necessary
1781 $context->mark_dirty();
1782 // If the user is the current user, then do full reload of capabilities too.
1783 if (!empty($USER->id) && $USER->id == $ra->userid) {
1784 reload_all_capabilities();
1786 events_trigger('role_unassigned', $ra);
1792 // do this once more for all manual role assignments
1793 if ($includemanual) {
1794 $params['component'] = '';
1795 role_unassign_all($params, $subcontexts, false);
1800 * Determines if a user is currently logged in
1802 * @category access
1804 * @return bool
1806 function isloggedin() {
1807 global $USER;
1809 return (!empty($USER->id));
1813 * Determines if a user is logged in as real guest user with username 'guest'.
1815 * @category access
1817 * @param int|object $user mixed user object or id, $USER if not specified
1818 * @return bool true if user is the real guest user, false if not logged in or other user
1820 function isguestuser($user = null) {
1821 global $USER, $DB, $CFG;
1823 // make sure we have the user id cached in config table, because we are going to use it a lot
1824 if (empty($CFG->siteguest)) {
1825 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1826 // guest does not exist yet, weird
1827 return false;
1829 set_config('siteguest', $guestid);
1831 if ($user === null) {
1832 $user = $USER;
1835 if ($user === null) {
1836 // happens when setting the $USER
1837 return false;
1839 } else if (is_numeric($user)) {
1840 return ($CFG->siteguest == $user);
1842 } else if (is_object($user)) {
1843 if (empty($user->id)) {
1844 return false; // not logged in means is not be guest
1845 } else {
1846 return ($CFG->siteguest == $user->id);
1849 } else {
1850 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1855 * Does user have a (temporary or real) guest access to course?
1857 * @category access
1859 * @param context $context
1860 * @param stdClass|int $user
1861 * @return bool
1863 function is_guest(context $context, $user = null) {
1864 global $USER;
1866 // first find the course context
1867 $coursecontext = $context->get_course_context();
1869 // make sure there is a real user specified
1870 if ($user === null) {
1871 $userid = isset($USER->id) ? $USER->id : 0;
1872 } else {
1873 $userid = is_object($user) ? $user->id : $user;
1876 if (isguestuser($userid)) {
1877 // can not inspect or be enrolled
1878 return true;
1881 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1882 // viewing users appear out of nowhere, they are neither guests nor participants
1883 return false;
1886 // consider only real active enrolments here
1887 if (is_enrolled($coursecontext, $user, '', true)) {
1888 return false;
1891 return true;
1895 * Returns true if the user has moodle/course:view capability in the course,
1896 * this is intended for admins, managers (aka small admins), inspectors, etc.
1898 * @category access
1900 * @param context $context
1901 * @param int|stdClass $user if null $USER is used
1902 * @param string $withcapability extra capability name
1903 * @return bool
1905 function is_viewing(context $context, $user = null, $withcapability = '') {
1906 // first find the course context
1907 $coursecontext = $context->get_course_context();
1909 if (isguestuser($user)) {
1910 // can not inspect
1911 return false;
1914 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1915 // admins are allowed to inspect courses
1916 return false;
1919 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1920 // site admins always have the capability, but the enrolment above blocks
1921 return false;
1924 return true;
1928 * Returns true if user is enrolled (is participating) in course
1929 * this is intended for students and teachers.
1931 * Since 2.2 the result for active enrolments and current user are cached.
1933 * @package core_enrol
1934 * @category access
1936 * @param context $context
1937 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1938 * @param string $withcapability extra capability name
1939 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1940 * @return bool
1942 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1943 global $USER, $DB;
1945 // first find the course context
1946 $coursecontext = $context->get_course_context();
1948 // make sure there is a real user specified
1949 if ($user === null) {
1950 $userid = isset($USER->id) ? $USER->id : 0;
1951 } else {
1952 $userid = is_object($user) ? $user->id : $user;
1955 if (empty($userid)) {
1956 // not-logged-in!
1957 return false;
1958 } else if (isguestuser($userid)) {
1959 // guest account can not be enrolled anywhere
1960 return false;
1963 if ($coursecontext->instanceid == SITEID) {
1964 // everybody participates on frontpage
1965 } else {
1966 // try cached info first - the enrolled flag is set only when active enrolment present
1967 if ($USER->id == $userid) {
1968 $coursecontext->reload_if_dirty();
1969 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1970 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
1971 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1972 return false;
1974 return true;
1979 if ($onlyactive) {
1980 // look for active enrolments only
1981 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1983 if ($until === false) {
1984 return false;
1987 if ($USER->id == $userid) {
1988 if ($until == 0) {
1989 $until = ENROL_MAX_TIMESTAMP;
1991 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
1992 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
1993 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
1994 remove_temp_course_roles($coursecontext);
1998 } else {
1999 // any enrolment is good for us here, even outdated, disabled or inactive
2000 $sql = "SELECT 'x'
2001 FROM {user_enrolments} ue
2002 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2003 JOIN {user} u ON u.id = ue.userid
2004 WHERE ue.userid = :userid AND u.deleted = 0";
2005 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2006 if (!$DB->record_exists_sql($sql, $params)) {
2007 return false;
2012 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2013 return false;
2016 return true;
2020 * Returns true if the user is able to access the course.
2022 * This function is in no way, shape, or form a substitute for require_login.
2023 * It should only be used in circumstances where it is not possible to call require_login
2024 * such as the navigation.
2026 * This function checks many of the methods of access to a course such as the view
2027 * capability, enrollments, and guest access. It also makes use of the cache
2028 * generated by require_login for guest access.
2030 * The flags within the $USER object that are used here should NEVER be used outside
2031 * of this function can_access_course and require_login. Doing so WILL break future
2032 * versions.
2034 * @param stdClass $course record
2035 * @param stdClass|int|null $user user record or id, current user if null
2036 * @param string $withcapability Check for this capability as well.
2037 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2038 * @return boolean Returns true if the user is able to access the course
2040 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
2041 global $DB, $USER;
2043 // this function originally accepted $coursecontext parameter
2044 if ($course instanceof context) {
2045 if ($course instanceof context_course) {
2046 debugging('deprecated context parameter, please use $course record');
2047 $coursecontext = $course;
2048 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2049 } else {
2050 debugging('Invalid context parameter, please use $course record');
2051 return false;
2053 } else {
2054 $coursecontext = context_course::instance($course->id);
2057 if (!isset($USER->id)) {
2058 // should never happen
2059 $USER->id = 0;
2060 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
2063 // make sure there is a user specified
2064 if ($user === null) {
2065 $userid = $USER->id;
2066 } else {
2067 $userid = is_object($user) ? $user->id : $user;
2069 unset($user);
2071 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2072 return false;
2075 if ($userid == $USER->id) {
2076 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2077 // the fact that somebody switched role means they can access the course no matter to what role they switched
2078 return true;
2082 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2083 return false;
2086 if (is_viewing($coursecontext, $userid)) {
2087 return true;
2090 if ($userid != $USER->id) {
2091 // for performance reasons we do not verify temporary guest access for other users, sorry...
2092 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2095 // === from here we deal only with $USER ===
2097 $coursecontext->reload_if_dirty();
2099 if (isset($USER->enrol['enrolled'][$course->id])) {
2100 if ($USER->enrol['enrolled'][$course->id] > time()) {
2101 return true;
2104 if (isset($USER->enrol['tempguest'][$course->id])) {
2105 if ($USER->enrol['tempguest'][$course->id] > time()) {
2106 return true;
2110 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2111 return true;
2114 // if not enrolled try to gain temporary guest access
2115 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2116 $enrols = enrol_get_plugins(true);
2117 foreach($instances as $instance) {
2118 if (!isset($enrols[$instance->enrol])) {
2119 continue;
2121 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2122 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2123 if ($until !== false and $until > time()) {
2124 $USER->enrol['tempguest'][$course->id] = $until;
2125 return true;
2128 if (isset($USER->enrol['tempguest'][$course->id])) {
2129 unset($USER->enrol['tempguest'][$course->id]);
2130 remove_temp_course_roles($coursecontext);
2133 return false;
2137 * Returns array with sql code and parameters returning all ids
2138 * of users enrolled into course.
2140 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2142 * @package core_enrol
2143 * @category access
2145 * @param context $context
2146 * @param string $withcapability
2147 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2148 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2149 * @return array list($sql, $params)
2151 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2152 global $DB, $CFG;
2154 // use unique prefix just in case somebody makes some SQL magic with the result
2155 static $i = 0;
2156 $i++;
2157 $prefix = 'eu'.$i.'_';
2159 // first find the course context
2160 $coursecontext = $context->get_course_context();
2162 $isfrontpage = ($coursecontext->instanceid == SITEID);
2164 $joins = array();
2165 $wheres = array();
2166 $params = array();
2168 list($contextids, $contextpaths) = get_context_info_list($context);
2170 // get all relevant capability info for all roles
2171 if ($withcapability) {
2172 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2173 $cparams['cap'] = $withcapability;
2175 $defs = array();
2176 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2177 FROM {role_capabilities} rc
2178 JOIN {context} ctx on rc.contextid = ctx.id
2179 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2180 $rcs = $DB->get_records_sql($sql, $cparams);
2181 foreach ($rcs as $rc) {
2182 $defs[$rc->path][$rc->roleid] = $rc->permission;
2185 $access = array();
2186 if (!empty($defs)) {
2187 foreach ($contextpaths as $path) {
2188 if (empty($defs[$path])) {
2189 continue;
2191 foreach($defs[$path] as $roleid => $perm) {
2192 if ($perm == CAP_PROHIBIT) {
2193 $access[$roleid] = CAP_PROHIBIT;
2194 continue;
2196 if (!isset($access[$roleid])) {
2197 $access[$roleid] = (int)$perm;
2203 unset($defs);
2205 // make lists of roles that are needed and prohibited
2206 $needed = array(); // one of these is enough
2207 $prohibited = array(); // must not have any of these
2208 foreach ($access as $roleid => $perm) {
2209 if ($perm == CAP_PROHIBIT) {
2210 unset($needed[$roleid]);
2211 $prohibited[$roleid] = true;
2212 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2213 $needed[$roleid] = true;
2217 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2218 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2220 $nobody = false;
2222 if ($isfrontpage) {
2223 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2224 $nobody = true;
2225 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2226 // everybody not having prohibit has the capability
2227 $needed = array();
2228 } else if (empty($needed)) {
2229 $nobody = true;
2231 } else {
2232 if (!empty($prohibited[$defaultuserroleid])) {
2233 $nobody = true;
2234 } else if (!empty($needed[$defaultuserroleid])) {
2235 // everybody not having prohibit has the capability
2236 $needed = array();
2237 } else if (empty($needed)) {
2238 $nobody = true;
2242 if ($nobody) {
2243 // nobody can match so return some SQL that does not return any results
2244 $wheres[] = "1 = 2";
2246 } else {
2248 if ($needed) {
2249 $ctxids = implode(',', $contextids);
2250 $roleids = implode(',', array_keys($needed));
2251 $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))";
2254 if ($prohibited) {
2255 $ctxids = implode(',', $contextids);
2256 $roleids = implode(',', array_keys($prohibited));
2257 $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))";
2258 $wheres[] = "{$prefix}ra4.id IS NULL";
2261 if ($groupid) {
2262 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2263 $params["{$prefix}gmid"] = $groupid;
2267 } else {
2268 if ($groupid) {
2269 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2270 $params["{$prefix}gmid"] = $groupid;
2274 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2275 $params["{$prefix}guestid"] = $CFG->siteguest;
2277 if ($isfrontpage) {
2278 // all users are "enrolled" on the frontpage
2279 } else {
2280 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2281 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2282 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2284 if ($onlyactive) {
2285 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2286 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2287 $now = round(time(), -2); // rounding helps caching in DB
2288 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2289 $prefix.'active'=>ENROL_USER_ACTIVE,
2290 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2294 $joins = implode("\n", $joins);
2295 $wheres = "WHERE ".implode(" AND ", $wheres);
2297 $sql = "SELECT DISTINCT {$prefix}u.id
2298 FROM {user} {$prefix}u
2299 $joins
2300 $wheres";
2302 return array($sql, $params);
2306 * Returns list of users enrolled into course.
2308 * @package core_enrol
2309 * @category access
2311 * @param context $context
2312 * @param string $withcapability
2313 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2314 * @param string $userfields requested user record fields
2315 * @param string $orderby
2316 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2317 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2318 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2319 * @return array of user records
2321 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
2322 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
2323 global $DB;
2325 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2326 $sql = "SELECT $userfields
2327 FROM {user} u
2328 JOIN ($esql) je ON je.id = u.id
2329 WHERE u.deleted = 0";
2331 if ($orderby) {
2332 $sql = "$sql ORDER BY $orderby";
2333 } else {
2334 list($sort, $sortparams) = users_order_by_sql('u');
2335 $sql = "$sql ORDER BY $sort";
2336 $params = array_merge($params, $sortparams);
2339 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2343 * Counts list of users enrolled into course (as per above function)
2345 * @package core_enrol
2346 * @category access
2348 * @param context $context
2349 * @param string $withcapability
2350 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2351 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2352 * @return array of user records
2354 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2355 global $DB;
2357 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2358 $sql = "SELECT count(u.id)
2359 FROM {user} u
2360 JOIN ($esql) je ON je.id = u.id
2361 WHERE u.deleted = 0";
2363 return $DB->count_records_sql($sql, $params);
2367 * Loads the capability definitions for the component (from file).
2369 * Loads the capability definitions for the component (from file). If no
2370 * capabilities are defined for the component, we simply return an empty array.
2372 * @access private
2373 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2374 * @return array array of capabilities
2376 function load_capability_def($component) {
2377 $defpath = get_component_directory($component).'/db/access.php';
2379 $capabilities = array();
2380 if (file_exists($defpath)) {
2381 require($defpath);
2382 if (!empty(${$component.'_capabilities'})) {
2383 // BC capability array name
2384 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2385 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2386 $capabilities = ${$component.'_capabilities'};
2390 return $capabilities;
2394 * Gets the capabilities that have been cached in the database for this component.
2396 * @access private
2397 * @param string $component - examples: 'moodle', 'mod_forum'
2398 * @return array array of capabilities
2400 function get_cached_capabilities($component = 'moodle') {
2401 global $DB;
2402 return $DB->get_records('capabilities', array('component'=>$component));
2406 * Returns default capabilities for given role archetype.
2408 * @param string $archetype role archetype
2409 * @return array
2411 function get_default_capabilities($archetype) {
2412 global $DB;
2414 if (!$archetype) {
2415 return array();
2418 $alldefs = array();
2419 $defaults = array();
2420 $components = array();
2421 $allcaps = $DB->get_records('capabilities');
2423 foreach ($allcaps as $cap) {
2424 if (!in_array($cap->component, $components)) {
2425 $components[] = $cap->component;
2426 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2429 foreach($alldefs as $name=>$def) {
2430 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2431 if (isset($def['archetypes'])) {
2432 if (isset($def['archetypes'][$archetype])) {
2433 $defaults[$name] = $def['archetypes'][$archetype];
2435 // 'legacy' is for backward compatibility with 1.9 access.php
2436 } else {
2437 if (isset($def['legacy'][$archetype])) {
2438 $defaults[$name] = $def['legacy'][$archetype];
2443 return $defaults;
2447 * Reset role capabilities to default according to selected role archetype.
2448 * If no archetype selected, removes all capabilities.
2450 * @param int $roleid
2451 * @return void
2453 function reset_role_capabilities($roleid) {
2454 global $DB;
2456 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2457 $defaultcaps = get_default_capabilities($role->archetype);
2459 $systemcontext = context_system::instance();
2461 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2463 foreach($defaultcaps as $cap=>$permission) {
2464 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2469 * Updates the capabilities table with the component capability definitions.
2470 * If no parameters are given, the function updates the core moodle
2471 * capabilities.
2473 * Note that the absence of the db/access.php capabilities definition file
2474 * will cause any stored capabilities for the component to be removed from
2475 * the database.
2477 * @access private
2478 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2479 * @return boolean true if success, exception in case of any problems
2481 function update_capabilities($component = 'moodle') {
2482 global $DB, $OUTPUT;
2484 $storedcaps = array();
2486 $filecaps = load_capability_def($component);
2487 foreach($filecaps as $capname=>$unused) {
2488 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2489 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2493 $cachedcaps = get_cached_capabilities($component);
2494 if ($cachedcaps) {
2495 foreach ($cachedcaps as $cachedcap) {
2496 array_push($storedcaps, $cachedcap->name);
2497 // update risk bitmasks and context levels in existing capabilities if needed
2498 if (array_key_exists($cachedcap->name, $filecaps)) {
2499 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2500 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2502 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2503 $updatecap = new stdClass();
2504 $updatecap->id = $cachedcap->id;
2505 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2506 $DB->update_record('capabilities', $updatecap);
2508 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2509 $updatecap = new stdClass();
2510 $updatecap->id = $cachedcap->id;
2511 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2512 $DB->update_record('capabilities', $updatecap);
2515 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2516 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2518 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2519 $updatecap = new stdClass();
2520 $updatecap->id = $cachedcap->id;
2521 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2522 $DB->update_record('capabilities', $updatecap);
2528 // Are there new capabilities in the file definition?
2529 $newcaps = array();
2531 foreach ($filecaps as $filecap => $def) {
2532 if (!$storedcaps ||
2533 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2534 if (!array_key_exists('riskbitmask', $def)) {
2535 $def['riskbitmask'] = 0; // no risk if not specified
2537 $newcaps[$filecap] = $def;
2540 // Add new capabilities to the stored definition.
2541 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2542 foreach ($newcaps as $capname => $capdef) {
2543 $capability = new stdClass();
2544 $capability->name = $capname;
2545 $capability->captype = $capdef['captype'];
2546 $capability->contextlevel = $capdef['contextlevel'];
2547 $capability->component = $component;
2548 $capability->riskbitmask = $capdef['riskbitmask'];
2550 $DB->insert_record('capabilities', $capability, false);
2552 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2553 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2554 foreach ($rolecapabilities as $rolecapability){
2555 //assign_capability will update rather than insert if capability exists
2556 if (!assign_capability($capname, $rolecapability->permission,
2557 $rolecapability->roleid, $rolecapability->contextid, true)){
2558 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2562 // we ignore archetype key if we have cloned permissions
2563 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2564 assign_legacy_capabilities($capname, $capdef['archetypes']);
2565 // 'legacy' is for backward compatibility with 1.9 access.php
2566 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2567 assign_legacy_capabilities($capname, $capdef['legacy']);
2570 // Are there any capabilities that have been removed from the file
2571 // definition that we need to delete from the stored capabilities and
2572 // role assignments?
2573 capabilities_cleanup($component, $filecaps);
2575 // reset static caches
2576 accesslib_clear_all_caches(false);
2578 return true;
2582 * Deletes cached capabilities that are no longer needed by the component.
2583 * Also unassigns these capabilities from any roles that have them.
2585 * @access private
2586 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2587 * @param array $newcapdef array of the new capability definitions that will be
2588 * compared with the cached capabilities
2589 * @return int number of deprecated capabilities that have been removed
2591 function capabilities_cleanup($component, $newcapdef = null) {
2592 global $DB;
2594 $removedcount = 0;
2596 if ($cachedcaps = get_cached_capabilities($component)) {
2597 foreach ($cachedcaps as $cachedcap) {
2598 if (empty($newcapdef) ||
2599 array_key_exists($cachedcap->name, $newcapdef) === false) {
2601 // Remove from capabilities cache.
2602 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2603 $removedcount++;
2604 // Delete from roles.
2605 if ($roles = get_roles_with_capability($cachedcap->name)) {
2606 foreach($roles as $role) {
2607 if (!unassign_capability($cachedcap->name, $role->id)) {
2608 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2612 } // End if.
2615 return $removedcount;
2619 * Returns an array of all the known types of risk
2620 * The array keys can be used, for example as CSS class names, or in calls to
2621 * print_risk_icon. The values are the corresponding RISK_ constants.
2623 * @return array all the known types of risk.
2625 function get_all_risks() {
2626 return array(
2627 'riskmanagetrust' => RISK_MANAGETRUST,
2628 'riskconfig' => RISK_CONFIG,
2629 'riskxss' => RISK_XSS,
2630 'riskpersonal' => RISK_PERSONAL,
2631 'riskspam' => RISK_SPAM,
2632 'riskdataloss' => RISK_DATALOSS,
2637 * Return a link to moodle docs for a given capability name
2639 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2640 * @return string the human-readable capability name as a link to Moodle Docs.
2642 function get_capability_docs_link($capability) {
2643 $url = get_docs_url('Capabilities/' . $capability->name);
2644 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2648 * This function pulls out all the resolved capabilities (overrides and
2649 * defaults) of a role used in capability overrides in contexts at a given
2650 * context.
2652 * @param int $roleid
2653 * @param context $context
2654 * @param string $cap capability, optional, defaults to ''
2655 * @return array Array of capabilities
2657 function role_context_capabilities($roleid, context $context, $cap = '') {
2658 global $DB;
2660 $contexts = $context->get_parent_context_ids(true);
2661 $contexts = '('.implode(',', $contexts).')';
2663 $params = array($roleid);
2665 if ($cap) {
2666 $search = " AND rc.capability = ? ";
2667 $params[] = $cap;
2668 } else {
2669 $search = '';
2672 $sql = "SELECT rc.*
2673 FROM {role_capabilities} rc, {context} c
2674 WHERE rc.contextid in $contexts
2675 AND rc.roleid = ?
2676 AND rc.contextid = c.id $search
2677 ORDER BY c.contextlevel DESC, rc.capability DESC";
2679 $capabilities = array();
2681 if ($records = $DB->get_records_sql($sql, $params)) {
2682 // We are traversing via reverse order.
2683 foreach ($records as $record) {
2684 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2685 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2686 $capabilities[$record->capability] = $record->permission;
2690 return $capabilities;
2694 * Constructs array with contextids as first parameter and context paths,
2695 * in both cases bottom top including self.
2697 * @access private
2698 * @param context $context
2699 * @return array
2701 function get_context_info_list(context $context) {
2702 $contextids = explode('/', ltrim($context->path, '/'));
2703 $contextpaths = array();
2704 $contextids2 = $contextids;
2705 while ($contextids2) {
2706 $contextpaths[] = '/' . implode('/', $contextids2);
2707 array_pop($contextids2);
2709 return array($contextids, $contextpaths);
2713 * Check if context is the front page context or a context inside it
2715 * Returns true if this context is the front page context, or a context inside it,
2716 * otherwise false.
2718 * @param context $context a context object.
2719 * @return bool
2721 function is_inside_frontpage(context $context) {
2722 $frontpagecontext = context_course::instance(SITEID);
2723 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2727 * Returns capability information (cached)
2729 * @param string $capabilityname
2730 * @return stdClass or null if capability not found
2732 function get_capability_info($capabilityname) {
2733 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2735 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2737 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2738 $ACCESSLIB_PRIVATE->capabilities = array();
2739 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2740 foreach ($caps as $cap) {
2741 $capname = $cap->name;
2742 unset($cap->id);
2743 unset($cap->name);
2744 $cap->riskbitmask = (int)$cap->riskbitmask;
2745 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2749 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2753 * Returns the human-readable, translated version of the capability.
2754 * Basically a big switch statement.
2756 * @param string $capabilityname e.g. mod/choice:readresponses
2757 * @return string
2759 function get_capability_string($capabilityname) {
2761 // Typical capability name is 'plugintype/pluginname:capabilityname'
2762 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2764 if ($type === 'moodle') {
2765 $component = 'core_role';
2766 } else if ($type === 'quizreport') {
2767 //ugly hack!!
2768 $component = 'quiz_'.$name;
2769 } else {
2770 $component = $type.'_'.$name;
2773 $stringname = $name.':'.$capname;
2775 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2776 return get_string($stringname, $component);
2779 $dir = get_component_directory($component);
2780 if (!file_exists($dir)) {
2781 // plugin broken or does not exist, do not bother with printing of debug message
2782 return $capabilityname.' ???';
2785 // something is wrong in plugin, better print debug
2786 return get_string($stringname, $component);
2790 * This gets the mod/block/course/core etc strings.
2792 * @param string $component
2793 * @param int $contextlevel
2794 * @return string|bool String is success, false if failed
2796 function get_component_string($component, $contextlevel) {
2798 if ($component === 'moodle' or $component === 'core') {
2799 switch ($contextlevel) {
2800 // TODO: this should probably use context level names instead
2801 case CONTEXT_SYSTEM: return get_string('coresystem');
2802 case CONTEXT_USER: return get_string('users');
2803 case CONTEXT_COURSECAT: return get_string('categories');
2804 case CONTEXT_COURSE: return get_string('course');
2805 case CONTEXT_MODULE: return get_string('activities');
2806 case CONTEXT_BLOCK: return get_string('block');
2807 default: print_error('unknowncontext');
2811 list($type, $name) = normalize_component($component);
2812 $dir = get_plugin_directory($type, $name);
2813 if (!file_exists($dir)) {
2814 // plugin not installed, bad luck, there is no way to find the name
2815 return $component.' ???';
2818 switch ($type) {
2819 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2820 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2821 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2822 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2823 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2824 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2825 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2826 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2827 case 'mod':
2828 if (get_string_manager()->string_exists('pluginname', $component)) {
2829 return get_string('activity').': '.get_string('pluginname', $component);
2830 } else {
2831 return get_string('activity').': '.get_string('modulename', $component);
2833 default: return get_string('pluginname', $component);
2838 * Gets the list of roles assigned to this context and up (parents)
2839 * from the list of roles that are visible on user profile page
2840 * and participants page.
2842 * @param context $context
2843 * @return array
2845 function get_profile_roles(context $context) {
2846 global $CFG, $DB;
2848 if (empty($CFG->profileroles)) {
2849 return array();
2852 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2853 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2854 $params = array_merge($params, $cparams);
2856 if ($coursecontext = $context->get_course_context(false)) {
2857 $params['coursecontext'] = $coursecontext->id;
2858 } else {
2859 $params['coursecontext'] = 0;
2862 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2863 FROM {role_assignments} ra, {role} r
2864 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2865 WHERE r.id = ra.roleid
2866 AND ra.contextid $contextlist
2867 AND r.id $rallowed
2868 ORDER BY r.sortorder ASC";
2870 return $DB->get_records_sql($sql, $params);
2874 * Gets the list of roles assigned to this context and up (parents)
2876 * @param context $context
2877 * @return array
2879 function get_roles_used_in_context(context $context) {
2880 global $DB;
2882 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2884 if ($coursecontext = $context->get_course_context(false)) {
2885 $params['coursecontext'] = $coursecontext->id;
2886 } else {
2887 $params['coursecontext'] = 0;
2890 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2891 FROM {role_assignments} ra, {role} r
2892 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2893 WHERE r.id = ra.roleid
2894 AND ra.contextid $contextlist
2895 ORDER BY r.sortorder ASC";
2897 return $DB->get_records_sql($sql, $params);
2901 * This function is used to print roles column in user profile page.
2902 * It is using the CFG->profileroles to limit the list to only interesting roles.
2903 * (The permission tab has full details of user role assignments.)
2905 * @param int $userid
2906 * @param int $courseid
2907 * @return string
2909 function get_user_roles_in_course($userid, $courseid) {
2910 global $CFG, $DB;
2912 if (empty($CFG->profileroles)) {
2913 return '';
2916 if ($courseid == SITEID) {
2917 $context = context_system::instance();
2918 } else {
2919 $context = context_course::instance($courseid);
2922 if (empty($CFG->profileroles)) {
2923 return array();
2926 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2927 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2928 $params = array_merge($params, $cparams);
2930 if ($coursecontext = $context->get_course_context(false)) {
2931 $params['coursecontext'] = $coursecontext->id;
2932 } else {
2933 $params['coursecontext'] = 0;
2936 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2937 FROM {role_assignments} ra, {role} r
2938 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2939 WHERE r.id = ra.roleid
2940 AND ra.contextid $contextlist
2941 AND r.id $rallowed
2942 AND ra.userid = :userid
2943 ORDER BY r.sortorder ASC";
2944 $params['userid'] = $userid;
2946 $rolestring = '';
2948 if ($roles = $DB->get_records_sql($sql, $params)) {
2949 $rolenames = role_fix_names($roles, $context, ROLENAME_ALIAS, true); // Substitute aliases
2951 foreach ($rolenames as $roleid => $rolename) {
2952 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
2954 $rolestring = implode(',', $rolenames);
2957 return $rolestring;
2961 * Checks if a user can assign users to a particular role in this context
2963 * @param context $context
2964 * @param int $targetroleid - the id of the role you want to assign users to
2965 * @return boolean
2967 function user_can_assign(context $context, $targetroleid) {
2968 global $DB;
2970 // First check to see if the user is a site administrator.
2971 if (is_siteadmin()) {
2972 return true;
2975 // Check if user has override capability.
2976 // If not return false.
2977 if (!has_capability('moodle/role:assign', $context)) {
2978 return false;
2980 // pull out all active roles of this user from this context(or above)
2981 if ($userroles = get_user_roles($context)) {
2982 foreach ($userroles as $userrole) {
2983 // if any in the role_allow_override table, then it's ok
2984 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2985 return true;
2990 return false;
2994 * Returns all site roles in correct sort order.
2996 * Note: this method does not localise role names or descriptions,
2997 * use role_get_names() if you need role names.
2999 * @param context $context optional context for course role name aliases
3000 * @return array of role records with optional coursealias property
3002 function get_all_roles(context $context = null) {
3003 global $DB;
3005 if (!$context or !$coursecontext = $context->get_course_context(false)) {
3006 $coursecontext = null;
3009 if ($coursecontext) {
3010 $sql = "SELECT r.*, rn.name AS coursealias
3011 FROM {role} r
3012 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3013 ORDER BY r.sortorder ASC";
3014 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
3016 } else {
3017 return $DB->get_records('role', array(), 'sortorder ASC');
3022 * Returns roles of a specified archetype
3024 * @param string $archetype
3025 * @return array of full role records
3027 function get_archetype_roles($archetype) {
3028 global $DB;
3029 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
3033 * Gets all the user roles assigned in this context, or higher contexts
3034 * this is mainly used when checking if a user can assign a role, or overriding a role
3035 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3036 * allow_override tables
3038 * @param context $context
3039 * @param int $userid
3040 * @param bool $checkparentcontexts defaults to true
3041 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
3042 * @return array
3044 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
3045 global $USER, $DB;
3047 if (empty($userid)) {
3048 if (empty($USER->id)) {
3049 return array();
3051 $userid = $USER->id;
3054 if ($checkparentcontexts) {
3055 $contextids = $context->get_parent_context_ids();
3056 } else {
3057 $contextids = array();
3059 $contextids[] = $context->id;
3061 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3063 array_unshift($params, $userid);
3065 $sql = "SELECT ra.*, r.name, r.shortname
3066 FROM {role_assignments} ra, {role} r, {context} c
3067 WHERE ra.userid = ?
3068 AND ra.roleid = r.id
3069 AND ra.contextid = c.id
3070 AND ra.contextid $contextids
3071 ORDER BY $order";
3073 return $DB->get_records_sql($sql ,$params);
3077 * Like get_user_roles, but adds in the authenticated user role, and the front
3078 * page roles, if applicable.
3080 * @param context $context the context.
3081 * @param int $userid optional. Defaults to $USER->id
3082 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3084 function get_user_roles_with_special(context $context, $userid = 0) {
3085 global $CFG, $USER;
3087 if (empty($userid)) {
3088 if (empty($USER->id)) {
3089 return array();
3091 $userid = $USER->id;
3094 $ras = get_user_roles($context, $userid);
3096 // Add front-page role if relevant.
3097 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3098 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3099 is_inside_frontpage($context);
3100 if ($defaultfrontpageroleid && $isfrontpage) {
3101 $frontpagecontext = context_course::instance(SITEID);
3102 $ra = new stdClass();
3103 $ra->userid = $userid;
3104 $ra->contextid = $frontpagecontext->id;
3105 $ra->roleid = $defaultfrontpageroleid;
3106 $ras[] = $ra;
3109 // Add authenticated user role if relevant.
3110 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3111 if ($defaultuserroleid && !isguestuser($userid)) {
3112 $systemcontext = context_system::instance();
3113 $ra = new stdClass();
3114 $ra->userid = $userid;
3115 $ra->contextid = $systemcontext->id;
3116 $ra->roleid = $defaultuserroleid;
3117 $ras[] = $ra;
3120 return $ras;
3124 * Creates a record in the role_allow_override table
3126 * @param int $sroleid source roleid
3127 * @param int $troleid target roleid
3128 * @return void
3130 function allow_override($sroleid, $troleid) {
3131 global $DB;
3133 $record = new stdClass();
3134 $record->roleid = $sroleid;
3135 $record->allowoverride = $troleid;
3136 $DB->insert_record('role_allow_override', $record);
3140 * Creates a record in the role_allow_assign table
3142 * @param int $fromroleid source roleid
3143 * @param int $targetroleid target roleid
3144 * @return void
3146 function allow_assign($fromroleid, $targetroleid) {
3147 global $DB;
3149 $record = new stdClass();
3150 $record->roleid = $fromroleid;
3151 $record->allowassign = $targetroleid;
3152 $DB->insert_record('role_allow_assign', $record);
3156 * Creates a record in the role_allow_switch table
3158 * @param int $fromroleid source roleid
3159 * @param int $targetroleid target roleid
3160 * @return void
3162 function allow_switch($fromroleid, $targetroleid) {
3163 global $DB;
3165 $record = new stdClass();
3166 $record->roleid = $fromroleid;
3167 $record->allowswitch = $targetroleid;
3168 $DB->insert_record('role_allow_switch', $record);
3172 * Gets a list of roles that this user can assign in this context
3174 * @param context $context the context.
3175 * @param int $rolenamedisplay the type of role name to display. One of the
3176 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3177 * @param bool $withusercounts if true, count the number of users with each role.
3178 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3179 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3180 * if $withusercounts is true, returns a list of three arrays,
3181 * $rolenames, $rolecounts, and $nameswithcounts.
3183 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3184 global $USER, $DB;
3186 // make sure there is a real user specified
3187 if ($user === null) {
3188 $userid = isset($USER->id) ? $USER->id : 0;
3189 } else {
3190 $userid = is_object($user) ? $user->id : $user;
3193 if (!has_capability('moodle/role:assign', $context, $userid)) {
3194 if ($withusercounts) {
3195 return array(array(), array(), array());
3196 } else {
3197 return array();
3201 $params = array();
3202 $extrafields = '';
3204 if ($withusercounts) {
3205 $extrafields = ', (SELECT count(u.id)
3206 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3207 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3208 ) AS usercount';
3209 $params['conid'] = $context->id;
3212 if (is_siteadmin($userid)) {
3213 // show all roles allowed in this context to admins
3214 $assignrestriction = "";
3215 } else {
3216 $parents = $context->get_parent_context_ids(true);
3217 $contexts = implode(',' , $parents);
3218 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3219 FROM {role_allow_assign} raa
3220 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3221 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3222 ) ar ON ar.id = r.id";
3223 $params['userid'] = $userid;
3225 $params['contextlevel'] = $context->contextlevel;
3227 if ($coursecontext = $context->get_course_context(false)) {
3228 $params['coursecontext'] = $coursecontext->id;
3229 } else {
3230 $params['coursecontext'] = 0; // no course aliases
3231 $coursecontext = null;
3233 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3234 FROM {role} r
3235 $assignrestriction
3236 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3237 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3238 ORDER BY r.sortorder ASC";
3239 $roles = $DB->get_records_sql($sql, $params);
3241 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3243 if (!$withusercounts) {
3244 return $rolenames;
3247 $rolecounts = array();
3248 $nameswithcounts = array();
3249 foreach ($roles as $role) {
3250 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3251 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3253 return array($rolenames, $rolecounts, $nameswithcounts);
3257 * Gets a list of roles that this user can switch to in a context
3259 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3260 * This function just process the contents of the role_allow_switch table. You also need to
3261 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3263 * @param context $context a context.
3264 * @return array an array $roleid => $rolename.
3266 function get_switchable_roles(context $context) {
3267 global $USER, $DB;
3269 $params = array();
3270 $extrajoins = '';
3271 $extrawhere = '';
3272 if (!is_siteadmin()) {
3273 // Admins are allowed to switch to any role with.
3274 // Others are subject to the additional constraint that the switch-to role must be allowed by
3275 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3276 $parents = $context->get_parent_context_ids(true);
3277 $contexts = implode(',' , $parents);
3279 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3280 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3281 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3282 $params['userid'] = $USER->id;
3285 if ($coursecontext = $context->get_course_context(false)) {
3286 $params['coursecontext'] = $coursecontext->id;
3287 } else {
3288 $params['coursecontext'] = 0; // no course aliases
3289 $coursecontext = null;
3292 $query = "
3293 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3294 FROM (SELECT DISTINCT rc.roleid
3295 FROM {role_capabilities} rc
3296 $extrajoins
3297 $extrawhere) idlist
3298 JOIN {role} r ON r.id = idlist.roleid
3299 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3300 ORDER BY r.sortorder";
3301 $roles = $DB->get_records_sql($query, $params);
3303 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3307 * Gets a list of roles that this user can override in this context.
3309 * @param context $context the context.
3310 * @param int $rolenamedisplay the type of role name to display. One of the
3311 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3312 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3313 * @return array if $withcounts is false, then an array $roleid => $rolename.
3314 * if $withusercounts is true, returns a list of three arrays,
3315 * $rolenames, $rolecounts, and $nameswithcounts.
3317 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3318 global $USER, $DB;
3320 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3321 if ($withcounts) {
3322 return array(array(), array(), array());
3323 } else {
3324 return array();
3328 $parents = $context->get_parent_context_ids(true);
3329 $contexts = implode(',' , $parents);
3331 $params = array();
3332 $extrafields = '';
3334 $params['userid'] = $USER->id;
3335 if ($withcounts) {
3336 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3337 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3338 $params['conid'] = $context->id;
3341 if ($coursecontext = $context->get_course_context(false)) {
3342 $params['coursecontext'] = $coursecontext->id;
3343 } else {
3344 $params['coursecontext'] = 0; // no course aliases
3345 $coursecontext = null;
3348 if (is_siteadmin()) {
3349 // show all roles to admins
3350 $roles = $DB->get_records_sql("
3351 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3352 FROM {role} ro
3353 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3354 ORDER BY ro.sortorder ASC", $params);
3356 } else {
3357 $roles = $DB->get_records_sql("
3358 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3359 FROM {role} ro
3360 JOIN (SELECT DISTINCT r.id
3361 FROM {role} r
3362 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3363 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3364 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3365 ) inline_view ON ro.id = inline_view.id
3366 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3367 ORDER BY ro.sortorder ASC", $params);
3370 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3372 if (!$withcounts) {
3373 return $rolenames;
3376 $rolecounts = array();
3377 $nameswithcounts = array();
3378 foreach ($roles as $role) {
3379 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3380 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3382 return array($rolenames, $rolecounts, $nameswithcounts);
3386 * Create a role menu suitable for default role selection in enrol plugins.
3388 * @package core_enrol
3390 * @param context $context
3391 * @param int $addroleid current or default role - always added to list
3392 * @return array roleid=>localised role name
3394 function get_default_enrol_roles(context $context, $addroleid = null) {
3395 global $DB;
3397 $params = array('contextlevel'=>CONTEXT_COURSE);
3399 if ($coursecontext = $context->get_course_context(false)) {
3400 $params['coursecontext'] = $coursecontext->id;
3401 } else {
3402 $params['coursecontext'] = 0; // no course names
3403 $coursecontext = null;
3406 if ($addroleid) {
3407 $addrole = "OR r.id = :addroleid";
3408 $params['addroleid'] = $addroleid;
3409 } else {
3410 $addrole = "";
3413 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3414 FROM {role} r
3415 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3416 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3417 WHERE rcl.id IS NOT NULL $addrole
3418 ORDER BY sortorder DESC";
3420 $roles = $DB->get_records_sql($sql, $params);
3422 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3426 * Return context levels where this role is assignable.
3428 * @param integer $roleid the id of a role.
3429 * @return array list of the context levels at which this role may be assigned.
3431 function get_role_contextlevels($roleid) {
3432 global $DB;
3433 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3434 'contextlevel', 'id,contextlevel');
3438 * Return roles suitable for assignment at the specified context level.
3440 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3442 * @param integer $contextlevel a contextlevel.
3443 * @return array list of role ids that are assignable at this context level.
3445 function get_roles_for_contextlevels($contextlevel) {
3446 global $DB;
3447 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3448 '', 'id,roleid');
3452 * Returns default context levels where roles can be assigned.
3454 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3455 * from the array returned by get_role_archetypes();
3456 * @return array list of the context levels at which this type of role may be assigned by default.
3458 function get_default_contextlevels($rolearchetype) {
3459 static $defaults = array(
3460 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3461 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3462 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3463 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3464 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3465 'guest' => array(),
3466 'user' => array(),
3467 'frontpage' => array());
3469 if (isset($defaults[$rolearchetype])) {
3470 return $defaults[$rolearchetype];
3471 } else {
3472 return array();
3477 * Set the context levels at which a particular role can be assigned.
3478 * Throws exceptions in case of error.
3480 * @param integer $roleid the id of a role.
3481 * @param array $contextlevels the context levels at which this role should be assignable,
3482 * duplicate levels are removed.
3483 * @return void
3485 function set_role_contextlevels($roleid, array $contextlevels) {
3486 global $DB;
3487 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3488 $rcl = new stdClass();
3489 $rcl->roleid = $roleid;
3490 $contextlevels = array_unique($contextlevels);
3491 foreach ($contextlevels as $level) {
3492 $rcl->contextlevel = $level;
3493 $DB->insert_record('role_context_levels', $rcl, false, true);
3498 * Who has this capability in this context?
3500 * This can be a very expensive call - use sparingly and keep
3501 * the results if you are going to need them again soon.
3503 * Note if $fields is empty this function attempts to get u.*
3504 * which can get rather large - and has a serious perf impact
3505 * on some DBs.
3507 * @param context $context
3508 * @param string|array $capability - capability name(s)
3509 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3510 * @param string $sort - the sort order. Default is lastaccess time.
3511 * @param mixed $limitfrom - number of records to skip (offset)
3512 * @param mixed $limitnum - number of records to fetch
3513 * @param string|array $groups - single group or array of groups - only return
3514 * users who are in one of these group(s).
3515 * @param string|array $exceptions - list of users to exclude, comma separated or array
3516 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3517 * @param bool $view_ignored - use get_enrolled_sql() instead
3518 * @param bool $useviewallgroups if $groups is set the return users who
3519 * have capability both $capability and moodle/site:accessallgroups
3520 * in this context, as well as users who have $capability and who are
3521 * in $groups.
3522 * @return array of user records
3524 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3525 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3526 global $CFG, $DB;
3528 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3529 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3531 $ctxids = trim($context->path, '/');
3532 $ctxids = str_replace('/', ',', $ctxids);
3534 // Context is the frontpage
3535 $iscoursepage = false; // coursepage other than fp
3536 $isfrontpage = false;
3537 if ($context->contextlevel == CONTEXT_COURSE) {
3538 if ($context->instanceid == SITEID) {
3539 $isfrontpage = true;
3540 } else {
3541 $iscoursepage = true;
3544 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3546 $caps = (array)$capability;
3548 // construct list of context paths bottom-->top
3549 list($contextids, $paths) = get_context_info_list($context);
3551 // we need to find out all roles that have these capabilities either in definition or in overrides
3552 $defs = array();
3553 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3554 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3555 $params = array_merge($params, $params2);
3556 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3557 FROM {role_capabilities} rc
3558 JOIN {context} ctx on rc.contextid = ctx.id
3559 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3561 $rcs = $DB->get_records_sql($sql, $params);
3562 foreach ($rcs as $rc) {
3563 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3566 // go through the permissions bottom-->top direction to evaluate the current permission,
3567 // first one wins (prohibit is an exception that always wins)
3568 $access = array();
3569 foreach ($caps as $cap) {
3570 foreach ($paths as $path) {
3571 if (empty($defs[$cap][$path])) {
3572 continue;
3574 foreach($defs[$cap][$path] as $roleid => $perm) {
3575 if ($perm == CAP_PROHIBIT) {
3576 $access[$cap][$roleid] = CAP_PROHIBIT;
3577 continue;
3579 if (!isset($access[$cap][$roleid])) {
3580 $access[$cap][$roleid] = (int)$perm;
3586 // make lists of roles that are needed and prohibited in this context
3587 $needed = array(); // one of these is enough
3588 $prohibited = array(); // must not have any of these
3589 foreach ($caps as $cap) {
3590 if (empty($access[$cap])) {
3591 continue;
3593 foreach ($access[$cap] as $roleid => $perm) {
3594 if ($perm == CAP_PROHIBIT) {
3595 unset($needed[$cap][$roleid]);
3596 $prohibited[$cap][$roleid] = true;
3597 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3598 $needed[$cap][$roleid] = true;
3601 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3602 // easy, nobody has the permission
3603 unset($needed[$cap]);
3604 unset($prohibited[$cap]);
3605 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3606 // everybody is disqualified on the frontpage
3607 unset($needed[$cap]);
3608 unset($prohibited[$cap]);
3610 if (empty($prohibited[$cap])) {
3611 unset($prohibited[$cap]);
3615 if (empty($needed)) {
3616 // there can not be anybody if no roles match this request
3617 return array();
3620 if (empty($prohibited)) {
3621 // we can compact the needed roles
3622 $n = array();
3623 foreach ($needed as $cap) {
3624 foreach ($cap as $roleid=>$unused) {
3625 $n[$roleid] = true;
3628 $needed = array('any'=>$n);
3629 unset($n);
3632 // ***** Set up default fields ******
3633 if (empty($fields)) {
3634 if ($iscoursepage) {
3635 $fields = 'u.*, ul.timeaccess AS lastaccess';
3636 } else {
3637 $fields = 'u.*';
3639 } else {
3640 if (debugging('', DEBUG_DEVELOPER) && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3641 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3645 // Set up default sort
3646 if (empty($sort)) { // default to course lastaccess or just lastaccess
3647 if ($iscoursepage) {
3648 $sort = 'ul.timeaccess';
3649 } else {
3650 $sort = 'u.lastaccess';
3654 // Prepare query clauses
3655 $wherecond = array();
3656 $params = array();
3657 $joins = array();
3659 // User lastaccess JOIN
3660 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3661 // user_lastaccess is not required MDL-13810
3662 } else {
3663 if ($iscoursepage) {
3664 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3665 } else {
3666 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3670 // We never return deleted users or guest account.
3671 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3672 $params['guestid'] = $CFG->siteguest;
3674 // Groups
3675 if ($groups) {
3676 $groups = (array)$groups;
3677 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3678 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3679 $params = array_merge($params, $grpparams);
3681 if ($useviewallgroups) {
3682 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3683 if (!empty($viewallgroupsusers)) {
3684 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3685 } else {
3686 $wherecond[] = "($grouptest)";
3688 } else {
3689 $wherecond[] = "($grouptest)";
3693 // User exceptions
3694 if (!empty($exceptions)) {
3695 $exceptions = (array)$exceptions;
3696 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3697 $params = array_merge($params, $exparams);
3698 $wherecond[] = "u.id $exsql";
3701 // now add the needed and prohibited roles conditions as joins
3702 if (!empty($needed['any'])) {
3703 // simple case - there are no prohibits involved
3704 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3705 // everybody
3706 } else {
3707 $joins[] = "JOIN (SELECT DISTINCT userid
3708 FROM {role_assignments}
3709 WHERE contextid IN ($ctxids)
3710 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3711 ) ra ON ra.userid = u.id";
3713 } else {
3714 $unions = array();
3715 $everybody = false;
3716 foreach ($needed as $cap=>$unused) {
3717 if (empty($prohibited[$cap])) {
3718 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3719 $everybody = true;
3720 break;
3721 } else {
3722 $unions[] = "SELECT userid
3723 FROM {role_assignments}
3724 WHERE contextid IN ($ctxids)
3725 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3727 } else {
3728 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3729 // nobody can have this cap because it is prevented in default roles
3730 continue;
3732 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3733 // everybody except the prohibitted - hiding does not matter
3734 $unions[] = "SELECT id AS userid
3735 FROM {user}
3736 WHERE id NOT IN (SELECT userid
3737 FROM {role_assignments}
3738 WHERE contextid IN ($ctxids)
3739 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3741 } else {
3742 $unions[] = "SELECT userid
3743 FROM {role_assignments}
3744 WHERE contextid IN ($ctxids)
3745 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3746 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3750 if (!$everybody) {
3751 if ($unions) {
3752 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3753 } else {
3754 // only prohibits found - nobody can be matched
3755 $wherecond[] = "1 = 2";
3760 // Collect WHERE conditions and needed joins
3761 $where = implode(' AND ', $wherecond);
3762 if ($where !== '') {
3763 $where = 'WHERE ' . $where;
3765 $joins = implode("\n", $joins);
3767 // Ok, let's get the users!
3768 $sql = "SELECT $fields
3769 FROM {user} u
3770 $joins
3771 $where
3772 ORDER BY $sort";
3774 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3778 * Re-sort a users array based on a sorting policy
3780 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3781 * based on a sorting policy. This is to support the odd practice of
3782 * sorting teachers by 'authority', where authority was "lowest id of the role
3783 * assignment".
3785 * Will execute 1 database query. Only suitable for small numbers of users, as it
3786 * uses an u.id IN() clause.
3788 * Notes about the sorting criteria.
3790 * As a default, we cannot rely on role.sortorder because then
3791 * admins/coursecreators will always win. That is why the sane
3792 * rule "is locality matters most", with sortorder as 2nd
3793 * consideration.
3795 * If you want role.sortorder, use the 'sortorder' policy, and
3796 * name explicitly what roles you want to cover. It's probably
3797 * a good idea to see what roles have the capabilities you want
3798 * (array_diff() them against roiles that have 'can-do-anything'
3799 * to weed out admin-ish roles. Or fetch a list of roles from
3800 * variables like $CFG->coursecontact .
3802 * @param array $users Users array, keyed on userid
3803 * @param context $context
3804 * @param array $roles ids of the roles to include, optional
3805 * @param string $sortpolicy defaults to locality, more about
3806 * @return array sorted copy of the array
3808 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3809 global $DB;
3811 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3812 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3813 if (empty($roles)) {
3814 $roleswhere = '';
3815 } else {
3816 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3819 $sql = "SELECT ra.userid
3820 FROM {role_assignments} ra
3821 JOIN {role} r
3822 ON ra.roleid=r.id
3823 JOIN {context} ctx
3824 ON ra.contextid=ctx.id
3825 WHERE $userswhere
3826 $contextwhere
3827 $roleswhere";
3829 // Default 'locality' policy -- read PHPDoc notes
3830 // about sort policies...
3831 $orderby = 'ORDER BY '
3832 .'ctx.depth DESC, ' /* locality wins */
3833 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3834 .'ra.id'; /* role assignment order tie-breaker */
3835 if ($sortpolicy === 'sortorder') {
3836 $orderby = 'ORDER BY '
3837 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3838 .'ra.id'; /* role assignment order tie-breaker */
3841 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3842 $sortedusers = array();
3843 $seen = array();
3845 foreach ($sortedids as $id) {
3846 // Avoid duplicates
3847 if (isset($seen[$id])) {
3848 continue;
3850 $seen[$id] = true;
3852 // assign
3853 $sortedusers[$id] = $users[$id];
3855 return $sortedusers;
3859 * Gets all the users assigned this role in this context or higher
3861 * @param int $roleid (can also be an array of ints!)
3862 * @param context $context
3863 * @param bool $parent if true, get list of users assigned in higher context too
3864 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3865 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3866 * null => use default sort from users_order_by_sql.
3867 * @param bool $all true means all, false means limit to enrolled users
3868 * @param string $group defaults to ''
3869 * @param mixed $limitfrom defaults to ''
3870 * @param mixed $limitnum defaults to ''
3871 * @param string $extrawheretest defaults to ''
3872 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3873 * @return array
3875 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3876 $sort = null, $all = true, $group = '',
3877 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3878 global $DB;
3880 if (empty($fields)) {
3881 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3882 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3883 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3884 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3885 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3888 $parentcontexts = '';
3889 if ($parent) {
3890 $parentcontexts = substr($context->path, 1); // kill leading slash
3891 $parentcontexts = str_replace('/', ',', $parentcontexts);
3892 if ($parentcontexts !== '') {
3893 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3897 if ($roleid) {
3898 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
3899 $roleselect = "AND ra.roleid $rids";
3900 } else {
3901 $params = array();
3902 $roleselect = '';
3905 if ($coursecontext = $context->get_course_context(false)) {
3906 $params['coursecontext'] = $coursecontext->id;
3907 } else {
3908 $params['coursecontext'] = 0;
3911 if ($group) {
3912 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3913 $groupselect = " AND gm.groupid = :groupid ";
3914 $params['groupid'] = $group;
3915 } else {
3916 $groupjoin = '';
3917 $groupselect = '';
3920 $params['contextid'] = $context->id;
3922 if ($extrawheretest) {
3923 $extrawheretest = ' AND ' . $extrawheretest;
3926 if ($whereorsortparams) {
3927 $params = array_merge($params, $whereorsortparams);
3930 if (!$sort) {
3931 list($sort, $sortparams) = users_order_by_sql('u');
3932 $params = array_merge($params, $sortparams);
3935 if ($all === null) {
3936 // Previously null was used to indicate that parameter was not used.
3937 $all = true;
3939 if (!$all and $coursecontext) {
3940 // Do not use get_enrolled_sql() here for performance reasons.
3941 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
3942 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
3943 $params['ecourseid'] = $coursecontext->instanceid;
3944 } else {
3945 $ejoin = "";
3948 $sql = "SELECT DISTINCT $fields, ra.roleid
3949 FROM {role_assignments} ra
3950 JOIN {user} u ON u.id = ra.userid
3951 JOIN {role} r ON ra.roleid = r.id
3952 $ejoin
3953 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3954 $groupjoin
3955 WHERE (ra.contextid = :contextid $parentcontexts)
3956 $roleselect
3957 $groupselect
3958 $extrawheretest
3959 ORDER BY $sort"; // join now so that we can just use fullname() later
3961 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3965 * Counts all the users assigned this role in this context or higher
3967 * @param int|array $roleid either int or an array of ints
3968 * @param context $context
3969 * @param bool $parent if true, get list of users assigned in higher context too
3970 * @return int Returns the result count
3972 function count_role_users($roleid, context $context, $parent = false) {
3973 global $DB;
3975 if ($parent) {
3976 if ($contexts = $context->get_parent_context_ids()) {
3977 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3978 } else {
3979 $parentcontexts = '';
3981 } else {
3982 $parentcontexts = '';
3985 if ($roleid) {
3986 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3987 $roleselect = "AND r.roleid $rids";
3988 } else {
3989 $params = array();
3990 $roleselect = '';
3993 array_unshift($params, $context->id);
3995 $sql = "SELECT COUNT(u.id)
3996 FROM {role_assignments} r
3997 JOIN {user} u ON u.id = r.userid
3998 WHERE (r.contextid = ? $parentcontexts)
3999 $roleselect
4000 AND u.deleted = 0";
4002 return $DB->count_records_sql($sql, $params);
4006 * This function gets the list of courses that this user has a particular capability in.
4007 * It is still not very efficient.
4009 * @param string $capability Capability in question
4010 * @param int $userid User ID or null for current user
4011 * @param bool $doanything True if 'doanything' is permitted (default)
4012 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4013 * otherwise use a comma-separated list of the fields you require, not including id
4014 * @param string $orderby If set, use a comma-separated list of fields from course
4015 * table with sql modifiers (DESC) if needed
4016 * @return array Array of courses, may have zero entries. Or false if query failed.
4018 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
4019 global $DB;
4021 // Convert fields list and ordering
4022 $fieldlist = '';
4023 if ($fieldsexceptid) {
4024 $fields = explode(',', $fieldsexceptid);
4025 foreach($fields as $field) {
4026 $fieldlist .= ',c.'.$field;
4029 if ($orderby) {
4030 $fields = explode(',', $orderby);
4031 $orderby = '';
4032 foreach($fields as $field) {
4033 if ($orderby) {
4034 $orderby .= ',';
4036 $orderby .= 'c.'.$field;
4038 $orderby = 'ORDER BY '.$orderby;
4041 // Obtain a list of everything relevant about all courses including context.
4042 // Note the result can be used directly as a context (we are going to), the course
4043 // fields are just appended.
4045 $contextpreload = context_helper::get_preload_record_columns_sql('x');
4047 $courses = array();
4048 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
4049 FROM {course} c
4050 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
4051 $orderby");
4052 // Check capability for each course in turn
4053 foreach ($rs as $course) {
4054 context_helper::preload_from_record($course);
4055 $context = context_course::instance($course->id);
4056 if (has_capability($capability, $context, $userid, $doanything)) {
4057 // We've got the capability. Make the record look like a course record
4058 // and store it
4059 $courses[] = $course;
4062 $rs->close();
4063 return empty($courses) ? false : $courses;
4067 * This function finds the roles assigned directly to this context only
4068 * i.e. no roles in parent contexts
4070 * @param context $context
4071 * @return array
4073 function get_roles_on_exact_context(context $context) {
4074 global $DB;
4076 return $DB->get_records_sql("SELECT r.*
4077 FROM {role_assignments} ra, {role} r
4078 WHERE ra.roleid = r.id AND ra.contextid = ?",
4079 array($context->id));
4083 * Switches the current user to another role for the current session and only
4084 * in the given context.
4086 * The caller *must* check
4087 * - that this op is allowed
4088 * - that the requested role can be switched to in this context (use get_switchable_roles)
4089 * - that the requested role is NOT $CFG->defaultuserroleid
4091 * To "unswitch" pass 0 as the roleid.
4093 * This function *will* modify $USER->access - beware
4095 * @param integer $roleid the role to switch to.
4096 * @param context $context the context in which to perform the switch.
4097 * @return bool success or failure.
4099 function role_switch($roleid, context $context) {
4100 global $USER;
4103 // Plan of action
4105 // - Add the ghost RA to $USER->access
4106 // as $USER->access['rsw'][$path] = $roleid
4108 // - Make sure $USER->access['rdef'] has the roledefs
4109 // it needs to honour the switcherole
4111 // Roledefs will get loaded "deep" here - down to the last child
4112 // context. Note that
4114 // - When visiting subcontexts, our selective accessdata loading
4115 // will still work fine - though those ra/rdefs will be ignored
4116 // appropriately while the switch is in place
4118 // - If a switcherole happens at a category with tons of courses
4119 // (that have many overrides for switched-to role), the session
4120 // will get... quite large. Sometimes you just can't win.
4122 // To un-switch just unset($USER->access['rsw'][$path])
4124 // Note: it is not possible to switch to roles that do not have course:view
4126 if (!isset($USER->access)) {
4127 load_all_capabilities();
4131 // Add the switch RA
4132 if ($roleid == 0) {
4133 unset($USER->access['rsw'][$context->path]);
4134 return true;
4137 $USER->access['rsw'][$context->path] = $roleid;
4139 // Load roledefs
4140 load_role_access_by_context($roleid, $context, $USER->access);
4142 return true;
4146 * Checks if the user has switched roles within the given course.
4148 * Note: You can only switch roles within the course, hence it takes a course id
4149 * rather than a context. On that note Petr volunteered to implement this across
4150 * all other contexts, all requests for this should be forwarded to him ;)
4152 * @param int $courseid The id of the course to check
4153 * @return bool True if the user has switched roles within the course.
4155 function is_role_switched($courseid) {
4156 global $USER;
4157 $context = context_course::instance($courseid, MUST_EXIST);
4158 return (!empty($USER->access['rsw'][$context->path]));
4162 * Get any role that has an override on exact context
4164 * @param context $context The context to check
4165 * @return array An array of roles
4167 function get_roles_with_override_on_context(context $context) {
4168 global $DB;
4170 return $DB->get_records_sql("SELECT r.*
4171 FROM {role_capabilities} rc, {role} r
4172 WHERE rc.roleid = r.id AND rc.contextid = ?",
4173 array($context->id));
4177 * Get all capabilities for this role on this context (overrides)
4179 * @param stdClass $role
4180 * @param context $context
4181 * @return array
4183 function get_capabilities_from_role_on_context($role, context $context) {
4184 global $DB;
4186 return $DB->get_records_sql("SELECT *
4187 FROM {role_capabilities}
4188 WHERE contextid = ? AND roleid = ?",
4189 array($context->id, $role->id));
4193 * Find out which roles has assignment on this context
4195 * @param context $context
4196 * @return array
4199 function get_roles_with_assignment_on_context(context $context) {
4200 global $DB;
4202 return $DB->get_records_sql("SELECT r.*
4203 FROM {role_assignments} ra, {role} r
4204 WHERE ra.roleid = r.id AND ra.contextid = ?",
4205 array($context->id));
4209 * Find all user assignment of users for this role, on this context
4211 * @param stdClass $role
4212 * @param context $context
4213 * @return array
4215 function get_users_from_role_on_context($role, context $context) {
4216 global $DB;
4218 return $DB->get_records_sql("SELECT *
4219 FROM {role_assignments}
4220 WHERE contextid = ? AND roleid = ?",
4221 array($context->id, $role->id));
4225 * Simple function returning a boolean true if user has roles
4226 * in context or parent contexts, otherwise false.
4228 * @param int $userid
4229 * @param int $roleid
4230 * @param int $contextid empty means any context
4231 * @return bool
4233 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4234 global $DB;
4236 if ($contextid) {
4237 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4238 return false;
4240 $parents = $context->get_parent_context_ids(true);
4241 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4242 $params['userid'] = $userid;
4243 $params['roleid'] = $roleid;
4245 $sql = "SELECT COUNT(ra.id)
4246 FROM {role_assignments} ra
4247 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4249 $count = $DB->get_field_sql($sql, $params);
4250 return ($count > 0);
4252 } else {
4253 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4258 * Get localised role name or alias if exists and format the text.
4260 * @param stdClass $role role object
4261 * - optional 'coursealias' property should be included for performance reasons if course context used
4262 * - description property is not required here
4263 * @param context|bool $context empty means system context
4264 * @param int $rolenamedisplay type of role name
4265 * @return string localised role name or course role name alias
4267 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4268 global $DB;
4270 if ($rolenamedisplay == ROLENAME_SHORT) {
4271 return $role->shortname;
4274 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4275 $coursecontext = null;
4278 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4279 $role = clone($role); // Do not modify parameters.
4280 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4281 $role->coursealias = $r->name;
4282 } else {
4283 $role->coursealias = null;
4287 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4288 if ($coursecontext) {
4289 return $role->coursealias;
4290 } else {
4291 return null;
4295 if (trim($role->name) !== '') {
4296 // For filtering always use context where was the thing defined - system for roles here.
4297 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4299 } else {
4300 // Empty role->name means we want to see localised role name based on shortname,
4301 // only default roles are supposed to be localised.
4302 switch ($role->shortname) {
4303 case 'manager': $original = get_string('manager', 'role'); break;
4304 case 'coursecreator': $original = get_string('coursecreators'); break;
4305 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4306 case 'teacher': $original = get_string('noneditingteacher'); break;
4307 case 'student': $original = get_string('defaultcoursestudent'); break;
4308 case 'guest': $original = get_string('guest'); break;
4309 case 'user': $original = get_string('authenticateduser'); break;
4310 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4311 // We should not get here, the role UI should require the name for custom roles!
4312 default: $original = $role->shortname; break;
4316 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4317 return $original;
4320 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4321 return "$original ($role->shortname)";
4324 if ($rolenamedisplay == ROLENAME_ALIAS) {
4325 if ($coursecontext and trim($role->coursealias) !== '') {
4326 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4327 } else {
4328 return $original;
4332 if ($rolenamedisplay == ROLENAME_BOTH) {
4333 if ($coursecontext and trim($role->coursealias) !== '') {
4334 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4335 } else {
4336 return $original;
4340 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4344 * Returns localised role description if available.
4345 * If the name is empty it tries to find the default role name using
4346 * hardcoded list of default role names or other methods in the future.
4348 * @param stdClass $role
4349 * @return string localised role name
4351 function role_get_description(stdClass $role) {
4352 if (!html_is_blank($role->description)) {
4353 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4356 switch ($role->shortname) {
4357 case 'manager': return get_string('managerdescription', 'role');
4358 case 'coursecreator': return get_string('coursecreatorsdescription');
4359 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4360 case 'teacher': return get_string('noneditingteacherdescription');
4361 case 'student': return get_string('defaultcoursestudentdescription');
4362 case 'guest': return get_string('guestdescription');
4363 case 'user': return get_string('authenticateduserdescription');
4364 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4365 default: return '';
4370 * Get all the localised role names for a context.
4372 * In new installs default roles have empty names, this function
4373 * add localised role names using current language pack.
4375 * @param context $context the context, null means system context
4376 * @param array of role objects with a ->localname field containing the context-specific role name.
4377 * @param int $rolenamedisplay
4378 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4379 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4381 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4382 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4386 * Prepare list of roles for display, apply aliases and localise default role names.
4388 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4389 * @param context $context the context, null means system context
4390 * @param int $rolenamedisplay
4391 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4392 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4394 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4395 global $DB;
4397 if (empty($roleoptions)) {
4398 return array();
4401 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4402 $coursecontext = null;
4405 // We usually need all role columns...
4406 $first = reset($roleoptions);
4407 if ($returnmenu === null) {
4408 $returnmenu = !is_object($first);
4411 if (!is_object($first) or !property_exists($first, 'shortname')) {
4412 $allroles = get_all_roles($context);
4413 foreach ($roleoptions as $rid => $unused) {
4414 $roleoptions[$rid] = $allroles[$rid];
4418 // Inject coursealias if necessary.
4419 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4420 $first = reset($roleoptions);
4421 if (!property_exists($first, 'coursealias')) {
4422 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4423 foreach ($aliasnames as $alias) {
4424 if (isset($roleoptions[$alias->roleid])) {
4425 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4431 // Add localname property.
4432 foreach ($roleoptions as $rid => $role) {
4433 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4436 if (!$returnmenu) {
4437 return $roleoptions;
4440 $menu = array();
4441 foreach ($roleoptions as $rid => $role) {
4442 $menu[$rid] = $role->localname;
4445 return $menu;
4449 * Aids in detecting if a new line is required when reading a new capability
4451 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4452 * when we read in a new capability.
4453 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4454 * but when we are in grade, all reports/import/export capabilities should be together
4456 * @param string $cap component string a
4457 * @param string $comp component string b
4458 * @param int $contextlevel
4459 * @return bool whether 2 component are in different "sections"
4461 function component_level_changed($cap, $comp, $contextlevel) {
4463 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4464 $compsa = explode('/', $cap->component);
4465 $compsb = explode('/', $comp);
4467 // list of system reports
4468 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4469 return false;
4472 // we are in gradebook, still
4473 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4474 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4475 return false;
4478 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4479 return false;
4483 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4487 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4488 * and return an array of roleids in order.
4490 * @param array $allroles array of roles, as returned by get_all_roles();
4491 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4493 function fix_role_sortorder($allroles) {
4494 global $DB;
4496 $rolesort = array();
4497 $i = 0;
4498 foreach ($allroles as $role) {
4499 $rolesort[$i] = $role->id;
4500 if ($role->sortorder != $i) {
4501 $r = new stdClass();
4502 $r->id = $role->id;
4503 $r->sortorder = $i;
4504 $DB->update_record('role', $r);
4505 $allroles[$role->id]->sortorder = $i;
4507 $i++;
4509 return $rolesort;
4513 * Switch the sort order of two roles (used in admin/roles/manage.php).
4515 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4516 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4517 * @return boolean success or failure
4519 function switch_roles($first, $second) {
4520 global $DB;
4521 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4522 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4523 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4524 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4525 return $result;
4529 * Duplicates all the base definitions of a role
4531 * @param stdClass $sourcerole role to copy from
4532 * @param int $targetrole id of role to copy to
4534 function role_cap_duplicate($sourcerole, $targetrole) {
4535 global $DB;
4537 $systemcontext = context_system::instance();
4538 $caps = $DB->get_records_sql("SELECT *
4539 FROM {role_capabilities}
4540 WHERE roleid = ? AND contextid = ?",
4541 array($sourcerole->id, $systemcontext->id));
4542 // adding capabilities
4543 foreach ($caps as $cap) {
4544 unset($cap->id);
4545 $cap->roleid = $targetrole;
4546 $DB->insert_record('role_capabilities', $cap);
4551 * Returns two lists, this can be used to find out if user has capability.
4552 * Having any needed role and no forbidden role in this context means
4553 * user has this capability in this context.
4554 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4556 * @param stdClass $context
4557 * @param string $capability
4558 * @return array($neededroles, $forbiddenroles)
4560 function get_roles_with_cap_in_context($context, $capability) {
4561 global $DB;
4563 $ctxids = trim($context->path, '/'); // kill leading slash
4564 $ctxids = str_replace('/', ',', $ctxids);
4566 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4567 FROM {role_capabilities} rc
4568 JOIN {context} ctx ON ctx.id = rc.contextid
4569 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4570 ORDER BY rc.roleid ASC, ctx.depth DESC";
4571 $params = array('cap'=>$capability);
4573 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4574 // no cap definitions --> no capability
4575 return array(array(), array());
4578 $forbidden = array();
4579 $needed = array();
4580 foreach($capdefs as $def) {
4581 if (isset($forbidden[$def->roleid])) {
4582 continue;
4584 if ($def->permission == CAP_PROHIBIT) {
4585 $forbidden[$def->roleid] = $def->roleid;
4586 unset($needed[$def->roleid]);
4587 continue;
4589 if (!isset($needed[$def->roleid])) {
4590 if ($def->permission == CAP_ALLOW) {
4591 $needed[$def->roleid] = true;
4592 } else if ($def->permission == CAP_PREVENT) {
4593 $needed[$def->roleid] = false;
4597 unset($capdefs);
4599 // remove all those roles not allowing
4600 foreach($needed as $key=>$value) {
4601 if (!$value) {
4602 unset($needed[$key]);
4603 } else {
4604 $needed[$key] = $key;
4608 return array($needed, $forbidden);
4612 * Returns an array of role IDs that have ALL of the the supplied capabilities
4613 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4615 * @param stdClass $context
4616 * @param array $capabilities An array of capabilities
4617 * @return array of roles with all of the required capabilities
4619 function get_roles_with_caps_in_context($context, $capabilities) {
4620 $neededarr = array();
4621 $forbiddenarr = array();
4622 foreach($capabilities as $caprequired) {
4623 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4626 $rolesthatcanrate = array();
4627 if (!empty($neededarr)) {
4628 foreach ($neededarr as $needed) {
4629 if (empty($rolesthatcanrate)) {
4630 $rolesthatcanrate = $needed;
4631 } else {
4632 //only want roles that have all caps
4633 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4637 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4638 foreach ($forbiddenarr as $forbidden) {
4639 //remove any roles that are forbidden any of the caps
4640 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4643 return $rolesthatcanrate;
4647 * Returns an array of role names that have ALL of the the supplied capabilities
4648 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4650 * @param stdClass $context
4651 * @param array $capabilities An array of capabilities
4652 * @return array of roles with all of the required capabilities
4654 function get_role_names_with_caps_in_context($context, $capabilities) {
4655 global $DB;
4657 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4658 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4660 $roles = array();
4661 foreach ($rolesthatcanrate as $r) {
4662 $roles[$r] = $allroles[$r];
4665 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4669 * This function verifies the prohibit comes from this context
4670 * and there are no more prohibits in parent contexts.
4672 * @param int $roleid
4673 * @param context $context
4674 * @param string $capability name
4675 * @return bool
4677 function prohibit_is_removable($roleid, context $context, $capability) {
4678 global $DB;
4680 $ctxids = trim($context->path, '/'); // kill leading slash
4681 $ctxids = str_replace('/', ',', $ctxids);
4683 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4685 $sql = "SELECT ctx.id
4686 FROM {role_capabilities} rc
4687 JOIN {context} ctx ON ctx.id = rc.contextid
4688 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4689 ORDER BY ctx.depth DESC";
4691 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4692 // no prohibits == nothing to remove
4693 return true;
4696 if (count($prohibits) > 1) {
4697 // more prohibits can not be removed
4698 return false;
4701 return !empty($prohibits[$context->id]);
4705 * More user friendly role permission changing,
4706 * it should produce as few overrides as possible.
4708 * @param int $roleid
4709 * @param stdClass $context
4710 * @param string $capname capability name
4711 * @param int $permission
4712 * @return void
4714 function role_change_permission($roleid, $context, $capname, $permission) {
4715 global $DB;
4717 if ($permission == CAP_INHERIT) {
4718 unassign_capability($capname, $roleid, $context->id);
4719 $context->mark_dirty();
4720 return;
4723 $ctxids = trim($context->path, '/'); // kill leading slash
4724 $ctxids = str_replace('/', ',', $ctxids);
4726 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4728 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4729 FROM {role_capabilities} rc
4730 JOIN {context} ctx ON ctx.id = rc.contextid
4731 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4732 ORDER BY ctx.depth DESC";
4734 if ($existing = $DB->get_records_sql($sql, $params)) {
4735 foreach($existing as $e) {
4736 if ($e->permission == CAP_PROHIBIT) {
4737 // prohibit can not be overridden, no point in changing anything
4738 return;
4741 $lowest = array_shift($existing);
4742 if ($lowest->permission == $permission) {
4743 // permission already set in this context or parent - nothing to do
4744 return;
4746 if ($existing) {
4747 $parent = array_shift($existing);
4748 if ($parent->permission == $permission) {
4749 // permission already set in parent context or parent - just unset in this context
4750 // we do this because we want as few overrides as possible for performance reasons
4751 unassign_capability($capname, $roleid, $context->id);
4752 $context->mark_dirty();
4753 return;
4757 } else {
4758 if ($permission == CAP_PREVENT) {
4759 // nothing means role does not have permission
4760 return;
4764 // assign the needed capability
4765 assign_capability($capname, $permission, $roleid, $context->id, true);
4767 // force cap reloading
4768 $context->mark_dirty();
4773 * Basic moodle context abstraction class.
4775 * Google confirms that no other important framework is using "context" class,
4776 * we could use something else like mcontext or moodle_context, but we need to type
4777 * this very often which would be annoying and it would take too much space...
4779 * This class is derived from stdClass for backwards compatibility with
4780 * odl $context record that was returned from DML $DB->get_record()
4782 * @package core_access
4783 * @category access
4784 * @copyright Petr Skoda {@link http://skodak.org}
4785 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4786 * @since 2.2
4788 * @property-read int $id context id
4789 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4790 * @property-read int $instanceid id of related instance in each context
4791 * @property-read string $path path to context, starts with system context
4792 * @property-read int $depth
4794 abstract class context extends stdClass implements IteratorAggregate {
4797 * The context id
4798 * Can be accessed publicly through $context->id
4799 * @var int
4801 protected $_id;
4804 * The context level
4805 * Can be accessed publicly through $context->contextlevel
4806 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4808 protected $_contextlevel;
4811 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4812 * Can be accessed publicly through $context->instanceid
4813 * @var int
4815 protected $_instanceid;
4818 * The path to the context always starting from the system context
4819 * Can be accessed publicly through $context->path
4820 * @var string
4822 protected $_path;
4825 * The depth of the context in relation to parent contexts
4826 * Can be accessed publicly through $context->depth
4827 * @var int
4829 protected $_depth;
4832 * @var array Context caching info
4834 private static $cache_contextsbyid = array();
4837 * @var array Context caching info
4839 private static $cache_contexts = array();
4842 * Context count
4843 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4844 * @var int
4846 protected static $cache_count = 0;
4849 * @var array Context caching info
4851 protected static $cache_preloaded = array();
4854 * @var context_system The system context once initialised
4856 protected static $systemcontext = null;
4859 * Resets the cache to remove all data.
4860 * @static
4862 protected static function reset_caches() {
4863 self::$cache_contextsbyid = array();
4864 self::$cache_contexts = array();
4865 self::$cache_count = 0;
4866 self::$cache_preloaded = array();
4868 self::$systemcontext = null;
4872 * Adds a context to the cache. If the cache is full, discards a batch of
4873 * older entries.
4875 * @static
4876 * @param context $context New context to add
4877 * @return void
4879 protected static function cache_add(context $context) {
4880 if (isset(self::$cache_contextsbyid[$context->id])) {
4881 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4882 return;
4885 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4886 $i = 0;
4887 foreach(self::$cache_contextsbyid as $ctx) {
4888 $i++;
4889 if ($i <= 100) {
4890 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4891 continue;
4893 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4894 // we remove oldest third of the contexts to make room for more contexts
4895 break;
4897 unset(self::$cache_contextsbyid[$ctx->id]);
4898 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4899 self::$cache_count--;
4903 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4904 self::$cache_contextsbyid[$context->id] = $context;
4905 self::$cache_count++;
4909 * Removes a context from the cache.
4911 * @static
4912 * @param context $context Context object to remove
4913 * @return void
4915 protected static function cache_remove(context $context) {
4916 if (!isset(self::$cache_contextsbyid[$context->id])) {
4917 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4918 return;
4920 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4921 unset(self::$cache_contextsbyid[$context->id]);
4923 self::$cache_count--;
4925 if (self::$cache_count < 0) {
4926 self::$cache_count = 0;
4931 * Gets a context from the cache.
4933 * @static
4934 * @param int $contextlevel Context level
4935 * @param int $instance Instance ID
4936 * @return context|bool Context or false if not in cache
4938 protected static function cache_get($contextlevel, $instance) {
4939 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4940 return self::$cache_contexts[$contextlevel][$instance];
4942 return false;
4946 * Gets a context from the cache based on its id.
4948 * @static
4949 * @param int $id Context ID
4950 * @return context|bool Context or false if not in cache
4952 protected static function cache_get_by_id($id) {
4953 if (isset(self::$cache_contextsbyid[$id])) {
4954 return self::$cache_contextsbyid[$id];
4956 return false;
4960 * Preloads context information from db record and strips the cached info.
4962 * @static
4963 * @param stdClass $rec
4964 * @return void (modifies $rec)
4966 protected static function preload_from_record(stdClass $rec) {
4967 if (empty($rec->ctxid) or empty($rec->ctxlevel) or empty($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
4968 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4969 return;
4972 // note: in PHP5 the objects are passed by reference, no need to return $rec
4973 $record = new stdClass();
4974 $record->id = $rec->ctxid; unset($rec->ctxid);
4975 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
4976 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
4977 $record->path = $rec->ctxpath; unset($rec->ctxpath);
4978 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
4980 return context::create_instance_from_record($record);
4984 // ====== magic methods =======
4987 * Magic setter method, we do not want anybody to modify properties from the outside
4988 * @param string $name
4989 * @param mixed $value
4991 public function __set($name, $value) {
4992 debugging('Can not change context instance properties!');
4996 * Magic method getter, redirects to read only values.
4997 * @param string $name
4998 * @return mixed
5000 public function __get($name) {
5001 switch ($name) {
5002 case 'id': return $this->_id;
5003 case 'contextlevel': return $this->_contextlevel;
5004 case 'instanceid': return $this->_instanceid;
5005 case 'path': return $this->_path;
5006 case 'depth': return $this->_depth;
5008 default:
5009 debugging('Invalid context property accessed! '.$name);
5010 return null;
5015 * Full support for isset on our magic read only properties.
5016 * @param string $name
5017 * @return bool
5019 public function __isset($name) {
5020 switch ($name) {
5021 case 'id': return isset($this->_id);
5022 case 'contextlevel': return isset($this->_contextlevel);
5023 case 'instanceid': return isset($this->_instanceid);
5024 case 'path': return isset($this->_path);
5025 case 'depth': return isset($this->_depth);
5027 default: return false;
5033 * ALl properties are read only, sorry.
5034 * @param string $name
5036 public function __unset($name) {
5037 debugging('Can not unset context instance properties!');
5040 // ====== implementing method from interface IteratorAggregate ======
5043 * Create an iterator because magic vars can't be seen by 'foreach'.
5045 * Now we can convert context object to array using convert_to_array(),
5046 * and feed it properly to json_encode().
5048 public function getIterator() {
5049 $ret = array(
5050 'id' => $this->id,
5051 'contextlevel' => $this->contextlevel,
5052 'instanceid' => $this->instanceid,
5053 'path' => $this->path,
5054 'depth' => $this->depth
5056 return new ArrayIterator($ret);
5059 // ====== general context methods ======
5062 * Constructor is protected so that devs are forced to
5063 * use context_xxx::instance() or context::instance_by_id().
5065 * @param stdClass $record
5067 protected function __construct(stdClass $record) {
5068 $this->_id = $record->id;
5069 $this->_contextlevel = (int)$record->contextlevel;
5070 $this->_instanceid = $record->instanceid;
5071 $this->_path = $record->path;
5072 $this->_depth = $record->depth;
5076 * This function is also used to work around 'protected' keyword problems in context_helper.
5077 * @static
5078 * @param stdClass $record
5079 * @return context instance
5081 protected static function create_instance_from_record(stdClass $record) {
5082 $classname = context_helper::get_class_for_level($record->contextlevel);
5084 if ($context = context::cache_get_by_id($record->id)) {
5085 return $context;
5088 $context = new $classname($record);
5089 context::cache_add($context);
5091 return $context;
5095 * Copy prepared new contexts from temp table to context table,
5096 * we do this in db specific way for perf reasons only.
5097 * @static
5099 protected static function merge_context_temp_table() {
5100 global $DB;
5102 /* MDL-11347:
5103 * - mysql does not allow to use FROM in UPDATE statements
5104 * - using two tables after UPDATE works in mysql, but might give unexpected
5105 * results in pg 8 (depends on configuration)
5106 * - using table alias in UPDATE does not work in pg < 8.2
5108 * Different code for each database - mostly for performance reasons
5111 $dbfamily = $DB->get_dbfamily();
5112 if ($dbfamily == 'mysql') {
5113 $updatesql = "UPDATE {context} ct, {context_temp} temp
5114 SET ct.path = temp.path,
5115 ct.depth = temp.depth
5116 WHERE ct.id = temp.id";
5117 } else if ($dbfamily == 'oracle') {
5118 $updatesql = "UPDATE {context} ct
5119 SET (ct.path, ct.depth) =
5120 (SELECT temp.path, temp.depth
5121 FROM {context_temp} temp
5122 WHERE temp.id=ct.id)
5123 WHERE EXISTS (SELECT 'x'
5124 FROM {context_temp} temp
5125 WHERE temp.id = ct.id)";
5126 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5127 $updatesql = "UPDATE {context}
5128 SET path = temp.path,
5129 depth = temp.depth
5130 FROM {context_temp} temp
5131 WHERE temp.id={context}.id";
5132 } else {
5133 // sqlite and others
5134 $updatesql = "UPDATE {context}
5135 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5136 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5137 WHERE id IN (SELECT id FROM {context_temp})";
5140 $DB->execute($updatesql);
5144 * Get a context instance as an object, from a given context id.
5146 * @static
5147 * @param int $id context id
5148 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5149 * MUST_EXIST means throw exception if no record found
5150 * @return context|bool the context object or false if not found
5152 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5153 global $DB;
5155 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5156 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5157 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5160 if ($id == SYSCONTEXTID) {
5161 return context_system::instance(0, $strictness);
5164 if (is_array($id) or is_object($id) or empty($id)) {
5165 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5168 if ($context = context::cache_get_by_id($id)) {
5169 return $context;
5172 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5173 return context::create_instance_from_record($record);
5176 return false;
5180 * Update context info after moving context in the tree structure.
5182 * @param context $newparent
5183 * @return void
5185 public function update_moved(context $newparent) {
5186 global $DB;
5188 $frompath = $this->_path;
5189 $newpath = $newparent->path . '/' . $this->_id;
5191 $trans = $DB->start_delegated_transaction();
5193 $this->mark_dirty();
5195 $setdepth = '';
5196 if (($newparent->depth +1) != $this->_depth) {
5197 $diff = $newparent->depth - $this->_depth + 1;
5198 $setdepth = ", depth = depth + $diff";
5200 $sql = "UPDATE {context}
5201 SET path = ?
5202 $setdepth
5203 WHERE id = ?";
5204 $params = array($newpath, $this->_id);
5205 $DB->execute($sql, $params);
5207 $this->_path = $newpath;
5208 $this->_depth = $newparent->depth + 1;
5210 $sql = "UPDATE {context}
5211 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5212 $setdepth
5213 WHERE path LIKE ?";
5214 $params = array($newpath, "{$frompath}/%");
5215 $DB->execute($sql, $params);
5217 $this->mark_dirty();
5219 context::reset_caches();
5221 $trans->allow_commit();
5225 * Remove all context path info and optionally rebuild it.
5227 * @param bool $rebuild
5228 * @return void
5230 public function reset_paths($rebuild = true) {
5231 global $DB;
5233 if ($this->_path) {
5234 $this->mark_dirty();
5236 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5237 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5238 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5239 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5240 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5241 $this->_depth = 0;
5242 $this->_path = null;
5245 if ($rebuild) {
5246 context_helper::build_all_paths(false);
5249 context::reset_caches();
5253 * Delete all data linked to content, do not delete the context record itself
5255 public function delete_content() {
5256 global $CFG, $DB;
5258 blocks_delete_all_for_context($this->_id);
5259 filter_delete_all_for_context($this->_id);
5261 require_once($CFG->dirroot . '/comment/lib.php');
5262 comment::delete_comments(array('contextid'=>$this->_id));
5264 require_once($CFG->dirroot.'/rating/lib.php');
5265 $delopt = new stdclass();
5266 $delopt->contextid = $this->_id;
5267 $rm = new rating_manager();
5268 $rm->delete_ratings($delopt);
5270 // delete all files attached to this context
5271 $fs = get_file_storage();
5272 $fs->delete_area_files($this->_id);
5274 // delete all advanced grading data attached to this context
5275 require_once($CFG->dirroot.'/grade/grading/lib.php');
5276 grading_manager::delete_all_for_context($this->_id);
5278 // now delete stuff from role related tables, role_unassign_all
5279 // and unenrol should be called earlier to do proper cleanup
5280 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5281 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5282 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5286 * Delete the context content and the context record itself
5288 public function delete() {
5289 global $DB;
5291 // double check the context still exists
5292 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5293 context::cache_remove($this);
5294 return;
5297 $this->delete_content();
5298 $DB->delete_records('context', array('id'=>$this->_id));
5299 // purge static context cache if entry present
5300 context::cache_remove($this);
5302 // do not mark dirty contexts if parents unknown
5303 if (!is_null($this->_path) and $this->_depth > 0) {
5304 $this->mark_dirty();
5308 // ====== context level related methods ======
5311 * Utility method for context creation
5313 * @static
5314 * @param int $contextlevel
5315 * @param int $instanceid
5316 * @param string $parentpath
5317 * @return stdClass context record
5319 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5320 global $DB;
5322 $record = new stdClass();
5323 $record->contextlevel = $contextlevel;
5324 $record->instanceid = $instanceid;
5325 $record->depth = 0;
5326 $record->path = null; //not known before insert
5328 $record->id = $DB->insert_record('context', $record);
5330 // now add path if known - it can be added later
5331 if (!is_null($parentpath)) {
5332 $record->path = $parentpath.'/'.$record->id;
5333 $record->depth = substr_count($record->path, '/');
5334 $DB->update_record('context', $record);
5337 return $record;
5341 * Returns human readable context identifier.
5343 * @param boolean $withprefix whether to prefix the name of the context with the
5344 * type of context, e.g. User, Course, Forum, etc.
5345 * @param boolean $short whether to use the short name of the thing. Only applies
5346 * to course contexts
5347 * @return string the human readable context name.
5349 public function get_context_name($withprefix = true, $short = false) {
5350 // must be implemented in all context levels
5351 throw new coding_exception('can not get name of abstract context');
5355 * Returns the most relevant URL for this context.
5357 * @return moodle_url
5359 public abstract function get_url();
5362 * Returns array of relevant context capability records.
5364 * @return array
5366 public abstract function get_capabilities();
5369 * Recursive function which, given a context, find all its children context ids.
5371 * For course category contexts it will return immediate children and all subcategory contexts.
5372 * It will NOT recurse into courses or subcategories categories.
5373 * If you want to do that, call it on the returned courses/categories.
5375 * When called for a course context, it will return the modules and blocks
5376 * displayed in the course page and blocks displayed on the module pages.
5378 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5379 * contexts ;-)
5381 * @return array Array of child records
5383 public function get_child_contexts() {
5384 global $DB;
5386 $sql = "SELECT ctx.*
5387 FROM {context} ctx
5388 WHERE ctx.path LIKE ?";
5389 $params = array($this->_path.'/%');
5390 $records = $DB->get_records_sql($sql, $params);
5392 $result = array();
5393 foreach ($records as $record) {
5394 $result[$record->id] = context::create_instance_from_record($record);
5397 return $result;
5401 * Returns parent contexts of this context in reversed order, i.e. parent first,
5402 * then grand parent, etc.
5404 * @param bool $includeself tre means include self too
5405 * @return array of context instances
5407 public function get_parent_contexts($includeself = false) {
5408 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5409 return array();
5412 $result = array();
5413 foreach ($contextids as $contextid) {
5414 $parent = context::instance_by_id($contextid, MUST_EXIST);
5415 $result[$parent->id] = $parent;
5418 return $result;
5422 * Returns parent contexts of this context in reversed order, i.e. parent first,
5423 * then grand parent, etc.
5425 * @param bool $includeself tre means include self too
5426 * @return array of context ids
5428 public function get_parent_context_ids($includeself = false) {
5429 if (empty($this->_path)) {
5430 return array();
5433 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5434 $parentcontexts = explode('/', $parentcontexts);
5435 if (!$includeself) {
5436 array_pop($parentcontexts); // and remove its own id
5439 return array_reverse($parentcontexts);
5443 * Returns parent context
5445 * @return context
5447 public function get_parent_context() {
5448 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5449 return false;
5452 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5453 $parentcontexts = explode('/', $parentcontexts);
5454 array_pop($parentcontexts); // self
5455 $contextid = array_pop($parentcontexts); // immediate parent
5457 return context::instance_by_id($contextid, MUST_EXIST);
5461 * Is this context part of any course? If yes return course context.
5463 * @param bool $strict true means throw exception if not found, false means return false if not found
5464 * @return course_context context of the enclosing course, null if not found or exception
5466 public function get_course_context($strict = true) {
5467 if ($strict) {
5468 throw new coding_exception('Context does not belong to any course.');
5469 } else {
5470 return false;
5475 * Returns sql necessary for purging of stale context instances.
5477 * @static
5478 * @return string cleanup SQL
5480 protected static function get_cleanup_sql() {
5481 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5485 * Rebuild context paths and depths at context level.
5487 * @static
5488 * @param bool $force
5489 * @return void
5491 protected static function build_paths($force) {
5492 throw new coding_exception('build_paths() method must be implemented in all context levels');
5496 * Create missing context instances at given level
5498 * @static
5499 * @return void
5501 protected static function create_level_instances() {
5502 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5506 * Reset all cached permissions and definitions if the necessary.
5507 * @return void
5509 public function reload_if_dirty() {
5510 global $ACCESSLIB_PRIVATE, $USER;
5512 // Load dirty contexts list if needed
5513 if (CLI_SCRIPT) {
5514 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5515 // we do not load dirty flags in CLI and cron
5516 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5518 } else {
5519 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5520 if (!isset($USER->access['time'])) {
5521 // nothing was loaded yet, we do not need to check dirty contexts now
5522 return;
5524 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5525 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5529 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5530 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5531 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5532 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5533 reload_all_capabilities();
5534 break;
5540 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5542 public function mark_dirty() {
5543 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5545 if (during_initial_install()) {
5546 return;
5549 // only if it is a non-empty string
5550 if (is_string($this->_path) && $this->_path !== '') {
5551 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5552 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5553 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5554 } else {
5555 if (CLI_SCRIPT) {
5556 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5557 } else {
5558 if (isset($USER->access['time'])) {
5559 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5560 } else {
5561 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5563 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5572 * Context maintenance and helper methods.
5574 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5575 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5576 * level implementation from the rest of code, the code completion returns what developers need.
5578 * Thank you Tim Hunt for helping me with this nasty trick.
5580 * @package core_access
5581 * @category access
5582 * @copyright Petr Skoda {@link http://skodak.org}
5583 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5584 * @since 2.2
5586 class context_helper extends context {
5589 * @var array An array mapping context levels to classes
5591 private static $alllevels = array(
5592 CONTEXT_SYSTEM => 'context_system',
5593 CONTEXT_USER => 'context_user',
5594 CONTEXT_COURSECAT => 'context_coursecat',
5595 CONTEXT_COURSE => 'context_course',
5596 CONTEXT_MODULE => 'context_module',
5597 CONTEXT_BLOCK => 'context_block',
5601 * Instance does not make sense here, only static use
5603 protected function __construct() {
5607 * Returns a class name of the context level class
5609 * @static
5610 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5611 * @return string class name of the context class
5613 public static function get_class_for_level($contextlevel) {
5614 if (isset(self::$alllevels[$contextlevel])) {
5615 return self::$alllevels[$contextlevel];
5616 } else {
5617 throw new coding_exception('Invalid context level specified');
5622 * Returns a list of all context levels
5624 * @static
5625 * @return array int=>string (level=>level class name)
5627 public static function get_all_levels() {
5628 return self::$alllevels;
5632 * Remove stale contexts that belonged to deleted instances.
5633 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5635 * @static
5636 * @return void
5638 public static function cleanup_instances() {
5639 global $DB;
5640 $sqls = array();
5641 foreach (self::$alllevels as $level=>$classname) {
5642 $sqls[] = $classname::get_cleanup_sql();
5645 $sql = implode(" UNION ", $sqls);
5647 // it is probably better to use transactions, it might be faster too
5648 $transaction = $DB->start_delegated_transaction();
5650 $rs = $DB->get_recordset_sql($sql);
5651 foreach ($rs as $record) {
5652 $context = context::create_instance_from_record($record);
5653 $context->delete();
5655 $rs->close();
5657 $transaction->allow_commit();
5661 * Create all context instances at the given level and above.
5663 * @static
5664 * @param int $contextlevel null means all levels
5665 * @param bool $buildpaths
5666 * @return void
5668 public static function create_instances($contextlevel = null, $buildpaths = true) {
5669 foreach (self::$alllevels as $level=>$classname) {
5670 if ($contextlevel and $level > $contextlevel) {
5671 // skip potential sub-contexts
5672 continue;
5674 $classname::create_level_instances();
5675 if ($buildpaths) {
5676 $classname::build_paths(false);
5682 * Rebuild paths and depths in all context levels.
5684 * @static
5685 * @param bool $force false means add missing only
5686 * @return void
5688 public static function build_all_paths($force = false) {
5689 foreach (self::$alllevels as $classname) {
5690 $classname::build_paths($force);
5693 // reset static course cache - it might have incorrect cached data
5694 accesslib_clear_all_caches(true);
5698 * Resets the cache to remove all data.
5699 * @static
5701 public static function reset_caches() {
5702 context::reset_caches();
5706 * Returns all fields necessary for context preloading from user $rec.
5708 * This helps with performance when dealing with hundreds of contexts.
5710 * @static
5711 * @param string $tablealias context table alias in the query
5712 * @return array (table.column=>alias, ...)
5714 public static function get_preload_record_columns($tablealias) {
5715 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5719 * Returns all fields necessary for context preloading from user $rec.
5721 * This helps with performance when dealing with hundreds of contexts.
5723 * @static
5724 * @param string $tablealias context table alias in the query
5725 * @return string
5727 public static function get_preload_record_columns_sql($tablealias) {
5728 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5732 * Preloads context information from db record and strips the cached info.
5734 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5736 * @static
5737 * @param stdClass $rec
5738 * @return void (modifies $rec)
5740 public static function preload_from_record(stdClass $rec) {
5741 context::preload_from_record($rec);
5745 * Preload all contexts instances from course.
5747 * To be used if you expect multiple queries for course activities...
5749 * @static
5750 * @param int $courseid
5752 public static function preload_course($courseid) {
5753 // Users can call this multiple times without doing any harm
5754 if (isset(context::$cache_preloaded[$courseid])) {
5755 return;
5757 $coursecontext = context_course::instance($courseid);
5758 $coursecontext->get_child_contexts();
5760 context::$cache_preloaded[$courseid] = true;
5764 * Delete context instance
5766 * @static
5767 * @param int $contextlevel
5768 * @param int $instanceid
5769 * @return void
5771 public static function delete_instance($contextlevel, $instanceid) {
5772 global $DB;
5774 // double check the context still exists
5775 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5776 $context = context::create_instance_from_record($record);
5777 $context->delete();
5778 } else {
5779 // we should try to purge the cache anyway
5784 * Returns the name of specified context level
5786 * @static
5787 * @param int $contextlevel
5788 * @return string name of the context level
5790 public static function get_level_name($contextlevel) {
5791 $classname = context_helper::get_class_for_level($contextlevel);
5792 return $classname::get_level_name();
5796 * not used
5798 public function get_url() {
5802 * not used
5804 public function get_capabilities() {
5810 * System context class
5812 * @package core_access
5813 * @category access
5814 * @copyright Petr Skoda {@link http://skodak.org}
5815 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5816 * @since 2.2
5818 class context_system extends context {
5820 * Please use context_system::instance() if you need the instance of context.
5822 * @param stdClass $record
5824 protected function __construct(stdClass $record) {
5825 parent::__construct($record);
5826 if ($record->contextlevel != CONTEXT_SYSTEM) {
5827 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5832 * Returns human readable context level name.
5834 * @static
5835 * @return string the human readable context level name.
5837 public static function get_level_name() {
5838 return get_string('coresystem');
5842 * Returns human readable context identifier.
5844 * @param boolean $withprefix does not apply to system context
5845 * @param boolean $short does not apply to system context
5846 * @return string the human readable context name.
5848 public function get_context_name($withprefix = true, $short = false) {
5849 return self::get_level_name();
5853 * Returns the most relevant URL for this context.
5855 * @return moodle_url
5857 public function get_url() {
5858 return new moodle_url('/');
5862 * Returns array of relevant context capability records.
5864 * @return array
5866 public function get_capabilities() {
5867 global $DB;
5869 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5871 $params = array();
5872 $sql = "SELECT *
5873 FROM {capabilities}";
5875 return $DB->get_records_sql($sql.' '.$sort, $params);
5879 * Create missing context instances at system context
5880 * @static
5882 protected static function create_level_instances() {
5883 // nothing to do here, the system context is created automatically in installer
5884 self::instance(0);
5888 * Returns system context instance.
5890 * @static
5891 * @param int $instanceid
5892 * @param int $strictness
5893 * @param bool $cache
5894 * @return context_system context instance
5896 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
5897 global $DB;
5899 if ($instanceid != 0) {
5900 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5903 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5904 if (!isset(context::$systemcontext)) {
5905 $record = new stdClass();
5906 $record->id = SYSCONTEXTID;
5907 $record->contextlevel = CONTEXT_SYSTEM;
5908 $record->instanceid = 0;
5909 $record->path = '/'.SYSCONTEXTID;
5910 $record->depth = 1;
5911 context::$systemcontext = new context_system($record);
5913 return context::$systemcontext;
5917 try {
5918 // we ignore the strictness completely because system context must except except during install
5919 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5920 } catch (dml_exception $e) {
5921 //table or record does not exist
5922 if (!during_initial_install()) {
5923 // do not mess with system context after install, it simply must exist
5924 throw $e;
5926 $record = null;
5929 if (!$record) {
5930 $record = new stdClass();
5931 $record->contextlevel = CONTEXT_SYSTEM;
5932 $record->instanceid = 0;
5933 $record->depth = 1;
5934 $record->path = null; //not known before insert
5936 try {
5937 if ($DB->count_records('context')) {
5938 // contexts already exist, this is very weird, system must be first!!!
5939 return null;
5941 if (defined('SYSCONTEXTID')) {
5942 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5943 $record->id = SYSCONTEXTID;
5944 $DB->import_record('context', $record);
5945 $DB->get_manager()->reset_sequence('context');
5946 } else {
5947 $record->id = $DB->insert_record('context', $record);
5949 } catch (dml_exception $e) {
5950 // can not create context - table does not exist yet, sorry
5951 return null;
5955 if ($record->instanceid != 0) {
5956 // this is very weird, somebody must be messing with context table
5957 debugging('Invalid system context detected');
5960 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5961 // fix path if necessary, initial install or path reset
5962 $record->depth = 1;
5963 $record->path = '/'.$record->id;
5964 $DB->update_record('context', $record);
5967 if (!defined('SYSCONTEXTID')) {
5968 define('SYSCONTEXTID', $record->id);
5971 context::$systemcontext = new context_system($record);
5972 return context::$systemcontext;
5976 * Returns all site contexts except the system context, DO NOT call on production servers!!
5978 * Contexts are not cached.
5980 * @return array
5982 public function get_child_contexts() {
5983 global $DB;
5985 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
5987 // Just get all the contexts except for CONTEXT_SYSTEM level
5988 // and hope we don't OOM in the process - don't cache
5989 $sql = "SELECT c.*
5990 FROM {context} c
5991 WHERE contextlevel > ".CONTEXT_SYSTEM;
5992 $records = $DB->get_records_sql($sql);
5994 $result = array();
5995 foreach ($records as $record) {
5996 $result[$record->id] = context::create_instance_from_record($record);
5999 return $result;
6003 * Returns sql necessary for purging of stale context instances.
6005 * @static
6006 * @return string cleanup SQL
6008 protected static function get_cleanup_sql() {
6009 $sql = "
6010 SELECT c.*
6011 FROM {context} c
6012 WHERE 1=2
6015 return $sql;
6019 * Rebuild context paths and depths at system context level.
6021 * @static
6022 * @param bool $force
6024 protected static function build_paths($force) {
6025 global $DB;
6027 /* note: ignore $force here, we always do full test of system context */
6029 // exactly one record must exist
6030 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6032 if ($record->instanceid != 0) {
6033 debugging('Invalid system context detected');
6036 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6037 debugging('Invalid SYSCONTEXTID detected');
6040 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6041 // fix path if necessary, initial install or path reset
6042 $record->depth = 1;
6043 $record->path = '/'.$record->id;
6044 $DB->update_record('context', $record);
6051 * User context class
6053 * @package core_access
6054 * @category access
6055 * @copyright Petr Skoda {@link http://skodak.org}
6056 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6057 * @since 2.2
6059 class context_user extends context {
6061 * Please use context_user::instance($userid) if you need the instance of context.
6062 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6064 * @param stdClass $record
6066 protected function __construct(stdClass $record) {
6067 parent::__construct($record);
6068 if ($record->contextlevel != CONTEXT_USER) {
6069 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6074 * Returns human readable context level name.
6076 * @static
6077 * @return string the human readable context level name.
6079 public static function get_level_name() {
6080 return get_string('user');
6084 * Returns human readable context identifier.
6086 * @param boolean $withprefix whether to prefix the name of the context with User
6087 * @param boolean $short does not apply to user context
6088 * @return string the human readable context name.
6090 public function get_context_name($withprefix = true, $short = false) {
6091 global $DB;
6093 $name = '';
6094 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6095 if ($withprefix){
6096 $name = get_string('user').': ';
6098 $name .= fullname($user);
6100 return $name;
6104 * Returns the most relevant URL for this context.
6106 * @return moodle_url
6108 public function get_url() {
6109 global $COURSE;
6111 if ($COURSE->id == SITEID) {
6112 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6113 } else {
6114 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6116 return $url;
6120 * Returns array of relevant context capability records.
6122 * @return array
6124 public function get_capabilities() {
6125 global $DB;
6127 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6129 $extracaps = array('moodle/grade:viewall');
6130 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6131 $sql = "SELECT *
6132 FROM {capabilities}
6133 WHERE contextlevel = ".CONTEXT_USER."
6134 OR name $extra";
6136 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6140 * Returns user context instance.
6142 * @static
6143 * @param int $instanceid
6144 * @param int $strictness
6145 * @return context_user context instance
6147 public static function instance($instanceid, $strictness = MUST_EXIST) {
6148 global $DB;
6150 if ($context = context::cache_get(CONTEXT_USER, $instanceid)) {
6151 return $context;
6154 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_USER, 'instanceid'=>$instanceid))) {
6155 if ($user = $DB->get_record('user', array('id'=>$instanceid, 'deleted'=>0), 'id', $strictness)) {
6156 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6160 if ($record) {
6161 $context = new context_user($record);
6162 context::cache_add($context);
6163 return $context;
6166 return false;
6170 * Create missing context instances at user context level
6171 * @static
6173 protected static function create_level_instances() {
6174 global $DB;
6176 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6177 SELECT ".CONTEXT_USER.", u.id
6178 FROM {user} u
6179 WHERE u.deleted = 0
6180 AND NOT EXISTS (SELECT 'x'
6181 FROM {context} cx
6182 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6183 $DB->execute($sql);
6187 * Returns sql necessary for purging of stale context instances.
6189 * @static
6190 * @return string cleanup SQL
6192 protected static function get_cleanup_sql() {
6193 $sql = "
6194 SELECT c.*
6195 FROM {context} c
6196 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6197 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6200 return $sql;
6204 * Rebuild context paths and depths at user context level.
6206 * @static
6207 * @param bool $force
6209 protected static function build_paths($force) {
6210 global $DB;
6212 // First update normal users.
6213 $path = $DB->sql_concat('?', 'id');
6214 $pathstart = '/' . SYSCONTEXTID . '/';
6215 $params = array($pathstart);
6217 if ($force) {
6218 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6219 $params[] = $pathstart;
6220 } else {
6221 $where = "depth = 0 OR path IS NULL";
6224 $sql = "UPDATE {context}
6225 SET depth = 2,
6226 path = {$path}
6227 WHERE contextlevel = " . CONTEXT_USER . "
6228 AND ($where)";
6229 $DB->execute($sql, $params);
6235 * Course category context class
6237 * @package core_access
6238 * @category access
6239 * @copyright Petr Skoda {@link http://skodak.org}
6240 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6241 * @since 2.2
6243 class context_coursecat extends context {
6245 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6246 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6248 * @param stdClass $record
6250 protected function __construct(stdClass $record) {
6251 parent::__construct($record);
6252 if ($record->contextlevel != CONTEXT_COURSECAT) {
6253 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6258 * Returns human readable context level name.
6260 * @static
6261 * @return string the human readable context level name.
6263 public static function get_level_name() {
6264 return get_string('category');
6268 * Returns human readable context identifier.
6270 * @param boolean $withprefix whether to prefix the name of the context with Category
6271 * @param boolean $short does not apply to course categories
6272 * @return string the human readable context name.
6274 public function get_context_name($withprefix = true, $short = false) {
6275 global $DB;
6277 $name = '';
6278 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6279 if ($withprefix){
6280 $name = get_string('category').': ';
6282 $name .= format_string($category->name, true, array('context' => $this));
6284 return $name;
6288 * Returns the most relevant URL for this context.
6290 * @return moodle_url
6292 public function get_url() {
6293 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6297 * Returns array of relevant context capability records.
6299 * @return array
6301 public function get_capabilities() {
6302 global $DB;
6304 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6306 $params = array();
6307 $sql = "SELECT *
6308 FROM {capabilities}
6309 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6311 return $DB->get_records_sql($sql.' '.$sort, $params);
6315 * Returns course category context instance.
6317 * @static
6318 * @param int $instanceid
6319 * @param int $strictness
6320 * @return context_coursecat context instance
6322 public static function instance($instanceid, $strictness = MUST_EXIST) {
6323 global $DB;
6325 if ($context = context::cache_get(CONTEXT_COURSECAT, $instanceid)) {
6326 return $context;
6329 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSECAT, 'instanceid'=>$instanceid))) {
6330 if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), 'id,parent', $strictness)) {
6331 if ($category->parent) {
6332 $parentcontext = context_coursecat::instance($category->parent);
6333 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6334 } else {
6335 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6340 if ($record) {
6341 $context = new context_coursecat($record);
6342 context::cache_add($context);
6343 return $context;
6346 return false;
6350 * Returns immediate child contexts of category and all subcategories,
6351 * children of subcategories and courses are not returned.
6353 * @return array
6355 public function get_child_contexts() {
6356 global $DB;
6358 $sql = "SELECT ctx.*
6359 FROM {context} ctx
6360 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6361 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6362 $records = $DB->get_records_sql($sql, $params);
6364 $result = array();
6365 foreach ($records as $record) {
6366 $result[$record->id] = context::create_instance_from_record($record);
6369 return $result;
6373 * Create missing context instances at course category context level
6374 * @static
6376 protected static function create_level_instances() {
6377 global $DB;
6379 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6380 SELECT ".CONTEXT_COURSECAT.", cc.id
6381 FROM {course_categories} cc
6382 WHERE NOT EXISTS (SELECT 'x'
6383 FROM {context} cx
6384 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6385 $DB->execute($sql);
6389 * Returns sql necessary for purging of stale context instances.
6391 * @static
6392 * @return string cleanup SQL
6394 protected static function get_cleanup_sql() {
6395 $sql = "
6396 SELECT c.*
6397 FROM {context} c
6398 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6399 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6402 return $sql;
6406 * Rebuild context paths and depths at course category context level.
6408 * @static
6409 * @param bool $force
6411 protected static function build_paths($force) {
6412 global $DB;
6414 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6415 if ($force) {
6416 $ctxemptyclause = $emptyclause = '';
6417 } else {
6418 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6419 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6422 $base = '/'.SYSCONTEXTID;
6424 // Normal top level categories
6425 $sql = "UPDATE {context}
6426 SET depth=2,
6427 path=".$DB->sql_concat("'$base/'", 'id')."
6428 WHERE contextlevel=".CONTEXT_COURSECAT."
6429 AND EXISTS (SELECT 'x'
6430 FROM {course_categories} cc
6431 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6432 $emptyclause";
6433 $DB->execute($sql);
6435 // Deeper categories - one query per depthlevel
6436 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6437 for ($n=2; $n<=$maxdepth; $n++) {
6438 $sql = "INSERT INTO {context_temp} (id, path, depth)
6439 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6440 FROM {context} ctx
6441 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6442 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6443 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6444 $ctxemptyclause";
6445 $trans = $DB->start_delegated_transaction();
6446 $DB->delete_records('context_temp');
6447 $DB->execute($sql);
6448 context::merge_context_temp_table();
6449 $DB->delete_records('context_temp');
6450 $trans->allow_commit();
6459 * Course context class
6461 * @package core_access
6462 * @category access
6463 * @copyright Petr Skoda {@link http://skodak.org}
6464 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6465 * @since 2.2
6467 class context_course extends context {
6469 * Please use context_course::instance($courseid) if you need the instance of context.
6470 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6472 * @param stdClass $record
6474 protected function __construct(stdClass $record) {
6475 parent::__construct($record);
6476 if ($record->contextlevel != CONTEXT_COURSE) {
6477 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6482 * Returns human readable context level name.
6484 * @static
6485 * @return string the human readable context level name.
6487 public static function get_level_name() {
6488 return get_string('course');
6492 * Returns human readable context identifier.
6494 * @param boolean $withprefix whether to prefix the name of the context with Course
6495 * @param boolean $short whether to use the short name of the thing.
6496 * @return string the human readable context name.
6498 public function get_context_name($withprefix = true, $short = false) {
6499 global $DB;
6501 $name = '';
6502 if ($this->_instanceid == SITEID) {
6503 $name = get_string('frontpage', 'admin');
6504 } else {
6505 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6506 if ($withprefix){
6507 $name = get_string('course').': ';
6509 if ($short){
6510 $name .= format_string($course->shortname, true, array('context' => $this));
6511 } else {
6512 $name .= format_string(get_course_display_name_for_list($course));
6516 return $name;
6520 * Returns the most relevant URL for this context.
6522 * @return moodle_url
6524 public function get_url() {
6525 if ($this->_instanceid != SITEID) {
6526 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6529 return new moodle_url('/');
6533 * Returns array of relevant context capability records.
6535 * @return array
6537 public function get_capabilities() {
6538 global $DB;
6540 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6542 $params = array();
6543 $sql = "SELECT *
6544 FROM {capabilities}
6545 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6547 return $DB->get_records_sql($sql.' '.$sort, $params);
6551 * Is this context part of any course? If yes return course context.
6553 * @param bool $strict true means throw exception if not found, false means return false if not found
6554 * @return course_context context of the enclosing course, null if not found or exception
6556 public function get_course_context($strict = true) {
6557 return $this;
6561 * Returns course context instance.
6563 * @static
6564 * @param int $instanceid
6565 * @param int $strictness
6566 * @return context_course context instance
6568 public static function instance($instanceid, $strictness = MUST_EXIST) {
6569 global $DB;
6571 if ($context = context::cache_get(CONTEXT_COURSE, $instanceid)) {
6572 return $context;
6575 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$instanceid))) {
6576 if ($course = $DB->get_record('course', array('id'=>$instanceid), 'id,category', $strictness)) {
6577 if ($course->category) {
6578 $parentcontext = context_coursecat::instance($course->category);
6579 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6580 } else {
6581 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6586 if ($record) {
6587 $context = new context_course($record);
6588 context::cache_add($context);
6589 return $context;
6592 return false;
6596 * Create missing context instances at course context level
6597 * @static
6599 protected static function create_level_instances() {
6600 global $DB;
6602 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6603 SELECT ".CONTEXT_COURSE.", c.id
6604 FROM {course} c
6605 WHERE NOT EXISTS (SELECT 'x'
6606 FROM {context} cx
6607 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6608 $DB->execute($sql);
6612 * Returns sql necessary for purging of stale context instances.
6614 * @static
6615 * @return string cleanup SQL
6617 protected static function get_cleanup_sql() {
6618 $sql = "
6619 SELECT c.*
6620 FROM {context} c
6621 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6622 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6625 return $sql;
6629 * Rebuild context paths and depths at course context level.
6631 * @static
6632 * @param bool $force
6634 protected static function build_paths($force) {
6635 global $DB;
6637 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6638 if ($force) {
6639 $ctxemptyclause = $emptyclause = '';
6640 } else {
6641 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6642 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6645 $base = '/'.SYSCONTEXTID;
6647 // Standard frontpage
6648 $sql = "UPDATE {context}
6649 SET depth = 2,
6650 path = ".$DB->sql_concat("'$base/'", 'id')."
6651 WHERE contextlevel = ".CONTEXT_COURSE."
6652 AND EXISTS (SELECT 'x'
6653 FROM {course} c
6654 WHERE c.id = {context}.instanceid AND c.category = 0)
6655 $emptyclause";
6656 $DB->execute($sql);
6658 // standard courses
6659 $sql = "INSERT INTO {context_temp} (id, path, depth)
6660 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6661 FROM {context} ctx
6662 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6663 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6664 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6665 $ctxemptyclause";
6666 $trans = $DB->start_delegated_transaction();
6667 $DB->delete_records('context_temp');
6668 $DB->execute($sql);
6669 context::merge_context_temp_table();
6670 $DB->delete_records('context_temp');
6671 $trans->allow_commit();
6678 * Course module context class
6680 * @package core_access
6681 * @category access
6682 * @copyright Petr Skoda {@link http://skodak.org}
6683 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6684 * @since 2.2
6686 class context_module extends context {
6688 * Please use context_module::instance($cmid) if you need the instance of context.
6689 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6691 * @param stdClass $record
6693 protected function __construct(stdClass $record) {
6694 parent::__construct($record);
6695 if ($record->contextlevel != CONTEXT_MODULE) {
6696 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6701 * Returns human readable context level name.
6703 * @static
6704 * @return string the human readable context level name.
6706 public static function get_level_name() {
6707 return get_string('activitymodule');
6711 * Returns human readable context identifier.
6713 * @param boolean $withprefix whether to prefix the name of the context with the
6714 * module name, e.g. Forum, Glossary, etc.
6715 * @param boolean $short does not apply to module context
6716 * @return string the human readable context name.
6718 public function get_context_name($withprefix = true, $short = false) {
6719 global $DB;
6721 $name = '';
6722 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6723 FROM {course_modules} cm
6724 JOIN {modules} md ON md.id = cm.module
6725 WHERE cm.id = ?", array($this->_instanceid))) {
6726 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6727 if ($withprefix){
6728 $name = get_string('modulename', $cm->modname).': ';
6730 $name .= format_string($mod->name, true, array('context' => $this));
6733 return $name;
6737 * Returns the most relevant URL for this context.
6739 * @return moodle_url
6741 public function get_url() {
6742 global $DB;
6744 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6745 FROM {course_modules} cm
6746 JOIN {modules} md ON md.id = cm.module
6747 WHERE cm.id = ?", array($this->_instanceid))) {
6748 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6751 return new moodle_url('/');
6755 * Returns array of relevant context capability records.
6757 * @return array
6759 public function get_capabilities() {
6760 global $DB, $CFG;
6762 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6764 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6765 $module = $DB->get_record('modules', array('id'=>$cm->module));
6767 $subcaps = array();
6768 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6769 if (file_exists($subpluginsfile)) {
6770 $subplugins = array(); // should be redefined in the file
6771 include($subpluginsfile);
6772 if (!empty($subplugins)) {
6773 foreach (array_keys($subplugins) as $subplugintype) {
6774 foreach (array_keys(get_plugin_list($subplugintype)) as $subpluginname) {
6775 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6781 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6782 $extracaps = array();
6783 if (file_exists($modfile)) {
6784 include_once($modfile);
6785 $modfunction = $module->name.'_get_extra_capabilities';
6786 if (function_exists($modfunction)) {
6787 $extracaps = $modfunction();
6791 $extracaps = array_merge($subcaps, $extracaps);
6792 $extra = '';
6793 list($extra, $params) = $DB->get_in_or_equal(
6794 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
6795 if (!empty($extra)) {
6796 $extra = "OR name $extra";
6798 $sql = "SELECT *
6799 FROM {capabilities}
6800 WHERE (contextlevel = ".CONTEXT_MODULE."
6801 AND (component = :component OR component = 'moodle'))
6802 $extra";
6803 $params['component'] = "mod_$module->name";
6805 return $DB->get_records_sql($sql.' '.$sort, $params);
6809 * Is this context part of any course? If yes return course context.
6811 * @param bool $strict true means throw exception if not found, false means return false if not found
6812 * @return course_context context of the enclosing course, null if not found or exception
6814 public function get_course_context($strict = true) {
6815 return $this->get_parent_context();
6819 * Returns module context instance.
6821 * @static
6822 * @param int $instanceid
6823 * @param int $strictness
6824 * @return context_module context instance
6826 public static function instance($instanceid, $strictness = MUST_EXIST) {
6827 global $DB;
6829 if ($context = context::cache_get(CONTEXT_MODULE, $instanceid)) {
6830 return $context;
6833 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$instanceid))) {
6834 if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), 'id,course', $strictness)) {
6835 $parentcontext = context_course::instance($cm->course);
6836 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
6840 if ($record) {
6841 $context = new context_module($record);
6842 context::cache_add($context);
6843 return $context;
6846 return false;
6850 * Create missing context instances at module context level
6851 * @static
6853 protected static function create_level_instances() {
6854 global $DB;
6856 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6857 SELECT ".CONTEXT_MODULE.", cm.id
6858 FROM {course_modules} cm
6859 WHERE NOT EXISTS (SELECT 'x'
6860 FROM {context} cx
6861 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
6862 $DB->execute($sql);
6866 * Returns sql necessary for purging of stale context instances.
6868 * @static
6869 * @return string cleanup SQL
6871 protected static function get_cleanup_sql() {
6872 $sql = "
6873 SELECT c.*
6874 FROM {context} c
6875 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6876 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
6879 return $sql;
6883 * Rebuild context paths and depths at module context level.
6885 * @static
6886 * @param bool $force
6888 protected static function build_paths($force) {
6889 global $DB;
6891 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
6892 if ($force) {
6893 $ctxemptyclause = '';
6894 } else {
6895 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6898 $sql = "INSERT INTO {context_temp} (id, path, depth)
6899 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6900 FROM {context} ctx
6901 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
6902 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
6903 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6904 $ctxemptyclause";
6905 $trans = $DB->start_delegated_transaction();
6906 $DB->delete_records('context_temp');
6907 $DB->execute($sql);
6908 context::merge_context_temp_table();
6909 $DB->delete_records('context_temp');
6910 $trans->allow_commit();
6917 * Block context class
6919 * @package core_access
6920 * @category access
6921 * @copyright Petr Skoda {@link http://skodak.org}
6922 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6923 * @since 2.2
6925 class context_block extends context {
6927 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6928 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6930 * @param stdClass $record
6932 protected function __construct(stdClass $record) {
6933 parent::__construct($record);
6934 if ($record->contextlevel != CONTEXT_BLOCK) {
6935 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6940 * Returns human readable context level name.
6942 * @static
6943 * @return string the human readable context level name.
6945 public static function get_level_name() {
6946 return get_string('block');
6950 * Returns human readable context identifier.
6952 * @param boolean $withprefix whether to prefix the name of the context with Block
6953 * @param boolean $short does not apply to block context
6954 * @return string the human readable context name.
6956 public function get_context_name($withprefix = true, $short = false) {
6957 global $DB, $CFG;
6959 $name = '';
6960 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
6961 global $CFG;
6962 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
6963 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
6964 $blockname = "block_$blockinstance->blockname";
6965 if ($blockobject = new $blockname()) {
6966 if ($withprefix){
6967 $name = get_string('block').': ';
6969 $name .= $blockobject->title;
6973 return $name;
6977 * Returns the most relevant URL for this context.
6979 * @return moodle_url
6981 public function get_url() {
6982 $parentcontexts = $this->get_parent_context();
6983 return $parentcontexts->get_url();
6987 * Returns array of relevant context capability records.
6989 * @return array
6991 public function get_capabilities() {
6992 global $DB;
6994 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6996 $params = array();
6997 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
6999 $extra = '';
7000 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7001 if ($extracaps) {
7002 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7003 $extra = "OR name $extra";
7006 $sql = "SELECT *
7007 FROM {capabilities}
7008 WHERE (contextlevel = ".CONTEXT_BLOCK."
7009 AND component = :component)
7010 $extra";
7011 $params['component'] = 'block_' . $bi->blockname;
7013 return $DB->get_records_sql($sql.' '.$sort, $params);
7017 * Is this context part of any course? If yes return course context.
7019 * @param bool $strict true means throw exception if not found, false means return false if not found
7020 * @return course_context context of the enclosing course, null if not found or exception
7022 public function get_course_context($strict = true) {
7023 $parentcontext = $this->get_parent_context();
7024 return $parentcontext->get_course_context($strict);
7028 * Returns block context instance.
7030 * @static
7031 * @param int $instanceid
7032 * @param int $strictness
7033 * @return context_block context instance
7035 public static function instance($instanceid, $strictness = MUST_EXIST) {
7036 global $DB;
7038 if ($context = context::cache_get(CONTEXT_BLOCK, $instanceid)) {
7039 return $context;
7042 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$instanceid))) {
7043 if ($bi = $DB->get_record('block_instances', array('id'=>$instanceid), 'id,parentcontextid', $strictness)) {
7044 $parentcontext = context::instance_by_id($bi->parentcontextid);
7045 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7049 if ($record) {
7050 $context = new context_block($record);
7051 context::cache_add($context);
7052 return $context;
7055 return false;
7059 * Block do not have child contexts...
7060 * @return array
7062 public function get_child_contexts() {
7063 return array();
7067 * Create missing context instances at block context level
7068 * @static
7070 protected static function create_level_instances() {
7071 global $DB;
7073 $sql = "INSERT INTO {context} (contextlevel, instanceid)
7074 SELECT ".CONTEXT_BLOCK.", bi.id
7075 FROM {block_instances} bi
7076 WHERE NOT EXISTS (SELECT 'x'
7077 FROM {context} cx
7078 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7079 $DB->execute($sql);
7083 * Returns sql necessary for purging of stale context instances.
7085 * @static
7086 * @return string cleanup SQL
7088 protected static function get_cleanup_sql() {
7089 $sql = "
7090 SELECT c.*
7091 FROM {context} c
7092 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7093 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7096 return $sql;
7100 * Rebuild context paths and depths at block context level.
7102 * @static
7103 * @param bool $force
7105 protected static function build_paths($force) {
7106 global $DB;
7108 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7109 if ($force) {
7110 $ctxemptyclause = '';
7111 } else {
7112 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7115 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7116 $sql = "INSERT INTO {context_temp} (id, path, depth)
7117 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7118 FROM {context} ctx
7119 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7120 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7121 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7122 $ctxemptyclause";
7123 $trans = $DB->start_delegated_transaction();
7124 $DB->delete_records('context_temp');
7125 $DB->execute($sql);
7126 context::merge_context_temp_table();
7127 $DB->delete_records('context_temp');
7128 $trans->allow_commit();
7134 // ============== DEPRECATED FUNCTIONS ==========================================
7135 // Old context related functions were deprecated in 2.0, it is recommended
7136 // to use context classes in new code. Old function can be used when
7137 // creating patches that are supposed to be backported to older stable branches.
7138 // These deprecated functions will not be removed in near future,
7139 // before removing devs will be warned with a debugging message first,
7140 // then we will add error message and only after that we can remove the functions
7141 // completely.
7145 * Not available any more, use load_temp_course_role() instead.
7147 * @deprecated since 2.2
7148 * @param stdClass $context
7149 * @param int $roleid
7150 * @param array $accessdata
7151 * @return array
7153 function load_temp_role($context, $roleid, array $accessdata) {
7154 debugging('load_temp_role() is deprecated, please use load_temp_course_role() instead, temp role not loaded.');
7155 return $accessdata;
7159 * Not available any more, use remove_temp_course_roles() instead.
7161 * @deprecated since 2.2
7162 * @param stdClass $context
7163 * @param array $accessdata
7164 * @return array access data
7166 function remove_temp_roles($context, array $accessdata) {
7167 debugging('remove_temp_role() is deprecated, please use remove_temp_course_roles() instead.');
7168 return $accessdata;
7172 * Returns system context or null if can not be created yet.
7174 * @deprecated since 2.2, use context_system::instance()
7175 * @param bool $cache use caching
7176 * @return context system context (null if context table not created yet)
7178 function get_system_context($cache = true) {
7179 return context_system::instance(0, IGNORE_MISSING, $cache);
7183 * Get the context instance as an object. This function will create the
7184 * context instance if it does not exist yet.
7186 * @deprecated since 2.2, use context_course::instance() or other relevant class instead
7187 * @param integer $contextlevel The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
7188 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
7189 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
7190 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
7191 * MUST_EXIST means throw exception if no record or multiple records found
7192 * @return context The context object.
7194 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
7195 $instances = (array)$instance;
7196 $contexts = array();
7198 $classname = context_helper::get_class_for_level($contextlevel);
7200 // we do not load multiple contexts any more, PAGE should be responsible for any preloading
7201 foreach ($instances as $inst) {
7202 $contexts[$inst] = $classname::instance($inst, $strictness);
7205 if (is_array($instance)) {
7206 return $contexts;
7207 } else {
7208 return $contexts[$instance];
7213 * Get a context instance as an object, from a given context id.
7215 * @deprecated since 2.2, use context::instance_by_id($id) instead
7216 * @param int $id context id
7217 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
7218 * MUST_EXIST means throw exception if no record or multiple records found
7219 * @return context|bool the context object or false if not found.
7221 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
7222 return context::instance_by_id($id, $strictness);
7226 * Recursive function which, given a context, find all parent context ids,
7227 * and return the array in reverse order, i.e. parent first, then grand
7228 * parent, etc.
7230 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
7231 * @param context $context
7232 * @param bool $includeself optional, defaults to false
7233 * @return array
7235 function get_parent_contexts(context $context, $includeself = false) {
7236 return $context->get_parent_context_ids($includeself);
7240 * Return the id of the parent of this context, or false if there is no parent (only happens if this
7241 * is the site context.)
7243 * @deprecated since 2.2, use $context->get_parent_context() instead
7244 * @param context $context
7245 * @return integer the id of the parent context.
7247 function get_parent_contextid(context $context) {
7248 if ($parent = $context->get_parent_context()) {
7249 return $parent->id;
7250 } else {
7251 return false;
7256 * Recursive function which, given a context, find all its children context ids.
7258 * For course category contexts it will return immediate children only categories and courses.
7259 * It will NOT recurse into courses or child categories.
7260 * If you want to do that, call it on the returned courses/categories.
7262 * When called for a course context, it will return the modules and blocks
7263 * displayed in the course page.
7265 * If called on a user/course/module context it _will_ populate the cache with the appropriate
7266 * contexts ;-)
7268 * @deprecated since 2.2, use $context->get_child_contexts() instead
7269 * @param context $context
7270 * @return array Array of child records
7272 function get_child_contexts(context $context) {
7273 return $context->get_child_contexts();
7277 * Precreates all contexts including all parents
7279 * @deprecated since 2.2
7280 * @param int $contextlevel empty means all
7281 * @param bool $buildpaths update paths and depths
7282 * @return void
7284 function create_contexts($contextlevel = null, $buildpaths = true) {
7285 context_helper::create_instances($contextlevel, $buildpaths);
7289 * Remove stale context records
7291 * @deprecated since 2.2, use context_helper::cleanup_instances() instead
7292 * @return bool
7294 function cleanup_contexts() {
7295 context_helper::cleanup_instances();
7296 return true;
7300 * Populate context.path and context.depth where missing.
7302 * @deprecated since 2.2, use context_helper::build_all_paths() instead
7303 * @param bool $force force a complete rebuild of the path and depth fields, defaults to false
7304 * @return void
7306 function build_context_path($force = false) {
7307 context_helper::build_all_paths($force);
7311 * Rebuild all related context depth and path caches
7313 * @deprecated since 2.2
7314 * @param array $fixcontexts array of contexts, strongtyped
7315 * @return void
7317 function rebuild_contexts(array $fixcontexts) {
7318 foreach ($fixcontexts as $fixcontext) {
7319 $fixcontext->reset_paths(false);
7321 context_helper::build_all_paths(false);
7325 * Preloads all contexts relating to a course: course, modules. Block contexts
7326 * are no longer loaded here. The contexts for all the blocks on the current
7327 * page are now efficiently loaded by {@link block_manager::load_blocks()}.
7329 * @deprecated since 2.2
7330 * @param int $courseid Course ID
7331 * @return void
7333 function preload_course_contexts($courseid) {
7334 context_helper::preload_course($courseid);
7338 * Preloads context information together with instances.
7339 * Use context_instance_preload() to strip the context info from the record and cache the context instance.
7341 * @deprecated since 2.2
7342 * @param string $joinon for example 'u.id'
7343 * @param string $contextlevel context level of instance in $joinon
7344 * @param string $tablealias context table alias
7345 * @return array with two values - select and join part
7347 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
7348 $select = ", ".context_helper::get_preload_record_columns_sql($tablealias);
7349 $join = "LEFT JOIN {context} $tablealias ON ($tablealias.instanceid = $joinon AND $tablealias.contextlevel = $contextlevel)";
7350 return array($select, $join);
7354 * Preloads context information from db record and strips the cached info.
7355 * The db request has to contain both the $join and $select from context_instance_preload_sql()
7357 * @deprecated since 2.2
7358 * @param stdClass $rec
7359 * @return void (modifies $rec)
7361 function context_instance_preload(stdClass $rec) {
7362 context_helper::preload_from_record($rec);
7366 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
7368 * @deprecated since 2.2, use $context->mark_dirty() instead
7369 * @param string $path context path
7371 function mark_context_dirty($path) {
7372 global $CFG, $USER, $ACCESSLIB_PRIVATE;
7374 if (during_initial_install()) {
7375 return;
7378 // only if it is a non-empty string
7379 if (is_string($path) && $path !== '') {
7380 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+$CFG->sessiontimeout);
7381 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
7382 $ACCESSLIB_PRIVATE->dirtycontexts[$path] = 1;
7383 } else {
7384 if (CLI_SCRIPT) {
7385 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
7386 } else {
7387 if (isset($USER->access['time'])) {
7388 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
7389 } else {
7390 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
7392 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
7399 * Update the path field of the context and all dep. subcontexts that follow
7401 * Update the path field of the context and
7402 * all the dependent subcontexts that follow
7403 * the move.
7405 * The most important thing here is to be as
7406 * DB efficient as possible. This op can have a
7407 * massive impact in the DB.
7409 * @deprecated since 2.2
7410 * @param context $context context obj
7411 * @param context $newparent new parent obj
7412 * @return void
7414 function context_moved(context $context, context $newparent) {
7415 $context->update_moved($newparent);
7419 * Remove a context record and any dependent entries,
7420 * removes context from static context cache too
7422 * @deprecated since 2.2, use $context->delete_content() instead
7423 * @param int $contextlevel
7424 * @param int $instanceid
7425 * @param bool $deleterecord false means keep record for now
7426 * @return bool returns true or throws an exception
7428 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
7429 if ($deleterecord) {
7430 context_helper::delete_instance($contextlevel, $instanceid);
7431 } else {
7432 $classname = context_helper::get_class_for_level($contextlevel);
7433 if ($context = $classname::instance($instanceid, IGNORE_MISSING)) {
7434 $context->delete_content();
7438 return true;
7442 * Returns context level name
7444 * @deprecated since 2.2
7445 * @param integer $contextlevel $context->context level. One of the CONTEXT_... constants.
7446 * @return string the name for this type of context.
7448 function get_contextlevel_name($contextlevel) {
7449 return context_helper::get_level_name($contextlevel);
7453 * Prints human readable context identifier.
7455 * @deprecated since 2.2
7456 * @param context $context the context.
7457 * @param boolean $withprefix whether to prefix the name of the context with the
7458 * type of context, e.g. User, Course, Forum, etc.
7459 * @param boolean $short whether to user the short name of the thing. Only applies
7460 * to course contexts
7461 * @return string the human readable context name.
7463 function print_context_name(context $context, $withprefix = true, $short = false) {
7464 return $context->get_context_name($withprefix, $short);
7468 * Get a URL for a context, if there is a natural one. For example, for
7469 * CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
7470 * user profile page.
7472 * @deprecated since 2.2
7473 * @param context $context the context.
7474 * @return moodle_url
7476 function get_context_url(context $context) {
7477 return $context->get_url();
7481 * Is this context part of any course? if yes return course context,
7482 * if not return null or throw exception.
7484 * @deprecated since 2.2, use $context->get_course_context() instead
7485 * @param context $context
7486 * @return course_context context of the enclosing course, null if not found or exception
7488 function get_course_context(context $context) {
7489 return $context->get_course_context(true);
7493 * Returns current course id or null if outside of course based on context parameter.
7495 * @deprecated since 2.2, use $context->get_course_context instead
7496 * @param context $context
7497 * @return int|bool related course id or false
7499 function get_courseid_from_context(context $context) {
7500 if ($coursecontext = $context->get_course_context(false)) {
7501 return $coursecontext->instanceid;
7502 } else {
7503 return false;
7508 * Get an array of courses where cap requested is available
7509 * and user is enrolled, this can be relatively slow.
7511 * @deprecated since 2.2, use enrol_get_users_courses() instead
7512 * @param int $userid A user id. By default (null) checks the permissions of the current user.
7513 * @param string $cap - name of the capability
7514 * @param array $accessdata_ignored
7515 * @param bool $doanything_ignored
7516 * @param string $sort - sorting fields - prefix each fieldname with "c."
7517 * @param array $fields - additional fields you are interested in...
7518 * @param int $limit_ignored
7519 * @return array $courses - ordered array of course objects - see notes above
7521 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
7523 $courses = enrol_get_users_courses($userid, true, $fields, $sort);
7524 foreach ($courses as $id=>$course) {
7525 $context = context_course::instance($id);
7526 if (!has_capability($cap, $context, $userid)) {
7527 unset($courses[$id]);
7531 return $courses;
7535 * Extracts the relevant capabilities given a contextid.
7536 * All case based, example an instance of forum context.
7537 * Will fetch all forum related capabilities, while course contexts
7538 * Will fetch all capabilities
7540 * capabilities
7541 * `name` varchar(150) NOT NULL,
7542 * `captype` varchar(50) NOT NULL,
7543 * `contextlevel` int(10) NOT NULL,
7544 * `component` varchar(100) NOT NULL,
7546 * @deprecated since 2.2
7547 * @param context $context
7548 * @return array
7550 function fetch_context_capabilities(context $context) {
7551 return $context->get_capabilities();
7555 * Runs get_records select on context table and returns the result
7556 * Does get_records_select on the context table, and returns the results ordered
7557 * by contextlevel, and then the natural sort order within each level.
7558 * for the purpose of $select, you need to know that the context table has been
7559 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7561 * @deprecated since 2.2
7562 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7563 * @param array $params any parameters required by $select.
7564 * @return array the requested context records.
7566 function get_sorted_contexts($select, $params = array()) {
7568 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7570 global $DB;
7571 if ($select) {
7572 $select = 'WHERE ' . $select;
7574 return $DB->get_records_sql("
7575 SELECT ctx.*
7576 FROM {context} ctx
7577 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7578 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7579 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7580 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7581 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7582 $select
7583 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7584 ", $params);
7588 * This is really slow!!! do not use above course context level
7590 * @deprecated since 2.2
7591 * @param int $roleid
7592 * @param context $context
7593 * @return array
7595 function get_role_context_caps($roleid, context $context) {
7596 global $DB;
7598 //this is really slow!!!! - do not use above course context level!
7599 $result = array();
7600 $result[$context->id] = array();
7602 // first emulate the parent context capabilities merging into context
7603 $searchcontexts = array_reverse($context->get_parent_context_ids(true));
7604 foreach ($searchcontexts as $cid) {
7605 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7606 foreach ($capabilities as $cap) {
7607 if (!array_key_exists($cap->capability, $result[$context->id])) {
7608 $result[$context->id][$cap->capability] = 0;
7610 $result[$context->id][$cap->capability] += $cap->permission;
7615 // now go through the contexts below given context
7616 $searchcontexts = array_keys($context->get_child_contexts());
7617 foreach ($searchcontexts as $cid) {
7618 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7619 foreach ($capabilities as $cap) {
7620 if (!array_key_exists($cap->contextid, $result)) {
7621 $result[$cap->contextid] = array();
7623 $result[$cap->contextid][$cap->capability] = $cap->permission;
7628 return $result;
7632 * Gets a string for sql calls, searching for stuff in this context or above
7634 * NOTE: use $DB->get_in_or_equal($context->get_parent_context_ids()...
7636 * @deprecated since 2.2, $context->use get_parent_context_ids() instead
7637 * @param context $context
7638 * @return string
7640 function get_related_contexts_string(context $context) {
7642 if ($parents = $context->get_parent_context_ids()) {
7643 return (' IN ('.$context->id.','.implode(',', $parents).')');
7644 } else {
7645 return (' ='.$context->id);
7650 * Given context and array of users, returns array of users whose enrolment status is suspended,
7651 * or enrolment has expired or has not started. Also removes those users from the given array
7653 * @param context $context context in which suspended users should be extracted.
7654 * @param array $users list of users.
7655 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7656 * @return array list of suspended users.
7658 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7659 global $DB;
7661 // Get active enrolled users.
7662 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7663 $activeusers = $DB->get_records_sql($sql, $params);
7665 // Move suspended users to a separate array & remove from the initial one.
7666 $susers = array();
7667 if (sizeof($activeusers)) {
7668 foreach ($users as $userid => $user) {
7669 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7670 $susers[$userid] = $user;
7671 unset($users[$userid]);
7675 return $susers;
7679 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7680 * or enrolment has expired or not started.
7682 * @param context $context context in which user enrolment is checked.
7683 * @return array list of suspended user id's.
7685 function get_suspended_userids($context){
7686 global $DB;
7688 // Get all enrolled users.
7689 list($sql, $params) = get_enrolled_sql($context);
7690 $users = $DB->get_records_sql($sql, $params);
7692 // Get active enrolled users.
7693 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7694 $activeusers = $DB->get_records_sql($sql, $params);
7696 $susers = array();
7697 if (sizeof($activeusers) != sizeof($users)) {
7698 foreach ($users as $userid => $user) {
7699 if (!array_key_exists($userid, $activeusers)) {
7700 $susers[$userid] = $userid;
7704 return $susers;