MDL-45652 core_backup: display warning on restore destination form when necessary...
[moodle.git] / lib / accesslib.php
blob147da15a83ce82bbb2c6bf63a2155f1645a6e61d
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 * Is course creator going to have capability in a new course?
551 * This is intended to be used in enrolment plugins before or during course creation,
552 * do not use after the course is fully created.
554 * @category access
556 * @param string $capability the name of the capability to check.
557 * @param context $context course or category context where is course going to be created
558 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
559 * @return boolean true if the user will have this capability.
561 * @throws coding_exception if different type of context submitted
563 function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) {
564 global $CFG;
566 if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) {
567 throw new coding_exception('Only course or course category context expected');
570 if (has_capability($capability, $context, $user)) {
571 // User already has the capability, it could be only removed if CAP_PROHIBIT
572 // was involved here, but we ignore that.
573 return true;
576 if (!has_capability('moodle/course:create', $context, $user)) {
577 return false;
580 if (!enrol_is_enabled('manual')) {
581 return false;
584 if (empty($CFG->creatornewroleid)) {
585 return false;
588 if ($context->contextlevel == CONTEXT_COURSE) {
589 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
590 return false;
592 } else {
593 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
594 return false;
598 // Most likely they will be enrolled after the course creation is finished,
599 // does the new role have the required capability?
600 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
601 return isset($neededroles[$CFG->creatornewroleid]);
605 * Check if the user is an admin at the site level.
607 * Please note that use of proper capabilities is always encouraged,
608 * this function is supposed to be used from core or for temporary hacks.
610 * @category access
612 * @param int|stdClass $user_or_id user id or user object
613 * @return bool true if user is one of the administrators, false otherwise
615 function is_siteadmin($user_or_id = null) {
616 global $CFG, $USER;
618 if ($user_or_id === null) {
619 $user_or_id = $USER;
622 if (empty($user_or_id)) {
623 return false;
625 if (!empty($user_or_id->id)) {
626 $userid = $user_or_id->id;
627 } else {
628 $userid = $user_or_id;
631 // Because this script is called many times (150+ for course page) with
632 // the same parameters, it is worth doing minor optimisations. This static
633 // cache stores the value for a single userid, saving about 2ms from course
634 // page load time without using significant memory. As the static cache
635 // also includes the value it depends on, this cannot break unit tests.
636 static $knownid, $knownresult, $knownsiteadmins;
637 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
638 return $knownresult;
640 $knownid = $userid;
641 $knownsiteadmins = $CFG->siteadmins;
643 $siteadmins = explode(',', $CFG->siteadmins);
644 $knownresult = in_array($userid, $siteadmins);
645 return $knownresult;
649 * Returns true if user has at least one role assign
650 * of 'coursecontact' role (is potentially listed in some course descriptions).
652 * @param int $userid
653 * @return bool
655 function has_coursecontact_role($userid) {
656 global $DB, $CFG;
658 if (empty($CFG->coursecontact)) {
659 return false;
661 $sql = "SELECT 1
662 FROM {role_assignments}
663 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
664 return $DB->record_exists_sql($sql, array('userid'=>$userid));
668 * Does the user have a capability to do something?
670 * Walk the accessdata array and return true/false.
671 * Deals with prohibits, role switching, aggregating
672 * capabilities, etc.
674 * The main feature of here is being FAST and with no
675 * side effects.
677 * Notes:
679 * Switch Role merges with default role
680 * ------------------------------------
681 * If you are a teacher in course X, you have at least
682 * teacher-in-X + defaultloggedinuser-sitewide. So in the
683 * course you'll have techer+defaultloggedinuser.
684 * We try to mimic that in switchrole.
686 * Permission evaluation
687 * ---------------------
688 * Originally there was an extremely complicated way
689 * to determine the user access that dealt with
690 * "locality" or role assignments and role overrides.
691 * Now we simply evaluate access for each role separately
692 * and then verify if user has at least one role with allow
693 * and at the same time no role with prohibit.
695 * @access private
696 * @param string $capability
697 * @param context $context
698 * @param array $accessdata
699 * @return bool
701 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
702 global $CFG;
704 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
705 $path = $context->path;
706 $paths = array($path);
707 while($path = rtrim($path, '0123456789')) {
708 $path = rtrim($path, '/');
709 if ($path === '') {
710 break;
712 $paths[] = $path;
715 $roles = array();
716 $switchedrole = false;
718 // Find out if role switched
719 if (!empty($accessdata['rsw'])) {
720 // From the bottom up...
721 foreach ($paths as $path) {
722 if (isset($accessdata['rsw'][$path])) {
723 // Found a switchrole assignment - check for that role _plus_ the default user role
724 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
725 $switchedrole = true;
726 break;
731 if (!$switchedrole) {
732 // get all users roles in this context and above
733 foreach ($paths as $path) {
734 if (isset($accessdata['ra'][$path])) {
735 foreach ($accessdata['ra'][$path] as $roleid) {
736 $roles[$roleid] = null;
742 // Now find out what access is given to each role, going bottom-->up direction
743 $allowed = false;
744 foreach ($roles as $roleid => $ignored) {
745 foreach ($paths as $path) {
746 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
747 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
748 if ($perm === CAP_PROHIBIT) {
749 // any CAP_PROHIBIT found means no permission for the user
750 return false;
752 if (is_null($roles[$roleid])) {
753 $roles[$roleid] = $perm;
757 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
758 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
761 return $allowed;
765 * A convenience function that tests has_capability, and displays an error if
766 * the user does not have that capability.
768 * NOTE before Moodle 2.0, this function attempted to make an appropriate
769 * require_login call before checking the capability. This is no longer the case.
770 * You must call require_login (or one of its variants) if you want to check the
771 * user is logged in, before you call this function.
773 * @see has_capability()
775 * @param string $capability the name of the capability to check. For example mod/forum:view
776 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
777 * @param int $userid A user id. By default (null) checks the permissions of the current user.
778 * @param bool $doanything If false, ignore effect of admin role assignment
779 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
780 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
781 * @return void terminates with an error if the user does not have the given capability.
783 function require_capability($capability, context $context, $userid = null, $doanything = true,
784 $errormessage = 'nopermissions', $stringfile = '') {
785 if (!has_capability($capability, $context, $userid, $doanything)) {
786 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
791 * Return a nested array showing role assignments
792 * all relevant role capabilities for the user at
793 * site/course_category/course levels
795 * We do _not_ delve deeper than courses because the number of
796 * overrides at the module/block levels can be HUGE.
798 * [ra] => [/path][roleid]=roleid
799 * [rdef] => [/path:roleid][capability]=permission
801 * @access private
802 * @param int $userid - the id of the user
803 * @return array access info array
805 function get_user_access_sitewide($userid) {
806 global $CFG, $DB, $ACCESSLIB_PRIVATE;
808 /* Get in a few cheap DB queries...
809 * - role assignments
810 * - relevant role caps
811 * - above and within this user's RAs
812 * - below this user's RAs - limited to course level
815 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
816 $raparents = array();
817 $accessdata = get_empty_accessdata();
819 // start with the default role
820 if (!empty($CFG->defaultuserroleid)) {
821 $syscontext = context_system::instance();
822 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
823 $raparents[$CFG->defaultuserroleid][$syscontext->id] = $syscontext->id;
826 // load the "default frontpage role"
827 if (!empty($CFG->defaultfrontpageroleid)) {
828 $frontpagecontext = context_course::instance(get_site()->id);
829 if ($frontpagecontext->path) {
830 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
831 $raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->id] = $frontpagecontext->id;
835 // preload every assigned role at and above course context
836 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
837 FROM {role_assignments} ra
838 JOIN {context} ctx
839 ON ctx.id = ra.contextid
840 LEFT JOIN {block_instances} bi
841 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
842 LEFT JOIN {context} bpctx
843 ON (bpctx.id = bi.parentcontextid)
844 WHERE ra.userid = :userid
845 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")";
846 $params = array('userid'=>$userid);
847 $rs = $DB->get_recordset_sql($sql, $params);
848 foreach ($rs as $ra) {
849 // RAs leafs are arrays to support multi-role assignments...
850 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
851 $raparents[$ra->roleid][$ra->contextid] = $ra->contextid;
853 $rs->close();
855 if (empty($raparents)) {
856 return $accessdata;
859 // now get overrides of interesting roles in all interesting child contexts
860 // hopefully we will not run out of SQL limits here,
861 // users would have to have very many roles at/above course context...
862 $sqls = array();
863 $params = array();
865 static $cp = 0;
866 foreach ($raparents as $roleid=>$ras) {
867 $cp++;
868 list($sqlcids, $cids) = $DB->get_in_or_equal($ras, SQL_PARAMS_NAMED, 'c'.$cp.'_');
869 $params = array_merge($params, $cids);
870 $params['r'.$cp] = $roleid;
871 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
872 FROM {role_capabilities} rc
873 JOIN {context} ctx
874 ON (ctx.id = rc.contextid)
875 JOIN {context} pctx
876 ON (pctx.id $sqlcids
877 AND (ctx.id = pctx.id
878 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
879 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
880 LEFT JOIN {block_instances} bi
881 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
882 LEFT JOIN {context} bpctx
883 ON (bpctx.id = bi.parentcontextid)
884 WHERE rc.roleid = :r{$cp}
885 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")
889 // fixed capability order is necessary for rdef dedupe
890 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
892 foreach ($rs as $rd) {
893 $k = $rd->path.':'.$rd->roleid;
894 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
896 $rs->close();
898 // share the role definitions
899 foreach ($accessdata['rdef'] as $k=>$unused) {
900 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
901 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
903 $accessdata['rdef_count']++;
904 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
907 return $accessdata;
911 * Add to the access ctrl array the data needed by a user for a given course.
913 * This function injects all course related access info into the accessdata array.
915 * @access private
916 * @param int $userid the id of the user
917 * @param context_course $coursecontext course context
918 * @param array $accessdata accessdata array (modified)
919 * @return void modifies $accessdata parameter
921 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
922 global $DB, $CFG, $ACCESSLIB_PRIVATE;
924 if (empty($coursecontext->path)) {
925 // weird, this should not happen
926 return;
929 if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
930 // already loaded, great!
931 return;
934 $roles = array();
936 if (empty($userid)) {
937 if (!empty($CFG->notloggedinroleid)) {
938 $roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
941 } else if (isguestuser($userid)) {
942 if ($guestrole = get_guest_role()) {
943 $roles[$guestrole->id] = $guestrole->id;
946 } else {
947 // Interesting role assignments at, above and below the course context
948 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
949 $params['userid'] = $userid;
950 $params['children'] = $coursecontext->path."/%";
951 $sql = "SELECT ra.*, ctx.path
952 FROM {role_assignments} ra
953 JOIN {context} ctx ON ra.contextid = ctx.id
954 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
955 $rs = $DB->get_recordset_sql($sql, $params);
957 // add missing role definitions
958 foreach ($rs as $ra) {
959 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
960 $roles[$ra->roleid] = $ra->roleid;
962 $rs->close();
964 // add the "default frontpage role" when on the frontpage
965 if (!empty($CFG->defaultfrontpageroleid)) {
966 $frontpagecontext = context_course::instance(get_site()->id);
967 if ($frontpagecontext->id == $coursecontext->id) {
968 $roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
972 // do not forget the default role
973 if (!empty($CFG->defaultuserroleid)) {
974 $roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
978 if (!$roles) {
979 // weird, default roles must be missing...
980 $accessdata['loaded'][$coursecontext->instanceid] = 1;
981 return;
984 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
985 $params = array('c'=>$coursecontext->id);
986 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
987 $params = array_merge($params, $rparams);
988 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
989 $params = array_merge($params, $rparams);
991 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
992 FROM {role_capabilities} rc
993 JOIN {context} ctx
994 ON (ctx.id = rc.contextid)
995 JOIN {context} cctx
996 ON (cctx.id = :c
997 AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
998 WHERE rc.roleid $roleids
999 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
1000 $rs = $DB->get_recordset_sql($sql, $params);
1002 $newrdefs = array();
1003 foreach ($rs as $rd) {
1004 $k = $rd->path.':'.$rd->roleid;
1005 if (isset($accessdata['rdef'][$k])) {
1006 continue;
1008 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
1010 $rs->close();
1012 // share new role definitions
1013 foreach ($newrdefs as $k=>$unused) {
1014 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
1015 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
1017 $accessdata['rdef_count']++;
1018 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1021 $accessdata['loaded'][$coursecontext->instanceid] = 1;
1023 // we want to deduplicate the USER->access from time to time, this looks like a good place,
1024 // because we have to do it before the end of session
1025 dedupe_user_access();
1029 * Add to the access ctrl array the data needed by a role for a given context.
1031 * The data is added in the rdef key.
1032 * This role-centric function is useful for role_switching
1033 * and temporary course roles.
1035 * @access private
1036 * @param int $roleid the id of the user
1037 * @param context $context needs path!
1038 * @param array $accessdata accessdata array (is modified)
1039 * @return array
1041 function load_role_access_by_context($roleid, context $context, &$accessdata) {
1042 global $DB, $ACCESSLIB_PRIVATE;
1044 /* Get the relevant rolecaps into rdef
1045 * - relevant role caps
1046 * - at ctx and above
1047 * - below this ctx
1050 if (empty($context->path)) {
1051 // weird, this should not happen
1052 return;
1055 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
1056 $params['roleid'] = $roleid;
1057 $params['childpath'] = $context->path.'/%';
1059 $sql = "SELECT ctx.path, rc.capability, rc.permission
1060 FROM {role_capabilities} rc
1061 JOIN {context} ctx ON (rc.contextid = ctx.id)
1062 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
1063 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
1064 $rs = $DB->get_recordset_sql($sql, $params);
1066 $newrdefs = array();
1067 foreach ($rs as $rd) {
1068 $k = $rd->path.':'.$roleid;
1069 if (isset($accessdata['rdef'][$k])) {
1070 continue;
1072 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
1074 $rs->close();
1076 // share new role definitions
1077 foreach ($newrdefs as $k=>$unused) {
1078 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
1079 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
1081 $accessdata['rdef_count']++;
1082 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1087 * Returns empty accessdata structure.
1089 * @access private
1090 * @return array empt accessdata
1092 function get_empty_accessdata() {
1093 $accessdata = array(); // named list
1094 $accessdata['ra'] = array();
1095 $accessdata['rdef'] = array();
1096 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
1097 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
1098 $accessdata['loaded'] = array(); // loaded course contexts
1099 $accessdata['time'] = time();
1100 $accessdata['rsw'] = array();
1102 return $accessdata;
1106 * Get accessdata for a given user.
1108 * @access private
1109 * @param int $userid
1110 * @param bool $preloadonly true means do not return access array
1111 * @return array accessdata
1113 function get_user_accessdata($userid, $preloadonly=false) {
1114 global $CFG, $ACCESSLIB_PRIVATE, $USER;
1116 if (!empty($USER->access['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1117 // share rdef from USER session with rolepermissions cache in order to conserve memory
1118 foreach ($USER->access['rdef'] as $k=>$v) {
1119 $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->access['rdef'][$k];
1121 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->access;
1124 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
1125 if (empty($userid)) {
1126 if (!empty($CFG->notloggedinroleid)) {
1127 $accessdata = get_role_access($CFG->notloggedinroleid);
1128 } else {
1129 // weird
1130 return get_empty_accessdata();
1133 } else if (isguestuser($userid)) {
1134 if ($guestrole = get_guest_role()) {
1135 $accessdata = get_role_access($guestrole->id);
1136 } else {
1137 //weird
1138 return get_empty_accessdata();
1141 } else {
1142 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1145 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1148 if ($preloadonly) {
1149 return;
1150 } else {
1151 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1156 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1157 * this function looks for contexts with the same overrides and shares them.
1159 * @access private
1160 * @return void
1162 function dedupe_user_access() {
1163 global $USER;
1165 if (CLI_SCRIPT) {
1166 // no session in CLI --> no compression necessary
1167 return;
1170 if (empty($USER->access['rdef_count'])) {
1171 // weird, this should not happen
1172 return;
1175 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1176 if ($USER->access['rdef_count'] - $USER->access['rdef_lcc'] > 10) {
1177 // do not compress after each change, wait till there is more stuff to be done
1178 return;
1181 $hashmap = array();
1182 foreach ($USER->access['rdef'] as $k=>$def) {
1183 $hash = sha1(serialize($def));
1184 if (isset($hashmap[$hash])) {
1185 $USER->access['rdef'][$k] =& $hashmap[$hash];
1186 } else {
1187 $hashmap[$hash] =& $USER->access['rdef'][$k];
1191 $USER->access['rdef_lcc'] = $USER->access['rdef_count'];
1195 * A convenience function to completely load all the capabilities
1196 * for the current user. It is called from has_capability() and functions change permissions.
1198 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1199 * @see check_enrolment_plugins()
1201 * @access private
1202 * @return void
1204 function load_all_capabilities() {
1205 global $USER;
1207 // roles not installed yet - we are in the middle of installation
1208 if (during_initial_install()) {
1209 return;
1212 if (!isset($USER->id)) {
1213 // this should not happen
1214 $USER->id = 0;
1217 unset($USER->access);
1218 $USER->access = get_user_accessdata($USER->id);
1220 // deduplicate the overrides to minimize session size
1221 dedupe_user_access();
1223 // Clear to force a refresh
1224 unset($USER->mycourses);
1226 // init/reset internal enrol caches - active course enrolments and temp access
1227 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1231 * A convenience function to completely reload all the capabilities
1232 * for the current user when roles have been updated in a relevant
1233 * context -- but PRESERVING switchroles and loginas.
1234 * This function resets all accesslib and context caches.
1236 * That is - completely transparent to the user.
1238 * Note: reloads $USER->access completely.
1240 * @access private
1241 * @return void
1243 function reload_all_capabilities() {
1244 global $USER, $DB, $ACCESSLIB_PRIVATE;
1246 // copy switchroles
1247 $sw = array();
1248 if (!empty($USER->access['rsw'])) {
1249 $sw = $USER->access['rsw'];
1252 accesslib_clear_all_caches(true);
1253 unset($USER->access);
1254 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
1256 load_all_capabilities();
1258 foreach ($sw as $path => $roleid) {
1259 if ($record = $DB->get_record('context', array('path'=>$path))) {
1260 $context = context::instance_by_id($record->id);
1261 role_switch($roleid, $context);
1267 * Adds a temp role to current USER->access array.
1269 * Useful for the "temporary guest" access we grant to logged-in users.
1270 * This is useful for enrol plugins only.
1272 * @since Moodle 2.2
1273 * @param context_course $coursecontext
1274 * @param int $roleid
1275 * @return void
1277 function load_temp_course_role(context_course $coursecontext, $roleid) {
1278 global $USER, $SITE;
1280 if (empty($roleid)) {
1281 debugging('invalid role specified in load_temp_course_role()');
1282 return;
1285 if ($coursecontext->instanceid == $SITE->id) {
1286 debugging('Can not use temp roles on the frontpage');
1287 return;
1290 if (!isset($USER->access)) {
1291 load_all_capabilities();
1294 $coursecontext->reload_if_dirty();
1296 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1297 return;
1300 // load course stuff first
1301 load_course_context($USER->id, $coursecontext, $USER->access);
1303 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1305 load_role_access_by_context($roleid, $coursecontext, $USER->access);
1309 * Removes any extra guest roles from current USER->access array.
1310 * This is useful for enrol plugins only.
1312 * @since Moodle 2.2
1313 * @param context_course $coursecontext
1314 * @return void
1316 function remove_temp_course_roles(context_course $coursecontext) {
1317 global $DB, $USER, $SITE;
1319 if ($coursecontext->instanceid == $SITE->id) {
1320 debugging('Can not use temp roles on the frontpage');
1321 return;
1324 if (empty($USER->access['ra'][$coursecontext->path])) {
1325 //no roles here, weird
1326 return;
1329 $sql = "SELECT DISTINCT ra.roleid AS id
1330 FROM {role_assignments} ra
1331 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1332 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1334 $USER->access['ra'][$coursecontext->path] = array();
1335 foreach($ras as $r) {
1336 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1341 * Returns array of all role archetypes.
1343 * @return array
1345 function get_role_archetypes() {
1346 return array(
1347 'manager' => 'manager',
1348 'coursecreator' => 'coursecreator',
1349 'editingteacher' => 'editingteacher',
1350 'teacher' => 'teacher',
1351 'student' => 'student',
1352 'guest' => 'guest',
1353 'user' => 'user',
1354 'frontpage' => 'frontpage'
1359 * Assign the defaults found in this capability definition to roles that have
1360 * the corresponding legacy capabilities assigned to them.
1362 * @param string $capability
1363 * @param array $legacyperms an array in the format (example):
1364 * 'guest' => CAP_PREVENT,
1365 * 'student' => CAP_ALLOW,
1366 * 'teacher' => CAP_ALLOW,
1367 * 'editingteacher' => CAP_ALLOW,
1368 * 'coursecreator' => CAP_ALLOW,
1369 * 'manager' => CAP_ALLOW
1370 * @return boolean success or failure.
1372 function assign_legacy_capabilities($capability, $legacyperms) {
1374 $archetypes = get_role_archetypes();
1376 foreach ($legacyperms as $type => $perm) {
1378 $systemcontext = context_system::instance();
1379 if ($type === 'admin') {
1380 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1381 $type = 'manager';
1384 if (!array_key_exists($type, $archetypes)) {
1385 print_error('invalidlegacy', '', '', $type);
1388 if ($roles = get_archetype_roles($type)) {
1389 foreach ($roles as $role) {
1390 // Assign a site level capability.
1391 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1392 return false;
1397 return true;
1401 * Verify capability risks.
1403 * @param stdClass $capability a capability - a row from the capabilities table.
1404 * @return boolean whether this capability is safe - that is, whether people with the
1405 * safeoverrides capability should be allowed to change it.
1407 function is_safe_capability($capability) {
1408 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1412 * Get the local override (if any) for a given capability in a role in a context
1414 * @param int $roleid
1415 * @param int $contextid
1416 * @param string $capability
1417 * @return stdClass local capability override
1419 function get_local_override($roleid, $contextid, $capability) {
1420 global $DB;
1421 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1425 * Returns context instance plus related course and cm instances
1427 * @param int $contextid
1428 * @return array of ($context, $course, $cm)
1430 function get_context_info_array($contextid) {
1431 global $DB;
1433 $context = context::instance_by_id($contextid, MUST_EXIST);
1434 $course = null;
1435 $cm = null;
1437 if ($context->contextlevel == CONTEXT_COURSE) {
1438 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1440 } else if ($context->contextlevel == CONTEXT_MODULE) {
1441 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1442 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1444 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1445 $parent = $context->get_parent_context();
1447 if ($parent->contextlevel == CONTEXT_COURSE) {
1448 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1449 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1450 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1451 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1455 return array($context, $course, $cm);
1459 * Function that creates a role
1461 * @param string $name role name
1462 * @param string $shortname role short name
1463 * @param string $description role description
1464 * @param string $archetype
1465 * @return int id or dml_exception
1467 function create_role($name, $shortname, $description, $archetype = '') {
1468 global $DB;
1470 if (strpos($archetype, 'moodle/legacy:') !== false) {
1471 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1474 // verify role archetype actually exists
1475 $archetypes = get_role_archetypes();
1476 if (empty($archetypes[$archetype])) {
1477 $archetype = '';
1480 // Insert the role record.
1481 $role = new stdClass();
1482 $role->name = $name;
1483 $role->shortname = $shortname;
1484 $role->description = $description;
1485 $role->archetype = $archetype;
1487 //find free sortorder number
1488 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1489 if (empty($role->sortorder)) {
1490 $role->sortorder = 1;
1492 $id = $DB->insert_record('role', $role);
1494 return $id;
1498 * Function that deletes a role and cleanups up after it
1500 * @param int $roleid id of role to delete
1501 * @return bool always true
1503 function delete_role($roleid) {
1504 global $DB;
1506 // first unssign all users
1507 role_unassign_all(array('roleid'=>$roleid));
1509 // cleanup all references to this role, ignore errors
1510 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1511 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1512 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1513 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1514 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1515 $DB->delete_records('role_names', array('roleid'=>$roleid));
1516 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1518 // Get role record before it's deleted.
1519 $role = $DB->get_record('role', array('id'=>$roleid));
1521 // Finally delete the role itself.
1522 $DB->delete_records('role', array('id'=>$roleid));
1524 // Trigger event.
1525 $event = \core\event\role_deleted::create(
1526 array(
1527 'context' => context_system::instance(),
1528 'objectid' => $roleid,
1529 'other' =>
1530 array(
1531 'shortname' => $role->shortname,
1532 'description' => $role->description,
1533 'archetype' => $role->archetype
1537 $event->add_record_snapshot('role', $role);
1538 $event->trigger();
1540 return true;
1544 * Function to write context specific overrides, or default capabilities.
1546 * NOTE: use $context->mark_dirty() after this
1548 * @param string $capability string name
1549 * @param int $permission CAP_ constants
1550 * @param int $roleid role id
1551 * @param int|context $contextid context id
1552 * @param bool $overwrite
1553 * @return bool always true or exception
1555 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1556 global $USER, $DB;
1558 if ($contextid instanceof context) {
1559 $context = $contextid;
1560 } else {
1561 $context = context::instance_by_id($contextid);
1564 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1565 unassign_capability($capability, $roleid, $context->id);
1566 return true;
1569 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1571 if ($existing and !$overwrite) { // We want to keep whatever is there already
1572 return true;
1575 $cap = new stdClass();
1576 $cap->contextid = $context->id;
1577 $cap->roleid = $roleid;
1578 $cap->capability = $capability;
1579 $cap->permission = $permission;
1580 $cap->timemodified = time();
1581 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1583 if ($existing) {
1584 $cap->id = $existing->id;
1585 $DB->update_record('role_capabilities', $cap);
1586 } else {
1587 if ($DB->record_exists('context', array('id'=>$context->id))) {
1588 $DB->insert_record('role_capabilities', $cap);
1591 return true;
1595 * Unassign a capability from a role.
1597 * NOTE: use $context->mark_dirty() after this
1599 * @param string $capability the name of the capability
1600 * @param int $roleid the role id
1601 * @param int|context $contextid null means all contexts
1602 * @return boolean true or exception
1604 function unassign_capability($capability, $roleid, $contextid = null) {
1605 global $DB;
1607 if (!empty($contextid)) {
1608 if ($contextid instanceof context) {
1609 $context = $contextid;
1610 } else {
1611 $context = context::instance_by_id($contextid);
1613 // delete from context rel, if this is the last override in this context
1614 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1615 } else {
1616 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1618 return true;
1622 * Get the roles that have a given capability assigned to it
1624 * This function does not resolve the actual permission of the capability.
1625 * It just checks for permissions and overrides.
1626 * Use get_roles_with_cap_in_context() if resolution is required.
1628 * @param string $capability capability name (string)
1629 * @param string $permission optional, the permission defined for this capability
1630 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1631 * @param stdClass $context null means any
1632 * @return array of role records
1634 function get_roles_with_capability($capability, $permission = null, $context = null) {
1635 global $DB;
1637 if ($context) {
1638 $contexts = $context->get_parent_context_ids(true);
1639 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1640 $contextsql = "AND rc.contextid $insql";
1641 } else {
1642 $params = array();
1643 $contextsql = '';
1646 if ($permission) {
1647 $permissionsql = " AND rc.permission = :permission";
1648 $params['permission'] = $permission;
1649 } else {
1650 $permissionsql = '';
1653 $sql = "SELECT r.*
1654 FROM {role} r
1655 WHERE r.id IN (SELECT rc.roleid
1656 FROM {role_capabilities} rc
1657 WHERE rc.capability = :capname
1658 $contextsql
1659 $permissionsql)";
1660 $params['capname'] = $capability;
1663 return $DB->get_records_sql($sql, $params);
1667 * This function makes a role-assignment (a role for a user in a particular context)
1669 * @param int $roleid the role of the id
1670 * @param int $userid userid
1671 * @param int|context $contextid id of the context
1672 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1673 * @param int $itemid id of enrolment/auth plugin
1674 * @param string $timemodified defaults to current time
1675 * @return int new/existing id of the assignment
1677 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1678 global $USER, $DB;
1680 // first of all detect if somebody is using old style parameters
1681 if ($contextid === 0 or is_numeric($component)) {
1682 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1685 // now validate all parameters
1686 if (empty($roleid)) {
1687 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1690 if (empty($userid)) {
1691 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1694 if ($itemid) {
1695 if (strpos($component, '_') === false) {
1696 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1698 } else {
1699 $itemid = 0;
1700 if ($component !== '' and strpos($component, '_') === false) {
1701 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1705 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1706 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1709 if ($contextid instanceof context) {
1710 $context = $contextid;
1711 } else {
1712 $context = context::instance_by_id($contextid, MUST_EXIST);
1715 if (!$timemodified) {
1716 $timemodified = time();
1719 // Check for existing entry
1720 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1722 if ($ras) {
1723 // role already assigned - this should not happen
1724 if (count($ras) > 1) {
1725 // very weird - remove all duplicates!
1726 $ra = array_shift($ras);
1727 foreach ($ras as $r) {
1728 $DB->delete_records('role_assignments', array('id'=>$r->id));
1730 } else {
1731 $ra = reset($ras);
1734 // actually there is no need to update, reset anything or trigger any event, so just return
1735 return $ra->id;
1738 // Create a new entry
1739 $ra = new stdClass();
1740 $ra->roleid = $roleid;
1741 $ra->contextid = $context->id;
1742 $ra->userid = $userid;
1743 $ra->component = $component;
1744 $ra->itemid = $itemid;
1745 $ra->timemodified = $timemodified;
1746 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1747 $ra->sortorder = 0;
1749 $ra->id = $DB->insert_record('role_assignments', $ra);
1751 // mark context as dirty - again expensive, but needed
1752 $context->mark_dirty();
1754 if (!empty($USER->id) && $USER->id == $userid) {
1755 // If the user is the current user, then do full reload of capabilities too.
1756 reload_all_capabilities();
1759 $event = \core\event\role_assigned::create(array(
1760 'context' => $context,
1761 'objectid' => $ra->roleid,
1762 'relateduserid' => $ra->userid,
1763 'other' => array(
1764 'id' => $ra->id,
1765 'component' => $ra->component,
1766 'itemid' => $ra->itemid
1769 $event->add_record_snapshot('role_assignments', $ra);
1770 $event->trigger();
1772 return $ra->id;
1776 * Removes one role assignment
1778 * @param int $roleid
1779 * @param int $userid
1780 * @param int $contextid
1781 * @param string $component
1782 * @param int $itemid
1783 * @return void
1785 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1786 // first make sure the params make sense
1787 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1788 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1791 if ($itemid) {
1792 if (strpos($component, '_') === false) {
1793 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1795 } else {
1796 $itemid = 0;
1797 if ($component !== '' and strpos($component, '_') === false) {
1798 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1802 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1806 * Removes multiple role assignments, parameters may contain:
1807 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1809 * @param array $params role assignment parameters
1810 * @param bool $subcontexts unassign in subcontexts too
1811 * @param bool $includemanual include manual role assignments too
1812 * @return void
1814 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1815 global $USER, $CFG, $DB;
1817 if (!$params) {
1818 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1821 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1822 foreach ($params as $key=>$value) {
1823 if (!in_array($key, $allowed)) {
1824 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1828 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1829 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1832 if ($includemanual) {
1833 if (!isset($params['component']) or $params['component'] === '') {
1834 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1838 if ($subcontexts) {
1839 if (empty($params['contextid'])) {
1840 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1844 $ras = $DB->get_records('role_assignments', $params);
1845 foreach($ras as $ra) {
1846 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1847 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1848 // this is a bit expensive but necessary
1849 $context->mark_dirty();
1850 // If the user is the current user, then do full reload of capabilities too.
1851 if (!empty($USER->id) && $USER->id == $ra->userid) {
1852 reload_all_capabilities();
1854 $event = \core\event\role_unassigned::create(array(
1855 'context' => $context,
1856 'objectid' => $ra->roleid,
1857 'relateduserid' => $ra->userid,
1858 'other' => array(
1859 'id' => $ra->id,
1860 'component' => $ra->component,
1861 'itemid' => $ra->itemid
1864 $event->add_record_snapshot('role_assignments', $ra);
1865 $event->trigger();
1868 unset($ras);
1870 // process subcontexts
1871 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1872 if ($params['contextid'] instanceof context) {
1873 $context = $params['contextid'];
1874 } else {
1875 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1878 if ($context) {
1879 $contexts = $context->get_child_contexts();
1880 $mparams = $params;
1881 foreach($contexts as $context) {
1882 $mparams['contextid'] = $context->id;
1883 $ras = $DB->get_records('role_assignments', $mparams);
1884 foreach($ras as $ra) {
1885 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1886 // this is a bit expensive but necessary
1887 $context->mark_dirty();
1888 // If the user is the current user, then do full reload of capabilities too.
1889 if (!empty($USER->id) && $USER->id == $ra->userid) {
1890 reload_all_capabilities();
1892 $event = \core\event\role_unassigned::create(
1893 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1894 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1895 $event->add_record_snapshot('role_assignments', $ra);
1896 $event->trigger();
1902 // do this once more for all manual role assignments
1903 if ($includemanual) {
1904 $params['component'] = '';
1905 role_unassign_all($params, $subcontexts, false);
1910 * Determines if a user is currently logged in
1912 * @category access
1914 * @return bool
1916 function isloggedin() {
1917 global $USER;
1919 return (!empty($USER->id));
1923 * Determines if a user is logged in as real guest user with username 'guest'.
1925 * @category access
1927 * @param int|object $user mixed user object or id, $USER if not specified
1928 * @return bool true if user is the real guest user, false if not logged in or other user
1930 function isguestuser($user = null) {
1931 global $USER, $DB, $CFG;
1933 // make sure we have the user id cached in config table, because we are going to use it a lot
1934 if (empty($CFG->siteguest)) {
1935 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1936 // guest does not exist yet, weird
1937 return false;
1939 set_config('siteguest', $guestid);
1941 if ($user === null) {
1942 $user = $USER;
1945 if ($user === null) {
1946 // happens when setting the $USER
1947 return false;
1949 } else if (is_numeric($user)) {
1950 return ($CFG->siteguest == $user);
1952 } else if (is_object($user)) {
1953 if (empty($user->id)) {
1954 return false; // not logged in means is not be guest
1955 } else {
1956 return ($CFG->siteguest == $user->id);
1959 } else {
1960 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1965 * Does user have a (temporary or real) guest access to course?
1967 * @category access
1969 * @param context $context
1970 * @param stdClass|int $user
1971 * @return bool
1973 function is_guest(context $context, $user = null) {
1974 global $USER;
1976 // first find the course context
1977 $coursecontext = $context->get_course_context();
1979 // make sure there is a real user specified
1980 if ($user === null) {
1981 $userid = isset($USER->id) ? $USER->id : 0;
1982 } else {
1983 $userid = is_object($user) ? $user->id : $user;
1986 if (isguestuser($userid)) {
1987 // can not inspect or be enrolled
1988 return true;
1991 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1992 // viewing users appear out of nowhere, they are neither guests nor participants
1993 return false;
1996 // consider only real active enrolments here
1997 if (is_enrolled($coursecontext, $user, '', true)) {
1998 return false;
2001 return true;
2005 * Returns true if the user has moodle/course:view capability in the course,
2006 * this is intended for admins, managers (aka small admins), inspectors, etc.
2008 * @category access
2010 * @param context $context
2011 * @param int|stdClass $user if null $USER is used
2012 * @param string $withcapability extra capability name
2013 * @return bool
2015 function is_viewing(context $context, $user = null, $withcapability = '') {
2016 // first find the course context
2017 $coursecontext = $context->get_course_context();
2019 if (isguestuser($user)) {
2020 // can not inspect
2021 return false;
2024 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
2025 // admins are allowed to inspect courses
2026 return false;
2029 if ($withcapability and !has_capability($withcapability, $context, $user)) {
2030 // site admins always have the capability, but the enrolment above blocks
2031 return false;
2034 return true;
2038 * Returns true if user is enrolled (is participating) in course
2039 * this is intended for students and teachers.
2041 * Since 2.2 the result for active enrolments and current user are cached.
2043 * @package core_enrol
2044 * @category access
2046 * @param context $context
2047 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
2048 * @param string $withcapability extra capability name
2049 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2050 * @return bool
2052 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
2053 global $USER, $DB;
2055 // first find the course context
2056 $coursecontext = $context->get_course_context();
2058 // make sure there is a real user specified
2059 if ($user === null) {
2060 $userid = isset($USER->id) ? $USER->id : 0;
2061 } else {
2062 $userid = is_object($user) ? $user->id : $user;
2065 if (empty($userid)) {
2066 // not-logged-in!
2067 return false;
2068 } else if (isguestuser($userid)) {
2069 // guest account can not be enrolled anywhere
2070 return false;
2073 if ($coursecontext->instanceid == SITEID) {
2074 // everybody participates on frontpage
2075 } else {
2076 // try cached info first - the enrolled flag is set only when active enrolment present
2077 if ($USER->id == $userid) {
2078 $coursecontext->reload_if_dirty();
2079 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
2080 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
2081 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2082 return false;
2084 return true;
2089 if ($onlyactive) {
2090 // look for active enrolments only
2091 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
2093 if ($until === false) {
2094 return false;
2097 if ($USER->id == $userid) {
2098 if ($until == 0) {
2099 $until = ENROL_MAX_TIMESTAMP;
2101 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
2102 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
2103 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
2104 remove_temp_course_roles($coursecontext);
2108 } else {
2109 // any enrolment is good for us here, even outdated, disabled or inactive
2110 $sql = "SELECT 'x'
2111 FROM {user_enrolments} ue
2112 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2113 JOIN {user} u ON u.id = ue.userid
2114 WHERE ue.userid = :userid AND u.deleted = 0";
2115 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2116 if (!$DB->record_exists_sql($sql, $params)) {
2117 return false;
2122 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2123 return false;
2126 return true;
2130 * Returns true if the user is able to access the course.
2132 * This function is in no way, shape, or form a substitute for require_login.
2133 * It should only be used in circumstances where it is not possible to call require_login
2134 * such as the navigation.
2136 * This function checks many of the methods of access to a course such as the view
2137 * capability, enrollments, and guest access. It also makes use of the cache
2138 * generated by require_login for guest access.
2140 * The flags within the $USER object that are used here should NEVER be used outside
2141 * of this function can_access_course and require_login. Doing so WILL break future
2142 * versions.
2144 * @param stdClass $course record
2145 * @param stdClass|int|null $user user record or id, current user if null
2146 * @param string $withcapability Check for this capability as well.
2147 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2148 * @return boolean Returns true if the user is able to access the course
2150 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
2151 global $DB, $USER;
2153 // this function originally accepted $coursecontext parameter
2154 if ($course instanceof context) {
2155 if ($course instanceof context_course) {
2156 debugging('deprecated context parameter, please use $course record');
2157 $coursecontext = $course;
2158 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2159 } else {
2160 debugging('Invalid context parameter, please use $course record');
2161 return false;
2163 } else {
2164 $coursecontext = context_course::instance($course->id);
2167 if (!isset($USER->id)) {
2168 // should never happen
2169 $USER->id = 0;
2170 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
2173 // make sure there is a user specified
2174 if ($user === null) {
2175 $userid = $USER->id;
2176 } else {
2177 $userid = is_object($user) ? $user->id : $user;
2179 unset($user);
2181 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2182 return false;
2185 if ($userid == $USER->id) {
2186 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2187 // the fact that somebody switched role means they can access the course no matter to what role they switched
2188 return true;
2192 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2193 return false;
2196 if (is_viewing($coursecontext, $userid)) {
2197 return true;
2200 if ($userid != $USER->id) {
2201 // for performance reasons we do not verify temporary guest access for other users, sorry...
2202 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2205 // === from here we deal only with $USER ===
2207 $coursecontext->reload_if_dirty();
2209 if (isset($USER->enrol['enrolled'][$course->id])) {
2210 if ($USER->enrol['enrolled'][$course->id] > time()) {
2211 return true;
2214 if (isset($USER->enrol['tempguest'][$course->id])) {
2215 if ($USER->enrol['tempguest'][$course->id] > time()) {
2216 return true;
2220 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2221 return true;
2224 // if not enrolled try to gain temporary guest access
2225 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2226 $enrols = enrol_get_plugins(true);
2227 foreach($instances as $instance) {
2228 if (!isset($enrols[$instance->enrol])) {
2229 continue;
2231 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2232 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2233 if ($until !== false and $until > time()) {
2234 $USER->enrol['tempguest'][$course->id] = $until;
2235 return true;
2238 if (isset($USER->enrol['tempguest'][$course->id])) {
2239 unset($USER->enrol['tempguest'][$course->id]);
2240 remove_temp_course_roles($coursecontext);
2243 return false;
2247 * Returns array with sql code and parameters returning all ids
2248 * of users enrolled into course.
2250 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2252 * @package core_enrol
2253 * @category access
2255 * @param context $context
2256 * @param string $withcapability
2257 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2258 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2259 * @return array list($sql, $params)
2261 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2262 global $DB, $CFG;
2264 // use unique prefix just in case somebody makes some SQL magic with the result
2265 static $i = 0;
2266 $i++;
2267 $prefix = 'eu'.$i.'_';
2269 // first find the course context
2270 $coursecontext = $context->get_course_context();
2272 $isfrontpage = ($coursecontext->instanceid == SITEID);
2274 $joins = array();
2275 $wheres = array();
2276 $params = array();
2278 list($contextids, $contextpaths) = get_context_info_list($context);
2280 // get all relevant capability info for all roles
2281 if ($withcapability) {
2282 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2283 $cparams['cap'] = $withcapability;
2285 $defs = array();
2286 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2287 FROM {role_capabilities} rc
2288 JOIN {context} ctx on rc.contextid = ctx.id
2289 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2290 $rcs = $DB->get_records_sql($sql, $cparams);
2291 foreach ($rcs as $rc) {
2292 $defs[$rc->path][$rc->roleid] = $rc->permission;
2295 $access = array();
2296 if (!empty($defs)) {
2297 foreach ($contextpaths as $path) {
2298 if (empty($defs[$path])) {
2299 continue;
2301 foreach($defs[$path] as $roleid => $perm) {
2302 if ($perm == CAP_PROHIBIT) {
2303 $access[$roleid] = CAP_PROHIBIT;
2304 continue;
2306 if (!isset($access[$roleid])) {
2307 $access[$roleid] = (int)$perm;
2313 unset($defs);
2315 // make lists of roles that are needed and prohibited
2316 $needed = array(); // one of these is enough
2317 $prohibited = array(); // must not have any of these
2318 foreach ($access as $roleid => $perm) {
2319 if ($perm == CAP_PROHIBIT) {
2320 unset($needed[$roleid]);
2321 $prohibited[$roleid] = true;
2322 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2323 $needed[$roleid] = true;
2327 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2328 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2330 $nobody = false;
2332 if ($isfrontpage) {
2333 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2334 $nobody = true;
2335 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2336 // everybody not having prohibit has the capability
2337 $needed = array();
2338 } else if (empty($needed)) {
2339 $nobody = true;
2341 } else {
2342 if (!empty($prohibited[$defaultuserroleid])) {
2343 $nobody = true;
2344 } else if (!empty($needed[$defaultuserroleid])) {
2345 // everybody not having prohibit has the capability
2346 $needed = array();
2347 } else if (empty($needed)) {
2348 $nobody = true;
2352 if ($nobody) {
2353 // nobody can match so return some SQL that does not return any results
2354 $wheres[] = "1 = 2";
2356 } else {
2358 if ($needed) {
2359 $ctxids = implode(',', $contextids);
2360 $roleids = implode(',', array_keys($needed));
2361 $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))";
2364 if ($prohibited) {
2365 $ctxids = implode(',', $contextids);
2366 $roleids = implode(',', array_keys($prohibited));
2367 $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))";
2368 $wheres[] = "{$prefix}ra4.id IS NULL";
2371 if ($groupid) {
2372 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2373 $params["{$prefix}gmid"] = $groupid;
2377 } else {
2378 if ($groupid) {
2379 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2380 $params["{$prefix}gmid"] = $groupid;
2384 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2385 $params["{$prefix}guestid"] = $CFG->siteguest;
2387 if ($isfrontpage) {
2388 // all users are "enrolled" on the frontpage
2389 } else {
2390 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2391 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2392 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2394 if ($onlyactive) {
2395 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2396 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2397 $now = round(time(), -2); // rounding helps caching in DB
2398 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2399 $prefix.'active'=>ENROL_USER_ACTIVE,
2400 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2404 $joins = implode("\n", $joins);
2405 $wheres = "WHERE ".implode(" AND ", $wheres);
2407 $sql = "SELECT DISTINCT {$prefix}u.id
2408 FROM {user} {$prefix}u
2409 $joins
2410 $wheres";
2412 return array($sql, $params);
2416 * Returns list of users enrolled into course.
2418 * @package core_enrol
2419 * @category access
2421 * @param context $context
2422 * @param string $withcapability
2423 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2424 * @param string $userfields requested user record fields
2425 * @param string $orderby
2426 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2427 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2428 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2429 * @return array of user records
2431 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
2432 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
2433 global $DB;
2435 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2436 $sql = "SELECT $userfields
2437 FROM {user} u
2438 JOIN ($esql) je ON je.id = u.id
2439 WHERE u.deleted = 0";
2441 if ($orderby) {
2442 $sql = "$sql ORDER BY $orderby";
2443 } else {
2444 list($sort, $sortparams) = users_order_by_sql('u');
2445 $sql = "$sql ORDER BY $sort";
2446 $params = array_merge($params, $sortparams);
2449 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2453 * Counts list of users enrolled into course (as per above function)
2455 * @package core_enrol
2456 * @category access
2458 * @param context $context
2459 * @param string $withcapability
2460 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2461 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2462 * @return array of user records
2464 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2465 global $DB;
2467 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2468 $sql = "SELECT count(u.id)
2469 FROM {user} u
2470 JOIN ($esql) je ON je.id = u.id
2471 WHERE u.deleted = 0";
2473 return $DB->count_records_sql($sql, $params);
2477 * Loads the capability definitions for the component (from file).
2479 * Loads the capability definitions for the component (from file). If no
2480 * capabilities are defined for the component, we simply return an empty array.
2482 * @access private
2483 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2484 * @return array array of capabilities
2486 function load_capability_def($component) {
2487 $defpath = core_component::get_component_directory($component).'/db/access.php';
2489 $capabilities = array();
2490 if (file_exists($defpath)) {
2491 require($defpath);
2492 if (!empty(${$component.'_capabilities'})) {
2493 // BC capability array name
2494 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2495 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2496 $capabilities = ${$component.'_capabilities'};
2500 return $capabilities;
2504 * Gets the capabilities that have been cached in the database for this component.
2506 * @access private
2507 * @param string $component - examples: 'moodle', 'mod_forum'
2508 * @return array array of capabilities
2510 function get_cached_capabilities($component = 'moodle') {
2511 global $DB;
2512 return $DB->get_records('capabilities', array('component'=>$component));
2516 * Returns default capabilities for given role archetype.
2518 * @param string $archetype role archetype
2519 * @return array
2521 function get_default_capabilities($archetype) {
2522 global $DB;
2524 if (!$archetype) {
2525 return array();
2528 $alldefs = array();
2529 $defaults = array();
2530 $components = array();
2531 $allcaps = $DB->get_records('capabilities');
2533 foreach ($allcaps as $cap) {
2534 if (!in_array($cap->component, $components)) {
2535 $components[] = $cap->component;
2536 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2539 foreach($alldefs as $name=>$def) {
2540 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2541 if (isset($def['archetypes'])) {
2542 if (isset($def['archetypes'][$archetype])) {
2543 $defaults[$name] = $def['archetypes'][$archetype];
2545 // 'legacy' is for backward compatibility with 1.9 access.php
2546 } else {
2547 if (isset($def['legacy'][$archetype])) {
2548 $defaults[$name] = $def['legacy'][$archetype];
2553 return $defaults;
2557 * Return default roles that can be assigned, overridden or switched
2558 * by give role archetype.
2560 * @param string $type assign|override|switch
2561 * @param string $archetype
2562 * @return array of role ids
2564 function get_default_role_archetype_allows($type, $archetype) {
2565 global $DB;
2567 if (empty($archetype)) {
2568 return array();
2571 $roles = $DB->get_records('role');
2572 $archetypemap = array();
2573 foreach ($roles as $role) {
2574 if ($role->archetype) {
2575 $archetypemap[$role->archetype][$role->id] = $role->id;
2579 $defaults = array(
2580 'assign' => array(
2581 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2582 'coursecreator' => array(),
2583 'editingteacher' => array('teacher', 'student'),
2584 'teacher' => array(),
2585 'student' => array(),
2586 'guest' => array(),
2587 'user' => array(),
2588 'frontpage' => array(),
2590 'override' => array(
2591 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2592 'coursecreator' => array(),
2593 'editingteacher' => array('teacher', 'student', 'guest'),
2594 'teacher' => array(),
2595 'student' => array(),
2596 'guest' => array(),
2597 'user' => array(),
2598 'frontpage' => array(),
2600 'switch' => array(
2601 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2602 'coursecreator' => array(),
2603 'editingteacher' => array('teacher', 'student', 'guest'),
2604 'teacher' => array('student', 'guest'),
2605 'student' => array(),
2606 'guest' => array(),
2607 'user' => array(),
2608 'frontpage' => array(),
2612 if (!isset($defaults[$type][$archetype])) {
2613 debugging("Unknown type '$type'' or archetype '$archetype''");
2614 return array();
2617 $return = array();
2618 foreach ($defaults[$type][$archetype] as $at) {
2619 if (isset($archetypemap[$at])) {
2620 foreach ($archetypemap[$at] as $roleid) {
2621 $return[$roleid] = $roleid;
2626 return $return;
2630 * Reset role capabilities to default according to selected role archetype.
2631 * If no archetype selected, removes all capabilities.
2633 * This applies to capabilities that are assigned to the role (that you could
2634 * edit in the 'define roles' interface), and not to any capability overrides
2635 * in different locations.
2637 * @param int $roleid ID of role to reset capabilities for
2639 function reset_role_capabilities($roleid) {
2640 global $DB;
2642 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2643 $defaultcaps = get_default_capabilities($role->archetype);
2645 $systemcontext = context_system::instance();
2647 $DB->delete_records('role_capabilities',
2648 array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2650 foreach($defaultcaps as $cap=>$permission) {
2651 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2654 // Mark the system context dirty.
2655 context_system::instance()->mark_dirty();
2659 * Updates the capabilities table with the component capability definitions.
2660 * If no parameters are given, the function updates the core moodle
2661 * capabilities.
2663 * Note that the absence of the db/access.php capabilities definition file
2664 * will cause any stored capabilities for the component to be removed from
2665 * the database.
2667 * @access private
2668 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2669 * @return boolean true if success, exception in case of any problems
2671 function update_capabilities($component = 'moodle') {
2672 global $DB, $OUTPUT;
2674 $storedcaps = array();
2676 $filecaps = load_capability_def($component);
2677 foreach($filecaps as $capname=>$unused) {
2678 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2679 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2683 $cachedcaps = get_cached_capabilities($component);
2684 if ($cachedcaps) {
2685 foreach ($cachedcaps as $cachedcap) {
2686 array_push($storedcaps, $cachedcap->name);
2687 // update risk bitmasks and context levels in existing capabilities if needed
2688 if (array_key_exists($cachedcap->name, $filecaps)) {
2689 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2690 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2692 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2693 $updatecap = new stdClass();
2694 $updatecap->id = $cachedcap->id;
2695 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2696 $DB->update_record('capabilities', $updatecap);
2698 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2699 $updatecap = new stdClass();
2700 $updatecap->id = $cachedcap->id;
2701 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2702 $DB->update_record('capabilities', $updatecap);
2705 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2706 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2708 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2709 $updatecap = new stdClass();
2710 $updatecap->id = $cachedcap->id;
2711 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2712 $DB->update_record('capabilities', $updatecap);
2718 // Are there new capabilities in the file definition?
2719 $newcaps = array();
2721 foreach ($filecaps as $filecap => $def) {
2722 if (!$storedcaps ||
2723 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2724 if (!array_key_exists('riskbitmask', $def)) {
2725 $def['riskbitmask'] = 0; // no risk if not specified
2727 $newcaps[$filecap] = $def;
2730 // Add new capabilities to the stored definition.
2731 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2732 foreach ($newcaps as $capname => $capdef) {
2733 $capability = new stdClass();
2734 $capability->name = $capname;
2735 $capability->captype = $capdef['captype'];
2736 $capability->contextlevel = $capdef['contextlevel'];
2737 $capability->component = $component;
2738 $capability->riskbitmask = $capdef['riskbitmask'];
2740 $DB->insert_record('capabilities', $capability, false);
2742 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2743 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2744 foreach ($rolecapabilities as $rolecapability){
2745 //assign_capability will update rather than insert if capability exists
2746 if (!assign_capability($capname, $rolecapability->permission,
2747 $rolecapability->roleid, $rolecapability->contextid, true)){
2748 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2752 // we ignore archetype key if we have cloned permissions
2753 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2754 assign_legacy_capabilities($capname, $capdef['archetypes']);
2755 // 'legacy' is for backward compatibility with 1.9 access.php
2756 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2757 assign_legacy_capabilities($capname, $capdef['legacy']);
2760 // Are there any capabilities that have been removed from the file
2761 // definition that we need to delete from the stored capabilities and
2762 // role assignments?
2763 capabilities_cleanup($component, $filecaps);
2765 // reset static caches
2766 accesslib_clear_all_caches(false);
2768 return true;
2772 * Deletes cached capabilities that are no longer needed by the component.
2773 * Also unassigns these capabilities from any roles that have them.
2774 * NOTE: this function is called from lib/db/upgrade.php
2776 * @access private
2777 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2778 * @param array $newcapdef array of the new capability definitions that will be
2779 * compared with the cached capabilities
2780 * @return int number of deprecated capabilities that have been removed
2782 function capabilities_cleanup($component, $newcapdef = null) {
2783 global $DB;
2785 $removedcount = 0;
2787 if ($cachedcaps = get_cached_capabilities($component)) {
2788 foreach ($cachedcaps as $cachedcap) {
2789 if (empty($newcapdef) ||
2790 array_key_exists($cachedcap->name, $newcapdef) === false) {
2792 // Remove from capabilities cache.
2793 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2794 $removedcount++;
2795 // Delete from roles.
2796 if ($roles = get_roles_with_capability($cachedcap->name)) {
2797 foreach($roles as $role) {
2798 if (!unassign_capability($cachedcap->name, $role->id)) {
2799 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2803 } // End if.
2806 return $removedcount;
2810 * Returns an array of all the known types of risk
2811 * The array keys can be used, for example as CSS class names, or in calls to
2812 * print_risk_icon. The values are the corresponding RISK_ constants.
2814 * @return array all the known types of risk.
2816 function get_all_risks() {
2817 return array(
2818 'riskmanagetrust' => RISK_MANAGETRUST,
2819 'riskconfig' => RISK_CONFIG,
2820 'riskxss' => RISK_XSS,
2821 'riskpersonal' => RISK_PERSONAL,
2822 'riskspam' => RISK_SPAM,
2823 'riskdataloss' => RISK_DATALOSS,
2828 * Return a link to moodle docs for a given capability name
2830 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2831 * @return string the human-readable capability name as a link to Moodle Docs.
2833 function get_capability_docs_link($capability) {
2834 $url = get_docs_url('Capabilities/' . $capability->name);
2835 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2839 * This function pulls out all the resolved capabilities (overrides and
2840 * defaults) of a role used in capability overrides in contexts at a given
2841 * context.
2843 * @param int $roleid
2844 * @param context $context
2845 * @param string $cap capability, optional, defaults to ''
2846 * @return array Array of capabilities
2848 function role_context_capabilities($roleid, context $context, $cap = '') {
2849 global $DB;
2851 $contexts = $context->get_parent_context_ids(true);
2852 $contexts = '('.implode(',', $contexts).')';
2854 $params = array($roleid);
2856 if ($cap) {
2857 $search = " AND rc.capability = ? ";
2858 $params[] = $cap;
2859 } else {
2860 $search = '';
2863 $sql = "SELECT rc.*
2864 FROM {role_capabilities} rc, {context} c
2865 WHERE rc.contextid in $contexts
2866 AND rc.roleid = ?
2867 AND rc.contextid = c.id $search
2868 ORDER BY c.contextlevel DESC, rc.capability DESC";
2870 $capabilities = array();
2872 if ($records = $DB->get_records_sql($sql, $params)) {
2873 // We are traversing via reverse order.
2874 foreach ($records as $record) {
2875 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2876 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2877 $capabilities[$record->capability] = $record->permission;
2881 return $capabilities;
2885 * Constructs array with contextids as first parameter and context paths,
2886 * in both cases bottom top including self.
2888 * @access private
2889 * @param context $context
2890 * @return array
2892 function get_context_info_list(context $context) {
2893 $contextids = explode('/', ltrim($context->path, '/'));
2894 $contextpaths = array();
2895 $contextids2 = $contextids;
2896 while ($contextids2) {
2897 $contextpaths[] = '/' . implode('/', $contextids2);
2898 array_pop($contextids2);
2900 return array($contextids, $contextpaths);
2904 * Check if context is the front page context or a context inside it
2906 * Returns true if this context is the front page context, or a context inside it,
2907 * otherwise false.
2909 * @param context $context a context object.
2910 * @return bool
2912 function is_inside_frontpage(context $context) {
2913 $frontpagecontext = context_course::instance(SITEID);
2914 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2918 * Returns capability information (cached)
2920 * @param string $capabilityname
2921 * @return stdClass or null if capability not found
2923 function get_capability_info($capabilityname) {
2924 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2926 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2928 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2929 $ACCESSLIB_PRIVATE->capabilities = array();
2930 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2931 foreach ($caps as $cap) {
2932 $capname = $cap->name;
2933 unset($cap->id);
2934 unset($cap->name);
2935 $cap->riskbitmask = (int)$cap->riskbitmask;
2936 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2940 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2944 * Returns the human-readable, translated version of the capability.
2945 * Basically a big switch statement.
2947 * @param string $capabilityname e.g. mod/choice:readresponses
2948 * @return string
2950 function get_capability_string($capabilityname) {
2952 // Typical capability name is 'plugintype/pluginname:capabilityname'
2953 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2955 if ($type === 'moodle') {
2956 $component = 'core_role';
2957 } else if ($type === 'quizreport') {
2958 //ugly hack!!
2959 $component = 'quiz_'.$name;
2960 } else {
2961 $component = $type.'_'.$name;
2964 $stringname = $name.':'.$capname;
2966 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2967 return get_string($stringname, $component);
2970 $dir = core_component::get_component_directory($component);
2971 if (!file_exists($dir)) {
2972 // plugin broken or does not exist, do not bother with printing of debug message
2973 return $capabilityname.' ???';
2976 // something is wrong in plugin, better print debug
2977 return get_string($stringname, $component);
2981 * This gets the mod/block/course/core etc strings.
2983 * @param string $component
2984 * @param int $contextlevel
2985 * @return string|bool String is success, false if failed
2987 function get_component_string($component, $contextlevel) {
2989 if ($component === 'moodle' or $component === 'core') {
2990 switch ($contextlevel) {
2991 // TODO: this should probably use context level names instead
2992 case CONTEXT_SYSTEM: return get_string('coresystem');
2993 case CONTEXT_USER: return get_string('users');
2994 case CONTEXT_COURSECAT: return get_string('categories');
2995 case CONTEXT_COURSE: return get_string('course');
2996 case CONTEXT_MODULE: return get_string('activities');
2997 case CONTEXT_BLOCK: return get_string('block');
2998 default: print_error('unknowncontext');
3002 list($type, $name) = core_component::normalize_component($component);
3003 $dir = core_component::get_plugin_directory($type, $name);
3004 if (!file_exists($dir)) {
3005 // plugin not installed, bad luck, there is no way to find the name
3006 return $component.' ???';
3009 switch ($type) {
3010 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
3011 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
3012 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
3013 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
3014 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
3015 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
3016 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
3017 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
3018 case 'mod':
3019 if (get_string_manager()->string_exists('pluginname', $component)) {
3020 return get_string('activity').': '.get_string('pluginname', $component);
3021 } else {
3022 return get_string('activity').': '.get_string('modulename', $component);
3024 default: return get_string('pluginname', $component);
3029 * Gets the list of roles assigned to this context and up (parents)
3030 * from the list of roles that are visible on user profile page
3031 * and participants page.
3033 * @param context $context
3034 * @return array
3036 function get_profile_roles(context $context) {
3037 global $CFG, $DB;
3039 if (empty($CFG->profileroles)) {
3040 return array();
3043 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
3044 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
3045 $params = array_merge($params, $cparams);
3047 if ($coursecontext = $context->get_course_context(false)) {
3048 $params['coursecontext'] = $coursecontext->id;
3049 } else {
3050 $params['coursecontext'] = 0;
3053 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3054 FROM {role_assignments} ra, {role} r
3055 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3056 WHERE r.id = ra.roleid
3057 AND ra.contextid $contextlist
3058 AND r.id $rallowed
3059 ORDER BY r.sortorder ASC";
3061 return $DB->get_records_sql($sql, $params);
3065 * Gets the list of roles assigned to this context and up (parents)
3067 * @param context $context
3068 * @return array
3070 function get_roles_used_in_context(context $context) {
3071 global $DB;
3073 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
3075 if ($coursecontext = $context->get_course_context(false)) {
3076 $params['coursecontext'] = $coursecontext->id;
3077 } else {
3078 $params['coursecontext'] = 0;
3081 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3082 FROM {role_assignments} ra, {role} r
3083 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3084 WHERE r.id = ra.roleid
3085 AND ra.contextid $contextlist
3086 ORDER BY r.sortorder ASC";
3088 return $DB->get_records_sql($sql, $params);
3092 * This function is used to print roles column in user profile page.
3093 * It is using the CFG->profileroles to limit the list to only interesting roles.
3094 * (The permission tab has full details of user role assignments.)
3096 * @param int $userid
3097 * @param int $courseid
3098 * @return string
3100 function get_user_roles_in_course($userid, $courseid) {
3101 global $CFG, $DB;
3103 if (empty($CFG->profileroles)) {
3104 return '';
3107 if ($courseid == SITEID) {
3108 $context = context_system::instance();
3109 } else {
3110 $context = context_course::instance($courseid);
3113 if (empty($CFG->profileroles)) {
3114 return array();
3117 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
3118 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
3119 $params = array_merge($params, $cparams);
3121 if ($coursecontext = $context->get_course_context(false)) {
3122 $params['coursecontext'] = $coursecontext->id;
3123 } else {
3124 $params['coursecontext'] = 0;
3127 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3128 FROM {role_assignments} ra, {role} r
3129 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3130 WHERE r.id = ra.roleid
3131 AND ra.contextid $contextlist
3132 AND r.id $rallowed
3133 AND ra.userid = :userid
3134 ORDER BY r.sortorder ASC";
3135 $params['userid'] = $userid;
3137 $rolestring = '';
3139 if ($roles = $DB->get_records_sql($sql, $params)) {
3140 $rolenames = role_fix_names($roles, $context, ROLENAME_ALIAS, true); // Substitute aliases
3142 foreach ($rolenames as $roleid => $rolename) {
3143 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
3145 $rolestring = implode(',', $rolenames);
3148 return $rolestring;
3152 * Checks if a user can assign users to a particular role in this context
3154 * @param context $context
3155 * @param int $targetroleid - the id of the role you want to assign users to
3156 * @return boolean
3158 function user_can_assign(context $context, $targetroleid) {
3159 global $DB;
3161 // First check to see if the user is a site administrator.
3162 if (is_siteadmin()) {
3163 return true;
3166 // Check if user has override capability.
3167 // If not return false.
3168 if (!has_capability('moodle/role:assign', $context)) {
3169 return false;
3171 // pull out all active roles of this user from this context(or above)
3172 if ($userroles = get_user_roles($context)) {
3173 foreach ($userroles as $userrole) {
3174 // if any in the role_allow_override table, then it's ok
3175 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
3176 return true;
3181 return false;
3185 * Returns all site roles in correct sort order.
3187 * Note: this method does not localise role names or descriptions,
3188 * use role_get_names() if you need role names.
3190 * @param context $context optional context for course role name aliases
3191 * @return array of role records with optional coursealias property
3193 function get_all_roles(context $context = null) {
3194 global $DB;
3196 if (!$context or !$coursecontext = $context->get_course_context(false)) {
3197 $coursecontext = null;
3200 if ($coursecontext) {
3201 $sql = "SELECT r.*, rn.name AS coursealias
3202 FROM {role} r
3203 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3204 ORDER BY r.sortorder ASC";
3205 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
3207 } else {
3208 return $DB->get_records('role', array(), 'sortorder ASC');
3213 * Returns roles of a specified archetype
3215 * @param string $archetype
3216 * @return array of full role records
3218 function get_archetype_roles($archetype) {
3219 global $DB;
3220 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
3224 * Gets all the user roles assigned in this context, or higher contexts
3225 * this is mainly used when checking if a user can assign a role, or overriding a role
3226 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3227 * allow_override tables
3229 * @param context $context
3230 * @param int $userid
3231 * @param bool $checkparentcontexts defaults to true
3232 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
3233 * @return array
3235 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
3236 global $USER, $DB;
3238 if (empty($userid)) {
3239 if (empty($USER->id)) {
3240 return array();
3242 $userid = $USER->id;
3245 if ($checkparentcontexts) {
3246 $contextids = $context->get_parent_context_ids();
3247 } else {
3248 $contextids = array();
3250 $contextids[] = $context->id;
3252 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3254 array_unshift($params, $userid);
3256 $sql = "SELECT ra.*, r.name, r.shortname
3257 FROM {role_assignments} ra, {role} r, {context} c
3258 WHERE ra.userid = ?
3259 AND ra.roleid = r.id
3260 AND ra.contextid = c.id
3261 AND ra.contextid $contextids
3262 ORDER BY $order";
3264 return $DB->get_records_sql($sql ,$params);
3268 * Like get_user_roles, but adds in the authenticated user role, and the front
3269 * page roles, if applicable.
3271 * @param context $context the context.
3272 * @param int $userid optional. Defaults to $USER->id
3273 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3275 function get_user_roles_with_special(context $context, $userid = 0) {
3276 global $CFG, $USER;
3278 if (empty($userid)) {
3279 if (empty($USER->id)) {
3280 return array();
3282 $userid = $USER->id;
3285 $ras = get_user_roles($context, $userid);
3287 // Add front-page role if relevant.
3288 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3289 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3290 is_inside_frontpage($context);
3291 if ($defaultfrontpageroleid && $isfrontpage) {
3292 $frontpagecontext = context_course::instance(SITEID);
3293 $ra = new stdClass();
3294 $ra->userid = $userid;
3295 $ra->contextid = $frontpagecontext->id;
3296 $ra->roleid = $defaultfrontpageroleid;
3297 $ras[] = $ra;
3300 // Add authenticated user role if relevant.
3301 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3302 if ($defaultuserroleid && !isguestuser($userid)) {
3303 $systemcontext = context_system::instance();
3304 $ra = new stdClass();
3305 $ra->userid = $userid;
3306 $ra->contextid = $systemcontext->id;
3307 $ra->roleid = $defaultuserroleid;
3308 $ras[] = $ra;
3311 return $ras;
3315 * Creates a record in the role_allow_override table
3317 * @param int $sroleid source roleid
3318 * @param int $troleid target roleid
3319 * @return void
3321 function allow_override($sroleid, $troleid) {
3322 global $DB;
3324 $record = new stdClass();
3325 $record->roleid = $sroleid;
3326 $record->allowoverride = $troleid;
3327 $DB->insert_record('role_allow_override', $record);
3331 * Creates a record in the role_allow_assign table
3333 * @param int $fromroleid source roleid
3334 * @param int $targetroleid target roleid
3335 * @return void
3337 function allow_assign($fromroleid, $targetroleid) {
3338 global $DB;
3340 $record = new stdClass();
3341 $record->roleid = $fromroleid;
3342 $record->allowassign = $targetroleid;
3343 $DB->insert_record('role_allow_assign', $record);
3347 * Creates a record in the role_allow_switch table
3349 * @param int $fromroleid source roleid
3350 * @param int $targetroleid target roleid
3351 * @return void
3353 function allow_switch($fromroleid, $targetroleid) {
3354 global $DB;
3356 $record = new stdClass();
3357 $record->roleid = $fromroleid;
3358 $record->allowswitch = $targetroleid;
3359 $DB->insert_record('role_allow_switch', $record);
3363 * Gets a list of roles that this user can assign in this context
3365 * @param context $context the context.
3366 * @param int $rolenamedisplay the type of role name to display. One of the
3367 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3368 * @param bool $withusercounts if true, count the number of users with each role.
3369 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3370 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3371 * if $withusercounts is true, returns a list of three arrays,
3372 * $rolenames, $rolecounts, and $nameswithcounts.
3374 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3375 global $USER, $DB;
3377 // make sure there is a real user specified
3378 if ($user === null) {
3379 $userid = isset($USER->id) ? $USER->id : 0;
3380 } else {
3381 $userid = is_object($user) ? $user->id : $user;
3384 if (!has_capability('moodle/role:assign', $context, $userid)) {
3385 if ($withusercounts) {
3386 return array(array(), array(), array());
3387 } else {
3388 return array();
3392 $params = array();
3393 $extrafields = '';
3395 if ($withusercounts) {
3396 $extrafields = ', (SELECT count(u.id)
3397 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3398 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3399 ) AS usercount';
3400 $params['conid'] = $context->id;
3403 if (is_siteadmin($userid)) {
3404 // show all roles allowed in this context to admins
3405 $assignrestriction = "";
3406 } else {
3407 $parents = $context->get_parent_context_ids(true);
3408 $contexts = implode(',' , $parents);
3409 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3410 FROM {role_allow_assign} raa
3411 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3412 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3413 ) ar ON ar.id = r.id";
3414 $params['userid'] = $userid;
3416 $params['contextlevel'] = $context->contextlevel;
3418 if ($coursecontext = $context->get_course_context(false)) {
3419 $params['coursecontext'] = $coursecontext->id;
3420 } else {
3421 $params['coursecontext'] = 0; // no course aliases
3422 $coursecontext = null;
3424 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3425 FROM {role} r
3426 $assignrestriction
3427 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3428 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3429 ORDER BY r.sortorder ASC";
3430 $roles = $DB->get_records_sql($sql, $params);
3432 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3434 if (!$withusercounts) {
3435 return $rolenames;
3438 $rolecounts = array();
3439 $nameswithcounts = array();
3440 foreach ($roles as $role) {
3441 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3442 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3444 return array($rolenames, $rolecounts, $nameswithcounts);
3448 * Gets a list of roles that this user can switch to in a context
3450 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3451 * This function just process the contents of the role_allow_switch table. You also need to
3452 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3454 * @param context $context a context.
3455 * @return array an array $roleid => $rolename.
3457 function get_switchable_roles(context $context) {
3458 global $USER, $DB;
3460 $params = array();
3461 $extrajoins = '';
3462 $extrawhere = '';
3463 if (!is_siteadmin()) {
3464 // Admins are allowed to switch to any role with.
3465 // Others are subject to the additional constraint that the switch-to role must be allowed by
3466 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3467 $parents = $context->get_parent_context_ids(true);
3468 $contexts = implode(',' , $parents);
3470 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3471 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3472 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3473 $params['userid'] = $USER->id;
3476 if ($coursecontext = $context->get_course_context(false)) {
3477 $params['coursecontext'] = $coursecontext->id;
3478 } else {
3479 $params['coursecontext'] = 0; // no course aliases
3480 $coursecontext = null;
3483 $query = "
3484 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3485 FROM (SELECT DISTINCT rc.roleid
3486 FROM {role_capabilities} rc
3487 $extrajoins
3488 $extrawhere) idlist
3489 JOIN {role} r ON r.id = idlist.roleid
3490 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3491 ORDER BY r.sortorder";
3492 $roles = $DB->get_records_sql($query, $params);
3494 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3498 * Gets a list of roles that this user can override in this context.
3500 * @param context $context the context.
3501 * @param int $rolenamedisplay the type of role name to display. One of the
3502 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3503 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3504 * @return array if $withcounts is false, then an array $roleid => $rolename.
3505 * if $withusercounts is true, returns a list of three arrays,
3506 * $rolenames, $rolecounts, and $nameswithcounts.
3508 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3509 global $USER, $DB;
3511 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3512 if ($withcounts) {
3513 return array(array(), array(), array());
3514 } else {
3515 return array();
3519 $parents = $context->get_parent_context_ids(true);
3520 $contexts = implode(',' , $parents);
3522 $params = array();
3523 $extrafields = '';
3525 $params['userid'] = $USER->id;
3526 if ($withcounts) {
3527 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3528 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3529 $params['conid'] = $context->id;
3532 if ($coursecontext = $context->get_course_context(false)) {
3533 $params['coursecontext'] = $coursecontext->id;
3534 } else {
3535 $params['coursecontext'] = 0; // no course aliases
3536 $coursecontext = null;
3539 if (is_siteadmin()) {
3540 // show all roles to admins
3541 $roles = $DB->get_records_sql("
3542 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3543 FROM {role} ro
3544 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3545 ORDER BY ro.sortorder ASC", $params);
3547 } else {
3548 $roles = $DB->get_records_sql("
3549 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3550 FROM {role} ro
3551 JOIN (SELECT DISTINCT r.id
3552 FROM {role} r
3553 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3554 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3555 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3556 ) inline_view ON ro.id = inline_view.id
3557 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3558 ORDER BY ro.sortorder ASC", $params);
3561 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3563 if (!$withcounts) {
3564 return $rolenames;
3567 $rolecounts = array();
3568 $nameswithcounts = array();
3569 foreach ($roles as $role) {
3570 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3571 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3573 return array($rolenames, $rolecounts, $nameswithcounts);
3577 * Create a role menu suitable for default role selection in enrol plugins.
3579 * @package core_enrol
3581 * @param context $context
3582 * @param int $addroleid current or default role - always added to list
3583 * @return array roleid=>localised role name
3585 function get_default_enrol_roles(context $context, $addroleid = null) {
3586 global $DB;
3588 $params = array('contextlevel'=>CONTEXT_COURSE);
3590 if ($coursecontext = $context->get_course_context(false)) {
3591 $params['coursecontext'] = $coursecontext->id;
3592 } else {
3593 $params['coursecontext'] = 0; // no course names
3594 $coursecontext = null;
3597 if ($addroleid) {
3598 $addrole = "OR r.id = :addroleid";
3599 $params['addroleid'] = $addroleid;
3600 } else {
3601 $addrole = "";
3604 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3605 FROM {role} r
3606 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3607 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3608 WHERE rcl.id IS NOT NULL $addrole
3609 ORDER BY sortorder DESC";
3611 $roles = $DB->get_records_sql($sql, $params);
3613 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3617 * Return context levels where this role is assignable.
3619 * @param integer $roleid the id of a role.
3620 * @return array list of the context levels at which this role may be assigned.
3622 function get_role_contextlevels($roleid) {
3623 global $DB;
3624 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3625 'contextlevel', 'id,contextlevel');
3629 * Return roles suitable for assignment at the specified context level.
3631 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3633 * @param integer $contextlevel a contextlevel.
3634 * @return array list of role ids that are assignable at this context level.
3636 function get_roles_for_contextlevels($contextlevel) {
3637 global $DB;
3638 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3639 '', 'id,roleid');
3643 * Returns default context levels where roles can be assigned.
3645 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3646 * from the array returned by get_role_archetypes();
3647 * @return array list of the context levels at which this type of role may be assigned by default.
3649 function get_default_contextlevels($rolearchetype) {
3650 static $defaults = array(
3651 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3652 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3653 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3654 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3655 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3656 'guest' => array(),
3657 'user' => array(),
3658 'frontpage' => array());
3660 if (isset($defaults[$rolearchetype])) {
3661 return $defaults[$rolearchetype];
3662 } else {
3663 return array();
3668 * Set the context levels at which a particular role can be assigned.
3669 * Throws exceptions in case of error.
3671 * @param integer $roleid the id of a role.
3672 * @param array $contextlevels the context levels at which this role should be assignable,
3673 * duplicate levels are removed.
3674 * @return void
3676 function set_role_contextlevels($roleid, array $contextlevels) {
3677 global $DB;
3678 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3679 $rcl = new stdClass();
3680 $rcl->roleid = $roleid;
3681 $contextlevels = array_unique($contextlevels);
3682 foreach ($contextlevels as $level) {
3683 $rcl->contextlevel = $level;
3684 $DB->insert_record('role_context_levels', $rcl, false, true);
3689 * Who has this capability in this context?
3691 * This can be a very expensive call - use sparingly and keep
3692 * the results if you are going to need them again soon.
3694 * Note if $fields is empty this function attempts to get u.*
3695 * which can get rather large - and has a serious perf impact
3696 * on some DBs.
3698 * @param context $context
3699 * @param string|array $capability - capability name(s)
3700 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3701 * @param string $sort - the sort order. Default is lastaccess time.
3702 * @param mixed $limitfrom - number of records to skip (offset)
3703 * @param mixed $limitnum - number of records to fetch
3704 * @param string|array $groups - single group or array of groups - only return
3705 * users who are in one of these group(s).
3706 * @param string|array $exceptions - list of users to exclude, comma separated or array
3707 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3708 * @param bool $view_ignored - use get_enrolled_sql() instead
3709 * @param bool $useviewallgroups if $groups is set the return users who
3710 * have capability both $capability and moodle/site:accessallgroups
3711 * in this context, as well as users who have $capability and who are
3712 * in $groups.
3713 * @return array of user records
3715 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3716 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3717 global $CFG, $DB;
3719 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3720 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3722 $ctxids = trim($context->path, '/');
3723 $ctxids = str_replace('/', ',', $ctxids);
3725 // Context is the frontpage
3726 $iscoursepage = false; // coursepage other than fp
3727 $isfrontpage = false;
3728 if ($context->contextlevel == CONTEXT_COURSE) {
3729 if ($context->instanceid == SITEID) {
3730 $isfrontpage = true;
3731 } else {
3732 $iscoursepage = true;
3735 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3737 $caps = (array)$capability;
3739 // construct list of context paths bottom-->top
3740 list($contextids, $paths) = get_context_info_list($context);
3742 // we need to find out all roles that have these capabilities either in definition or in overrides
3743 $defs = array();
3744 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3745 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3746 $params = array_merge($params, $params2);
3747 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3748 FROM {role_capabilities} rc
3749 JOIN {context} ctx on rc.contextid = ctx.id
3750 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3752 $rcs = $DB->get_records_sql($sql, $params);
3753 foreach ($rcs as $rc) {
3754 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3757 // go through the permissions bottom-->top direction to evaluate the current permission,
3758 // first one wins (prohibit is an exception that always wins)
3759 $access = array();
3760 foreach ($caps as $cap) {
3761 foreach ($paths as $path) {
3762 if (empty($defs[$cap][$path])) {
3763 continue;
3765 foreach($defs[$cap][$path] as $roleid => $perm) {
3766 if ($perm == CAP_PROHIBIT) {
3767 $access[$cap][$roleid] = CAP_PROHIBIT;
3768 continue;
3770 if (!isset($access[$cap][$roleid])) {
3771 $access[$cap][$roleid] = (int)$perm;
3777 // make lists of roles that are needed and prohibited in this context
3778 $needed = array(); // one of these is enough
3779 $prohibited = array(); // must not have any of these
3780 foreach ($caps as $cap) {
3781 if (empty($access[$cap])) {
3782 continue;
3784 foreach ($access[$cap] as $roleid => $perm) {
3785 if ($perm == CAP_PROHIBIT) {
3786 unset($needed[$cap][$roleid]);
3787 $prohibited[$cap][$roleid] = true;
3788 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3789 $needed[$cap][$roleid] = true;
3792 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3793 // easy, nobody has the permission
3794 unset($needed[$cap]);
3795 unset($prohibited[$cap]);
3796 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3797 // everybody is disqualified on the frontpage
3798 unset($needed[$cap]);
3799 unset($prohibited[$cap]);
3801 if (empty($prohibited[$cap])) {
3802 unset($prohibited[$cap]);
3806 if (empty($needed)) {
3807 // there can not be anybody if no roles match this request
3808 return array();
3811 if (empty($prohibited)) {
3812 // we can compact the needed roles
3813 $n = array();
3814 foreach ($needed as $cap) {
3815 foreach ($cap as $roleid=>$unused) {
3816 $n[$roleid] = true;
3819 $needed = array('any'=>$n);
3820 unset($n);
3823 // ***** Set up default fields ******
3824 if (empty($fields)) {
3825 if ($iscoursepage) {
3826 $fields = 'u.*, ul.timeaccess AS lastaccess';
3827 } else {
3828 $fields = 'u.*';
3830 } else {
3831 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3832 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3836 // Set up default sort
3837 if (empty($sort)) { // default to course lastaccess or just lastaccess
3838 if ($iscoursepage) {
3839 $sort = 'ul.timeaccess';
3840 } else {
3841 $sort = 'u.lastaccess';
3845 // Prepare query clauses
3846 $wherecond = array();
3847 $params = array();
3848 $joins = array();
3850 // User lastaccess JOIN
3851 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3852 // user_lastaccess is not required MDL-13810
3853 } else {
3854 if ($iscoursepage) {
3855 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3856 } else {
3857 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3861 // We never return deleted users or guest account.
3862 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3863 $params['guestid'] = $CFG->siteguest;
3865 // Groups
3866 if ($groups) {
3867 $groups = (array)$groups;
3868 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3869 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3870 $params = array_merge($params, $grpparams);
3872 if ($useviewallgroups) {
3873 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3874 if (!empty($viewallgroupsusers)) {
3875 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3876 } else {
3877 $wherecond[] = "($grouptest)";
3879 } else {
3880 $wherecond[] = "($grouptest)";
3884 // User exceptions
3885 if (!empty($exceptions)) {
3886 $exceptions = (array)$exceptions;
3887 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3888 $params = array_merge($params, $exparams);
3889 $wherecond[] = "u.id $exsql";
3892 // now add the needed and prohibited roles conditions as joins
3893 if (!empty($needed['any'])) {
3894 // simple case - there are no prohibits involved
3895 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3896 // everybody
3897 } else {
3898 $joins[] = "JOIN (SELECT DISTINCT userid
3899 FROM {role_assignments}
3900 WHERE contextid IN ($ctxids)
3901 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3902 ) ra ON ra.userid = u.id";
3904 } else {
3905 $unions = array();
3906 $everybody = false;
3907 foreach ($needed as $cap=>$unused) {
3908 if (empty($prohibited[$cap])) {
3909 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3910 $everybody = true;
3911 break;
3912 } else {
3913 $unions[] = "SELECT userid
3914 FROM {role_assignments}
3915 WHERE contextid IN ($ctxids)
3916 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3918 } else {
3919 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3920 // nobody can have this cap because it is prevented in default roles
3921 continue;
3923 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3924 // everybody except the prohibitted - hiding does not matter
3925 $unions[] = "SELECT id AS userid
3926 FROM {user}
3927 WHERE id NOT IN (SELECT userid
3928 FROM {role_assignments}
3929 WHERE contextid IN ($ctxids)
3930 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3932 } else {
3933 $unions[] = "SELECT userid
3934 FROM {role_assignments}
3935 WHERE contextid IN ($ctxids)
3936 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3937 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3941 if (!$everybody) {
3942 if ($unions) {
3943 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3944 } else {
3945 // only prohibits found - nobody can be matched
3946 $wherecond[] = "1 = 2";
3951 // Collect WHERE conditions and needed joins
3952 $where = implode(' AND ', $wherecond);
3953 if ($where !== '') {
3954 $where = 'WHERE ' . $where;
3956 $joins = implode("\n", $joins);
3958 // Ok, let's get the users!
3959 $sql = "SELECT $fields
3960 FROM {user} u
3961 $joins
3962 $where
3963 ORDER BY $sort";
3965 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3969 * Re-sort a users array based on a sorting policy
3971 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3972 * based on a sorting policy. This is to support the odd practice of
3973 * sorting teachers by 'authority', where authority was "lowest id of the role
3974 * assignment".
3976 * Will execute 1 database query. Only suitable for small numbers of users, as it
3977 * uses an u.id IN() clause.
3979 * Notes about the sorting criteria.
3981 * As a default, we cannot rely on role.sortorder because then
3982 * admins/coursecreators will always win. That is why the sane
3983 * rule "is locality matters most", with sortorder as 2nd
3984 * consideration.
3986 * If you want role.sortorder, use the 'sortorder' policy, and
3987 * name explicitly what roles you want to cover. It's probably
3988 * a good idea to see what roles have the capabilities you want
3989 * (array_diff() them against roiles that have 'can-do-anything'
3990 * to weed out admin-ish roles. Or fetch a list of roles from
3991 * variables like $CFG->coursecontact .
3993 * @param array $users Users array, keyed on userid
3994 * @param context $context
3995 * @param array $roles ids of the roles to include, optional
3996 * @param string $sortpolicy defaults to locality, more about
3997 * @return array sorted copy of the array
3999 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
4000 global $DB;
4002 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
4003 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
4004 if (empty($roles)) {
4005 $roleswhere = '';
4006 } else {
4007 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
4010 $sql = "SELECT ra.userid
4011 FROM {role_assignments} ra
4012 JOIN {role} r
4013 ON ra.roleid=r.id
4014 JOIN {context} ctx
4015 ON ra.contextid=ctx.id
4016 WHERE $userswhere
4017 $contextwhere
4018 $roleswhere";
4020 // Default 'locality' policy -- read PHPDoc notes
4021 // about sort policies...
4022 $orderby = 'ORDER BY '
4023 .'ctx.depth DESC, ' /* locality wins */
4024 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
4025 .'ra.id'; /* role assignment order tie-breaker */
4026 if ($sortpolicy === 'sortorder') {
4027 $orderby = 'ORDER BY '
4028 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
4029 .'ra.id'; /* role assignment order tie-breaker */
4032 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
4033 $sortedusers = array();
4034 $seen = array();
4036 foreach ($sortedids as $id) {
4037 // Avoid duplicates
4038 if (isset($seen[$id])) {
4039 continue;
4041 $seen[$id] = true;
4043 // assign
4044 $sortedusers[$id] = $users[$id];
4046 return $sortedusers;
4050 * Gets all the users assigned this role in this context or higher
4052 * @param int $roleid (can also be an array of ints!)
4053 * @param context $context
4054 * @param bool $parent if true, get list of users assigned in higher context too
4055 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
4056 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
4057 * null => use default sort from users_order_by_sql.
4058 * @param bool $all true means all, false means limit to enrolled users
4059 * @param string $group defaults to ''
4060 * @param mixed $limitfrom defaults to ''
4061 * @param mixed $limitnum defaults to ''
4062 * @param string $extrawheretest defaults to ''
4063 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
4064 * @return array
4066 function get_role_users($roleid, context $context, $parent = false, $fields = '',
4067 $sort = null, $all = true, $group = '',
4068 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
4069 global $DB;
4071 if (empty($fields)) {
4072 $allnames = get_all_user_name_fields(true, 'u');
4073 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
4074 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
4075 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
4076 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
4077 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
4080 $parentcontexts = '';
4081 if ($parent) {
4082 $parentcontexts = substr($context->path, 1); // kill leading slash
4083 $parentcontexts = str_replace('/', ',', $parentcontexts);
4084 if ($parentcontexts !== '') {
4085 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4089 if ($roleid) {
4090 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
4091 $roleselect = "AND ra.roleid $rids";
4092 } else {
4093 $params = array();
4094 $roleselect = '';
4097 if ($coursecontext = $context->get_course_context(false)) {
4098 $params['coursecontext'] = $coursecontext->id;
4099 } else {
4100 $params['coursecontext'] = 0;
4103 if ($group) {
4104 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
4105 $groupselect = " AND gm.groupid = :groupid ";
4106 $params['groupid'] = $group;
4107 } else {
4108 $groupjoin = '';
4109 $groupselect = '';
4112 $params['contextid'] = $context->id;
4114 if ($extrawheretest) {
4115 $extrawheretest = ' AND ' . $extrawheretest;
4118 if ($whereorsortparams) {
4119 $params = array_merge($params, $whereorsortparams);
4122 if (!$sort) {
4123 list($sort, $sortparams) = users_order_by_sql('u');
4124 $params = array_merge($params, $sortparams);
4127 if ($all === null) {
4128 // Previously null was used to indicate that parameter was not used.
4129 $all = true;
4131 if (!$all and $coursecontext) {
4132 // Do not use get_enrolled_sql() here for performance reasons.
4133 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
4134 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
4135 $params['ecourseid'] = $coursecontext->instanceid;
4136 } else {
4137 $ejoin = "";
4140 $sql = "SELECT DISTINCT $fields, ra.roleid
4141 FROM {role_assignments} ra
4142 JOIN {user} u ON u.id = ra.userid
4143 JOIN {role} r ON ra.roleid = r.id
4144 $ejoin
4145 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
4146 $groupjoin
4147 WHERE (ra.contextid = :contextid $parentcontexts)
4148 $roleselect
4149 $groupselect
4150 $extrawheretest
4151 ORDER BY $sort"; // join now so that we can just use fullname() later
4153 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
4157 * Counts all the users assigned this role in this context or higher
4159 * @param int|array $roleid either int or an array of ints
4160 * @param context $context
4161 * @param bool $parent if true, get list of users assigned in higher context too
4162 * @return int Returns the result count
4164 function count_role_users($roleid, context $context, $parent = false) {
4165 global $DB;
4167 if ($parent) {
4168 if ($contexts = $context->get_parent_context_ids()) {
4169 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4170 } else {
4171 $parentcontexts = '';
4173 } else {
4174 $parentcontexts = '';
4177 if ($roleid) {
4178 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
4179 $roleselect = "AND r.roleid $rids";
4180 } else {
4181 $params = array();
4182 $roleselect = '';
4185 array_unshift($params, $context->id);
4187 $sql = "SELECT COUNT(u.id)
4188 FROM {role_assignments} r
4189 JOIN {user} u ON u.id = r.userid
4190 WHERE (r.contextid = ? $parentcontexts)
4191 $roleselect
4192 AND u.deleted = 0";
4194 return $DB->count_records_sql($sql, $params);
4198 * This function gets the list of courses that this user has a particular capability in.
4199 * It is still not very efficient.
4201 * @param string $capability Capability in question
4202 * @param int $userid User ID or null for current user
4203 * @param bool $doanything True if 'doanything' is permitted (default)
4204 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4205 * otherwise use a comma-separated list of the fields you require, not including id
4206 * @param string $orderby If set, use a comma-separated list of fields from course
4207 * table with sql modifiers (DESC) if needed
4208 * @return array Array of courses, may have zero entries. Or false if query failed.
4210 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
4211 global $DB;
4213 // Convert fields list and ordering
4214 $fieldlist = '';
4215 if ($fieldsexceptid) {
4216 $fields = explode(',', $fieldsexceptid);
4217 foreach($fields as $field) {
4218 $fieldlist .= ',c.'.$field;
4221 if ($orderby) {
4222 $fields = explode(',', $orderby);
4223 $orderby = '';
4224 foreach($fields as $field) {
4225 if ($orderby) {
4226 $orderby .= ',';
4228 $orderby .= 'c.'.$field;
4230 $orderby = 'ORDER BY '.$orderby;
4233 // Obtain a list of everything relevant about all courses including context.
4234 // Note the result can be used directly as a context (we are going to), the course
4235 // fields are just appended.
4237 $contextpreload = context_helper::get_preload_record_columns_sql('x');
4239 $courses = array();
4240 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
4241 FROM {course} c
4242 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
4243 $orderby");
4244 // Check capability for each course in turn
4245 foreach ($rs as $course) {
4246 context_helper::preload_from_record($course);
4247 $context = context_course::instance($course->id);
4248 if (has_capability($capability, $context, $userid, $doanything)) {
4249 // We've got the capability. Make the record look like a course record
4250 // and store it
4251 $courses[] = $course;
4254 $rs->close();
4255 return empty($courses) ? false : $courses;
4259 * This function finds the roles assigned directly to this context only
4260 * i.e. no roles in parent contexts
4262 * @param context $context
4263 * @return array
4265 function get_roles_on_exact_context(context $context) {
4266 global $DB;
4268 return $DB->get_records_sql("SELECT r.*
4269 FROM {role_assignments} ra, {role} r
4270 WHERE ra.roleid = r.id AND ra.contextid = ?",
4271 array($context->id));
4275 * Switches the current user to another role for the current session and only
4276 * in the given context.
4278 * The caller *must* check
4279 * - that this op is allowed
4280 * - that the requested role can be switched to in this context (use get_switchable_roles)
4281 * - that the requested role is NOT $CFG->defaultuserroleid
4283 * To "unswitch" pass 0 as the roleid.
4285 * This function *will* modify $USER->access - beware
4287 * @param integer $roleid the role to switch to.
4288 * @param context $context the context in which to perform the switch.
4289 * @return bool success or failure.
4291 function role_switch($roleid, context $context) {
4292 global $USER;
4295 // Plan of action
4297 // - Add the ghost RA to $USER->access
4298 // as $USER->access['rsw'][$path] = $roleid
4300 // - Make sure $USER->access['rdef'] has the roledefs
4301 // it needs to honour the switcherole
4303 // Roledefs will get loaded "deep" here - down to the last child
4304 // context. Note that
4306 // - When visiting subcontexts, our selective accessdata loading
4307 // will still work fine - though those ra/rdefs will be ignored
4308 // appropriately while the switch is in place
4310 // - If a switcherole happens at a category with tons of courses
4311 // (that have many overrides for switched-to role), the session
4312 // will get... quite large. Sometimes you just can't win.
4314 // To un-switch just unset($USER->access['rsw'][$path])
4316 // Note: it is not possible to switch to roles that do not have course:view
4318 if (!isset($USER->access)) {
4319 load_all_capabilities();
4323 // Add the switch RA
4324 if ($roleid == 0) {
4325 unset($USER->access['rsw'][$context->path]);
4326 return true;
4329 $USER->access['rsw'][$context->path] = $roleid;
4331 // Load roledefs
4332 load_role_access_by_context($roleid, $context, $USER->access);
4334 return true;
4338 * Checks if the user has switched roles within the given course.
4340 * Note: You can only switch roles within the course, hence it takes a course id
4341 * rather than a context. On that note Petr volunteered to implement this across
4342 * all other contexts, all requests for this should be forwarded to him ;)
4344 * @param int $courseid The id of the course to check
4345 * @return bool True if the user has switched roles within the course.
4347 function is_role_switched($courseid) {
4348 global $USER;
4349 $context = context_course::instance($courseid, MUST_EXIST);
4350 return (!empty($USER->access['rsw'][$context->path]));
4354 * Get any role that has an override on exact context
4356 * @param context $context The context to check
4357 * @return array An array of roles
4359 function get_roles_with_override_on_context(context $context) {
4360 global $DB;
4362 return $DB->get_records_sql("SELECT r.*
4363 FROM {role_capabilities} rc, {role} r
4364 WHERE rc.roleid = r.id AND rc.contextid = ?",
4365 array($context->id));
4369 * Get all capabilities for this role on this context (overrides)
4371 * @param stdClass $role
4372 * @param context $context
4373 * @return array
4375 function get_capabilities_from_role_on_context($role, context $context) {
4376 global $DB;
4378 return $DB->get_records_sql("SELECT *
4379 FROM {role_capabilities}
4380 WHERE contextid = ? AND roleid = ?",
4381 array($context->id, $role->id));
4385 * Find out which roles has assignment on this context
4387 * @param context $context
4388 * @return array
4391 function get_roles_with_assignment_on_context(context $context) {
4392 global $DB;
4394 return $DB->get_records_sql("SELECT r.*
4395 FROM {role_assignments} ra, {role} r
4396 WHERE ra.roleid = r.id AND ra.contextid = ?",
4397 array($context->id));
4401 * Find all user assignment of users for this role, on this context
4403 * @param stdClass $role
4404 * @param context $context
4405 * @return array
4407 function get_users_from_role_on_context($role, context $context) {
4408 global $DB;
4410 return $DB->get_records_sql("SELECT *
4411 FROM {role_assignments}
4412 WHERE contextid = ? AND roleid = ?",
4413 array($context->id, $role->id));
4417 * Simple function returning a boolean true if user has roles
4418 * in context or parent contexts, otherwise false.
4420 * @param int $userid
4421 * @param int $roleid
4422 * @param int $contextid empty means any context
4423 * @return bool
4425 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4426 global $DB;
4428 if ($contextid) {
4429 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4430 return false;
4432 $parents = $context->get_parent_context_ids(true);
4433 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4434 $params['userid'] = $userid;
4435 $params['roleid'] = $roleid;
4437 $sql = "SELECT COUNT(ra.id)
4438 FROM {role_assignments} ra
4439 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4441 $count = $DB->get_field_sql($sql, $params);
4442 return ($count > 0);
4444 } else {
4445 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4450 * Get localised role name or alias if exists and format the text.
4452 * @param stdClass $role role object
4453 * - optional 'coursealias' property should be included for performance reasons if course context used
4454 * - description property is not required here
4455 * @param context|bool $context empty means system context
4456 * @param int $rolenamedisplay type of role name
4457 * @return string localised role name or course role name alias
4459 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4460 global $DB;
4462 if ($rolenamedisplay == ROLENAME_SHORT) {
4463 return $role->shortname;
4466 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4467 $coursecontext = null;
4470 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4471 $role = clone($role); // Do not modify parameters.
4472 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4473 $role->coursealias = $r->name;
4474 } else {
4475 $role->coursealias = null;
4479 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4480 if ($coursecontext) {
4481 return $role->coursealias;
4482 } else {
4483 return null;
4487 if (trim($role->name) !== '') {
4488 // For filtering always use context where was the thing defined - system for roles here.
4489 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4491 } else {
4492 // Empty role->name means we want to see localised role name based on shortname,
4493 // only default roles are supposed to be localised.
4494 switch ($role->shortname) {
4495 case 'manager': $original = get_string('manager', 'role'); break;
4496 case 'coursecreator': $original = get_string('coursecreators'); break;
4497 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4498 case 'teacher': $original = get_string('noneditingteacher'); break;
4499 case 'student': $original = get_string('defaultcoursestudent'); break;
4500 case 'guest': $original = get_string('guest'); break;
4501 case 'user': $original = get_string('authenticateduser'); break;
4502 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4503 // We should not get here, the role UI should require the name for custom roles!
4504 default: $original = $role->shortname; break;
4508 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4509 return $original;
4512 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4513 return "$original ($role->shortname)";
4516 if ($rolenamedisplay == ROLENAME_ALIAS) {
4517 if ($coursecontext and trim($role->coursealias) !== '') {
4518 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4519 } else {
4520 return $original;
4524 if ($rolenamedisplay == ROLENAME_BOTH) {
4525 if ($coursecontext and trim($role->coursealias) !== '') {
4526 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4527 } else {
4528 return $original;
4532 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4536 * Returns localised role description if available.
4537 * If the name is empty it tries to find the default role name using
4538 * hardcoded list of default role names or other methods in the future.
4540 * @param stdClass $role
4541 * @return string localised role name
4543 function role_get_description(stdClass $role) {
4544 if (!html_is_blank($role->description)) {
4545 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4548 switch ($role->shortname) {
4549 case 'manager': return get_string('managerdescription', 'role');
4550 case 'coursecreator': return get_string('coursecreatorsdescription');
4551 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4552 case 'teacher': return get_string('noneditingteacherdescription');
4553 case 'student': return get_string('defaultcoursestudentdescription');
4554 case 'guest': return get_string('guestdescription');
4555 case 'user': return get_string('authenticateduserdescription');
4556 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4557 default: return '';
4562 * Get all the localised role names for a context.
4564 * In new installs default roles have empty names, this function
4565 * add localised role names using current language pack.
4567 * @param context $context the context, null means system context
4568 * @param array of role objects with a ->localname field containing the context-specific role name.
4569 * @param int $rolenamedisplay
4570 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4571 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4573 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4574 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4578 * Prepare list of roles for display, apply aliases and localise default role names.
4580 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4581 * @param context $context the context, null means system context
4582 * @param int $rolenamedisplay
4583 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4584 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4586 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4587 global $DB;
4589 if (empty($roleoptions)) {
4590 return array();
4593 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4594 $coursecontext = null;
4597 // We usually need all role columns...
4598 $first = reset($roleoptions);
4599 if ($returnmenu === null) {
4600 $returnmenu = !is_object($first);
4603 if (!is_object($first) or !property_exists($first, 'shortname')) {
4604 $allroles = get_all_roles($context);
4605 foreach ($roleoptions as $rid => $unused) {
4606 $roleoptions[$rid] = $allroles[$rid];
4610 // Inject coursealias if necessary.
4611 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4612 $first = reset($roleoptions);
4613 if (!property_exists($first, 'coursealias')) {
4614 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4615 foreach ($aliasnames as $alias) {
4616 if (isset($roleoptions[$alias->roleid])) {
4617 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4623 // Add localname property.
4624 foreach ($roleoptions as $rid => $role) {
4625 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4628 if (!$returnmenu) {
4629 return $roleoptions;
4632 $menu = array();
4633 foreach ($roleoptions as $rid => $role) {
4634 $menu[$rid] = $role->localname;
4637 return $menu;
4641 * Aids in detecting if a new line is required when reading a new capability
4643 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4644 * when we read in a new capability.
4645 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4646 * but when we are in grade, all reports/import/export capabilities should be together
4648 * @param string $cap component string a
4649 * @param string $comp component string b
4650 * @param int $contextlevel
4651 * @return bool whether 2 component are in different "sections"
4653 function component_level_changed($cap, $comp, $contextlevel) {
4655 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4656 $compsa = explode('/', $cap->component);
4657 $compsb = explode('/', $comp);
4659 // list of system reports
4660 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4661 return false;
4664 // we are in gradebook, still
4665 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4666 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4667 return false;
4670 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4671 return false;
4675 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4679 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4680 * and return an array of roleids in order.
4682 * @param array $allroles array of roles, as returned by get_all_roles();
4683 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4685 function fix_role_sortorder($allroles) {
4686 global $DB;
4688 $rolesort = array();
4689 $i = 0;
4690 foreach ($allroles as $role) {
4691 $rolesort[$i] = $role->id;
4692 if ($role->sortorder != $i) {
4693 $r = new stdClass();
4694 $r->id = $role->id;
4695 $r->sortorder = $i;
4696 $DB->update_record('role', $r);
4697 $allroles[$role->id]->sortorder = $i;
4699 $i++;
4701 return $rolesort;
4705 * Switch the sort order of two roles (used in admin/roles/manage.php).
4707 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4708 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4709 * @return boolean success or failure
4711 function switch_roles($first, $second) {
4712 global $DB;
4713 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4714 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4715 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4716 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4717 return $result;
4721 * Duplicates all the base definitions of a role
4723 * @param stdClass $sourcerole role to copy from
4724 * @param int $targetrole id of role to copy to
4726 function role_cap_duplicate($sourcerole, $targetrole) {
4727 global $DB;
4729 $systemcontext = context_system::instance();
4730 $caps = $DB->get_records_sql("SELECT *
4731 FROM {role_capabilities}
4732 WHERE roleid = ? AND contextid = ?",
4733 array($sourcerole->id, $systemcontext->id));
4734 // adding capabilities
4735 foreach ($caps as $cap) {
4736 unset($cap->id);
4737 $cap->roleid = $targetrole;
4738 $DB->insert_record('role_capabilities', $cap);
4743 * Returns two lists, this can be used to find out if user has capability.
4744 * Having any needed role and no forbidden role in this context means
4745 * user has this capability in this context.
4746 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4748 * @param stdClass $context
4749 * @param string $capability
4750 * @return array($neededroles, $forbiddenroles)
4752 function get_roles_with_cap_in_context($context, $capability) {
4753 global $DB;
4755 $ctxids = trim($context->path, '/'); // kill leading slash
4756 $ctxids = str_replace('/', ',', $ctxids);
4758 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4759 FROM {role_capabilities} rc
4760 JOIN {context} ctx ON ctx.id = rc.contextid
4761 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4762 ORDER BY rc.roleid ASC, ctx.depth DESC";
4763 $params = array('cap'=>$capability);
4765 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4766 // no cap definitions --> no capability
4767 return array(array(), array());
4770 $forbidden = array();
4771 $needed = array();
4772 foreach($capdefs as $def) {
4773 if (isset($forbidden[$def->roleid])) {
4774 continue;
4776 if ($def->permission == CAP_PROHIBIT) {
4777 $forbidden[$def->roleid] = $def->roleid;
4778 unset($needed[$def->roleid]);
4779 continue;
4781 if (!isset($needed[$def->roleid])) {
4782 if ($def->permission == CAP_ALLOW) {
4783 $needed[$def->roleid] = true;
4784 } else if ($def->permission == CAP_PREVENT) {
4785 $needed[$def->roleid] = false;
4789 unset($capdefs);
4791 // remove all those roles not allowing
4792 foreach($needed as $key=>$value) {
4793 if (!$value) {
4794 unset($needed[$key]);
4795 } else {
4796 $needed[$key] = $key;
4800 return array($needed, $forbidden);
4804 * Returns an array of role IDs that have ALL of the the supplied capabilities
4805 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4807 * @param stdClass $context
4808 * @param array $capabilities An array of capabilities
4809 * @return array of roles with all of the required capabilities
4811 function get_roles_with_caps_in_context($context, $capabilities) {
4812 $neededarr = array();
4813 $forbiddenarr = array();
4814 foreach($capabilities as $caprequired) {
4815 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4818 $rolesthatcanrate = array();
4819 if (!empty($neededarr)) {
4820 foreach ($neededarr as $needed) {
4821 if (empty($rolesthatcanrate)) {
4822 $rolesthatcanrate = $needed;
4823 } else {
4824 //only want roles that have all caps
4825 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4829 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4830 foreach ($forbiddenarr as $forbidden) {
4831 //remove any roles that are forbidden any of the caps
4832 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4835 return $rolesthatcanrate;
4839 * Returns an array of role names that have ALL of the the supplied capabilities
4840 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4842 * @param stdClass $context
4843 * @param array $capabilities An array of capabilities
4844 * @return array of roles with all of the required capabilities
4846 function get_role_names_with_caps_in_context($context, $capabilities) {
4847 global $DB;
4849 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4850 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4852 $roles = array();
4853 foreach ($rolesthatcanrate as $r) {
4854 $roles[$r] = $allroles[$r];
4857 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4861 * This function verifies the prohibit comes from this context
4862 * and there are no more prohibits in parent contexts.
4864 * @param int $roleid
4865 * @param context $context
4866 * @param string $capability name
4867 * @return bool
4869 function prohibit_is_removable($roleid, context $context, $capability) {
4870 global $DB;
4872 $ctxids = trim($context->path, '/'); // kill leading slash
4873 $ctxids = str_replace('/', ',', $ctxids);
4875 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4877 $sql = "SELECT ctx.id
4878 FROM {role_capabilities} rc
4879 JOIN {context} ctx ON ctx.id = rc.contextid
4880 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4881 ORDER BY ctx.depth DESC";
4883 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4884 // no prohibits == nothing to remove
4885 return true;
4888 if (count($prohibits) > 1) {
4889 // more prohibits can not be removed
4890 return false;
4893 return !empty($prohibits[$context->id]);
4897 * More user friendly role permission changing,
4898 * it should produce as few overrides as possible.
4900 * @param int $roleid
4901 * @param stdClass $context
4902 * @param string $capname capability name
4903 * @param int $permission
4904 * @return void
4906 function role_change_permission($roleid, $context, $capname, $permission) {
4907 global $DB;
4909 if ($permission == CAP_INHERIT) {
4910 unassign_capability($capname, $roleid, $context->id);
4911 $context->mark_dirty();
4912 return;
4915 $ctxids = trim($context->path, '/'); // kill leading slash
4916 $ctxids = str_replace('/', ',', $ctxids);
4918 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4920 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4921 FROM {role_capabilities} rc
4922 JOIN {context} ctx ON ctx.id = rc.contextid
4923 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4924 ORDER BY ctx.depth DESC";
4926 if ($existing = $DB->get_records_sql($sql, $params)) {
4927 foreach($existing as $e) {
4928 if ($e->permission == CAP_PROHIBIT) {
4929 // prohibit can not be overridden, no point in changing anything
4930 return;
4933 $lowest = array_shift($existing);
4934 if ($lowest->permission == $permission) {
4935 // permission already set in this context or parent - nothing to do
4936 return;
4938 if ($existing) {
4939 $parent = array_shift($existing);
4940 if ($parent->permission == $permission) {
4941 // permission already set in parent context or parent - just unset in this context
4942 // we do this because we want as few overrides as possible for performance reasons
4943 unassign_capability($capname, $roleid, $context->id);
4944 $context->mark_dirty();
4945 return;
4949 } else {
4950 if ($permission == CAP_PREVENT) {
4951 // nothing means role does not have permission
4952 return;
4956 // assign the needed capability
4957 assign_capability($capname, $permission, $roleid, $context->id, true);
4959 // force cap reloading
4960 $context->mark_dirty();
4965 * Basic moodle context abstraction class.
4967 * Google confirms that no other important framework is using "context" class,
4968 * we could use something else like mcontext or moodle_context, but we need to type
4969 * this very often which would be annoying and it would take too much space...
4971 * This class is derived from stdClass for backwards compatibility with
4972 * odl $context record that was returned from DML $DB->get_record()
4974 * @package core_access
4975 * @category access
4976 * @copyright Petr Skoda {@link http://skodak.org}
4977 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4978 * @since Moodle 2.2
4980 * @property-read int $id context id
4981 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4982 * @property-read int $instanceid id of related instance in each context
4983 * @property-read string $path path to context, starts with system context
4984 * @property-read int $depth
4986 abstract class context extends stdClass implements IteratorAggregate {
4989 * The context id
4990 * Can be accessed publicly through $context->id
4991 * @var int
4993 protected $_id;
4996 * The context level
4997 * Can be accessed publicly through $context->contextlevel
4998 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
5000 protected $_contextlevel;
5003 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
5004 * Can be accessed publicly through $context->instanceid
5005 * @var int
5007 protected $_instanceid;
5010 * The path to the context always starting from the system context
5011 * Can be accessed publicly through $context->path
5012 * @var string
5014 protected $_path;
5017 * The depth of the context in relation to parent contexts
5018 * Can be accessed publicly through $context->depth
5019 * @var int
5021 protected $_depth;
5024 * @var array Context caching info
5026 private static $cache_contextsbyid = array();
5029 * @var array Context caching info
5031 private static $cache_contexts = array();
5034 * Context count
5035 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
5036 * @var int
5038 protected static $cache_count = 0;
5041 * @var array Context caching info
5043 protected static $cache_preloaded = array();
5046 * @var context_system The system context once initialised
5048 protected static $systemcontext = null;
5051 * Resets the cache to remove all data.
5052 * @static
5054 protected static function reset_caches() {
5055 self::$cache_contextsbyid = array();
5056 self::$cache_contexts = array();
5057 self::$cache_count = 0;
5058 self::$cache_preloaded = array();
5060 self::$systemcontext = null;
5064 * Adds a context to the cache. If the cache is full, discards a batch of
5065 * older entries.
5067 * @static
5068 * @param context $context New context to add
5069 * @return void
5071 protected static function cache_add(context $context) {
5072 if (isset(self::$cache_contextsbyid[$context->id])) {
5073 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5074 return;
5077 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
5078 $i = 0;
5079 foreach(self::$cache_contextsbyid as $ctx) {
5080 $i++;
5081 if ($i <= 100) {
5082 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
5083 continue;
5085 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
5086 // we remove oldest third of the contexts to make room for more contexts
5087 break;
5089 unset(self::$cache_contextsbyid[$ctx->id]);
5090 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
5091 self::$cache_count--;
5095 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
5096 self::$cache_contextsbyid[$context->id] = $context;
5097 self::$cache_count++;
5101 * Removes a context from the cache.
5103 * @static
5104 * @param context $context Context object to remove
5105 * @return void
5107 protected static function cache_remove(context $context) {
5108 if (!isset(self::$cache_contextsbyid[$context->id])) {
5109 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5110 return;
5112 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
5113 unset(self::$cache_contextsbyid[$context->id]);
5115 self::$cache_count--;
5117 if (self::$cache_count < 0) {
5118 self::$cache_count = 0;
5123 * Gets a context from the cache.
5125 * @static
5126 * @param int $contextlevel Context level
5127 * @param int $instance Instance ID
5128 * @return context|bool Context or false if not in cache
5130 protected static function cache_get($contextlevel, $instance) {
5131 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
5132 return self::$cache_contexts[$contextlevel][$instance];
5134 return false;
5138 * Gets a context from the cache based on its id.
5140 * @static
5141 * @param int $id Context ID
5142 * @return context|bool Context or false if not in cache
5144 protected static function cache_get_by_id($id) {
5145 if (isset(self::$cache_contextsbyid[$id])) {
5146 return self::$cache_contextsbyid[$id];
5148 return false;
5152 * Preloads context information from db record and strips the cached info.
5154 * @static
5155 * @param stdClass $rec
5156 * @return void (modifies $rec)
5158 protected static function preload_from_record(stdClass $rec) {
5159 if (empty($rec->ctxid) or empty($rec->ctxlevel) or empty($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
5160 // $rec does not have enough data, passed here repeatedly or context does not exist yet
5161 return;
5164 // note: in PHP5 the objects are passed by reference, no need to return $rec
5165 $record = new stdClass();
5166 $record->id = $rec->ctxid; unset($rec->ctxid);
5167 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
5168 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
5169 $record->path = $rec->ctxpath; unset($rec->ctxpath);
5170 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
5172 return context::create_instance_from_record($record);
5176 // ====== magic methods =======
5179 * Magic setter method, we do not want anybody to modify properties from the outside
5180 * @param string $name
5181 * @param mixed $value
5183 public function __set($name, $value) {
5184 debugging('Can not change context instance properties!');
5188 * Magic method getter, redirects to read only values.
5189 * @param string $name
5190 * @return mixed
5192 public function __get($name) {
5193 switch ($name) {
5194 case 'id': return $this->_id;
5195 case 'contextlevel': return $this->_contextlevel;
5196 case 'instanceid': return $this->_instanceid;
5197 case 'path': return $this->_path;
5198 case 'depth': return $this->_depth;
5200 default:
5201 debugging('Invalid context property accessed! '.$name);
5202 return null;
5207 * Full support for isset on our magic read only properties.
5208 * @param string $name
5209 * @return bool
5211 public function __isset($name) {
5212 switch ($name) {
5213 case 'id': return isset($this->_id);
5214 case 'contextlevel': return isset($this->_contextlevel);
5215 case 'instanceid': return isset($this->_instanceid);
5216 case 'path': return isset($this->_path);
5217 case 'depth': return isset($this->_depth);
5219 default: return false;
5225 * ALl properties are read only, sorry.
5226 * @param string $name
5228 public function __unset($name) {
5229 debugging('Can not unset context instance properties!');
5232 // ====== implementing method from interface IteratorAggregate ======
5235 * Create an iterator because magic vars can't be seen by 'foreach'.
5237 * Now we can convert context object to array using convert_to_array(),
5238 * and feed it properly to json_encode().
5240 public function getIterator() {
5241 $ret = array(
5242 'id' => $this->id,
5243 'contextlevel' => $this->contextlevel,
5244 'instanceid' => $this->instanceid,
5245 'path' => $this->path,
5246 'depth' => $this->depth
5248 return new ArrayIterator($ret);
5251 // ====== general context methods ======
5254 * Constructor is protected so that devs are forced to
5255 * use context_xxx::instance() or context::instance_by_id().
5257 * @param stdClass $record
5259 protected function __construct(stdClass $record) {
5260 $this->_id = (int)$record->id;
5261 $this->_contextlevel = (int)$record->contextlevel;
5262 $this->_instanceid = $record->instanceid;
5263 $this->_path = $record->path;
5264 $this->_depth = $record->depth;
5268 * This function is also used to work around 'protected' keyword problems in context_helper.
5269 * @static
5270 * @param stdClass $record
5271 * @return context instance
5273 protected static function create_instance_from_record(stdClass $record) {
5274 $classname = context_helper::get_class_for_level($record->contextlevel);
5276 if ($context = context::cache_get_by_id($record->id)) {
5277 return $context;
5280 $context = new $classname($record);
5281 context::cache_add($context);
5283 return $context;
5287 * Copy prepared new contexts from temp table to context table,
5288 * we do this in db specific way for perf reasons only.
5289 * @static
5291 protected static function merge_context_temp_table() {
5292 global $DB;
5294 /* MDL-11347:
5295 * - mysql does not allow to use FROM in UPDATE statements
5296 * - using two tables after UPDATE works in mysql, but might give unexpected
5297 * results in pg 8 (depends on configuration)
5298 * - using table alias in UPDATE does not work in pg < 8.2
5300 * Different code for each database - mostly for performance reasons
5303 $dbfamily = $DB->get_dbfamily();
5304 if ($dbfamily == 'mysql') {
5305 $updatesql = "UPDATE {context} ct, {context_temp} temp
5306 SET ct.path = temp.path,
5307 ct.depth = temp.depth
5308 WHERE ct.id = temp.id";
5309 } else if ($dbfamily == 'oracle') {
5310 $updatesql = "UPDATE {context} ct
5311 SET (ct.path, ct.depth) =
5312 (SELECT temp.path, temp.depth
5313 FROM {context_temp} temp
5314 WHERE temp.id=ct.id)
5315 WHERE EXISTS (SELECT 'x'
5316 FROM {context_temp} temp
5317 WHERE temp.id = ct.id)";
5318 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5319 $updatesql = "UPDATE {context}
5320 SET path = temp.path,
5321 depth = temp.depth
5322 FROM {context_temp} temp
5323 WHERE temp.id={context}.id";
5324 } else {
5325 // sqlite and others
5326 $updatesql = "UPDATE {context}
5327 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5328 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5329 WHERE id IN (SELECT id FROM {context_temp})";
5332 $DB->execute($updatesql);
5336 * Get a context instance as an object, from a given context id.
5338 * @static
5339 * @param int $id context id
5340 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5341 * MUST_EXIST means throw exception if no record found
5342 * @return context|bool the context object or false if not found
5344 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5345 global $DB;
5347 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5348 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5349 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5352 if ($id == SYSCONTEXTID) {
5353 return context_system::instance(0, $strictness);
5356 if (is_array($id) or is_object($id) or empty($id)) {
5357 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5360 if ($context = context::cache_get_by_id($id)) {
5361 return $context;
5364 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5365 return context::create_instance_from_record($record);
5368 return false;
5372 * Update context info after moving context in the tree structure.
5374 * @param context $newparent
5375 * @return void
5377 public function update_moved(context $newparent) {
5378 global $DB;
5380 $frompath = $this->_path;
5381 $newpath = $newparent->path . '/' . $this->_id;
5383 $trans = $DB->start_delegated_transaction();
5385 $this->mark_dirty();
5387 $setdepth = '';
5388 if (($newparent->depth +1) != $this->_depth) {
5389 $diff = $newparent->depth - $this->_depth + 1;
5390 $setdepth = ", depth = depth + $diff";
5392 $sql = "UPDATE {context}
5393 SET path = ?
5394 $setdepth
5395 WHERE id = ?";
5396 $params = array($newpath, $this->_id);
5397 $DB->execute($sql, $params);
5399 $this->_path = $newpath;
5400 $this->_depth = $newparent->depth + 1;
5402 $sql = "UPDATE {context}
5403 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5404 $setdepth
5405 WHERE path LIKE ?";
5406 $params = array($newpath, "{$frompath}/%");
5407 $DB->execute($sql, $params);
5409 $this->mark_dirty();
5411 context::reset_caches();
5413 $trans->allow_commit();
5417 * Remove all context path info and optionally rebuild it.
5419 * @param bool $rebuild
5420 * @return void
5422 public function reset_paths($rebuild = true) {
5423 global $DB;
5425 if ($this->_path) {
5426 $this->mark_dirty();
5428 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5429 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5430 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5431 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5432 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5433 $this->_depth = 0;
5434 $this->_path = null;
5437 if ($rebuild) {
5438 context_helper::build_all_paths(false);
5441 context::reset_caches();
5445 * Delete all data linked to content, do not delete the context record itself
5447 public function delete_content() {
5448 global $CFG, $DB;
5450 blocks_delete_all_for_context($this->_id);
5451 filter_delete_all_for_context($this->_id);
5453 require_once($CFG->dirroot . '/comment/lib.php');
5454 comment::delete_comments(array('contextid'=>$this->_id));
5456 require_once($CFG->dirroot.'/rating/lib.php');
5457 $delopt = new stdclass();
5458 $delopt->contextid = $this->_id;
5459 $rm = new rating_manager();
5460 $rm->delete_ratings($delopt);
5462 // delete all files attached to this context
5463 $fs = get_file_storage();
5464 $fs->delete_area_files($this->_id);
5466 // Delete all repository instances attached to this context.
5467 require_once($CFG->dirroot . '/repository/lib.php');
5468 repository::delete_all_for_context($this->_id);
5470 // delete all advanced grading data attached to this context
5471 require_once($CFG->dirroot.'/grade/grading/lib.php');
5472 grading_manager::delete_all_for_context($this->_id);
5474 // now delete stuff from role related tables, role_unassign_all
5475 // and unenrol should be called earlier to do proper cleanup
5476 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5477 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5478 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5482 * Delete the context content and the context record itself
5484 public function delete() {
5485 global $DB;
5487 if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5488 throw new coding_exception('Cannot delete system context');
5491 // double check the context still exists
5492 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5493 context::cache_remove($this);
5494 return;
5497 $this->delete_content();
5498 $DB->delete_records('context', array('id'=>$this->_id));
5499 // purge static context cache if entry present
5500 context::cache_remove($this);
5502 // do not mark dirty contexts if parents unknown
5503 if (!is_null($this->_path) and $this->_depth > 0) {
5504 $this->mark_dirty();
5508 // ====== context level related methods ======
5511 * Utility method for context creation
5513 * @static
5514 * @param int $contextlevel
5515 * @param int $instanceid
5516 * @param string $parentpath
5517 * @return stdClass context record
5519 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5520 global $DB;
5522 $record = new stdClass();
5523 $record->contextlevel = $contextlevel;
5524 $record->instanceid = $instanceid;
5525 $record->depth = 0;
5526 $record->path = null; //not known before insert
5528 $record->id = $DB->insert_record('context', $record);
5530 // now add path if known - it can be added later
5531 if (!is_null($parentpath)) {
5532 $record->path = $parentpath.'/'.$record->id;
5533 $record->depth = substr_count($record->path, '/');
5534 $DB->update_record('context', $record);
5537 return $record;
5541 * Returns human readable context identifier.
5543 * @param boolean $withprefix whether to prefix the name of the context with the
5544 * type of context, e.g. User, Course, Forum, etc.
5545 * @param boolean $short whether to use the short name of the thing. Only applies
5546 * to course contexts
5547 * @return string the human readable context name.
5549 public function get_context_name($withprefix = true, $short = false) {
5550 // must be implemented in all context levels
5551 throw new coding_exception('can not get name of abstract context');
5555 * Returns the most relevant URL for this context.
5557 * @return moodle_url
5559 public abstract function get_url();
5562 * Returns array of relevant context capability records.
5564 * @return array
5566 public abstract function get_capabilities();
5569 * Recursive function which, given a context, find all its children context ids.
5571 * For course category contexts it will return immediate children and all subcategory contexts.
5572 * It will NOT recurse into courses or subcategories categories.
5573 * If you want to do that, call it on the returned courses/categories.
5575 * When called for a course context, it will return the modules and blocks
5576 * displayed in the course page and blocks displayed on the module pages.
5578 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5579 * contexts ;-)
5581 * @return array Array of child records
5583 public function get_child_contexts() {
5584 global $DB;
5586 if (empty($this->_path) or empty($this->_depth)) {
5587 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5588 return array();
5591 $sql = "SELECT ctx.*
5592 FROM {context} ctx
5593 WHERE ctx.path LIKE ?";
5594 $params = array($this->_path.'/%');
5595 $records = $DB->get_records_sql($sql, $params);
5597 $result = array();
5598 foreach ($records as $record) {
5599 $result[$record->id] = context::create_instance_from_record($record);
5602 return $result;
5606 * Returns parent contexts of this context in reversed order, i.e. parent first,
5607 * then grand parent, etc.
5609 * @param bool $includeself tre means include self too
5610 * @return array of context instances
5612 public function get_parent_contexts($includeself = false) {
5613 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5614 return array();
5617 $result = array();
5618 foreach ($contextids as $contextid) {
5619 $parent = context::instance_by_id($contextid, MUST_EXIST);
5620 $result[$parent->id] = $parent;
5623 return $result;
5627 * Returns parent contexts of this context in reversed order, i.e. parent first,
5628 * then grand parent, etc.
5630 * @param bool $includeself tre means include self too
5631 * @return array of context ids
5633 public function get_parent_context_ids($includeself = false) {
5634 if (empty($this->_path)) {
5635 return array();
5638 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5639 $parentcontexts = explode('/', $parentcontexts);
5640 if (!$includeself) {
5641 array_pop($parentcontexts); // and remove its own id
5644 return array_reverse($parentcontexts);
5648 * Returns parent context
5650 * @return context
5652 public function get_parent_context() {
5653 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5654 return false;
5657 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5658 $parentcontexts = explode('/', $parentcontexts);
5659 array_pop($parentcontexts); // self
5660 $contextid = array_pop($parentcontexts); // immediate parent
5662 return context::instance_by_id($contextid, MUST_EXIST);
5666 * Is this context part of any course? If yes return course context.
5668 * @param bool $strict true means throw exception if not found, false means return false if not found
5669 * @return context_course context of the enclosing course, null if not found or exception
5671 public function get_course_context($strict = true) {
5672 if ($strict) {
5673 throw new coding_exception('Context does not belong to any course.');
5674 } else {
5675 return false;
5680 * Returns sql necessary for purging of stale context instances.
5682 * @static
5683 * @return string cleanup SQL
5685 protected static function get_cleanup_sql() {
5686 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5690 * Rebuild context paths and depths at context level.
5692 * @static
5693 * @param bool $force
5694 * @return void
5696 protected static function build_paths($force) {
5697 throw new coding_exception('build_paths() method must be implemented in all context levels');
5701 * Create missing context instances at given level
5703 * @static
5704 * @return void
5706 protected static function create_level_instances() {
5707 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5711 * Reset all cached permissions and definitions if the necessary.
5712 * @return void
5714 public function reload_if_dirty() {
5715 global $ACCESSLIB_PRIVATE, $USER;
5717 // Load dirty contexts list if needed
5718 if (CLI_SCRIPT) {
5719 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5720 // we do not load dirty flags in CLI and cron
5721 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5723 } else {
5724 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5725 if (!isset($USER->access['time'])) {
5726 // nothing was loaded yet, we do not need to check dirty contexts now
5727 return;
5729 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5730 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5734 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5735 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5736 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5737 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5738 reload_all_capabilities();
5739 break;
5745 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5747 public function mark_dirty() {
5748 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5750 if (during_initial_install()) {
5751 return;
5754 // only if it is a non-empty string
5755 if (is_string($this->_path) && $this->_path !== '') {
5756 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5757 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5758 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5759 } else {
5760 if (CLI_SCRIPT) {
5761 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5762 } else {
5763 if (isset($USER->access['time'])) {
5764 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5765 } else {
5766 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5768 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5777 * Context maintenance and helper methods.
5779 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5780 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5781 * level implementation from the rest of code, the code completion returns what developers need.
5783 * Thank you Tim Hunt for helping me with this nasty trick.
5785 * @package core_access
5786 * @category access
5787 * @copyright Petr Skoda {@link http://skodak.org}
5788 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5789 * @since Moodle 2.2
5791 class context_helper extends context {
5794 * @var array An array mapping context levels to classes
5796 private static $alllevels;
5799 * Instance does not make sense here, only static use
5801 protected function __construct() {
5805 * Reset internal context levels array.
5807 public static function reset_levels() {
5808 self::$alllevels = null;
5812 * Initialise context levels, call before using self::$alllevels.
5814 private static function init_levels() {
5815 global $CFG;
5817 if (isset(self::$alllevels)) {
5818 return;
5820 self::$alllevels = array(
5821 CONTEXT_SYSTEM => 'context_system',
5822 CONTEXT_USER => 'context_user',
5823 CONTEXT_COURSECAT => 'context_coursecat',
5824 CONTEXT_COURSE => 'context_course',
5825 CONTEXT_MODULE => 'context_module',
5826 CONTEXT_BLOCK => 'context_block',
5829 if (empty($CFG->custom_context_classes)) {
5830 return;
5833 $levels = $CFG->custom_context_classes;
5834 if (!is_array($levels)) {
5835 $levels = @unserialize($levels);
5837 if (!is_array($levels)) {
5838 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
5839 return;
5842 // Unsupported custom levels, use with care!!!
5843 foreach ($levels as $level => $classname) {
5844 self::$alllevels[$level] = $classname;
5846 ksort(self::$alllevels);
5850 * Returns a class name of the context level class
5852 * @static
5853 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5854 * @return string class name of the context class
5856 public static function get_class_for_level($contextlevel) {
5857 self::init_levels();
5858 if (isset(self::$alllevels[$contextlevel])) {
5859 return self::$alllevels[$contextlevel];
5860 } else {
5861 throw new coding_exception('Invalid context level specified');
5866 * Returns a list of all context levels
5868 * @static
5869 * @return array int=>string (level=>level class name)
5871 public static function get_all_levels() {
5872 self::init_levels();
5873 return self::$alllevels;
5877 * Remove stale contexts that belonged to deleted instances.
5878 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5880 * @static
5881 * @return void
5883 public static function cleanup_instances() {
5884 global $DB;
5885 self::init_levels();
5887 $sqls = array();
5888 foreach (self::$alllevels as $level=>$classname) {
5889 $sqls[] = $classname::get_cleanup_sql();
5892 $sql = implode(" UNION ", $sqls);
5894 // it is probably better to use transactions, it might be faster too
5895 $transaction = $DB->start_delegated_transaction();
5897 $rs = $DB->get_recordset_sql($sql);
5898 foreach ($rs as $record) {
5899 $context = context::create_instance_from_record($record);
5900 $context->delete();
5902 $rs->close();
5904 $transaction->allow_commit();
5908 * Create all context instances at the given level and above.
5910 * @static
5911 * @param int $contextlevel null means all levels
5912 * @param bool $buildpaths
5913 * @return void
5915 public static function create_instances($contextlevel = null, $buildpaths = true) {
5916 self::init_levels();
5917 foreach (self::$alllevels as $level=>$classname) {
5918 if ($contextlevel and $level > $contextlevel) {
5919 // skip potential sub-contexts
5920 continue;
5922 $classname::create_level_instances();
5923 if ($buildpaths) {
5924 $classname::build_paths(false);
5930 * Rebuild paths and depths in all context levels.
5932 * @static
5933 * @param bool $force false means add missing only
5934 * @return void
5936 public static function build_all_paths($force = false) {
5937 self::init_levels();
5938 foreach (self::$alllevels as $classname) {
5939 $classname::build_paths($force);
5942 // reset static course cache - it might have incorrect cached data
5943 accesslib_clear_all_caches(true);
5947 * Resets the cache to remove all data.
5948 * @static
5950 public static function reset_caches() {
5951 context::reset_caches();
5955 * Returns all fields necessary for context preloading from user $rec.
5957 * This helps with performance when dealing with hundreds of contexts.
5959 * @static
5960 * @param string $tablealias context table alias in the query
5961 * @return array (table.column=>alias, ...)
5963 public static function get_preload_record_columns($tablealias) {
5964 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5968 * Returns all fields necessary for context preloading from user $rec.
5970 * This helps with performance when dealing with hundreds of contexts.
5972 * @static
5973 * @param string $tablealias context table alias in the query
5974 * @return string
5976 public static function get_preload_record_columns_sql($tablealias) {
5977 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5981 * Preloads context information from db record and strips the cached info.
5983 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5985 * @static
5986 * @param stdClass $rec
5987 * @return void (modifies $rec)
5989 public static function preload_from_record(stdClass $rec) {
5990 context::preload_from_record($rec);
5994 * Preload all contexts instances from course.
5996 * To be used if you expect multiple queries for course activities...
5998 * @static
5999 * @param int $courseid
6001 public static function preload_course($courseid) {
6002 // Users can call this multiple times without doing any harm
6003 if (isset(context::$cache_preloaded[$courseid])) {
6004 return;
6006 $coursecontext = context_course::instance($courseid);
6007 $coursecontext->get_child_contexts();
6009 context::$cache_preloaded[$courseid] = true;
6013 * Delete context instance
6015 * @static
6016 * @param int $contextlevel
6017 * @param int $instanceid
6018 * @return void
6020 public static function delete_instance($contextlevel, $instanceid) {
6021 global $DB;
6023 // double check the context still exists
6024 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
6025 $context = context::create_instance_from_record($record);
6026 $context->delete();
6027 } else {
6028 // we should try to purge the cache anyway
6033 * Returns the name of specified context level
6035 * @static
6036 * @param int $contextlevel
6037 * @return string name of the context level
6039 public static function get_level_name($contextlevel) {
6040 $classname = context_helper::get_class_for_level($contextlevel);
6041 return $classname::get_level_name();
6045 * not used
6047 public function get_url() {
6051 * not used
6053 public function get_capabilities() {
6059 * System context class
6061 * @package core_access
6062 * @category access
6063 * @copyright Petr Skoda {@link http://skodak.org}
6064 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6065 * @since Moodle 2.2
6067 class context_system extends context {
6069 * Please use context_system::instance() if you need the instance of context.
6071 * @param stdClass $record
6073 protected function __construct(stdClass $record) {
6074 parent::__construct($record);
6075 if ($record->contextlevel != CONTEXT_SYSTEM) {
6076 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
6081 * Returns human readable context level name.
6083 * @static
6084 * @return string the human readable context level name.
6086 public static function get_level_name() {
6087 return get_string('coresystem');
6091 * Returns human readable context identifier.
6093 * @param boolean $withprefix does not apply to system context
6094 * @param boolean $short does not apply to system context
6095 * @return string the human readable context name.
6097 public function get_context_name($withprefix = true, $short = false) {
6098 return self::get_level_name();
6102 * Returns the most relevant URL for this context.
6104 * @return moodle_url
6106 public function get_url() {
6107 return new moodle_url('/');
6111 * Returns array of relevant context capability records.
6113 * @return array
6115 public function get_capabilities() {
6116 global $DB;
6118 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6120 $params = array();
6121 $sql = "SELECT *
6122 FROM {capabilities}";
6124 return $DB->get_records_sql($sql.' '.$sort, $params);
6128 * Create missing context instances at system context
6129 * @static
6131 protected static function create_level_instances() {
6132 // nothing to do here, the system context is created automatically in installer
6133 self::instance(0);
6137 * Returns system context instance.
6139 * @static
6140 * @param int $instanceid
6141 * @param int $strictness
6142 * @param bool $cache
6143 * @return context_system context instance
6145 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
6146 global $DB;
6148 if ($instanceid != 0) {
6149 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
6152 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
6153 if (!isset(context::$systemcontext)) {
6154 $record = new stdClass();
6155 $record->id = SYSCONTEXTID;
6156 $record->contextlevel = CONTEXT_SYSTEM;
6157 $record->instanceid = 0;
6158 $record->path = '/'.SYSCONTEXTID;
6159 $record->depth = 1;
6160 context::$systemcontext = new context_system($record);
6162 return context::$systemcontext;
6166 try {
6167 // We ignore the strictness completely because system context must exist except during install.
6168 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6169 } catch (dml_exception $e) {
6170 //table or record does not exist
6171 if (!during_initial_install()) {
6172 // do not mess with system context after install, it simply must exist
6173 throw $e;
6175 $record = null;
6178 if (!$record) {
6179 $record = new stdClass();
6180 $record->contextlevel = CONTEXT_SYSTEM;
6181 $record->instanceid = 0;
6182 $record->depth = 1;
6183 $record->path = null; //not known before insert
6185 try {
6186 if ($DB->count_records('context')) {
6187 // contexts already exist, this is very weird, system must be first!!!
6188 return null;
6190 if (defined('SYSCONTEXTID')) {
6191 // this would happen only in unittest on sites that went through weird 1.7 upgrade
6192 $record->id = SYSCONTEXTID;
6193 $DB->import_record('context', $record);
6194 $DB->get_manager()->reset_sequence('context');
6195 } else {
6196 $record->id = $DB->insert_record('context', $record);
6198 } catch (dml_exception $e) {
6199 // can not create context - table does not exist yet, sorry
6200 return null;
6204 if ($record->instanceid != 0) {
6205 // this is very weird, somebody must be messing with context table
6206 debugging('Invalid system context detected');
6209 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6210 // fix path if necessary, initial install or path reset
6211 $record->depth = 1;
6212 $record->path = '/'.$record->id;
6213 $DB->update_record('context', $record);
6216 if (!defined('SYSCONTEXTID')) {
6217 define('SYSCONTEXTID', $record->id);
6220 context::$systemcontext = new context_system($record);
6221 return context::$systemcontext;
6225 * Returns all site contexts except the system context, DO NOT call on production servers!!
6227 * Contexts are not cached.
6229 * @return array
6231 public function get_child_contexts() {
6232 global $DB;
6234 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6236 // Just get all the contexts except for CONTEXT_SYSTEM level
6237 // and hope we don't OOM in the process - don't cache
6238 $sql = "SELECT c.*
6239 FROM {context} c
6240 WHERE contextlevel > ".CONTEXT_SYSTEM;
6241 $records = $DB->get_records_sql($sql);
6243 $result = array();
6244 foreach ($records as $record) {
6245 $result[$record->id] = context::create_instance_from_record($record);
6248 return $result;
6252 * Returns sql necessary for purging of stale context instances.
6254 * @static
6255 * @return string cleanup SQL
6257 protected static function get_cleanup_sql() {
6258 $sql = "
6259 SELECT c.*
6260 FROM {context} c
6261 WHERE 1=2
6264 return $sql;
6268 * Rebuild context paths and depths at system context level.
6270 * @static
6271 * @param bool $force
6273 protected static function build_paths($force) {
6274 global $DB;
6276 /* note: ignore $force here, we always do full test of system context */
6278 // exactly one record must exist
6279 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6281 if ($record->instanceid != 0) {
6282 debugging('Invalid system context detected');
6285 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6286 debugging('Invalid SYSCONTEXTID detected');
6289 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6290 // fix path if necessary, initial install or path reset
6291 $record->depth = 1;
6292 $record->path = '/'.$record->id;
6293 $DB->update_record('context', $record);
6300 * User context class
6302 * @package core_access
6303 * @category access
6304 * @copyright Petr Skoda {@link http://skodak.org}
6305 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6306 * @since Moodle 2.2
6308 class context_user extends context {
6310 * Please use context_user::instance($userid) if you need the instance of context.
6311 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6313 * @param stdClass $record
6315 protected function __construct(stdClass $record) {
6316 parent::__construct($record);
6317 if ($record->contextlevel != CONTEXT_USER) {
6318 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6323 * Returns human readable context level name.
6325 * @static
6326 * @return string the human readable context level name.
6328 public static function get_level_name() {
6329 return get_string('user');
6333 * Returns human readable context identifier.
6335 * @param boolean $withprefix whether to prefix the name of the context with User
6336 * @param boolean $short does not apply to user context
6337 * @return string the human readable context name.
6339 public function get_context_name($withprefix = true, $short = false) {
6340 global $DB;
6342 $name = '';
6343 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6344 if ($withprefix){
6345 $name = get_string('user').': ';
6347 $name .= fullname($user);
6349 return $name;
6353 * Returns the most relevant URL for this context.
6355 * @return moodle_url
6357 public function get_url() {
6358 global $COURSE;
6360 if ($COURSE->id == SITEID) {
6361 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6362 } else {
6363 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6365 return $url;
6369 * Returns array of relevant context capability records.
6371 * @return array
6373 public function get_capabilities() {
6374 global $DB;
6376 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6378 $extracaps = array('moodle/grade:viewall');
6379 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6380 $sql = "SELECT *
6381 FROM {capabilities}
6382 WHERE contextlevel = ".CONTEXT_USER."
6383 OR name $extra";
6385 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6389 * Returns user context instance.
6391 * @static
6392 * @param int $instanceid
6393 * @param int $strictness
6394 * @return context_user context instance
6396 public static function instance($instanceid, $strictness = MUST_EXIST) {
6397 global $DB;
6399 if ($context = context::cache_get(CONTEXT_USER, $instanceid)) {
6400 return $context;
6403 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_USER, 'instanceid'=>$instanceid))) {
6404 if ($user = $DB->get_record('user', array('id'=>$instanceid, 'deleted'=>0), 'id', $strictness)) {
6405 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6409 if ($record) {
6410 $context = new context_user($record);
6411 context::cache_add($context);
6412 return $context;
6415 return false;
6419 * Create missing context instances at user context level
6420 * @static
6422 protected static function create_level_instances() {
6423 global $DB;
6425 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6426 SELECT ".CONTEXT_USER.", u.id
6427 FROM {user} u
6428 WHERE u.deleted = 0
6429 AND NOT EXISTS (SELECT 'x'
6430 FROM {context} cx
6431 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6432 $DB->execute($sql);
6436 * Returns sql necessary for purging of stale context instances.
6438 * @static
6439 * @return string cleanup SQL
6441 protected static function get_cleanup_sql() {
6442 $sql = "
6443 SELECT c.*
6444 FROM {context} c
6445 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6446 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6449 return $sql;
6453 * Rebuild context paths and depths at user context level.
6455 * @static
6456 * @param bool $force
6458 protected static function build_paths($force) {
6459 global $DB;
6461 // First update normal users.
6462 $path = $DB->sql_concat('?', 'id');
6463 $pathstart = '/' . SYSCONTEXTID . '/';
6464 $params = array($pathstart);
6466 if ($force) {
6467 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6468 $params[] = $pathstart;
6469 } else {
6470 $where = "depth = 0 OR path IS NULL";
6473 $sql = "UPDATE {context}
6474 SET depth = 2,
6475 path = {$path}
6476 WHERE contextlevel = " . CONTEXT_USER . "
6477 AND ($where)";
6478 $DB->execute($sql, $params);
6484 * Course category context class
6486 * @package core_access
6487 * @category access
6488 * @copyright Petr Skoda {@link http://skodak.org}
6489 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6490 * @since Moodle 2.2
6492 class context_coursecat extends context {
6494 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6495 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6497 * @param stdClass $record
6499 protected function __construct(stdClass $record) {
6500 parent::__construct($record);
6501 if ($record->contextlevel != CONTEXT_COURSECAT) {
6502 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6507 * Returns human readable context level name.
6509 * @static
6510 * @return string the human readable context level name.
6512 public static function get_level_name() {
6513 return get_string('category');
6517 * Returns human readable context identifier.
6519 * @param boolean $withprefix whether to prefix the name of the context with Category
6520 * @param boolean $short does not apply to course categories
6521 * @return string the human readable context name.
6523 public function get_context_name($withprefix = true, $short = false) {
6524 global $DB;
6526 $name = '';
6527 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6528 if ($withprefix){
6529 $name = get_string('category').': ';
6531 $name .= format_string($category->name, true, array('context' => $this));
6533 return $name;
6537 * Returns the most relevant URL for this context.
6539 * @return moodle_url
6541 public function get_url() {
6542 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6546 * Returns array of relevant context capability records.
6548 * @return array
6550 public function get_capabilities() {
6551 global $DB;
6553 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6555 $params = array();
6556 $sql = "SELECT *
6557 FROM {capabilities}
6558 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6560 return $DB->get_records_sql($sql.' '.$sort, $params);
6564 * Returns course category context instance.
6566 * @static
6567 * @param int $instanceid
6568 * @param int $strictness
6569 * @return context_coursecat context instance
6571 public static function instance($instanceid, $strictness = MUST_EXIST) {
6572 global $DB;
6574 if ($context = context::cache_get(CONTEXT_COURSECAT, $instanceid)) {
6575 return $context;
6578 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSECAT, 'instanceid'=>$instanceid))) {
6579 if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), 'id,parent', $strictness)) {
6580 if ($category->parent) {
6581 $parentcontext = context_coursecat::instance($category->parent);
6582 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6583 } else {
6584 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6589 if ($record) {
6590 $context = new context_coursecat($record);
6591 context::cache_add($context);
6592 return $context;
6595 return false;
6599 * Returns immediate child contexts of category and all subcategories,
6600 * children of subcategories and courses are not returned.
6602 * @return array
6604 public function get_child_contexts() {
6605 global $DB;
6607 if (empty($this->_path) or empty($this->_depth)) {
6608 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6609 return array();
6612 $sql = "SELECT ctx.*
6613 FROM {context} ctx
6614 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6615 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6616 $records = $DB->get_records_sql($sql, $params);
6618 $result = array();
6619 foreach ($records as $record) {
6620 $result[$record->id] = context::create_instance_from_record($record);
6623 return $result;
6627 * Create missing context instances at course category context level
6628 * @static
6630 protected static function create_level_instances() {
6631 global $DB;
6633 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6634 SELECT ".CONTEXT_COURSECAT.", cc.id
6635 FROM {course_categories} cc
6636 WHERE NOT EXISTS (SELECT 'x'
6637 FROM {context} cx
6638 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6639 $DB->execute($sql);
6643 * Returns sql necessary for purging of stale context instances.
6645 * @static
6646 * @return string cleanup SQL
6648 protected static function get_cleanup_sql() {
6649 $sql = "
6650 SELECT c.*
6651 FROM {context} c
6652 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6653 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6656 return $sql;
6660 * Rebuild context paths and depths at course category context level.
6662 * @static
6663 * @param bool $force
6665 protected static function build_paths($force) {
6666 global $DB;
6668 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6669 if ($force) {
6670 $ctxemptyclause = $emptyclause = '';
6671 } else {
6672 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6673 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6676 $base = '/'.SYSCONTEXTID;
6678 // Normal top level categories
6679 $sql = "UPDATE {context}
6680 SET depth=2,
6681 path=".$DB->sql_concat("'$base/'", 'id')."
6682 WHERE contextlevel=".CONTEXT_COURSECAT."
6683 AND EXISTS (SELECT 'x'
6684 FROM {course_categories} cc
6685 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6686 $emptyclause";
6687 $DB->execute($sql);
6689 // Deeper categories - one query per depthlevel
6690 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6691 for ($n=2; $n<=$maxdepth; $n++) {
6692 $sql = "INSERT INTO {context_temp} (id, path, depth)
6693 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6694 FROM {context} ctx
6695 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6696 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6697 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6698 $ctxemptyclause";
6699 $trans = $DB->start_delegated_transaction();
6700 $DB->delete_records('context_temp');
6701 $DB->execute($sql);
6702 context::merge_context_temp_table();
6703 $DB->delete_records('context_temp');
6704 $trans->allow_commit();
6713 * Course context class
6715 * @package core_access
6716 * @category access
6717 * @copyright Petr Skoda {@link http://skodak.org}
6718 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6719 * @since Moodle 2.2
6721 class context_course extends context {
6723 * Please use context_course::instance($courseid) if you need the instance of context.
6724 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6726 * @param stdClass $record
6728 protected function __construct(stdClass $record) {
6729 parent::__construct($record);
6730 if ($record->contextlevel != CONTEXT_COURSE) {
6731 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6736 * Returns human readable context level name.
6738 * @static
6739 * @return string the human readable context level name.
6741 public static function get_level_name() {
6742 return get_string('course');
6746 * Returns human readable context identifier.
6748 * @param boolean $withprefix whether to prefix the name of the context with Course
6749 * @param boolean $short whether to use the short name of the thing.
6750 * @return string the human readable context name.
6752 public function get_context_name($withprefix = true, $short = false) {
6753 global $DB;
6755 $name = '';
6756 if ($this->_instanceid == SITEID) {
6757 $name = get_string('frontpage', 'admin');
6758 } else {
6759 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6760 if ($withprefix){
6761 $name = get_string('course').': ';
6763 if ($short){
6764 $name .= format_string($course->shortname, true, array('context' => $this));
6765 } else {
6766 $name .= format_string(get_course_display_name_for_list($course));
6770 return $name;
6774 * Returns the most relevant URL for this context.
6776 * @return moodle_url
6778 public function get_url() {
6779 if ($this->_instanceid != SITEID) {
6780 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6783 return new moodle_url('/');
6787 * Returns array of relevant context capability records.
6789 * @return array
6791 public function get_capabilities() {
6792 global $DB;
6794 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6796 $params = array();
6797 $sql = "SELECT *
6798 FROM {capabilities}
6799 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6801 return $DB->get_records_sql($sql.' '.$sort, $params);
6805 * Is this context part of any course? If yes return course context.
6807 * @param bool $strict true means throw exception if not found, false means return false if not found
6808 * @return context_course context of the enclosing course, null if not found or exception
6810 public function get_course_context($strict = true) {
6811 return $this;
6815 * Returns course context instance.
6817 * @static
6818 * @param int $instanceid
6819 * @param int $strictness
6820 * @return context_course context instance
6822 public static function instance($instanceid, $strictness = MUST_EXIST) {
6823 global $DB;
6825 if ($context = context::cache_get(CONTEXT_COURSE, $instanceid)) {
6826 return $context;
6829 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$instanceid))) {
6830 if ($course = $DB->get_record('course', array('id'=>$instanceid), 'id,category', $strictness)) {
6831 if ($course->category) {
6832 $parentcontext = context_coursecat::instance($course->category);
6833 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6834 } else {
6835 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6840 if ($record) {
6841 $context = new context_course($record);
6842 context::cache_add($context);
6843 return $context;
6846 return false;
6850 * Create missing context instances at course context level
6851 * @static
6853 protected static function create_level_instances() {
6854 global $DB;
6856 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6857 SELECT ".CONTEXT_COURSE.", c.id
6858 FROM {course} c
6859 WHERE NOT EXISTS (SELECT 'x'
6860 FROM {context} cx
6861 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
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} co ON c.instanceid = co.id
6876 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6879 return $sql;
6883 * Rebuild context paths and depths at course 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_COURSE." AND (depth = 0 OR path IS NULL)")) {
6892 if ($force) {
6893 $ctxemptyclause = $emptyclause = '';
6894 } else {
6895 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6896 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6899 $base = '/'.SYSCONTEXTID;
6901 // Standard frontpage
6902 $sql = "UPDATE {context}
6903 SET depth = 2,
6904 path = ".$DB->sql_concat("'$base/'", 'id')."
6905 WHERE contextlevel = ".CONTEXT_COURSE."
6906 AND EXISTS (SELECT 'x'
6907 FROM {course} c
6908 WHERE c.id = {context}.instanceid AND c.category = 0)
6909 $emptyclause";
6910 $DB->execute($sql);
6912 // standard courses
6913 $sql = "INSERT INTO {context_temp} (id, path, depth)
6914 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6915 FROM {context} ctx
6916 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6917 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6918 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6919 $ctxemptyclause";
6920 $trans = $DB->start_delegated_transaction();
6921 $DB->delete_records('context_temp');
6922 $DB->execute($sql);
6923 context::merge_context_temp_table();
6924 $DB->delete_records('context_temp');
6925 $trans->allow_commit();
6932 * Course module context class
6934 * @package core_access
6935 * @category access
6936 * @copyright Petr Skoda {@link http://skodak.org}
6937 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6938 * @since Moodle 2.2
6940 class context_module extends context {
6942 * Please use context_module::instance($cmid) if you need the instance of context.
6943 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6945 * @param stdClass $record
6947 protected function __construct(stdClass $record) {
6948 parent::__construct($record);
6949 if ($record->contextlevel != CONTEXT_MODULE) {
6950 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6955 * Returns human readable context level name.
6957 * @static
6958 * @return string the human readable context level name.
6960 public static function get_level_name() {
6961 return get_string('activitymodule');
6965 * Returns human readable context identifier.
6967 * @param boolean $withprefix whether to prefix the name of the context with the
6968 * module name, e.g. Forum, Glossary, etc.
6969 * @param boolean $short does not apply to module context
6970 * @return string the human readable context name.
6972 public function get_context_name($withprefix = true, $short = false) {
6973 global $DB;
6975 $name = '';
6976 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6977 FROM {course_modules} cm
6978 JOIN {modules} md ON md.id = cm.module
6979 WHERE cm.id = ?", array($this->_instanceid))) {
6980 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6981 if ($withprefix){
6982 $name = get_string('modulename', $cm->modname).': ';
6984 $name .= format_string($mod->name, true, array('context' => $this));
6987 return $name;
6991 * Returns the most relevant URL for this context.
6993 * @return moodle_url
6995 public function get_url() {
6996 global $DB;
6998 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6999 FROM {course_modules} cm
7000 JOIN {modules} md ON md.id = cm.module
7001 WHERE cm.id = ?", array($this->_instanceid))) {
7002 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
7005 return new moodle_url('/');
7009 * Returns array of relevant context capability records.
7011 * @return array
7013 public function get_capabilities() {
7014 global $DB, $CFG;
7016 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7018 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
7019 $module = $DB->get_record('modules', array('id'=>$cm->module));
7021 $subcaps = array();
7022 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
7023 if (file_exists($subpluginsfile)) {
7024 $subplugins = array(); // should be redefined in the file
7025 include($subpluginsfile);
7026 if (!empty($subplugins)) {
7027 foreach (array_keys($subplugins) as $subplugintype) {
7028 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
7029 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
7035 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
7036 $extracaps = array();
7037 if (file_exists($modfile)) {
7038 include_once($modfile);
7039 $modfunction = $module->name.'_get_extra_capabilities';
7040 if (function_exists($modfunction)) {
7041 $extracaps = $modfunction();
7045 $extracaps = array_merge($subcaps, $extracaps);
7046 $extra = '';
7047 list($extra, $params) = $DB->get_in_or_equal(
7048 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
7049 if (!empty($extra)) {
7050 $extra = "OR name $extra";
7052 $sql = "SELECT *
7053 FROM {capabilities}
7054 WHERE (contextlevel = ".CONTEXT_MODULE."
7055 AND (component = :component OR component = 'moodle'))
7056 $extra";
7057 $params['component'] = "mod_$module->name";
7059 return $DB->get_records_sql($sql.' '.$sort, $params);
7063 * Is this context part of any course? If yes return course context.
7065 * @param bool $strict true means throw exception if not found, false means return false if not found
7066 * @return context_course context of the enclosing course, null if not found or exception
7068 public function get_course_context($strict = true) {
7069 return $this->get_parent_context();
7073 * Returns module context instance.
7075 * @static
7076 * @param int $instanceid
7077 * @param int $strictness
7078 * @return context_module context instance
7080 public static function instance($instanceid, $strictness = MUST_EXIST) {
7081 global $DB;
7083 if ($context = context::cache_get(CONTEXT_MODULE, $instanceid)) {
7084 return $context;
7087 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$instanceid))) {
7088 if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), 'id,course', $strictness)) {
7089 $parentcontext = context_course::instance($cm->course);
7090 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
7094 if ($record) {
7095 $context = new context_module($record);
7096 context::cache_add($context);
7097 return $context;
7100 return false;
7104 * Create missing context instances at module context level
7105 * @static
7107 protected static function create_level_instances() {
7108 global $DB;
7110 $sql = "INSERT INTO {context} (contextlevel, instanceid)
7111 SELECT ".CONTEXT_MODULE.", cm.id
7112 FROM {course_modules} cm
7113 WHERE NOT EXISTS (SELECT 'x'
7114 FROM {context} cx
7115 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
7116 $DB->execute($sql);
7120 * Returns sql necessary for purging of stale context instances.
7122 * @static
7123 * @return string cleanup SQL
7125 protected static function get_cleanup_sql() {
7126 $sql = "
7127 SELECT c.*
7128 FROM {context} c
7129 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
7130 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
7133 return $sql;
7137 * Rebuild context paths and depths at module context level.
7139 * @static
7140 * @param bool $force
7142 protected static function build_paths($force) {
7143 global $DB;
7145 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
7146 if ($force) {
7147 $ctxemptyclause = '';
7148 } else {
7149 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7152 $sql = "INSERT INTO {context_temp} (id, path, depth)
7153 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7154 FROM {context} ctx
7155 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
7156 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
7157 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7158 $ctxemptyclause";
7159 $trans = $DB->start_delegated_transaction();
7160 $DB->delete_records('context_temp');
7161 $DB->execute($sql);
7162 context::merge_context_temp_table();
7163 $DB->delete_records('context_temp');
7164 $trans->allow_commit();
7171 * Block context class
7173 * @package core_access
7174 * @category access
7175 * @copyright Petr Skoda {@link http://skodak.org}
7176 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7177 * @since Moodle 2.2
7179 class context_block extends context {
7181 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
7182 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7184 * @param stdClass $record
7186 protected function __construct(stdClass $record) {
7187 parent::__construct($record);
7188 if ($record->contextlevel != CONTEXT_BLOCK) {
7189 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
7194 * Returns human readable context level name.
7196 * @static
7197 * @return string the human readable context level name.
7199 public static function get_level_name() {
7200 return get_string('block');
7204 * Returns human readable context identifier.
7206 * @param boolean $withprefix whether to prefix the name of the context with Block
7207 * @param boolean $short does not apply to block context
7208 * @return string the human readable context name.
7210 public function get_context_name($withprefix = true, $short = false) {
7211 global $DB, $CFG;
7213 $name = '';
7214 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
7215 global $CFG;
7216 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7217 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7218 $blockname = "block_$blockinstance->blockname";
7219 if ($blockobject = new $blockname()) {
7220 if ($withprefix){
7221 $name = get_string('block').': ';
7223 $name .= $blockobject->title;
7227 return $name;
7231 * Returns the most relevant URL for this context.
7233 * @return moodle_url
7235 public function get_url() {
7236 $parentcontexts = $this->get_parent_context();
7237 return $parentcontexts->get_url();
7241 * Returns array of relevant context capability records.
7243 * @return array
7245 public function get_capabilities() {
7246 global $DB;
7248 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7250 $params = array();
7251 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
7253 $extra = '';
7254 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7255 if ($extracaps) {
7256 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7257 $extra = "OR name $extra";
7260 $sql = "SELECT *
7261 FROM {capabilities}
7262 WHERE (contextlevel = ".CONTEXT_BLOCK."
7263 AND component = :component)
7264 $extra";
7265 $params['component'] = 'block_' . $bi->blockname;
7267 return $DB->get_records_sql($sql.' '.$sort, $params);
7271 * Is this context part of any course? If yes return course context.
7273 * @param bool $strict true means throw exception if not found, false means return false if not found
7274 * @return context_course context of the enclosing course, null if not found or exception
7276 public function get_course_context($strict = true) {
7277 $parentcontext = $this->get_parent_context();
7278 return $parentcontext->get_course_context($strict);
7282 * Returns block context instance.
7284 * @static
7285 * @param int $instanceid
7286 * @param int $strictness
7287 * @return context_block context instance
7289 public static function instance($instanceid, $strictness = MUST_EXIST) {
7290 global $DB;
7292 if ($context = context::cache_get(CONTEXT_BLOCK, $instanceid)) {
7293 return $context;
7296 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$instanceid))) {
7297 if ($bi = $DB->get_record('block_instances', array('id'=>$instanceid), 'id,parentcontextid', $strictness)) {
7298 $parentcontext = context::instance_by_id($bi->parentcontextid);
7299 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7303 if ($record) {
7304 $context = new context_block($record);
7305 context::cache_add($context);
7306 return $context;
7309 return false;
7313 * Block do not have child contexts...
7314 * @return array
7316 public function get_child_contexts() {
7317 return array();
7321 * Create missing context instances at block context level
7322 * @static
7324 protected static function create_level_instances() {
7325 global $DB;
7327 $sql = "INSERT INTO {context} (contextlevel, instanceid)
7328 SELECT ".CONTEXT_BLOCK.", bi.id
7329 FROM {block_instances} bi
7330 WHERE NOT EXISTS (SELECT 'x'
7331 FROM {context} cx
7332 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7333 $DB->execute($sql);
7337 * Returns sql necessary for purging of stale context instances.
7339 * @static
7340 * @return string cleanup SQL
7342 protected static function get_cleanup_sql() {
7343 $sql = "
7344 SELECT c.*
7345 FROM {context} c
7346 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7347 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7350 return $sql;
7354 * Rebuild context paths and depths at block context level.
7356 * @static
7357 * @param bool $force
7359 protected static function build_paths($force) {
7360 global $DB;
7362 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7363 if ($force) {
7364 $ctxemptyclause = '';
7365 } else {
7366 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7369 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7370 $sql = "INSERT INTO {context_temp} (id, path, depth)
7371 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7372 FROM {context} ctx
7373 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7374 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7375 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7376 $ctxemptyclause";
7377 $trans = $DB->start_delegated_transaction();
7378 $DB->delete_records('context_temp');
7379 $DB->execute($sql);
7380 context::merge_context_temp_table();
7381 $DB->delete_records('context_temp');
7382 $trans->allow_commit();
7388 // ============== DEPRECATED FUNCTIONS ==========================================
7389 // Old context related functions were deprecated in 2.0, it is recommended
7390 // to use context classes in new code. Old function can be used when
7391 // creating patches that are supposed to be backported to older stable branches.
7392 // These deprecated functions will not be removed in near future,
7393 // before removing devs will be warned with a debugging message first,
7394 // then we will add error message and only after that we can remove the functions
7395 // completely.
7398 * Runs get_records select on context table and returns the result
7399 * Does get_records_select on the context table, and returns the results ordered
7400 * by contextlevel, and then the natural sort order within each level.
7401 * for the purpose of $select, you need to know that the context table has been
7402 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7404 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7405 * @param array $params any parameters required by $select.
7406 * @return array the requested context records.
7408 function get_sorted_contexts($select, $params = array()) {
7410 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7412 global $DB;
7413 if ($select) {
7414 $select = 'WHERE ' . $select;
7416 return $DB->get_records_sql("
7417 SELECT ctx.*
7418 FROM {context} ctx
7419 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7420 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7421 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7422 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7423 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7424 $select
7425 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7426 ", $params);
7430 * Given context and array of users, returns array of users whose enrolment status is suspended,
7431 * or enrolment has expired or has not started. Also removes those users from the given array
7433 * @param context $context context in which suspended users should be extracted.
7434 * @param array $users list of users.
7435 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7436 * @return array list of suspended users.
7438 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7439 global $DB;
7441 // Get active enrolled users.
7442 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7443 $activeusers = $DB->get_records_sql($sql, $params);
7445 // Move suspended users to a separate array & remove from the initial one.
7446 $susers = array();
7447 if (sizeof($activeusers)) {
7448 foreach ($users as $userid => $user) {
7449 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7450 $susers[$userid] = $user;
7451 unset($users[$userid]);
7455 return $susers;
7459 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7460 * or enrolment has expired or not started.
7462 * @param context $context context in which user enrolment is checked.
7463 * @return array list of suspended user id's.
7465 function get_suspended_userids($context){
7466 global $DB;
7468 // Get all enrolled users.
7469 list($sql, $params) = get_enrolled_sql($context);
7470 $users = $DB->get_records_sql($sql, $params);
7472 // Get active enrolled users.
7473 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7474 $activeusers = $DB->get_records_sql($sql, $params);
7476 $susers = array();
7477 if (sizeof($activeusers) != sizeof($users)) {
7478 foreach ($users as $userid => $user) {
7479 if (!array_key_exists($userid, $activeusers)) {
7480 $susers[$userid] = $userid;
7484 return $susers;