MDL-42754 Messages: Show noreply user notifications
[moodle.git] / lib / accesslib.php
blob45f07b49de8b315e8b55a1b2fbb96e1ca80528d9
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->acces['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1117 // share rdef from USER session with rolepermissions cache in order to conserve memory
1118 foreach($USER->acces['rdef'] as $k=>$v) {
1119 $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->acces['rdef'][$k];
1121 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->acces;
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 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 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;
1748 $ra->id = $DB->insert_record('role_assignments', $ra);
1750 // mark context as dirty - again expensive, but needed
1751 $context->mark_dirty();
1753 if (!empty($USER->id) && $USER->id == $userid) {
1754 // If the user is the current user, then do full reload of capabilities too.
1755 reload_all_capabilities();
1758 $event = \core\event\role_assigned::create(
1759 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1760 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1761 $event->add_record_snapshot('role_assignments', $ra);
1762 $event->trigger();
1764 return $ra->id;
1768 * Removes one role assignment
1770 * @param int $roleid
1771 * @param int $userid
1772 * @param int $contextid
1773 * @param string $component
1774 * @param int $itemid
1775 * @return void
1777 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1778 // first make sure the params make sense
1779 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1780 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1783 if ($itemid) {
1784 if (strpos($component, '_') === false) {
1785 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1787 } else {
1788 $itemid = 0;
1789 if ($component !== '' and strpos($component, '_') === false) {
1790 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1794 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1798 * Removes multiple role assignments, parameters may contain:
1799 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1801 * @param array $params role assignment parameters
1802 * @param bool $subcontexts unassign in subcontexts too
1803 * @param bool $includemanual include manual role assignments too
1804 * @return void
1806 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1807 global $USER, $CFG, $DB;
1809 if (!$params) {
1810 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1813 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1814 foreach ($params as $key=>$value) {
1815 if (!in_array($key, $allowed)) {
1816 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1820 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1821 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1824 if ($includemanual) {
1825 if (!isset($params['component']) or $params['component'] === '') {
1826 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1830 if ($subcontexts) {
1831 if (empty($params['contextid'])) {
1832 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1836 $ras = $DB->get_records('role_assignments', $params);
1837 foreach($ras as $ra) {
1838 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1839 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1840 // this is a bit expensive but necessary
1841 $context->mark_dirty();
1842 // If the user is the current user, then do full reload of capabilities too.
1843 if (!empty($USER->id) && $USER->id == $ra->userid) {
1844 reload_all_capabilities();
1846 $event = \core\event\role_unassigned::create(
1847 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1848 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1849 $event->add_record_snapshot('role_assignments', $ra);
1850 $event->trigger();
1853 unset($ras);
1855 // process subcontexts
1856 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1857 if ($params['contextid'] instanceof context) {
1858 $context = $params['contextid'];
1859 } else {
1860 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1863 if ($context) {
1864 $contexts = $context->get_child_contexts();
1865 $mparams = $params;
1866 foreach($contexts as $context) {
1867 $mparams['contextid'] = $context->id;
1868 $ras = $DB->get_records('role_assignments', $mparams);
1869 foreach($ras as $ra) {
1870 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1871 // this is a bit expensive but necessary
1872 $context->mark_dirty();
1873 // If the user is the current user, then do full reload of capabilities too.
1874 if (!empty($USER->id) && $USER->id == $ra->userid) {
1875 reload_all_capabilities();
1877 $event = \core\event\role_unassigned::create(
1878 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1879 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1880 $event->add_record_snapshot('role_assignments', $ra);
1881 $event->trigger();
1887 // do this once more for all manual role assignments
1888 if ($includemanual) {
1889 $params['component'] = '';
1890 role_unassign_all($params, $subcontexts, false);
1895 * Determines if a user is currently logged in
1897 * @category access
1899 * @return bool
1901 function isloggedin() {
1902 global $USER;
1904 return (!empty($USER->id));
1908 * Determines if a user is logged in as real guest user with username 'guest'.
1910 * @category access
1912 * @param int|object $user mixed user object or id, $USER if not specified
1913 * @return bool true if user is the real guest user, false if not logged in or other user
1915 function isguestuser($user = null) {
1916 global $USER, $DB, $CFG;
1918 // make sure we have the user id cached in config table, because we are going to use it a lot
1919 if (empty($CFG->siteguest)) {
1920 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1921 // guest does not exist yet, weird
1922 return false;
1924 set_config('siteguest', $guestid);
1926 if ($user === null) {
1927 $user = $USER;
1930 if ($user === null) {
1931 // happens when setting the $USER
1932 return false;
1934 } else if (is_numeric($user)) {
1935 return ($CFG->siteguest == $user);
1937 } else if (is_object($user)) {
1938 if (empty($user->id)) {
1939 return false; // not logged in means is not be guest
1940 } else {
1941 return ($CFG->siteguest == $user->id);
1944 } else {
1945 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1950 * Does user have a (temporary or real) guest access to course?
1952 * @category access
1954 * @param context $context
1955 * @param stdClass|int $user
1956 * @return bool
1958 function is_guest(context $context, $user = null) {
1959 global $USER;
1961 // first find the course context
1962 $coursecontext = $context->get_course_context();
1964 // make sure there is a real user specified
1965 if ($user === null) {
1966 $userid = isset($USER->id) ? $USER->id : 0;
1967 } else {
1968 $userid = is_object($user) ? $user->id : $user;
1971 if (isguestuser($userid)) {
1972 // can not inspect or be enrolled
1973 return true;
1976 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1977 // viewing users appear out of nowhere, they are neither guests nor participants
1978 return false;
1981 // consider only real active enrolments here
1982 if (is_enrolled($coursecontext, $user, '', true)) {
1983 return false;
1986 return true;
1990 * Returns true if the user has moodle/course:view capability in the course,
1991 * this is intended for admins, managers (aka small admins), inspectors, etc.
1993 * @category access
1995 * @param context $context
1996 * @param int|stdClass $user if null $USER is used
1997 * @param string $withcapability extra capability name
1998 * @return bool
2000 function is_viewing(context $context, $user = null, $withcapability = '') {
2001 // first find the course context
2002 $coursecontext = $context->get_course_context();
2004 if (isguestuser($user)) {
2005 // can not inspect
2006 return false;
2009 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
2010 // admins are allowed to inspect courses
2011 return false;
2014 if ($withcapability and !has_capability($withcapability, $context, $user)) {
2015 // site admins always have the capability, but the enrolment above blocks
2016 return false;
2019 return true;
2023 * Returns true if user is enrolled (is participating) in course
2024 * this is intended for students and teachers.
2026 * Since 2.2 the result for active enrolments and current user are cached.
2028 * @package core_enrol
2029 * @category access
2031 * @param context $context
2032 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
2033 * @param string $withcapability extra capability name
2034 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2035 * @return bool
2037 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
2038 global $USER, $DB;
2040 // first find the course context
2041 $coursecontext = $context->get_course_context();
2043 // make sure there is a real user specified
2044 if ($user === null) {
2045 $userid = isset($USER->id) ? $USER->id : 0;
2046 } else {
2047 $userid = is_object($user) ? $user->id : $user;
2050 if (empty($userid)) {
2051 // not-logged-in!
2052 return false;
2053 } else if (isguestuser($userid)) {
2054 // guest account can not be enrolled anywhere
2055 return false;
2058 if ($coursecontext->instanceid == SITEID) {
2059 // everybody participates on frontpage
2060 } else {
2061 // try cached info first - the enrolled flag is set only when active enrolment present
2062 if ($USER->id == $userid) {
2063 $coursecontext->reload_if_dirty();
2064 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
2065 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
2066 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2067 return false;
2069 return true;
2074 if ($onlyactive) {
2075 // look for active enrolments only
2076 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
2078 if ($until === false) {
2079 return false;
2082 if ($USER->id == $userid) {
2083 if ($until == 0) {
2084 $until = ENROL_MAX_TIMESTAMP;
2086 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
2087 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
2088 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
2089 remove_temp_course_roles($coursecontext);
2093 } else {
2094 // any enrolment is good for us here, even outdated, disabled or inactive
2095 $sql = "SELECT 'x'
2096 FROM {user_enrolments} ue
2097 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2098 JOIN {user} u ON u.id = ue.userid
2099 WHERE ue.userid = :userid AND u.deleted = 0";
2100 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2101 if (!$DB->record_exists_sql($sql, $params)) {
2102 return false;
2107 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2108 return false;
2111 return true;
2115 * Returns true if the user is able to access the course.
2117 * This function is in no way, shape, or form a substitute for require_login.
2118 * It should only be used in circumstances where it is not possible to call require_login
2119 * such as the navigation.
2121 * This function checks many of the methods of access to a course such as the view
2122 * capability, enrollments, and guest access. It also makes use of the cache
2123 * generated by require_login for guest access.
2125 * The flags within the $USER object that are used here should NEVER be used outside
2126 * of this function can_access_course and require_login. Doing so WILL break future
2127 * versions.
2129 * @param stdClass $course record
2130 * @param stdClass|int|null $user user record or id, current user if null
2131 * @param string $withcapability Check for this capability as well.
2132 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2133 * @return boolean Returns true if the user is able to access the course
2135 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
2136 global $DB, $USER;
2138 // this function originally accepted $coursecontext parameter
2139 if ($course instanceof context) {
2140 if ($course instanceof context_course) {
2141 debugging('deprecated context parameter, please use $course record');
2142 $coursecontext = $course;
2143 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2144 } else {
2145 debugging('Invalid context parameter, please use $course record');
2146 return false;
2148 } else {
2149 $coursecontext = context_course::instance($course->id);
2152 if (!isset($USER->id)) {
2153 // should never happen
2154 $USER->id = 0;
2155 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
2158 // make sure there is a user specified
2159 if ($user === null) {
2160 $userid = $USER->id;
2161 } else {
2162 $userid = is_object($user) ? $user->id : $user;
2164 unset($user);
2166 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2167 return false;
2170 if ($userid == $USER->id) {
2171 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2172 // the fact that somebody switched role means they can access the course no matter to what role they switched
2173 return true;
2177 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2178 return false;
2181 if (is_viewing($coursecontext, $userid)) {
2182 return true;
2185 if ($userid != $USER->id) {
2186 // for performance reasons we do not verify temporary guest access for other users, sorry...
2187 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2190 // === from here we deal only with $USER ===
2192 $coursecontext->reload_if_dirty();
2194 if (isset($USER->enrol['enrolled'][$course->id])) {
2195 if ($USER->enrol['enrolled'][$course->id] > time()) {
2196 return true;
2199 if (isset($USER->enrol['tempguest'][$course->id])) {
2200 if ($USER->enrol['tempguest'][$course->id] > time()) {
2201 return true;
2205 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2206 return true;
2209 // if not enrolled try to gain temporary guest access
2210 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2211 $enrols = enrol_get_plugins(true);
2212 foreach($instances as $instance) {
2213 if (!isset($enrols[$instance->enrol])) {
2214 continue;
2216 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2217 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2218 if ($until !== false and $until > time()) {
2219 $USER->enrol['tempguest'][$course->id] = $until;
2220 return true;
2223 if (isset($USER->enrol['tempguest'][$course->id])) {
2224 unset($USER->enrol['tempguest'][$course->id]);
2225 remove_temp_course_roles($coursecontext);
2228 return false;
2232 * Returns array with sql code and parameters returning all ids
2233 * of users enrolled into course.
2235 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2237 * @package core_enrol
2238 * @category access
2240 * @param context $context
2241 * @param string $withcapability
2242 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2243 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2244 * @return array list($sql, $params)
2246 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2247 global $DB, $CFG;
2249 // use unique prefix just in case somebody makes some SQL magic with the result
2250 static $i = 0;
2251 $i++;
2252 $prefix = 'eu'.$i.'_';
2254 // first find the course context
2255 $coursecontext = $context->get_course_context();
2257 $isfrontpage = ($coursecontext->instanceid == SITEID);
2259 $joins = array();
2260 $wheres = array();
2261 $params = array();
2263 list($contextids, $contextpaths) = get_context_info_list($context);
2265 // get all relevant capability info for all roles
2266 if ($withcapability) {
2267 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2268 $cparams['cap'] = $withcapability;
2270 $defs = array();
2271 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2272 FROM {role_capabilities} rc
2273 JOIN {context} ctx on rc.contextid = ctx.id
2274 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2275 $rcs = $DB->get_records_sql($sql, $cparams);
2276 foreach ($rcs as $rc) {
2277 $defs[$rc->path][$rc->roleid] = $rc->permission;
2280 $access = array();
2281 if (!empty($defs)) {
2282 foreach ($contextpaths as $path) {
2283 if (empty($defs[$path])) {
2284 continue;
2286 foreach($defs[$path] as $roleid => $perm) {
2287 if ($perm == CAP_PROHIBIT) {
2288 $access[$roleid] = CAP_PROHIBIT;
2289 continue;
2291 if (!isset($access[$roleid])) {
2292 $access[$roleid] = (int)$perm;
2298 unset($defs);
2300 // make lists of roles that are needed and prohibited
2301 $needed = array(); // one of these is enough
2302 $prohibited = array(); // must not have any of these
2303 foreach ($access as $roleid => $perm) {
2304 if ($perm == CAP_PROHIBIT) {
2305 unset($needed[$roleid]);
2306 $prohibited[$roleid] = true;
2307 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2308 $needed[$roleid] = true;
2312 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2313 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2315 $nobody = false;
2317 if ($isfrontpage) {
2318 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2319 $nobody = true;
2320 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2321 // everybody not having prohibit has the capability
2322 $needed = array();
2323 } else if (empty($needed)) {
2324 $nobody = true;
2326 } else {
2327 if (!empty($prohibited[$defaultuserroleid])) {
2328 $nobody = true;
2329 } else if (!empty($needed[$defaultuserroleid])) {
2330 // everybody not having prohibit has the capability
2331 $needed = array();
2332 } else if (empty($needed)) {
2333 $nobody = true;
2337 if ($nobody) {
2338 // nobody can match so return some SQL that does not return any results
2339 $wheres[] = "1 = 2";
2341 } else {
2343 if ($needed) {
2344 $ctxids = implode(',', $contextids);
2345 $roleids = implode(',', array_keys($needed));
2346 $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))";
2349 if ($prohibited) {
2350 $ctxids = implode(',', $contextids);
2351 $roleids = implode(',', array_keys($prohibited));
2352 $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))";
2353 $wheres[] = "{$prefix}ra4.id IS NULL";
2356 if ($groupid) {
2357 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2358 $params["{$prefix}gmid"] = $groupid;
2362 } else {
2363 if ($groupid) {
2364 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2365 $params["{$prefix}gmid"] = $groupid;
2369 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2370 $params["{$prefix}guestid"] = $CFG->siteguest;
2372 if ($isfrontpage) {
2373 // all users are "enrolled" on the frontpage
2374 } else {
2375 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2376 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2377 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2379 if ($onlyactive) {
2380 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2381 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2382 $now = round(time(), -2); // rounding helps caching in DB
2383 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2384 $prefix.'active'=>ENROL_USER_ACTIVE,
2385 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2389 $joins = implode("\n", $joins);
2390 $wheres = "WHERE ".implode(" AND ", $wheres);
2392 $sql = "SELECT DISTINCT {$prefix}u.id
2393 FROM {user} {$prefix}u
2394 $joins
2395 $wheres";
2397 return array($sql, $params);
2401 * Returns list of users enrolled into course.
2403 * @package core_enrol
2404 * @category access
2406 * @param context $context
2407 * @param string $withcapability
2408 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2409 * @param string $userfields requested user record fields
2410 * @param string $orderby
2411 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2412 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2413 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2414 * @return array of user records
2416 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
2417 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
2418 global $DB;
2420 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2421 $sql = "SELECT $userfields
2422 FROM {user} u
2423 JOIN ($esql) je ON je.id = u.id
2424 WHERE u.deleted = 0";
2426 if ($orderby) {
2427 $sql = "$sql ORDER BY $orderby";
2428 } else {
2429 list($sort, $sortparams) = users_order_by_sql('u');
2430 $sql = "$sql ORDER BY $sort";
2431 $params = array_merge($params, $sortparams);
2434 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2438 * Counts list of users enrolled into course (as per above function)
2440 * @package core_enrol
2441 * @category access
2443 * @param context $context
2444 * @param string $withcapability
2445 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2446 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2447 * @return array of user records
2449 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2450 global $DB;
2452 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2453 $sql = "SELECT count(u.id)
2454 FROM {user} u
2455 JOIN ($esql) je ON je.id = u.id
2456 WHERE u.deleted = 0";
2458 return $DB->count_records_sql($sql, $params);
2462 * Loads the capability definitions for the component (from file).
2464 * Loads the capability definitions for the component (from file). If no
2465 * capabilities are defined for the component, we simply return an empty array.
2467 * @access private
2468 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2469 * @return array array of capabilities
2471 function load_capability_def($component) {
2472 $defpath = core_component::get_component_directory($component).'/db/access.php';
2474 $capabilities = array();
2475 if (file_exists($defpath)) {
2476 require($defpath);
2477 if (!empty(${$component.'_capabilities'})) {
2478 // BC capability array name
2479 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2480 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2481 $capabilities = ${$component.'_capabilities'};
2485 return $capabilities;
2489 * Gets the capabilities that have been cached in the database for this component.
2491 * @access private
2492 * @param string $component - examples: 'moodle', 'mod_forum'
2493 * @return array array of capabilities
2495 function get_cached_capabilities($component = 'moodle') {
2496 global $DB;
2497 return $DB->get_records('capabilities', array('component'=>$component));
2501 * Returns default capabilities for given role archetype.
2503 * @param string $archetype role archetype
2504 * @return array
2506 function get_default_capabilities($archetype) {
2507 global $DB;
2509 if (!$archetype) {
2510 return array();
2513 $alldefs = array();
2514 $defaults = array();
2515 $components = array();
2516 $allcaps = $DB->get_records('capabilities');
2518 foreach ($allcaps as $cap) {
2519 if (!in_array($cap->component, $components)) {
2520 $components[] = $cap->component;
2521 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2524 foreach($alldefs as $name=>$def) {
2525 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2526 if (isset($def['archetypes'])) {
2527 if (isset($def['archetypes'][$archetype])) {
2528 $defaults[$name] = $def['archetypes'][$archetype];
2530 // 'legacy' is for backward compatibility with 1.9 access.php
2531 } else {
2532 if (isset($def['legacy'][$archetype])) {
2533 $defaults[$name] = $def['legacy'][$archetype];
2538 return $defaults;
2542 * Return default roles that can be assigned, overridden or switched
2543 * by give role archetype.
2545 * @param string $type assign|override|switch
2546 * @param string $archetype
2547 * @return array of role ids
2549 function get_default_role_archetype_allows($type, $archetype) {
2550 global $DB;
2552 if (empty($archetype)) {
2553 return array();
2556 $roles = $DB->get_records('role');
2557 $archetypemap = array();
2558 foreach ($roles as $role) {
2559 if ($role->archetype) {
2560 $archetypemap[$role->archetype][$role->id] = $role->id;
2564 $defaults = array(
2565 'assign' => array(
2566 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2567 'coursecreator' => array(),
2568 'editingteacher' => array('teacher', 'student'),
2569 'teacher' => array(),
2570 'student' => array(),
2571 'guest' => array(),
2572 'user' => array(),
2573 'frontpage' => array(),
2575 'override' => array(
2576 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2577 'coursecreator' => array(),
2578 'editingteacher' => array('teacher', 'student', 'guest'),
2579 'teacher' => array(),
2580 'student' => array(),
2581 'guest' => array(),
2582 'user' => array(),
2583 'frontpage' => array(),
2585 'switch' => array(
2586 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2587 'coursecreator' => array(),
2588 'editingteacher' => array('teacher', 'student', 'guest'),
2589 'teacher' => array('student', 'guest'),
2590 'student' => array(),
2591 'guest' => array(),
2592 'user' => array(),
2593 'frontpage' => array(),
2597 if (!isset($defaults[$type][$archetype])) {
2598 debugging("Unknown type '$type'' or archetype '$archetype''");
2599 return array();
2602 $return = array();
2603 foreach ($defaults[$type][$archetype] as $at) {
2604 if (isset($archetypemap[$at])) {
2605 foreach ($archetypemap[$at] as $roleid) {
2606 $return[$roleid] = $roleid;
2611 return $return;
2615 * Reset role capabilities to default according to selected role archetype.
2616 * If no archetype selected, removes all capabilities.
2618 * @param int $roleid
2619 * @return void
2621 function reset_role_capabilities($roleid) {
2622 global $DB;
2624 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2625 $defaultcaps = get_default_capabilities($role->archetype);
2627 $systemcontext = context_system::instance();
2629 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2631 foreach($defaultcaps as $cap=>$permission) {
2632 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2637 * Updates the capabilities table with the component capability definitions.
2638 * If no parameters are given, the function updates the core moodle
2639 * capabilities.
2641 * Note that the absence of the db/access.php capabilities definition file
2642 * will cause any stored capabilities for the component to be removed from
2643 * the database.
2645 * @access private
2646 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2647 * @return boolean true if success, exception in case of any problems
2649 function update_capabilities($component = 'moodle') {
2650 global $DB, $OUTPUT;
2652 $storedcaps = array();
2654 $filecaps = load_capability_def($component);
2655 foreach($filecaps as $capname=>$unused) {
2656 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2657 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2661 $cachedcaps = get_cached_capabilities($component);
2662 if ($cachedcaps) {
2663 foreach ($cachedcaps as $cachedcap) {
2664 array_push($storedcaps, $cachedcap->name);
2665 // update risk bitmasks and context levels in existing capabilities if needed
2666 if (array_key_exists($cachedcap->name, $filecaps)) {
2667 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2668 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2670 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2671 $updatecap = new stdClass();
2672 $updatecap->id = $cachedcap->id;
2673 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2674 $DB->update_record('capabilities', $updatecap);
2676 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2677 $updatecap = new stdClass();
2678 $updatecap->id = $cachedcap->id;
2679 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2680 $DB->update_record('capabilities', $updatecap);
2683 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2684 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2686 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2687 $updatecap = new stdClass();
2688 $updatecap->id = $cachedcap->id;
2689 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2690 $DB->update_record('capabilities', $updatecap);
2696 // Are there new capabilities in the file definition?
2697 $newcaps = array();
2699 foreach ($filecaps as $filecap => $def) {
2700 if (!$storedcaps ||
2701 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2702 if (!array_key_exists('riskbitmask', $def)) {
2703 $def['riskbitmask'] = 0; // no risk if not specified
2705 $newcaps[$filecap] = $def;
2708 // Add new capabilities to the stored definition.
2709 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2710 foreach ($newcaps as $capname => $capdef) {
2711 $capability = new stdClass();
2712 $capability->name = $capname;
2713 $capability->captype = $capdef['captype'];
2714 $capability->contextlevel = $capdef['contextlevel'];
2715 $capability->component = $component;
2716 $capability->riskbitmask = $capdef['riskbitmask'];
2718 $DB->insert_record('capabilities', $capability, false);
2720 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2721 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2722 foreach ($rolecapabilities as $rolecapability){
2723 //assign_capability will update rather than insert if capability exists
2724 if (!assign_capability($capname, $rolecapability->permission,
2725 $rolecapability->roleid, $rolecapability->contextid, true)){
2726 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2730 // we ignore archetype key if we have cloned permissions
2731 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2732 assign_legacy_capabilities($capname, $capdef['archetypes']);
2733 // 'legacy' is for backward compatibility with 1.9 access.php
2734 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2735 assign_legacy_capabilities($capname, $capdef['legacy']);
2738 // Are there any capabilities that have been removed from the file
2739 // definition that we need to delete from the stored capabilities and
2740 // role assignments?
2741 capabilities_cleanup($component, $filecaps);
2743 // reset static caches
2744 accesslib_clear_all_caches(false);
2746 return true;
2750 * Deletes cached capabilities that are no longer needed by the component.
2751 * Also unassigns these capabilities from any roles that have them.
2752 * NOTE: this function is called from lib/db/upgrade.php
2754 * @access private
2755 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2756 * @param array $newcapdef array of the new capability definitions that will be
2757 * compared with the cached capabilities
2758 * @return int number of deprecated capabilities that have been removed
2760 function capabilities_cleanup($component, $newcapdef = null) {
2761 global $DB;
2763 $removedcount = 0;
2765 if ($cachedcaps = get_cached_capabilities($component)) {
2766 foreach ($cachedcaps as $cachedcap) {
2767 if (empty($newcapdef) ||
2768 array_key_exists($cachedcap->name, $newcapdef) === false) {
2770 // Remove from capabilities cache.
2771 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2772 $removedcount++;
2773 // Delete from roles.
2774 if ($roles = get_roles_with_capability($cachedcap->name)) {
2775 foreach($roles as $role) {
2776 if (!unassign_capability($cachedcap->name, $role->id)) {
2777 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2781 } // End if.
2784 return $removedcount;
2788 * Returns an array of all the known types of risk
2789 * The array keys can be used, for example as CSS class names, or in calls to
2790 * print_risk_icon. The values are the corresponding RISK_ constants.
2792 * @return array all the known types of risk.
2794 function get_all_risks() {
2795 return array(
2796 'riskmanagetrust' => RISK_MANAGETRUST,
2797 'riskconfig' => RISK_CONFIG,
2798 'riskxss' => RISK_XSS,
2799 'riskpersonal' => RISK_PERSONAL,
2800 'riskspam' => RISK_SPAM,
2801 'riskdataloss' => RISK_DATALOSS,
2806 * Return a link to moodle docs for a given capability name
2808 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2809 * @return string the human-readable capability name as a link to Moodle Docs.
2811 function get_capability_docs_link($capability) {
2812 $url = get_docs_url('Capabilities/' . $capability->name);
2813 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2817 * This function pulls out all the resolved capabilities (overrides and
2818 * defaults) of a role used in capability overrides in contexts at a given
2819 * context.
2821 * @param int $roleid
2822 * @param context $context
2823 * @param string $cap capability, optional, defaults to ''
2824 * @return array Array of capabilities
2826 function role_context_capabilities($roleid, context $context, $cap = '') {
2827 global $DB;
2829 $contexts = $context->get_parent_context_ids(true);
2830 $contexts = '('.implode(',', $contexts).')';
2832 $params = array($roleid);
2834 if ($cap) {
2835 $search = " AND rc.capability = ? ";
2836 $params[] = $cap;
2837 } else {
2838 $search = '';
2841 $sql = "SELECT rc.*
2842 FROM {role_capabilities} rc, {context} c
2843 WHERE rc.contextid in $contexts
2844 AND rc.roleid = ?
2845 AND rc.contextid = c.id $search
2846 ORDER BY c.contextlevel DESC, rc.capability DESC";
2848 $capabilities = array();
2850 if ($records = $DB->get_records_sql($sql, $params)) {
2851 // We are traversing via reverse order.
2852 foreach ($records as $record) {
2853 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2854 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2855 $capabilities[$record->capability] = $record->permission;
2859 return $capabilities;
2863 * Constructs array with contextids as first parameter and context paths,
2864 * in both cases bottom top including self.
2866 * @access private
2867 * @param context $context
2868 * @return array
2870 function get_context_info_list(context $context) {
2871 $contextids = explode('/', ltrim($context->path, '/'));
2872 $contextpaths = array();
2873 $contextids2 = $contextids;
2874 while ($contextids2) {
2875 $contextpaths[] = '/' . implode('/', $contextids2);
2876 array_pop($contextids2);
2878 return array($contextids, $contextpaths);
2882 * Check if context is the front page context or a context inside it
2884 * Returns true if this context is the front page context, or a context inside it,
2885 * otherwise false.
2887 * @param context $context a context object.
2888 * @return bool
2890 function is_inside_frontpage(context $context) {
2891 $frontpagecontext = context_course::instance(SITEID);
2892 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2896 * Returns capability information (cached)
2898 * @param string $capabilityname
2899 * @return stdClass or null if capability not found
2901 function get_capability_info($capabilityname) {
2902 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2904 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2906 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2907 $ACCESSLIB_PRIVATE->capabilities = array();
2908 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2909 foreach ($caps as $cap) {
2910 $capname = $cap->name;
2911 unset($cap->id);
2912 unset($cap->name);
2913 $cap->riskbitmask = (int)$cap->riskbitmask;
2914 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2918 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2922 * Returns the human-readable, translated version of the capability.
2923 * Basically a big switch statement.
2925 * @param string $capabilityname e.g. mod/choice:readresponses
2926 * @return string
2928 function get_capability_string($capabilityname) {
2930 // Typical capability name is 'plugintype/pluginname:capabilityname'
2931 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2933 if ($type === 'moodle') {
2934 $component = 'core_role';
2935 } else if ($type === 'quizreport') {
2936 //ugly hack!!
2937 $component = 'quiz_'.$name;
2938 } else {
2939 $component = $type.'_'.$name;
2942 $stringname = $name.':'.$capname;
2944 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2945 return get_string($stringname, $component);
2948 $dir = core_component::get_component_directory($component);
2949 if (!file_exists($dir)) {
2950 // plugin broken or does not exist, do not bother with printing of debug message
2951 return $capabilityname.' ???';
2954 // something is wrong in plugin, better print debug
2955 return get_string($stringname, $component);
2959 * This gets the mod/block/course/core etc strings.
2961 * @param string $component
2962 * @param int $contextlevel
2963 * @return string|bool String is success, false if failed
2965 function get_component_string($component, $contextlevel) {
2967 if ($component === 'moodle' or $component === 'core') {
2968 switch ($contextlevel) {
2969 // TODO: this should probably use context level names instead
2970 case CONTEXT_SYSTEM: return get_string('coresystem');
2971 case CONTEXT_USER: return get_string('users');
2972 case CONTEXT_COURSECAT: return get_string('categories');
2973 case CONTEXT_COURSE: return get_string('course');
2974 case CONTEXT_MODULE: return get_string('activities');
2975 case CONTEXT_BLOCK: return get_string('block');
2976 default: print_error('unknowncontext');
2980 list($type, $name) = core_component::normalize_component($component);
2981 $dir = core_component::get_plugin_directory($type, $name);
2982 if (!file_exists($dir)) {
2983 // plugin not installed, bad luck, there is no way to find the name
2984 return $component.' ???';
2987 switch ($type) {
2988 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2989 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2990 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2991 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2992 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2993 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2994 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2995 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2996 case 'mod':
2997 if (get_string_manager()->string_exists('pluginname', $component)) {
2998 return get_string('activity').': '.get_string('pluginname', $component);
2999 } else {
3000 return get_string('activity').': '.get_string('modulename', $component);
3002 default: return get_string('pluginname', $component);
3007 * Gets the list of roles assigned to this context and up (parents)
3008 * from the list of roles that are visible on user profile page
3009 * and participants page.
3011 * @param context $context
3012 * @return array
3014 function get_profile_roles(context $context) {
3015 global $CFG, $DB;
3017 if (empty($CFG->profileroles)) {
3018 return array();
3021 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
3022 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
3023 $params = array_merge($params, $cparams);
3025 if ($coursecontext = $context->get_course_context(false)) {
3026 $params['coursecontext'] = $coursecontext->id;
3027 } else {
3028 $params['coursecontext'] = 0;
3031 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3032 FROM {role_assignments} ra, {role} r
3033 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3034 WHERE r.id = ra.roleid
3035 AND ra.contextid $contextlist
3036 AND r.id $rallowed
3037 ORDER BY r.sortorder ASC";
3039 return $DB->get_records_sql($sql, $params);
3043 * Gets the list of roles assigned to this context and up (parents)
3045 * @param context $context
3046 * @return array
3048 function get_roles_used_in_context(context $context) {
3049 global $DB;
3051 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
3053 if ($coursecontext = $context->get_course_context(false)) {
3054 $params['coursecontext'] = $coursecontext->id;
3055 } else {
3056 $params['coursecontext'] = 0;
3059 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3060 FROM {role_assignments} ra, {role} r
3061 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3062 WHERE r.id = ra.roleid
3063 AND ra.contextid $contextlist
3064 ORDER BY r.sortorder ASC";
3066 return $DB->get_records_sql($sql, $params);
3070 * This function is used to print roles column in user profile page.
3071 * It is using the CFG->profileroles to limit the list to only interesting roles.
3072 * (The permission tab has full details of user role assignments.)
3074 * @param int $userid
3075 * @param int $courseid
3076 * @return string
3078 function get_user_roles_in_course($userid, $courseid) {
3079 global $CFG, $DB;
3081 if (empty($CFG->profileroles)) {
3082 return '';
3085 if ($courseid == SITEID) {
3086 $context = context_system::instance();
3087 } else {
3088 $context = context_course::instance($courseid);
3091 if (empty($CFG->profileroles)) {
3092 return array();
3095 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
3096 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
3097 $params = array_merge($params, $cparams);
3099 if ($coursecontext = $context->get_course_context(false)) {
3100 $params['coursecontext'] = $coursecontext->id;
3101 } else {
3102 $params['coursecontext'] = 0;
3105 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3106 FROM {role_assignments} ra, {role} r
3107 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3108 WHERE r.id = ra.roleid
3109 AND ra.contextid $contextlist
3110 AND r.id $rallowed
3111 AND ra.userid = :userid
3112 ORDER BY r.sortorder ASC";
3113 $params['userid'] = $userid;
3115 $rolestring = '';
3117 if ($roles = $DB->get_records_sql($sql, $params)) {
3118 $rolenames = role_fix_names($roles, $context, ROLENAME_ALIAS, true); // Substitute aliases
3120 foreach ($rolenames as $roleid => $rolename) {
3121 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
3123 $rolestring = implode(',', $rolenames);
3126 return $rolestring;
3130 * Checks if a user can assign users to a particular role in this context
3132 * @param context $context
3133 * @param int $targetroleid - the id of the role you want to assign users to
3134 * @return boolean
3136 function user_can_assign(context $context, $targetroleid) {
3137 global $DB;
3139 // First check to see if the user is a site administrator.
3140 if (is_siteadmin()) {
3141 return true;
3144 // Check if user has override capability.
3145 // If not return false.
3146 if (!has_capability('moodle/role:assign', $context)) {
3147 return false;
3149 // pull out all active roles of this user from this context(or above)
3150 if ($userroles = get_user_roles($context)) {
3151 foreach ($userroles as $userrole) {
3152 // if any in the role_allow_override table, then it's ok
3153 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
3154 return true;
3159 return false;
3163 * Returns all site roles in correct sort order.
3165 * Note: this method does not localise role names or descriptions,
3166 * use role_get_names() if you need role names.
3168 * @param context $context optional context for course role name aliases
3169 * @return array of role records with optional coursealias property
3171 function get_all_roles(context $context = null) {
3172 global $DB;
3174 if (!$context or !$coursecontext = $context->get_course_context(false)) {
3175 $coursecontext = null;
3178 if ($coursecontext) {
3179 $sql = "SELECT r.*, rn.name AS coursealias
3180 FROM {role} r
3181 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3182 ORDER BY r.sortorder ASC";
3183 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
3185 } else {
3186 return $DB->get_records('role', array(), 'sortorder ASC');
3191 * Returns roles of a specified archetype
3193 * @param string $archetype
3194 * @return array of full role records
3196 function get_archetype_roles($archetype) {
3197 global $DB;
3198 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
3202 * Gets all the user roles assigned in this context, or higher contexts
3203 * this is mainly used when checking if a user can assign a role, or overriding a role
3204 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3205 * allow_override tables
3207 * @param context $context
3208 * @param int $userid
3209 * @param bool $checkparentcontexts defaults to true
3210 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
3211 * @return array
3213 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
3214 global $USER, $DB;
3216 if (empty($userid)) {
3217 if (empty($USER->id)) {
3218 return array();
3220 $userid = $USER->id;
3223 if ($checkparentcontexts) {
3224 $contextids = $context->get_parent_context_ids();
3225 } else {
3226 $contextids = array();
3228 $contextids[] = $context->id;
3230 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3232 array_unshift($params, $userid);
3234 $sql = "SELECT ra.*, r.name, r.shortname
3235 FROM {role_assignments} ra, {role} r, {context} c
3236 WHERE ra.userid = ?
3237 AND ra.roleid = r.id
3238 AND ra.contextid = c.id
3239 AND ra.contextid $contextids
3240 ORDER BY $order";
3242 return $DB->get_records_sql($sql ,$params);
3246 * Like get_user_roles, but adds in the authenticated user role, and the front
3247 * page roles, if applicable.
3249 * @param context $context the context.
3250 * @param int $userid optional. Defaults to $USER->id
3251 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3253 function get_user_roles_with_special(context $context, $userid = 0) {
3254 global $CFG, $USER;
3256 if (empty($userid)) {
3257 if (empty($USER->id)) {
3258 return array();
3260 $userid = $USER->id;
3263 $ras = get_user_roles($context, $userid);
3265 // Add front-page role if relevant.
3266 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3267 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3268 is_inside_frontpage($context);
3269 if ($defaultfrontpageroleid && $isfrontpage) {
3270 $frontpagecontext = context_course::instance(SITEID);
3271 $ra = new stdClass();
3272 $ra->userid = $userid;
3273 $ra->contextid = $frontpagecontext->id;
3274 $ra->roleid = $defaultfrontpageroleid;
3275 $ras[] = $ra;
3278 // Add authenticated user role if relevant.
3279 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3280 if ($defaultuserroleid && !isguestuser($userid)) {
3281 $systemcontext = context_system::instance();
3282 $ra = new stdClass();
3283 $ra->userid = $userid;
3284 $ra->contextid = $systemcontext->id;
3285 $ra->roleid = $defaultuserroleid;
3286 $ras[] = $ra;
3289 return $ras;
3293 * Creates a record in the role_allow_override table
3295 * @param int $sroleid source roleid
3296 * @param int $troleid target roleid
3297 * @return void
3299 function allow_override($sroleid, $troleid) {
3300 global $DB;
3302 $record = new stdClass();
3303 $record->roleid = $sroleid;
3304 $record->allowoverride = $troleid;
3305 $DB->insert_record('role_allow_override', $record);
3309 * Creates a record in the role_allow_assign table
3311 * @param int $fromroleid source roleid
3312 * @param int $targetroleid target roleid
3313 * @return void
3315 function allow_assign($fromroleid, $targetroleid) {
3316 global $DB;
3318 $record = new stdClass();
3319 $record->roleid = $fromroleid;
3320 $record->allowassign = $targetroleid;
3321 $DB->insert_record('role_allow_assign', $record);
3325 * Creates a record in the role_allow_switch table
3327 * @param int $fromroleid source roleid
3328 * @param int $targetroleid target roleid
3329 * @return void
3331 function allow_switch($fromroleid, $targetroleid) {
3332 global $DB;
3334 $record = new stdClass();
3335 $record->roleid = $fromroleid;
3336 $record->allowswitch = $targetroleid;
3337 $DB->insert_record('role_allow_switch', $record);
3341 * Gets a list of roles that this user can assign in this context
3343 * @param context $context the context.
3344 * @param int $rolenamedisplay the type of role name to display. One of the
3345 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3346 * @param bool $withusercounts if true, count the number of users with each role.
3347 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3348 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3349 * if $withusercounts is true, returns a list of three arrays,
3350 * $rolenames, $rolecounts, and $nameswithcounts.
3352 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3353 global $USER, $DB;
3355 // make sure there is a real user specified
3356 if ($user === null) {
3357 $userid = isset($USER->id) ? $USER->id : 0;
3358 } else {
3359 $userid = is_object($user) ? $user->id : $user;
3362 if (!has_capability('moodle/role:assign', $context, $userid)) {
3363 if ($withusercounts) {
3364 return array(array(), array(), array());
3365 } else {
3366 return array();
3370 $params = array();
3371 $extrafields = '';
3373 if ($withusercounts) {
3374 $extrafields = ', (SELECT count(u.id)
3375 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3376 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3377 ) AS usercount';
3378 $params['conid'] = $context->id;
3381 if (is_siteadmin($userid)) {
3382 // show all roles allowed in this context to admins
3383 $assignrestriction = "";
3384 } else {
3385 $parents = $context->get_parent_context_ids(true);
3386 $contexts = implode(',' , $parents);
3387 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3388 FROM {role_allow_assign} raa
3389 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3390 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3391 ) ar ON ar.id = r.id";
3392 $params['userid'] = $userid;
3394 $params['contextlevel'] = $context->contextlevel;
3396 if ($coursecontext = $context->get_course_context(false)) {
3397 $params['coursecontext'] = $coursecontext->id;
3398 } else {
3399 $params['coursecontext'] = 0; // no course aliases
3400 $coursecontext = null;
3402 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3403 FROM {role} r
3404 $assignrestriction
3405 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3406 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3407 ORDER BY r.sortorder ASC";
3408 $roles = $DB->get_records_sql($sql, $params);
3410 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3412 if (!$withusercounts) {
3413 return $rolenames;
3416 $rolecounts = array();
3417 $nameswithcounts = array();
3418 foreach ($roles as $role) {
3419 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3420 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3422 return array($rolenames, $rolecounts, $nameswithcounts);
3426 * Gets a list of roles that this user can switch to in a context
3428 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3429 * This function just process the contents of the role_allow_switch table. You also need to
3430 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3432 * @param context $context a context.
3433 * @return array an array $roleid => $rolename.
3435 function get_switchable_roles(context $context) {
3436 global $USER, $DB;
3438 $params = array();
3439 $extrajoins = '';
3440 $extrawhere = '';
3441 if (!is_siteadmin()) {
3442 // Admins are allowed to switch to any role with.
3443 // Others are subject to the additional constraint that the switch-to role must be allowed by
3444 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3445 $parents = $context->get_parent_context_ids(true);
3446 $contexts = implode(',' , $parents);
3448 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3449 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3450 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3451 $params['userid'] = $USER->id;
3454 if ($coursecontext = $context->get_course_context(false)) {
3455 $params['coursecontext'] = $coursecontext->id;
3456 } else {
3457 $params['coursecontext'] = 0; // no course aliases
3458 $coursecontext = null;
3461 $query = "
3462 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3463 FROM (SELECT DISTINCT rc.roleid
3464 FROM {role_capabilities} rc
3465 $extrajoins
3466 $extrawhere) idlist
3467 JOIN {role} r ON r.id = idlist.roleid
3468 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3469 ORDER BY r.sortorder";
3470 $roles = $DB->get_records_sql($query, $params);
3472 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3476 * Gets a list of roles that this user can override in this context.
3478 * @param context $context the context.
3479 * @param int $rolenamedisplay the type of role name to display. One of the
3480 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3481 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3482 * @return array if $withcounts is false, then an array $roleid => $rolename.
3483 * if $withusercounts is true, returns a list of three arrays,
3484 * $rolenames, $rolecounts, and $nameswithcounts.
3486 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3487 global $USER, $DB;
3489 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3490 if ($withcounts) {
3491 return array(array(), array(), array());
3492 } else {
3493 return array();
3497 $parents = $context->get_parent_context_ids(true);
3498 $contexts = implode(',' , $parents);
3500 $params = array();
3501 $extrafields = '';
3503 $params['userid'] = $USER->id;
3504 if ($withcounts) {
3505 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3506 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3507 $params['conid'] = $context->id;
3510 if ($coursecontext = $context->get_course_context(false)) {
3511 $params['coursecontext'] = $coursecontext->id;
3512 } else {
3513 $params['coursecontext'] = 0; // no course aliases
3514 $coursecontext = null;
3517 if (is_siteadmin()) {
3518 // show all roles to admins
3519 $roles = $DB->get_records_sql("
3520 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3521 FROM {role} ro
3522 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3523 ORDER BY ro.sortorder ASC", $params);
3525 } else {
3526 $roles = $DB->get_records_sql("
3527 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3528 FROM {role} ro
3529 JOIN (SELECT DISTINCT r.id
3530 FROM {role} r
3531 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3532 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3533 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3534 ) inline_view ON ro.id = inline_view.id
3535 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3536 ORDER BY ro.sortorder ASC", $params);
3539 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3541 if (!$withcounts) {
3542 return $rolenames;
3545 $rolecounts = array();
3546 $nameswithcounts = array();
3547 foreach ($roles as $role) {
3548 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3549 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3551 return array($rolenames, $rolecounts, $nameswithcounts);
3555 * Create a role menu suitable for default role selection in enrol plugins.
3557 * @package core_enrol
3559 * @param context $context
3560 * @param int $addroleid current or default role - always added to list
3561 * @return array roleid=>localised role name
3563 function get_default_enrol_roles(context $context, $addroleid = null) {
3564 global $DB;
3566 $params = array('contextlevel'=>CONTEXT_COURSE);
3568 if ($coursecontext = $context->get_course_context(false)) {
3569 $params['coursecontext'] = $coursecontext->id;
3570 } else {
3571 $params['coursecontext'] = 0; // no course names
3572 $coursecontext = null;
3575 if ($addroleid) {
3576 $addrole = "OR r.id = :addroleid";
3577 $params['addroleid'] = $addroleid;
3578 } else {
3579 $addrole = "";
3582 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3583 FROM {role} r
3584 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3585 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3586 WHERE rcl.id IS NOT NULL $addrole
3587 ORDER BY sortorder DESC";
3589 $roles = $DB->get_records_sql($sql, $params);
3591 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3595 * Return context levels where this role is assignable.
3597 * @param integer $roleid the id of a role.
3598 * @return array list of the context levels at which this role may be assigned.
3600 function get_role_contextlevels($roleid) {
3601 global $DB;
3602 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3603 'contextlevel', 'id,contextlevel');
3607 * Return roles suitable for assignment at the specified context level.
3609 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3611 * @param integer $contextlevel a contextlevel.
3612 * @return array list of role ids that are assignable at this context level.
3614 function get_roles_for_contextlevels($contextlevel) {
3615 global $DB;
3616 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3617 '', 'id,roleid');
3621 * Returns default context levels where roles can be assigned.
3623 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3624 * from the array returned by get_role_archetypes();
3625 * @return array list of the context levels at which this type of role may be assigned by default.
3627 function get_default_contextlevels($rolearchetype) {
3628 static $defaults = array(
3629 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3630 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3631 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3632 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3633 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3634 'guest' => array(),
3635 'user' => array(),
3636 'frontpage' => array());
3638 if (isset($defaults[$rolearchetype])) {
3639 return $defaults[$rolearchetype];
3640 } else {
3641 return array();
3646 * Set the context levels at which a particular role can be assigned.
3647 * Throws exceptions in case of error.
3649 * @param integer $roleid the id of a role.
3650 * @param array $contextlevels the context levels at which this role should be assignable,
3651 * duplicate levels are removed.
3652 * @return void
3654 function set_role_contextlevels($roleid, array $contextlevels) {
3655 global $DB;
3656 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3657 $rcl = new stdClass();
3658 $rcl->roleid = $roleid;
3659 $contextlevels = array_unique($contextlevels);
3660 foreach ($contextlevels as $level) {
3661 $rcl->contextlevel = $level;
3662 $DB->insert_record('role_context_levels', $rcl, false, true);
3667 * Who has this capability in this context?
3669 * This can be a very expensive call - use sparingly and keep
3670 * the results if you are going to need them again soon.
3672 * Note if $fields is empty this function attempts to get u.*
3673 * which can get rather large - and has a serious perf impact
3674 * on some DBs.
3676 * @param context $context
3677 * @param string|array $capability - capability name(s)
3678 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3679 * @param string $sort - the sort order. Default is lastaccess time.
3680 * @param mixed $limitfrom - number of records to skip (offset)
3681 * @param mixed $limitnum - number of records to fetch
3682 * @param string|array $groups - single group or array of groups - only return
3683 * users who are in one of these group(s).
3684 * @param string|array $exceptions - list of users to exclude, comma separated or array
3685 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3686 * @param bool $view_ignored - use get_enrolled_sql() instead
3687 * @param bool $useviewallgroups if $groups is set the return users who
3688 * have capability both $capability and moodle/site:accessallgroups
3689 * in this context, as well as users who have $capability and who are
3690 * in $groups.
3691 * @return array of user records
3693 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3694 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3695 global $CFG, $DB;
3697 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3698 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3700 $ctxids = trim($context->path, '/');
3701 $ctxids = str_replace('/', ',', $ctxids);
3703 // Context is the frontpage
3704 $iscoursepage = false; // coursepage other than fp
3705 $isfrontpage = false;
3706 if ($context->contextlevel == CONTEXT_COURSE) {
3707 if ($context->instanceid == SITEID) {
3708 $isfrontpage = true;
3709 } else {
3710 $iscoursepage = true;
3713 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3715 $caps = (array)$capability;
3717 // construct list of context paths bottom-->top
3718 list($contextids, $paths) = get_context_info_list($context);
3720 // we need to find out all roles that have these capabilities either in definition or in overrides
3721 $defs = array();
3722 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3723 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3724 $params = array_merge($params, $params2);
3725 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3726 FROM {role_capabilities} rc
3727 JOIN {context} ctx on rc.contextid = ctx.id
3728 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3730 $rcs = $DB->get_records_sql($sql, $params);
3731 foreach ($rcs as $rc) {
3732 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3735 // go through the permissions bottom-->top direction to evaluate the current permission,
3736 // first one wins (prohibit is an exception that always wins)
3737 $access = array();
3738 foreach ($caps as $cap) {
3739 foreach ($paths as $path) {
3740 if (empty($defs[$cap][$path])) {
3741 continue;
3743 foreach($defs[$cap][$path] as $roleid => $perm) {
3744 if ($perm == CAP_PROHIBIT) {
3745 $access[$cap][$roleid] = CAP_PROHIBIT;
3746 continue;
3748 if (!isset($access[$cap][$roleid])) {
3749 $access[$cap][$roleid] = (int)$perm;
3755 // make lists of roles that are needed and prohibited in this context
3756 $needed = array(); // one of these is enough
3757 $prohibited = array(); // must not have any of these
3758 foreach ($caps as $cap) {
3759 if (empty($access[$cap])) {
3760 continue;
3762 foreach ($access[$cap] as $roleid => $perm) {
3763 if ($perm == CAP_PROHIBIT) {
3764 unset($needed[$cap][$roleid]);
3765 $prohibited[$cap][$roleid] = true;
3766 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3767 $needed[$cap][$roleid] = true;
3770 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3771 // easy, nobody has the permission
3772 unset($needed[$cap]);
3773 unset($prohibited[$cap]);
3774 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3775 // everybody is disqualified on the frontpage
3776 unset($needed[$cap]);
3777 unset($prohibited[$cap]);
3779 if (empty($prohibited[$cap])) {
3780 unset($prohibited[$cap]);
3784 if (empty($needed)) {
3785 // there can not be anybody if no roles match this request
3786 return array();
3789 if (empty($prohibited)) {
3790 // we can compact the needed roles
3791 $n = array();
3792 foreach ($needed as $cap) {
3793 foreach ($cap as $roleid=>$unused) {
3794 $n[$roleid] = true;
3797 $needed = array('any'=>$n);
3798 unset($n);
3801 // ***** Set up default fields ******
3802 if (empty($fields)) {
3803 if ($iscoursepage) {
3804 $fields = 'u.*, ul.timeaccess AS lastaccess';
3805 } else {
3806 $fields = 'u.*';
3808 } else {
3809 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3810 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3814 // Set up default sort
3815 if (empty($sort)) { // default to course lastaccess or just lastaccess
3816 if ($iscoursepage) {
3817 $sort = 'ul.timeaccess';
3818 } else {
3819 $sort = 'u.lastaccess';
3823 // Prepare query clauses
3824 $wherecond = array();
3825 $params = array();
3826 $joins = array();
3828 // User lastaccess JOIN
3829 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3830 // user_lastaccess is not required MDL-13810
3831 } else {
3832 if ($iscoursepage) {
3833 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3834 } else {
3835 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3839 // We never return deleted users or guest account.
3840 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3841 $params['guestid'] = $CFG->siteguest;
3843 // Groups
3844 if ($groups) {
3845 $groups = (array)$groups;
3846 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3847 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3848 $params = array_merge($params, $grpparams);
3850 if ($useviewallgroups) {
3851 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3852 if (!empty($viewallgroupsusers)) {
3853 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3854 } else {
3855 $wherecond[] = "($grouptest)";
3857 } else {
3858 $wherecond[] = "($grouptest)";
3862 // User exceptions
3863 if (!empty($exceptions)) {
3864 $exceptions = (array)$exceptions;
3865 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3866 $params = array_merge($params, $exparams);
3867 $wherecond[] = "u.id $exsql";
3870 // now add the needed and prohibited roles conditions as joins
3871 if (!empty($needed['any'])) {
3872 // simple case - there are no prohibits involved
3873 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3874 // everybody
3875 } else {
3876 $joins[] = "JOIN (SELECT DISTINCT userid
3877 FROM {role_assignments}
3878 WHERE contextid IN ($ctxids)
3879 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3880 ) ra ON ra.userid = u.id";
3882 } else {
3883 $unions = array();
3884 $everybody = false;
3885 foreach ($needed as $cap=>$unused) {
3886 if (empty($prohibited[$cap])) {
3887 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3888 $everybody = true;
3889 break;
3890 } else {
3891 $unions[] = "SELECT userid
3892 FROM {role_assignments}
3893 WHERE contextid IN ($ctxids)
3894 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3896 } else {
3897 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3898 // nobody can have this cap because it is prevented in default roles
3899 continue;
3901 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3902 // everybody except the prohibitted - hiding does not matter
3903 $unions[] = "SELECT id AS userid
3904 FROM {user}
3905 WHERE id NOT IN (SELECT userid
3906 FROM {role_assignments}
3907 WHERE contextid IN ($ctxids)
3908 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3910 } else {
3911 $unions[] = "SELECT userid
3912 FROM {role_assignments}
3913 WHERE contextid IN ($ctxids)
3914 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3915 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3919 if (!$everybody) {
3920 if ($unions) {
3921 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3922 } else {
3923 // only prohibits found - nobody can be matched
3924 $wherecond[] = "1 = 2";
3929 // Collect WHERE conditions and needed joins
3930 $where = implode(' AND ', $wherecond);
3931 if ($where !== '') {
3932 $where = 'WHERE ' . $where;
3934 $joins = implode("\n", $joins);
3936 // Ok, let's get the users!
3937 $sql = "SELECT $fields
3938 FROM {user} u
3939 $joins
3940 $where
3941 ORDER BY $sort";
3943 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3947 * Re-sort a users array based on a sorting policy
3949 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3950 * based on a sorting policy. This is to support the odd practice of
3951 * sorting teachers by 'authority', where authority was "lowest id of the role
3952 * assignment".
3954 * Will execute 1 database query. Only suitable for small numbers of users, as it
3955 * uses an u.id IN() clause.
3957 * Notes about the sorting criteria.
3959 * As a default, we cannot rely on role.sortorder because then
3960 * admins/coursecreators will always win. That is why the sane
3961 * rule "is locality matters most", with sortorder as 2nd
3962 * consideration.
3964 * If you want role.sortorder, use the 'sortorder' policy, and
3965 * name explicitly what roles you want to cover. It's probably
3966 * a good idea to see what roles have the capabilities you want
3967 * (array_diff() them against roiles that have 'can-do-anything'
3968 * to weed out admin-ish roles. Or fetch a list of roles from
3969 * variables like $CFG->coursecontact .
3971 * @param array $users Users array, keyed on userid
3972 * @param context $context
3973 * @param array $roles ids of the roles to include, optional
3974 * @param string $sortpolicy defaults to locality, more about
3975 * @return array sorted copy of the array
3977 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3978 global $DB;
3980 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3981 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3982 if (empty($roles)) {
3983 $roleswhere = '';
3984 } else {
3985 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3988 $sql = "SELECT ra.userid
3989 FROM {role_assignments} ra
3990 JOIN {role} r
3991 ON ra.roleid=r.id
3992 JOIN {context} ctx
3993 ON ra.contextid=ctx.id
3994 WHERE $userswhere
3995 $contextwhere
3996 $roleswhere";
3998 // Default 'locality' policy -- read PHPDoc notes
3999 // about sort policies...
4000 $orderby = 'ORDER BY '
4001 .'ctx.depth DESC, ' /* locality wins */
4002 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
4003 .'ra.id'; /* role assignment order tie-breaker */
4004 if ($sortpolicy === 'sortorder') {
4005 $orderby = 'ORDER BY '
4006 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
4007 .'ra.id'; /* role assignment order tie-breaker */
4010 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
4011 $sortedusers = array();
4012 $seen = array();
4014 foreach ($sortedids as $id) {
4015 // Avoid duplicates
4016 if (isset($seen[$id])) {
4017 continue;
4019 $seen[$id] = true;
4021 // assign
4022 $sortedusers[$id] = $users[$id];
4024 return $sortedusers;
4028 * Gets all the users assigned this role in this context or higher
4030 * @param int $roleid (can also be an array of ints!)
4031 * @param context $context
4032 * @param bool $parent if true, get list of users assigned in higher context too
4033 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
4034 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
4035 * null => use default sort from users_order_by_sql.
4036 * @param bool $all true means all, false means limit to enrolled users
4037 * @param string $group defaults to ''
4038 * @param mixed $limitfrom defaults to ''
4039 * @param mixed $limitnum defaults to ''
4040 * @param string $extrawheretest defaults to ''
4041 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
4042 * @return array
4044 function get_role_users($roleid, context $context, $parent = false, $fields = '',
4045 $sort = null, $all = true, $group = '',
4046 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
4047 global $DB;
4049 if (empty($fields)) {
4050 $allnames = get_all_user_name_fields(true, 'u');
4051 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
4052 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
4053 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
4054 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
4055 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
4058 $parentcontexts = '';
4059 if ($parent) {
4060 $parentcontexts = substr($context->path, 1); // kill leading slash
4061 $parentcontexts = str_replace('/', ',', $parentcontexts);
4062 if ($parentcontexts !== '') {
4063 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4067 if ($roleid) {
4068 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
4069 $roleselect = "AND ra.roleid $rids";
4070 } else {
4071 $params = array();
4072 $roleselect = '';
4075 if ($coursecontext = $context->get_course_context(false)) {
4076 $params['coursecontext'] = $coursecontext->id;
4077 } else {
4078 $params['coursecontext'] = 0;
4081 if ($group) {
4082 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
4083 $groupselect = " AND gm.groupid = :groupid ";
4084 $params['groupid'] = $group;
4085 } else {
4086 $groupjoin = '';
4087 $groupselect = '';
4090 $params['contextid'] = $context->id;
4092 if ($extrawheretest) {
4093 $extrawheretest = ' AND ' . $extrawheretest;
4096 if ($whereorsortparams) {
4097 $params = array_merge($params, $whereorsortparams);
4100 if (!$sort) {
4101 list($sort, $sortparams) = users_order_by_sql('u');
4102 $params = array_merge($params, $sortparams);
4105 if ($all === null) {
4106 // Previously null was used to indicate that parameter was not used.
4107 $all = true;
4109 if (!$all and $coursecontext) {
4110 // Do not use get_enrolled_sql() here for performance reasons.
4111 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
4112 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
4113 $params['ecourseid'] = $coursecontext->instanceid;
4114 } else {
4115 $ejoin = "";
4118 $sql = "SELECT DISTINCT $fields, ra.roleid
4119 FROM {role_assignments} ra
4120 JOIN {user} u ON u.id = ra.userid
4121 JOIN {role} r ON ra.roleid = r.id
4122 $ejoin
4123 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
4124 $groupjoin
4125 WHERE (ra.contextid = :contextid $parentcontexts)
4126 $roleselect
4127 $groupselect
4128 $extrawheretest
4129 ORDER BY $sort"; // join now so that we can just use fullname() later
4131 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
4135 * Counts all the users assigned this role in this context or higher
4137 * @param int|array $roleid either int or an array of ints
4138 * @param context $context
4139 * @param bool $parent if true, get list of users assigned in higher context too
4140 * @return int Returns the result count
4142 function count_role_users($roleid, context $context, $parent = false) {
4143 global $DB;
4145 if ($parent) {
4146 if ($contexts = $context->get_parent_context_ids()) {
4147 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4148 } else {
4149 $parentcontexts = '';
4151 } else {
4152 $parentcontexts = '';
4155 if ($roleid) {
4156 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
4157 $roleselect = "AND r.roleid $rids";
4158 } else {
4159 $params = array();
4160 $roleselect = '';
4163 array_unshift($params, $context->id);
4165 $sql = "SELECT COUNT(u.id)
4166 FROM {role_assignments} r
4167 JOIN {user} u ON u.id = r.userid
4168 WHERE (r.contextid = ? $parentcontexts)
4169 $roleselect
4170 AND u.deleted = 0";
4172 return $DB->count_records_sql($sql, $params);
4176 * This function gets the list of courses that this user has a particular capability in.
4177 * It is still not very efficient.
4179 * @param string $capability Capability in question
4180 * @param int $userid User ID or null for current user
4181 * @param bool $doanything True if 'doanything' is permitted (default)
4182 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4183 * otherwise use a comma-separated list of the fields you require, not including id
4184 * @param string $orderby If set, use a comma-separated list of fields from course
4185 * table with sql modifiers (DESC) if needed
4186 * @return array Array of courses, may have zero entries. Or false if query failed.
4188 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
4189 global $DB;
4191 // Convert fields list and ordering
4192 $fieldlist = '';
4193 if ($fieldsexceptid) {
4194 $fields = explode(',', $fieldsexceptid);
4195 foreach($fields as $field) {
4196 $fieldlist .= ',c.'.$field;
4199 if ($orderby) {
4200 $fields = explode(',', $orderby);
4201 $orderby = '';
4202 foreach($fields as $field) {
4203 if ($orderby) {
4204 $orderby .= ',';
4206 $orderby .= 'c.'.$field;
4208 $orderby = 'ORDER BY '.$orderby;
4211 // Obtain a list of everything relevant about all courses including context.
4212 // Note the result can be used directly as a context (we are going to), the course
4213 // fields are just appended.
4215 $contextpreload = context_helper::get_preload_record_columns_sql('x');
4217 $courses = array();
4218 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
4219 FROM {course} c
4220 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
4221 $orderby");
4222 // Check capability for each course in turn
4223 foreach ($rs as $course) {
4224 context_helper::preload_from_record($course);
4225 $context = context_course::instance($course->id);
4226 if (has_capability($capability, $context, $userid, $doanything)) {
4227 // We've got the capability. Make the record look like a course record
4228 // and store it
4229 $courses[] = $course;
4232 $rs->close();
4233 return empty($courses) ? false : $courses;
4237 * This function finds the roles assigned directly to this context only
4238 * i.e. no roles in parent contexts
4240 * @param context $context
4241 * @return array
4243 function get_roles_on_exact_context(context $context) {
4244 global $DB;
4246 return $DB->get_records_sql("SELECT r.*
4247 FROM {role_assignments} ra, {role} r
4248 WHERE ra.roleid = r.id AND ra.contextid = ?",
4249 array($context->id));
4253 * Switches the current user to another role for the current session and only
4254 * in the given context.
4256 * The caller *must* check
4257 * - that this op is allowed
4258 * - that the requested role can be switched to in this context (use get_switchable_roles)
4259 * - that the requested role is NOT $CFG->defaultuserroleid
4261 * To "unswitch" pass 0 as the roleid.
4263 * This function *will* modify $USER->access - beware
4265 * @param integer $roleid the role to switch to.
4266 * @param context $context the context in which to perform the switch.
4267 * @return bool success or failure.
4269 function role_switch($roleid, context $context) {
4270 global $USER;
4273 // Plan of action
4275 // - Add the ghost RA to $USER->access
4276 // as $USER->access['rsw'][$path] = $roleid
4278 // - Make sure $USER->access['rdef'] has the roledefs
4279 // it needs to honour the switcherole
4281 // Roledefs will get loaded "deep" here - down to the last child
4282 // context. Note that
4284 // - When visiting subcontexts, our selective accessdata loading
4285 // will still work fine - though those ra/rdefs will be ignored
4286 // appropriately while the switch is in place
4288 // - If a switcherole happens at a category with tons of courses
4289 // (that have many overrides for switched-to role), the session
4290 // will get... quite large. Sometimes you just can't win.
4292 // To un-switch just unset($USER->access['rsw'][$path])
4294 // Note: it is not possible to switch to roles that do not have course:view
4296 if (!isset($USER->access)) {
4297 load_all_capabilities();
4301 // Add the switch RA
4302 if ($roleid == 0) {
4303 unset($USER->access['rsw'][$context->path]);
4304 return true;
4307 $USER->access['rsw'][$context->path] = $roleid;
4309 // Load roledefs
4310 load_role_access_by_context($roleid, $context, $USER->access);
4312 return true;
4316 * Checks if the user has switched roles within the given course.
4318 * Note: You can only switch roles within the course, hence it takes a course id
4319 * rather than a context. On that note Petr volunteered to implement this across
4320 * all other contexts, all requests for this should be forwarded to him ;)
4322 * @param int $courseid The id of the course to check
4323 * @return bool True if the user has switched roles within the course.
4325 function is_role_switched($courseid) {
4326 global $USER;
4327 $context = context_course::instance($courseid, MUST_EXIST);
4328 return (!empty($USER->access['rsw'][$context->path]));
4332 * Get any role that has an override on exact context
4334 * @param context $context The context to check
4335 * @return array An array of roles
4337 function get_roles_with_override_on_context(context $context) {
4338 global $DB;
4340 return $DB->get_records_sql("SELECT r.*
4341 FROM {role_capabilities} rc, {role} r
4342 WHERE rc.roleid = r.id AND rc.contextid = ?",
4343 array($context->id));
4347 * Get all capabilities for this role on this context (overrides)
4349 * @param stdClass $role
4350 * @param context $context
4351 * @return array
4353 function get_capabilities_from_role_on_context($role, context $context) {
4354 global $DB;
4356 return $DB->get_records_sql("SELECT *
4357 FROM {role_capabilities}
4358 WHERE contextid = ? AND roleid = ?",
4359 array($context->id, $role->id));
4363 * Find out which roles has assignment on this context
4365 * @param context $context
4366 * @return array
4369 function get_roles_with_assignment_on_context(context $context) {
4370 global $DB;
4372 return $DB->get_records_sql("SELECT r.*
4373 FROM {role_assignments} ra, {role} r
4374 WHERE ra.roleid = r.id AND ra.contextid = ?",
4375 array($context->id));
4379 * Find all user assignment of users for this role, on this context
4381 * @param stdClass $role
4382 * @param context $context
4383 * @return array
4385 function get_users_from_role_on_context($role, context $context) {
4386 global $DB;
4388 return $DB->get_records_sql("SELECT *
4389 FROM {role_assignments}
4390 WHERE contextid = ? AND roleid = ?",
4391 array($context->id, $role->id));
4395 * Simple function returning a boolean true if user has roles
4396 * in context or parent contexts, otherwise false.
4398 * @param int $userid
4399 * @param int $roleid
4400 * @param int $contextid empty means any context
4401 * @return bool
4403 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4404 global $DB;
4406 if ($contextid) {
4407 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4408 return false;
4410 $parents = $context->get_parent_context_ids(true);
4411 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4412 $params['userid'] = $userid;
4413 $params['roleid'] = $roleid;
4415 $sql = "SELECT COUNT(ra.id)
4416 FROM {role_assignments} ra
4417 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4419 $count = $DB->get_field_sql($sql, $params);
4420 return ($count > 0);
4422 } else {
4423 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4428 * Get localised role name or alias if exists and format the text.
4430 * @param stdClass $role role object
4431 * - optional 'coursealias' property should be included for performance reasons if course context used
4432 * - description property is not required here
4433 * @param context|bool $context empty means system context
4434 * @param int $rolenamedisplay type of role name
4435 * @return string localised role name or course role name alias
4437 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4438 global $DB;
4440 if ($rolenamedisplay == ROLENAME_SHORT) {
4441 return $role->shortname;
4444 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4445 $coursecontext = null;
4448 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4449 $role = clone($role); // Do not modify parameters.
4450 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4451 $role->coursealias = $r->name;
4452 } else {
4453 $role->coursealias = null;
4457 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4458 if ($coursecontext) {
4459 return $role->coursealias;
4460 } else {
4461 return null;
4465 if (trim($role->name) !== '') {
4466 // For filtering always use context where was the thing defined - system for roles here.
4467 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4469 } else {
4470 // Empty role->name means we want to see localised role name based on shortname,
4471 // only default roles are supposed to be localised.
4472 switch ($role->shortname) {
4473 case 'manager': $original = get_string('manager', 'role'); break;
4474 case 'coursecreator': $original = get_string('coursecreators'); break;
4475 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4476 case 'teacher': $original = get_string('noneditingteacher'); break;
4477 case 'student': $original = get_string('defaultcoursestudent'); break;
4478 case 'guest': $original = get_string('guest'); break;
4479 case 'user': $original = get_string('authenticateduser'); break;
4480 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4481 // We should not get here, the role UI should require the name for custom roles!
4482 default: $original = $role->shortname; break;
4486 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4487 return $original;
4490 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4491 return "$original ($role->shortname)";
4494 if ($rolenamedisplay == ROLENAME_ALIAS) {
4495 if ($coursecontext and trim($role->coursealias) !== '') {
4496 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4497 } else {
4498 return $original;
4502 if ($rolenamedisplay == ROLENAME_BOTH) {
4503 if ($coursecontext and trim($role->coursealias) !== '') {
4504 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4505 } else {
4506 return $original;
4510 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4514 * Returns localised role description if available.
4515 * If the name is empty it tries to find the default role name using
4516 * hardcoded list of default role names or other methods in the future.
4518 * @param stdClass $role
4519 * @return string localised role name
4521 function role_get_description(stdClass $role) {
4522 if (!html_is_blank($role->description)) {
4523 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4526 switch ($role->shortname) {
4527 case 'manager': return get_string('managerdescription', 'role');
4528 case 'coursecreator': return get_string('coursecreatorsdescription');
4529 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4530 case 'teacher': return get_string('noneditingteacherdescription');
4531 case 'student': return get_string('defaultcoursestudentdescription');
4532 case 'guest': return get_string('guestdescription');
4533 case 'user': return get_string('authenticateduserdescription');
4534 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4535 default: return '';
4540 * Get all the localised role names for a context.
4542 * In new installs default roles have empty names, this function
4543 * add localised role names using current language pack.
4545 * @param context $context the context, null means system context
4546 * @param array of role objects with a ->localname field containing the context-specific role name.
4547 * @param int $rolenamedisplay
4548 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4549 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4551 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4552 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4556 * Prepare list of roles for display, apply aliases and localise default role names.
4558 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4559 * @param context $context the context, null means system context
4560 * @param int $rolenamedisplay
4561 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4562 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4564 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4565 global $DB;
4567 if (empty($roleoptions)) {
4568 return array();
4571 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4572 $coursecontext = null;
4575 // We usually need all role columns...
4576 $first = reset($roleoptions);
4577 if ($returnmenu === null) {
4578 $returnmenu = !is_object($first);
4581 if (!is_object($first) or !property_exists($first, 'shortname')) {
4582 $allroles = get_all_roles($context);
4583 foreach ($roleoptions as $rid => $unused) {
4584 $roleoptions[$rid] = $allroles[$rid];
4588 // Inject coursealias if necessary.
4589 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4590 $first = reset($roleoptions);
4591 if (!property_exists($first, 'coursealias')) {
4592 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4593 foreach ($aliasnames as $alias) {
4594 if (isset($roleoptions[$alias->roleid])) {
4595 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4601 // Add localname property.
4602 foreach ($roleoptions as $rid => $role) {
4603 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4606 if (!$returnmenu) {
4607 return $roleoptions;
4610 $menu = array();
4611 foreach ($roleoptions as $rid => $role) {
4612 $menu[$rid] = $role->localname;
4615 return $menu;
4619 * Aids in detecting if a new line is required when reading a new capability
4621 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4622 * when we read in a new capability.
4623 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4624 * but when we are in grade, all reports/import/export capabilities should be together
4626 * @param string $cap component string a
4627 * @param string $comp component string b
4628 * @param int $contextlevel
4629 * @return bool whether 2 component are in different "sections"
4631 function component_level_changed($cap, $comp, $contextlevel) {
4633 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4634 $compsa = explode('/', $cap->component);
4635 $compsb = explode('/', $comp);
4637 // list of system reports
4638 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4639 return false;
4642 // we are in gradebook, still
4643 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4644 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4645 return false;
4648 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4649 return false;
4653 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4657 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4658 * and return an array of roleids in order.
4660 * @param array $allroles array of roles, as returned by get_all_roles();
4661 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4663 function fix_role_sortorder($allroles) {
4664 global $DB;
4666 $rolesort = array();
4667 $i = 0;
4668 foreach ($allroles as $role) {
4669 $rolesort[$i] = $role->id;
4670 if ($role->sortorder != $i) {
4671 $r = new stdClass();
4672 $r->id = $role->id;
4673 $r->sortorder = $i;
4674 $DB->update_record('role', $r);
4675 $allroles[$role->id]->sortorder = $i;
4677 $i++;
4679 return $rolesort;
4683 * Switch the sort order of two roles (used in admin/roles/manage.php).
4685 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4686 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4687 * @return boolean success or failure
4689 function switch_roles($first, $second) {
4690 global $DB;
4691 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4692 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4693 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4694 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4695 return $result;
4699 * Duplicates all the base definitions of a role
4701 * @param stdClass $sourcerole role to copy from
4702 * @param int $targetrole id of role to copy to
4704 function role_cap_duplicate($sourcerole, $targetrole) {
4705 global $DB;
4707 $systemcontext = context_system::instance();
4708 $caps = $DB->get_records_sql("SELECT *
4709 FROM {role_capabilities}
4710 WHERE roleid = ? AND contextid = ?",
4711 array($sourcerole->id, $systemcontext->id));
4712 // adding capabilities
4713 foreach ($caps as $cap) {
4714 unset($cap->id);
4715 $cap->roleid = $targetrole;
4716 $DB->insert_record('role_capabilities', $cap);
4721 * Returns two lists, this can be used to find out if user has capability.
4722 * Having any needed role and no forbidden role in this context means
4723 * user has this capability in this context.
4724 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4726 * @param stdClass $context
4727 * @param string $capability
4728 * @return array($neededroles, $forbiddenroles)
4730 function get_roles_with_cap_in_context($context, $capability) {
4731 global $DB;
4733 $ctxids = trim($context->path, '/'); // kill leading slash
4734 $ctxids = str_replace('/', ',', $ctxids);
4736 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4737 FROM {role_capabilities} rc
4738 JOIN {context} ctx ON ctx.id = rc.contextid
4739 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4740 ORDER BY rc.roleid ASC, ctx.depth DESC";
4741 $params = array('cap'=>$capability);
4743 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4744 // no cap definitions --> no capability
4745 return array(array(), array());
4748 $forbidden = array();
4749 $needed = array();
4750 foreach($capdefs as $def) {
4751 if (isset($forbidden[$def->roleid])) {
4752 continue;
4754 if ($def->permission == CAP_PROHIBIT) {
4755 $forbidden[$def->roleid] = $def->roleid;
4756 unset($needed[$def->roleid]);
4757 continue;
4759 if (!isset($needed[$def->roleid])) {
4760 if ($def->permission == CAP_ALLOW) {
4761 $needed[$def->roleid] = true;
4762 } else if ($def->permission == CAP_PREVENT) {
4763 $needed[$def->roleid] = false;
4767 unset($capdefs);
4769 // remove all those roles not allowing
4770 foreach($needed as $key=>$value) {
4771 if (!$value) {
4772 unset($needed[$key]);
4773 } else {
4774 $needed[$key] = $key;
4778 return array($needed, $forbidden);
4782 * Returns an array of role IDs that have ALL of the the supplied capabilities
4783 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4785 * @param stdClass $context
4786 * @param array $capabilities An array of capabilities
4787 * @return array of roles with all of the required capabilities
4789 function get_roles_with_caps_in_context($context, $capabilities) {
4790 $neededarr = array();
4791 $forbiddenarr = array();
4792 foreach($capabilities as $caprequired) {
4793 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4796 $rolesthatcanrate = array();
4797 if (!empty($neededarr)) {
4798 foreach ($neededarr as $needed) {
4799 if (empty($rolesthatcanrate)) {
4800 $rolesthatcanrate = $needed;
4801 } else {
4802 //only want roles that have all caps
4803 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4807 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4808 foreach ($forbiddenarr as $forbidden) {
4809 //remove any roles that are forbidden any of the caps
4810 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4813 return $rolesthatcanrate;
4817 * Returns an array of role names that have ALL of the the supplied capabilities
4818 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4820 * @param stdClass $context
4821 * @param array $capabilities An array of capabilities
4822 * @return array of roles with all of the required capabilities
4824 function get_role_names_with_caps_in_context($context, $capabilities) {
4825 global $DB;
4827 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4828 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4830 $roles = array();
4831 foreach ($rolesthatcanrate as $r) {
4832 $roles[$r] = $allroles[$r];
4835 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4839 * This function verifies the prohibit comes from this context
4840 * and there are no more prohibits in parent contexts.
4842 * @param int $roleid
4843 * @param context $context
4844 * @param string $capability name
4845 * @return bool
4847 function prohibit_is_removable($roleid, context $context, $capability) {
4848 global $DB;
4850 $ctxids = trim($context->path, '/'); // kill leading slash
4851 $ctxids = str_replace('/', ',', $ctxids);
4853 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4855 $sql = "SELECT ctx.id
4856 FROM {role_capabilities} rc
4857 JOIN {context} ctx ON ctx.id = rc.contextid
4858 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4859 ORDER BY ctx.depth DESC";
4861 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4862 // no prohibits == nothing to remove
4863 return true;
4866 if (count($prohibits) > 1) {
4867 // more prohibits can not be removed
4868 return false;
4871 return !empty($prohibits[$context->id]);
4875 * More user friendly role permission changing,
4876 * it should produce as few overrides as possible.
4878 * @param int $roleid
4879 * @param stdClass $context
4880 * @param string $capname capability name
4881 * @param int $permission
4882 * @return void
4884 function role_change_permission($roleid, $context, $capname, $permission) {
4885 global $DB;
4887 if ($permission == CAP_INHERIT) {
4888 unassign_capability($capname, $roleid, $context->id);
4889 $context->mark_dirty();
4890 return;
4893 $ctxids = trim($context->path, '/'); // kill leading slash
4894 $ctxids = str_replace('/', ',', $ctxids);
4896 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4898 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4899 FROM {role_capabilities} rc
4900 JOIN {context} ctx ON ctx.id = rc.contextid
4901 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4902 ORDER BY ctx.depth DESC";
4904 if ($existing = $DB->get_records_sql($sql, $params)) {
4905 foreach($existing as $e) {
4906 if ($e->permission == CAP_PROHIBIT) {
4907 // prohibit can not be overridden, no point in changing anything
4908 return;
4911 $lowest = array_shift($existing);
4912 if ($lowest->permission == $permission) {
4913 // permission already set in this context or parent - nothing to do
4914 return;
4916 if ($existing) {
4917 $parent = array_shift($existing);
4918 if ($parent->permission == $permission) {
4919 // permission already set in parent context or parent - just unset in this context
4920 // we do this because we want as few overrides as possible for performance reasons
4921 unassign_capability($capname, $roleid, $context->id);
4922 $context->mark_dirty();
4923 return;
4927 } else {
4928 if ($permission == CAP_PREVENT) {
4929 // nothing means role does not have permission
4930 return;
4934 // assign the needed capability
4935 assign_capability($capname, $permission, $roleid, $context->id, true);
4937 // force cap reloading
4938 $context->mark_dirty();
4943 * Basic moodle context abstraction class.
4945 * Google confirms that no other important framework is using "context" class,
4946 * we could use something else like mcontext or moodle_context, but we need to type
4947 * this very often which would be annoying and it would take too much space...
4949 * This class is derived from stdClass for backwards compatibility with
4950 * odl $context record that was returned from DML $DB->get_record()
4952 * @package core_access
4953 * @category access
4954 * @copyright Petr Skoda {@link http://skodak.org}
4955 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4956 * @since 2.2
4958 * @property-read int $id context id
4959 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4960 * @property-read int $instanceid id of related instance in each context
4961 * @property-read string $path path to context, starts with system context
4962 * @property-read int $depth
4964 abstract class context extends stdClass implements IteratorAggregate {
4967 * The context id
4968 * Can be accessed publicly through $context->id
4969 * @var int
4971 protected $_id;
4974 * The context level
4975 * Can be accessed publicly through $context->contextlevel
4976 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4978 protected $_contextlevel;
4981 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4982 * Can be accessed publicly through $context->instanceid
4983 * @var int
4985 protected $_instanceid;
4988 * The path to the context always starting from the system context
4989 * Can be accessed publicly through $context->path
4990 * @var string
4992 protected $_path;
4995 * The depth of the context in relation to parent contexts
4996 * Can be accessed publicly through $context->depth
4997 * @var int
4999 protected $_depth;
5002 * @var array Context caching info
5004 private static $cache_contextsbyid = array();
5007 * @var array Context caching info
5009 private static $cache_contexts = array();
5012 * Context count
5013 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
5014 * @var int
5016 protected static $cache_count = 0;
5019 * @var array Context caching info
5021 protected static $cache_preloaded = array();
5024 * @var context_system The system context once initialised
5026 protected static $systemcontext = null;
5029 * Resets the cache to remove all data.
5030 * @static
5032 protected static function reset_caches() {
5033 self::$cache_contextsbyid = array();
5034 self::$cache_contexts = array();
5035 self::$cache_count = 0;
5036 self::$cache_preloaded = array();
5038 self::$systemcontext = null;
5042 * Adds a context to the cache. If the cache is full, discards a batch of
5043 * older entries.
5045 * @static
5046 * @param context $context New context to add
5047 * @return void
5049 protected static function cache_add(context $context) {
5050 if (isset(self::$cache_contextsbyid[$context->id])) {
5051 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5052 return;
5055 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
5056 $i = 0;
5057 foreach(self::$cache_contextsbyid as $ctx) {
5058 $i++;
5059 if ($i <= 100) {
5060 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
5061 continue;
5063 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
5064 // we remove oldest third of the contexts to make room for more contexts
5065 break;
5067 unset(self::$cache_contextsbyid[$ctx->id]);
5068 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
5069 self::$cache_count--;
5073 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
5074 self::$cache_contextsbyid[$context->id] = $context;
5075 self::$cache_count++;
5079 * Removes a context from the cache.
5081 * @static
5082 * @param context $context Context object to remove
5083 * @return void
5085 protected static function cache_remove(context $context) {
5086 if (!isset(self::$cache_contextsbyid[$context->id])) {
5087 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5088 return;
5090 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
5091 unset(self::$cache_contextsbyid[$context->id]);
5093 self::$cache_count--;
5095 if (self::$cache_count < 0) {
5096 self::$cache_count = 0;
5101 * Gets a context from the cache.
5103 * @static
5104 * @param int $contextlevel Context level
5105 * @param int $instance Instance ID
5106 * @return context|bool Context or false if not in cache
5108 protected static function cache_get($contextlevel, $instance) {
5109 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
5110 return self::$cache_contexts[$contextlevel][$instance];
5112 return false;
5116 * Gets a context from the cache based on its id.
5118 * @static
5119 * @param int $id Context ID
5120 * @return context|bool Context or false if not in cache
5122 protected static function cache_get_by_id($id) {
5123 if (isset(self::$cache_contextsbyid[$id])) {
5124 return self::$cache_contextsbyid[$id];
5126 return false;
5130 * Preloads context information from db record and strips the cached info.
5132 * @static
5133 * @param stdClass $rec
5134 * @return void (modifies $rec)
5136 protected static function preload_from_record(stdClass $rec) {
5137 if (empty($rec->ctxid) or empty($rec->ctxlevel) or empty($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
5138 // $rec does not have enough data, passed here repeatedly or context does not exist yet
5139 return;
5142 // note: in PHP5 the objects are passed by reference, no need to return $rec
5143 $record = new stdClass();
5144 $record->id = $rec->ctxid; unset($rec->ctxid);
5145 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
5146 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
5147 $record->path = $rec->ctxpath; unset($rec->ctxpath);
5148 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
5150 return context::create_instance_from_record($record);
5154 // ====== magic methods =======
5157 * Magic setter method, we do not want anybody to modify properties from the outside
5158 * @param string $name
5159 * @param mixed $value
5161 public function __set($name, $value) {
5162 debugging('Can not change context instance properties!');
5166 * Magic method getter, redirects to read only values.
5167 * @param string $name
5168 * @return mixed
5170 public function __get($name) {
5171 switch ($name) {
5172 case 'id': return $this->_id;
5173 case 'contextlevel': return $this->_contextlevel;
5174 case 'instanceid': return $this->_instanceid;
5175 case 'path': return $this->_path;
5176 case 'depth': return $this->_depth;
5178 default:
5179 debugging('Invalid context property accessed! '.$name);
5180 return null;
5185 * Full support for isset on our magic read only properties.
5186 * @param string $name
5187 * @return bool
5189 public function __isset($name) {
5190 switch ($name) {
5191 case 'id': return isset($this->_id);
5192 case 'contextlevel': return isset($this->_contextlevel);
5193 case 'instanceid': return isset($this->_instanceid);
5194 case 'path': return isset($this->_path);
5195 case 'depth': return isset($this->_depth);
5197 default: return false;
5203 * ALl properties are read only, sorry.
5204 * @param string $name
5206 public function __unset($name) {
5207 debugging('Can not unset context instance properties!');
5210 // ====== implementing method from interface IteratorAggregate ======
5213 * Create an iterator because magic vars can't be seen by 'foreach'.
5215 * Now we can convert context object to array using convert_to_array(),
5216 * and feed it properly to json_encode().
5218 public function getIterator() {
5219 $ret = array(
5220 'id' => $this->id,
5221 'contextlevel' => $this->contextlevel,
5222 'instanceid' => $this->instanceid,
5223 'path' => $this->path,
5224 'depth' => $this->depth
5226 return new ArrayIterator($ret);
5229 // ====== general context methods ======
5232 * Constructor is protected so that devs are forced to
5233 * use context_xxx::instance() or context::instance_by_id().
5235 * @param stdClass $record
5237 protected function __construct(stdClass $record) {
5238 $this->_id = $record->id;
5239 $this->_contextlevel = (int)$record->contextlevel;
5240 $this->_instanceid = $record->instanceid;
5241 $this->_path = $record->path;
5242 $this->_depth = $record->depth;
5246 * This function is also used to work around 'protected' keyword problems in context_helper.
5247 * @static
5248 * @param stdClass $record
5249 * @return context instance
5251 protected static function create_instance_from_record(stdClass $record) {
5252 $classname = context_helper::get_class_for_level($record->contextlevel);
5254 if ($context = context::cache_get_by_id($record->id)) {
5255 return $context;
5258 $context = new $classname($record);
5259 context::cache_add($context);
5261 return $context;
5265 * Copy prepared new contexts from temp table to context table,
5266 * we do this in db specific way for perf reasons only.
5267 * @static
5269 protected static function merge_context_temp_table() {
5270 global $DB;
5272 /* MDL-11347:
5273 * - mysql does not allow to use FROM in UPDATE statements
5274 * - using two tables after UPDATE works in mysql, but might give unexpected
5275 * results in pg 8 (depends on configuration)
5276 * - using table alias in UPDATE does not work in pg < 8.2
5278 * Different code for each database - mostly for performance reasons
5281 $dbfamily = $DB->get_dbfamily();
5282 if ($dbfamily == 'mysql') {
5283 $updatesql = "UPDATE {context} ct, {context_temp} temp
5284 SET ct.path = temp.path,
5285 ct.depth = temp.depth
5286 WHERE ct.id = temp.id";
5287 } else if ($dbfamily == 'oracle') {
5288 $updatesql = "UPDATE {context} ct
5289 SET (ct.path, ct.depth) =
5290 (SELECT temp.path, temp.depth
5291 FROM {context_temp} temp
5292 WHERE temp.id=ct.id)
5293 WHERE EXISTS (SELECT 'x'
5294 FROM {context_temp} temp
5295 WHERE temp.id = ct.id)";
5296 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5297 $updatesql = "UPDATE {context}
5298 SET path = temp.path,
5299 depth = temp.depth
5300 FROM {context_temp} temp
5301 WHERE temp.id={context}.id";
5302 } else {
5303 // sqlite and others
5304 $updatesql = "UPDATE {context}
5305 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5306 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5307 WHERE id IN (SELECT id FROM {context_temp})";
5310 $DB->execute($updatesql);
5314 * Get a context instance as an object, from a given context id.
5316 * @static
5317 * @param int $id context id
5318 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5319 * MUST_EXIST means throw exception if no record found
5320 * @return context|bool the context object or false if not found
5322 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5323 global $DB;
5325 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5326 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5327 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5330 if ($id == SYSCONTEXTID) {
5331 return context_system::instance(0, $strictness);
5334 if (is_array($id) or is_object($id) or empty($id)) {
5335 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5338 if ($context = context::cache_get_by_id($id)) {
5339 return $context;
5342 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5343 return context::create_instance_from_record($record);
5346 return false;
5350 * Update context info after moving context in the tree structure.
5352 * @param context $newparent
5353 * @return void
5355 public function update_moved(context $newparent) {
5356 global $DB;
5358 $frompath = $this->_path;
5359 $newpath = $newparent->path . '/' . $this->_id;
5361 $trans = $DB->start_delegated_transaction();
5363 $this->mark_dirty();
5365 $setdepth = '';
5366 if (($newparent->depth +1) != $this->_depth) {
5367 $diff = $newparent->depth - $this->_depth + 1;
5368 $setdepth = ", depth = depth + $diff";
5370 $sql = "UPDATE {context}
5371 SET path = ?
5372 $setdepth
5373 WHERE id = ?";
5374 $params = array($newpath, $this->_id);
5375 $DB->execute($sql, $params);
5377 $this->_path = $newpath;
5378 $this->_depth = $newparent->depth + 1;
5380 $sql = "UPDATE {context}
5381 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5382 $setdepth
5383 WHERE path LIKE ?";
5384 $params = array($newpath, "{$frompath}/%");
5385 $DB->execute($sql, $params);
5387 $this->mark_dirty();
5389 context::reset_caches();
5391 $trans->allow_commit();
5395 * Remove all context path info and optionally rebuild it.
5397 * @param bool $rebuild
5398 * @return void
5400 public function reset_paths($rebuild = true) {
5401 global $DB;
5403 if ($this->_path) {
5404 $this->mark_dirty();
5406 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5407 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5408 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5409 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5410 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5411 $this->_depth = 0;
5412 $this->_path = null;
5415 if ($rebuild) {
5416 context_helper::build_all_paths(false);
5419 context::reset_caches();
5423 * Delete all data linked to content, do not delete the context record itself
5425 public function delete_content() {
5426 global $CFG, $DB;
5428 blocks_delete_all_for_context($this->_id);
5429 filter_delete_all_for_context($this->_id);
5431 require_once($CFG->dirroot . '/comment/lib.php');
5432 comment::delete_comments(array('contextid'=>$this->_id));
5434 require_once($CFG->dirroot.'/rating/lib.php');
5435 $delopt = new stdclass();
5436 $delopt->contextid = $this->_id;
5437 $rm = new rating_manager();
5438 $rm->delete_ratings($delopt);
5440 // delete all files attached to this context
5441 $fs = get_file_storage();
5442 $fs->delete_area_files($this->_id);
5444 // Delete all repository instances attached to this context.
5445 require_once($CFG->dirroot . '/repository/lib.php');
5446 repository::delete_all_for_context($this->_id);
5448 // delete all advanced grading data attached to this context
5449 require_once($CFG->dirroot.'/grade/grading/lib.php');
5450 grading_manager::delete_all_for_context($this->_id);
5452 // now delete stuff from role related tables, role_unassign_all
5453 // and unenrol should be called earlier to do proper cleanup
5454 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5455 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5456 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5460 * Delete the context content and the context record itself
5462 public function delete() {
5463 global $DB;
5465 // double check the context still exists
5466 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5467 context::cache_remove($this);
5468 return;
5471 $this->delete_content();
5472 $DB->delete_records('context', array('id'=>$this->_id));
5473 // purge static context cache if entry present
5474 context::cache_remove($this);
5476 // do not mark dirty contexts if parents unknown
5477 if (!is_null($this->_path) and $this->_depth > 0) {
5478 $this->mark_dirty();
5482 // ====== context level related methods ======
5485 * Utility method for context creation
5487 * @static
5488 * @param int $contextlevel
5489 * @param int $instanceid
5490 * @param string $parentpath
5491 * @return stdClass context record
5493 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5494 global $DB;
5496 $record = new stdClass();
5497 $record->contextlevel = $contextlevel;
5498 $record->instanceid = $instanceid;
5499 $record->depth = 0;
5500 $record->path = null; //not known before insert
5502 $record->id = $DB->insert_record('context', $record);
5504 // now add path if known - it can be added later
5505 if (!is_null($parentpath)) {
5506 $record->path = $parentpath.'/'.$record->id;
5507 $record->depth = substr_count($record->path, '/');
5508 $DB->update_record('context', $record);
5511 return $record;
5515 * Returns human readable context identifier.
5517 * @param boolean $withprefix whether to prefix the name of the context with the
5518 * type of context, e.g. User, Course, Forum, etc.
5519 * @param boolean $short whether to use the short name of the thing. Only applies
5520 * to course contexts
5521 * @return string the human readable context name.
5523 public function get_context_name($withprefix = true, $short = false) {
5524 // must be implemented in all context levels
5525 throw new coding_exception('can not get name of abstract context');
5529 * Returns the most relevant URL for this context.
5531 * @return moodle_url
5533 public abstract function get_url();
5536 * Returns array of relevant context capability records.
5538 * @return array
5540 public abstract function get_capabilities();
5543 * Recursive function which, given a context, find all its children context ids.
5545 * For course category contexts it will return immediate children and all subcategory contexts.
5546 * It will NOT recurse into courses or subcategories categories.
5547 * If you want to do that, call it on the returned courses/categories.
5549 * When called for a course context, it will return the modules and blocks
5550 * displayed in the course page and blocks displayed on the module pages.
5552 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5553 * contexts ;-)
5555 * @return array Array of child records
5557 public function get_child_contexts() {
5558 global $DB;
5560 $sql = "SELECT ctx.*
5561 FROM {context} ctx
5562 WHERE ctx.path LIKE ?";
5563 $params = array($this->_path.'/%');
5564 $records = $DB->get_records_sql($sql, $params);
5566 $result = array();
5567 foreach ($records as $record) {
5568 $result[$record->id] = context::create_instance_from_record($record);
5571 return $result;
5575 * Returns parent contexts of this context in reversed order, i.e. parent first,
5576 * then grand parent, etc.
5578 * @param bool $includeself tre means include self too
5579 * @return array of context instances
5581 public function get_parent_contexts($includeself = false) {
5582 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5583 return array();
5586 $result = array();
5587 foreach ($contextids as $contextid) {
5588 $parent = context::instance_by_id($contextid, MUST_EXIST);
5589 $result[$parent->id] = $parent;
5592 return $result;
5596 * Returns parent contexts of this context in reversed order, i.e. parent first,
5597 * then grand parent, etc.
5599 * @param bool $includeself tre means include self too
5600 * @return array of context ids
5602 public function get_parent_context_ids($includeself = false) {
5603 if (empty($this->_path)) {
5604 return array();
5607 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5608 $parentcontexts = explode('/', $parentcontexts);
5609 if (!$includeself) {
5610 array_pop($parentcontexts); // and remove its own id
5613 return array_reverse($parentcontexts);
5617 * Returns parent context
5619 * @return context
5621 public function get_parent_context() {
5622 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5623 return false;
5626 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5627 $parentcontexts = explode('/', $parentcontexts);
5628 array_pop($parentcontexts); // self
5629 $contextid = array_pop($parentcontexts); // immediate parent
5631 return context::instance_by_id($contextid, MUST_EXIST);
5635 * Is this context part of any course? If yes return course context.
5637 * @param bool $strict true means throw exception if not found, false means return false if not found
5638 * @return course_context context of the enclosing course, null if not found or exception
5640 public function get_course_context($strict = true) {
5641 if ($strict) {
5642 throw new coding_exception('Context does not belong to any course.');
5643 } else {
5644 return false;
5649 * Returns sql necessary for purging of stale context instances.
5651 * @static
5652 * @return string cleanup SQL
5654 protected static function get_cleanup_sql() {
5655 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5659 * Rebuild context paths and depths at context level.
5661 * @static
5662 * @param bool $force
5663 * @return void
5665 protected static function build_paths($force) {
5666 throw new coding_exception('build_paths() method must be implemented in all context levels');
5670 * Create missing context instances at given level
5672 * @static
5673 * @return void
5675 protected static function create_level_instances() {
5676 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5680 * Reset all cached permissions and definitions if the necessary.
5681 * @return void
5683 public function reload_if_dirty() {
5684 global $ACCESSLIB_PRIVATE, $USER;
5686 // Load dirty contexts list if needed
5687 if (CLI_SCRIPT) {
5688 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5689 // we do not load dirty flags in CLI and cron
5690 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5692 } else {
5693 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5694 if (!isset($USER->access['time'])) {
5695 // nothing was loaded yet, we do not need to check dirty contexts now
5696 return;
5698 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5699 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5703 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5704 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5705 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5706 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5707 reload_all_capabilities();
5708 break;
5714 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5716 public function mark_dirty() {
5717 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5719 if (during_initial_install()) {
5720 return;
5723 // only if it is a non-empty string
5724 if (is_string($this->_path) && $this->_path !== '') {
5725 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5726 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5727 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5728 } else {
5729 if (CLI_SCRIPT) {
5730 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5731 } else {
5732 if (isset($USER->access['time'])) {
5733 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5734 } else {
5735 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5737 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5746 * Context maintenance and helper methods.
5748 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5749 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5750 * level implementation from the rest of code, the code completion returns what developers need.
5752 * Thank you Tim Hunt for helping me with this nasty trick.
5754 * @package core_access
5755 * @category access
5756 * @copyright Petr Skoda {@link http://skodak.org}
5757 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5758 * @since 2.2
5760 class context_helper extends context {
5763 * @var array An array mapping context levels to classes
5765 private static $alllevels;
5768 * Instance does not make sense here, only static use
5770 protected function __construct() {
5774 * Initialise context levels, call before using self::$alllevels.
5776 private static function init_levels() {
5777 global $CFG;
5779 if (isset(self::$alllevels)) {
5780 return;
5782 self::$alllevels = array(
5783 CONTEXT_SYSTEM => 'context_system',
5784 CONTEXT_USER => 'context_user',
5785 CONTEXT_COURSECAT => 'context_coursecat',
5786 CONTEXT_COURSE => 'context_course',
5787 CONTEXT_MODULE => 'context_module',
5788 CONTEXT_BLOCK => 'context_block',
5791 if (empty($CFG->custom_context_classes)) {
5792 return;
5795 // Unsupported custom levels, use with care!!!
5796 foreach ($CFG->custom_context_classes as $level => $classname) {
5797 self::$alllevels[$level] = $classname;
5799 ksort(self::$alllevels);
5803 * Returns a class name of the context level class
5805 * @static
5806 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5807 * @return string class name of the context class
5809 public static function get_class_for_level($contextlevel) {
5810 self::init_levels();
5811 if (isset(self::$alllevels[$contextlevel])) {
5812 return self::$alllevels[$contextlevel];
5813 } else {
5814 throw new coding_exception('Invalid context level specified');
5819 * Returns a list of all context levels
5821 * @static
5822 * @return array int=>string (level=>level class name)
5824 public static function get_all_levels() {
5825 self::init_levels();
5826 return self::$alllevels;
5830 * Remove stale contexts that belonged to deleted instances.
5831 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5833 * @static
5834 * @return void
5836 public static function cleanup_instances() {
5837 global $DB;
5838 self::init_levels();
5840 $sqls = array();
5841 foreach (self::$alllevels as $level=>$classname) {
5842 $sqls[] = $classname::get_cleanup_sql();
5845 $sql = implode(" UNION ", $sqls);
5847 // it is probably better to use transactions, it might be faster too
5848 $transaction = $DB->start_delegated_transaction();
5850 $rs = $DB->get_recordset_sql($sql);
5851 foreach ($rs as $record) {
5852 $context = context::create_instance_from_record($record);
5853 $context->delete();
5855 $rs->close();
5857 $transaction->allow_commit();
5861 * Create all context instances at the given level and above.
5863 * @static
5864 * @param int $contextlevel null means all levels
5865 * @param bool $buildpaths
5866 * @return void
5868 public static function create_instances($contextlevel = null, $buildpaths = true) {
5869 self::init_levels();
5870 foreach (self::$alllevels as $level=>$classname) {
5871 if ($contextlevel and $level > $contextlevel) {
5872 // skip potential sub-contexts
5873 continue;
5875 $classname::create_level_instances();
5876 if ($buildpaths) {
5877 $classname::build_paths(false);
5883 * Rebuild paths and depths in all context levels.
5885 * @static
5886 * @param bool $force false means add missing only
5887 * @return void
5889 public static function build_all_paths($force = false) {
5890 self::init_levels();
5891 foreach (self::$alllevels as $classname) {
5892 $classname::build_paths($force);
5895 // reset static course cache - it might have incorrect cached data
5896 accesslib_clear_all_caches(true);
5900 * Resets the cache to remove all data.
5901 * @static
5903 public static function reset_caches() {
5904 context::reset_caches();
5908 * Returns all fields necessary for context preloading from user $rec.
5910 * This helps with performance when dealing with hundreds of contexts.
5912 * @static
5913 * @param string $tablealias context table alias in the query
5914 * @return array (table.column=>alias, ...)
5916 public static function get_preload_record_columns($tablealias) {
5917 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5921 * Returns all fields necessary for context preloading from user $rec.
5923 * This helps with performance when dealing with hundreds of contexts.
5925 * @static
5926 * @param string $tablealias context table alias in the query
5927 * @return string
5929 public static function get_preload_record_columns_sql($tablealias) {
5930 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5934 * Preloads context information from db record and strips the cached info.
5936 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5938 * @static
5939 * @param stdClass $rec
5940 * @return void (modifies $rec)
5942 public static function preload_from_record(stdClass $rec) {
5943 context::preload_from_record($rec);
5947 * Preload all contexts instances from course.
5949 * To be used if you expect multiple queries for course activities...
5951 * @static
5952 * @param int $courseid
5954 public static function preload_course($courseid) {
5955 // Users can call this multiple times without doing any harm
5956 if (isset(context::$cache_preloaded[$courseid])) {
5957 return;
5959 $coursecontext = context_course::instance($courseid);
5960 $coursecontext->get_child_contexts();
5962 context::$cache_preloaded[$courseid] = true;
5966 * Delete context instance
5968 * @static
5969 * @param int $contextlevel
5970 * @param int $instanceid
5971 * @return void
5973 public static function delete_instance($contextlevel, $instanceid) {
5974 global $DB;
5976 // double check the context still exists
5977 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5978 $context = context::create_instance_from_record($record);
5979 $context->delete();
5980 } else {
5981 // we should try to purge the cache anyway
5986 * Returns the name of specified context level
5988 * @static
5989 * @param int $contextlevel
5990 * @return string name of the context level
5992 public static function get_level_name($contextlevel) {
5993 $classname = context_helper::get_class_for_level($contextlevel);
5994 return $classname::get_level_name();
5998 * not used
6000 public function get_url() {
6004 * not used
6006 public function get_capabilities() {
6012 * System context class
6014 * @package core_access
6015 * @category access
6016 * @copyright Petr Skoda {@link http://skodak.org}
6017 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6018 * @since 2.2
6020 class context_system extends context {
6022 * Please use context_system::instance() if you need the instance of context.
6024 * @param stdClass $record
6026 protected function __construct(stdClass $record) {
6027 parent::__construct($record);
6028 if ($record->contextlevel != CONTEXT_SYSTEM) {
6029 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
6034 * Returns human readable context level name.
6036 * @static
6037 * @return string the human readable context level name.
6039 public static function get_level_name() {
6040 return get_string('coresystem');
6044 * Returns human readable context identifier.
6046 * @param boolean $withprefix does not apply to system context
6047 * @param boolean $short does not apply to system context
6048 * @return string the human readable context name.
6050 public function get_context_name($withprefix = true, $short = false) {
6051 return self::get_level_name();
6055 * Returns the most relevant URL for this context.
6057 * @return moodle_url
6059 public function get_url() {
6060 return new moodle_url('/');
6064 * Returns array of relevant context capability records.
6066 * @return array
6068 public function get_capabilities() {
6069 global $DB;
6071 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6073 $params = array();
6074 $sql = "SELECT *
6075 FROM {capabilities}";
6077 return $DB->get_records_sql($sql.' '.$sort, $params);
6081 * Create missing context instances at system context
6082 * @static
6084 protected static function create_level_instances() {
6085 // nothing to do here, the system context is created automatically in installer
6086 self::instance(0);
6090 * Returns system context instance.
6092 * @static
6093 * @param int $instanceid
6094 * @param int $strictness
6095 * @param bool $cache
6096 * @return context_system context instance
6098 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
6099 global $DB;
6101 if ($instanceid != 0) {
6102 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
6105 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
6106 if (!isset(context::$systemcontext)) {
6107 $record = new stdClass();
6108 $record->id = SYSCONTEXTID;
6109 $record->contextlevel = CONTEXT_SYSTEM;
6110 $record->instanceid = 0;
6111 $record->path = '/'.SYSCONTEXTID;
6112 $record->depth = 1;
6113 context::$systemcontext = new context_system($record);
6115 return context::$systemcontext;
6119 try {
6120 // We ignore the strictness completely because system context must exist except during install.
6121 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6122 } catch (dml_exception $e) {
6123 //table or record does not exist
6124 if (!during_initial_install()) {
6125 // do not mess with system context after install, it simply must exist
6126 throw $e;
6128 $record = null;
6131 if (!$record) {
6132 $record = new stdClass();
6133 $record->contextlevel = CONTEXT_SYSTEM;
6134 $record->instanceid = 0;
6135 $record->depth = 1;
6136 $record->path = null; //not known before insert
6138 try {
6139 if ($DB->count_records('context')) {
6140 // contexts already exist, this is very weird, system must be first!!!
6141 return null;
6143 if (defined('SYSCONTEXTID')) {
6144 // this would happen only in unittest on sites that went through weird 1.7 upgrade
6145 $record->id = SYSCONTEXTID;
6146 $DB->import_record('context', $record);
6147 $DB->get_manager()->reset_sequence('context');
6148 } else {
6149 $record->id = $DB->insert_record('context', $record);
6151 } catch (dml_exception $e) {
6152 // can not create context - table does not exist yet, sorry
6153 return null;
6157 if ($record->instanceid != 0) {
6158 // this is very weird, somebody must be messing with context table
6159 debugging('Invalid system context detected');
6162 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6163 // fix path if necessary, initial install or path reset
6164 $record->depth = 1;
6165 $record->path = '/'.$record->id;
6166 $DB->update_record('context', $record);
6169 if (!defined('SYSCONTEXTID')) {
6170 define('SYSCONTEXTID', $record->id);
6173 context::$systemcontext = new context_system($record);
6174 return context::$systemcontext;
6178 * Returns all site contexts except the system context, DO NOT call on production servers!!
6180 * Contexts are not cached.
6182 * @return array
6184 public function get_child_contexts() {
6185 global $DB;
6187 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6189 // Just get all the contexts except for CONTEXT_SYSTEM level
6190 // and hope we don't OOM in the process - don't cache
6191 $sql = "SELECT c.*
6192 FROM {context} c
6193 WHERE contextlevel > ".CONTEXT_SYSTEM;
6194 $records = $DB->get_records_sql($sql);
6196 $result = array();
6197 foreach ($records as $record) {
6198 $result[$record->id] = context::create_instance_from_record($record);
6201 return $result;
6205 * Returns sql necessary for purging of stale context instances.
6207 * @static
6208 * @return string cleanup SQL
6210 protected static function get_cleanup_sql() {
6211 $sql = "
6212 SELECT c.*
6213 FROM {context} c
6214 WHERE 1=2
6217 return $sql;
6221 * Rebuild context paths and depths at system context level.
6223 * @static
6224 * @param bool $force
6226 protected static function build_paths($force) {
6227 global $DB;
6229 /* note: ignore $force here, we always do full test of system context */
6231 // exactly one record must exist
6232 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6234 if ($record->instanceid != 0) {
6235 debugging('Invalid system context detected');
6238 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6239 debugging('Invalid SYSCONTEXTID detected');
6242 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6243 // fix path if necessary, initial install or path reset
6244 $record->depth = 1;
6245 $record->path = '/'.$record->id;
6246 $DB->update_record('context', $record);
6253 * User context class
6255 * @package core_access
6256 * @category access
6257 * @copyright Petr Skoda {@link http://skodak.org}
6258 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6259 * @since 2.2
6261 class context_user extends context {
6263 * Please use context_user::instance($userid) if you need the instance of context.
6264 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6266 * @param stdClass $record
6268 protected function __construct(stdClass $record) {
6269 parent::__construct($record);
6270 if ($record->contextlevel != CONTEXT_USER) {
6271 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6276 * Returns human readable context level name.
6278 * @static
6279 * @return string the human readable context level name.
6281 public static function get_level_name() {
6282 return get_string('user');
6286 * Returns human readable context identifier.
6288 * @param boolean $withprefix whether to prefix the name of the context with User
6289 * @param boolean $short does not apply to user context
6290 * @return string the human readable context name.
6292 public function get_context_name($withprefix = true, $short = false) {
6293 global $DB;
6295 $name = '';
6296 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6297 if ($withprefix){
6298 $name = get_string('user').': ';
6300 $name .= fullname($user);
6302 return $name;
6306 * Returns the most relevant URL for this context.
6308 * @return moodle_url
6310 public function get_url() {
6311 global $COURSE;
6313 if ($COURSE->id == SITEID) {
6314 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6315 } else {
6316 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6318 return $url;
6322 * Returns array of relevant context capability records.
6324 * @return array
6326 public function get_capabilities() {
6327 global $DB;
6329 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6331 $extracaps = array('moodle/grade:viewall');
6332 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6333 $sql = "SELECT *
6334 FROM {capabilities}
6335 WHERE contextlevel = ".CONTEXT_USER."
6336 OR name $extra";
6338 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6342 * Returns user context instance.
6344 * @static
6345 * @param int $instanceid
6346 * @param int $strictness
6347 * @return context_user context instance
6349 public static function instance($instanceid, $strictness = MUST_EXIST) {
6350 global $DB;
6352 if ($context = context::cache_get(CONTEXT_USER, $instanceid)) {
6353 return $context;
6356 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_USER, 'instanceid'=>$instanceid))) {
6357 if ($user = $DB->get_record('user', array('id'=>$instanceid, 'deleted'=>0), 'id', $strictness)) {
6358 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6362 if ($record) {
6363 $context = new context_user($record);
6364 context::cache_add($context);
6365 return $context;
6368 return false;
6372 * Create missing context instances at user context level
6373 * @static
6375 protected static function create_level_instances() {
6376 global $DB;
6378 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6379 SELECT ".CONTEXT_USER.", u.id
6380 FROM {user} u
6381 WHERE u.deleted = 0
6382 AND NOT EXISTS (SELECT 'x'
6383 FROM {context} cx
6384 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6385 $DB->execute($sql);
6389 * Returns sql necessary for purging of stale context instances.
6391 * @static
6392 * @return string cleanup SQL
6394 protected static function get_cleanup_sql() {
6395 $sql = "
6396 SELECT c.*
6397 FROM {context} c
6398 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6399 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6402 return $sql;
6406 * Rebuild context paths and depths at user context level.
6408 * @static
6409 * @param bool $force
6411 protected static function build_paths($force) {
6412 global $DB;
6414 // First update normal users.
6415 $path = $DB->sql_concat('?', 'id');
6416 $pathstart = '/' . SYSCONTEXTID . '/';
6417 $params = array($pathstart);
6419 if ($force) {
6420 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6421 $params[] = $pathstart;
6422 } else {
6423 $where = "depth = 0 OR path IS NULL";
6426 $sql = "UPDATE {context}
6427 SET depth = 2,
6428 path = {$path}
6429 WHERE contextlevel = " . CONTEXT_USER . "
6430 AND ($where)";
6431 $DB->execute($sql, $params);
6437 * Course category context class
6439 * @package core_access
6440 * @category access
6441 * @copyright Petr Skoda {@link http://skodak.org}
6442 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6443 * @since 2.2
6445 class context_coursecat extends context {
6447 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6448 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6450 * @param stdClass $record
6452 protected function __construct(stdClass $record) {
6453 parent::__construct($record);
6454 if ($record->contextlevel != CONTEXT_COURSECAT) {
6455 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6460 * Returns human readable context level name.
6462 * @static
6463 * @return string the human readable context level name.
6465 public static function get_level_name() {
6466 return get_string('category');
6470 * Returns human readable context identifier.
6472 * @param boolean $withprefix whether to prefix the name of the context with Category
6473 * @param boolean $short does not apply to course categories
6474 * @return string the human readable context name.
6476 public function get_context_name($withprefix = true, $short = false) {
6477 global $DB;
6479 $name = '';
6480 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6481 if ($withprefix){
6482 $name = get_string('category').': ';
6484 $name .= format_string($category->name, true, array('context' => $this));
6486 return $name;
6490 * Returns the most relevant URL for this context.
6492 * @return moodle_url
6494 public function get_url() {
6495 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6499 * Returns array of relevant context capability records.
6501 * @return array
6503 public function get_capabilities() {
6504 global $DB;
6506 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6508 $params = array();
6509 $sql = "SELECT *
6510 FROM {capabilities}
6511 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6513 return $DB->get_records_sql($sql.' '.$sort, $params);
6517 * Returns course category context instance.
6519 * @static
6520 * @param int $instanceid
6521 * @param int $strictness
6522 * @return context_coursecat context instance
6524 public static function instance($instanceid, $strictness = MUST_EXIST) {
6525 global $DB;
6527 if ($context = context::cache_get(CONTEXT_COURSECAT, $instanceid)) {
6528 return $context;
6531 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSECAT, 'instanceid'=>$instanceid))) {
6532 if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), 'id,parent', $strictness)) {
6533 if ($category->parent) {
6534 $parentcontext = context_coursecat::instance($category->parent);
6535 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6536 } else {
6537 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6542 if ($record) {
6543 $context = new context_coursecat($record);
6544 context::cache_add($context);
6545 return $context;
6548 return false;
6552 * Returns immediate child contexts of category and all subcategories,
6553 * children of subcategories and courses are not returned.
6555 * @return array
6557 public function get_child_contexts() {
6558 global $DB;
6560 $sql = "SELECT ctx.*
6561 FROM {context} ctx
6562 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6563 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6564 $records = $DB->get_records_sql($sql, $params);
6566 $result = array();
6567 foreach ($records as $record) {
6568 $result[$record->id] = context::create_instance_from_record($record);
6571 return $result;
6575 * Create missing context instances at course category context level
6576 * @static
6578 protected static function create_level_instances() {
6579 global $DB;
6581 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6582 SELECT ".CONTEXT_COURSECAT.", cc.id
6583 FROM {course_categories} cc
6584 WHERE NOT EXISTS (SELECT 'x'
6585 FROM {context} cx
6586 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6587 $DB->execute($sql);
6591 * Returns sql necessary for purging of stale context instances.
6593 * @static
6594 * @return string cleanup SQL
6596 protected static function get_cleanup_sql() {
6597 $sql = "
6598 SELECT c.*
6599 FROM {context} c
6600 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6601 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6604 return $sql;
6608 * Rebuild context paths and depths at course category context level.
6610 * @static
6611 * @param bool $force
6613 protected static function build_paths($force) {
6614 global $DB;
6616 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6617 if ($force) {
6618 $ctxemptyclause = $emptyclause = '';
6619 } else {
6620 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6621 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6624 $base = '/'.SYSCONTEXTID;
6626 // Normal top level categories
6627 $sql = "UPDATE {context}
6628 SET depth=2,
6629 path=".$DB->sql_concat("'$base/'", 'id')."
6630 WHERE contextlevel=".CONTEXT_COURSECAT."
6631 AND EXISTS (SELECT 'x'
6632 FROM {course_categories} cc
6633 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6634 $emptyclause";
6635 $DB->execute($sql);
6637 // Deeper categories - one query per depthlevel
6638 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6639 for ($n=2; $n<=$maxdepth; $n++) {
6640 $sql = "INSERT INTO {context_temp} (id, path, depth)
6641 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6642 FROM {context} ctx
6643 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6644 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6645 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6646 $ctxemptyclause";
6647 $trans = $DB->start_delegated_transaction();
6648 $DB->delete_records('context_temp');
6649 $DB->execute($sql);
6650 context::merge_context_temp_table();
6651 $DB->delete_records('context_temp');
6652 $trans->allow_commit();
6661 * Course context class
6663 * @package core_access
6664 * @category access
6665 * @copyright Petr Skoda {@link http://skodak.org}
6666 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6667 * @since 2.2
6669 class context_course extends context {
6671 * Please use context_course::instance($courseid) if you need the instance of context.
6672 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6674 * @param stdClass $record
6676 protected function __construct(stdClass $record) {
6677 parent::__construct($record);
6678 if ($record->contextlevel != CONTEXT_COURSE) {
6679 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6684 * Returns human readable context level name.
6686 * @static
6687 * @return string the human readable context level name.
6689 public static function get_level_name() {
6690 return get_string('course');
6694 * Returns human readable context identifier.
6696 * @param boolean $withprefix whether to prefix the name of the context with Course
6697 * @param boolean $short whether to use the short name of the thing.
6698 * @return string the human readable context name.
6700 public function get_context_name($withprefix = true, $short = false) {
6701 global $DB;
6703 $name = '';
6704 if ($this->_instanceid == SITEID) {
6705 $name = get_string('frontpage', 'admin');
6706 } else {
6707 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6708 if ($withprefix){
6709 $name = get_string('course').': ';
6711 if ($short){
6712 $name .= format_string($course->shortname, true, array('context' => $this));
6713 } else {
6714 $name .= format_string(get_course_display_name_for_list($course));
6718 return $name;
6722 * Returns the most relevant URL for this context.
6724 * @return moodle_url
6726 public function get_url() {
6727 if ($this->_instanceid != SITEID) {
6728 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6731 return new moodle_url('/');
6735 * Returns array of relevant context capability records.
6737 * @return array
6739 public function get_capabilities() {
6740 global $DB;
6742 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6744 $params = array();
6745 $sql = "SELECT *
6746 FROM {capabilities}
6747 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6749 return $DB->get_records_sql($sql.' '.$sort, $params);
6753 * Is this context part of any course? If yes return course context.
6755 * @param bool $strict true means throw exception if not found, false means return false if not found
6756 * @return course_context context of the enclosing course, null if not found or exception
6758 public function get_course_context($strict = true) {
6759 return $this;
6763 * Returns course context instance.
6765 * @static
6766 * @param int $instanceid
6767 * @param int $strictness
6768 * @return context_course context instance
6770 public static function instance($instanceid, $strictness = MUST_EXIST) {
6771 global $DB;
6773 if ($context = context::cache_get(CONTEXT_COURSE, $instanceid)) {
6774 return $context;
6777 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$instanceid))) {
6778 if ($course = $DB->get_record('course', array('id'=>$instanceid), 'id,category', $strictness)) {
6779 if ($course->category) {
6780 $parentcontext = context_coursecat::instance($course->category);
6781 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6782 } else {
6783 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6788 if ($record) {
6789 $context = new context_course($record);
6790 context::cache_add($context);
6791 return $context;
6794 return false;
6798 * Create missing context instances at course context level
6799 * @static
6801 protected static function create_level_instances() {
6802 global $DB;
6804 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6805 SELECT ".CONTEXT_COURSE.", c.id
6806 FROM {course} c
6807 WHERE NOT EXISTS (SELECT 'x'
6808 FROM {context} cx
6809 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6810 $DB->execute($sql);
6814 * Returns sql necessary for purging of stale context instances.
6816 * @static
6817 * @return string cleanup SQL
6819 protected static function get_cleanup_sql() {
6820 $sql = "
6821 SELECT c.*
6822 FROM {context} c
6823 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6824 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6827 return $sql;
6831 * Rebuild context paths and depths at course context level.
6833 * @static
6834 * @param bool $force
6836 protected static function build_paths($force) {
6837 global $DB;
6839 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6840 if ($force) {
6841 $ctxemptyclause = $emptyclause = '';
6842 } else {
6843 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6844 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6847 $base = '/'.SYSCONTEXTID;
6849 // Standard frontpage
6850 $sql = "UPDATE {context}
6851 SET depth = 2,
6852 path = ".$DB->sql_concat("'$base/'", 'id')."
6853 WHERE contextlevel = ".CONTEXT_COURSE."
6854 AND EXISTS (SELECT 'x'
6855 FROM {course} c
6856 WHERE c.id = {context}.instanceid AND c.category = 0)
6857 $emptyclause";
6858 $DB->execute($sql);
6860 // standard courses
6861 $sql = "INSERT INTO {context_temp} (id, path, depth)
6862 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6863 FROM {context} ctx
6864 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6865 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6866 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6867 $ctxemptyclause";
6868 $trans = $DB->start_delegated_transaction();
6869 $DB->delete_records('context_temp');
6870 $DB->execute($sql);
6871 context::merge_context_temp_table();
6872 $DB->delete_records('context_temp');
6873 $trans->allow_commit();
6880 * Course module context class
6882 * @package core_access
6883 * @category access
6884 * @copyright Petr Skoda {@link http://skodak.org}
6885 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6886 * @since 2.2
6888 class context_module extends context {
6890 * Please use context_module::instance($cmid) if you need the instance of context.
6891 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6893 * @param stdClass $record
6895 protected function __construct(stdClass $record) {
6896 parent::__construct($record);
6897 if ($record->contextlevel != CONTEXT_MODULE) {
6898 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6903 * Returns human readable context level name.
6905 * @static
6906 * @return string the human readable context level name.
6908 public static function get_level_name() {
6909 return get_string('activitymodule');
6913 * Returns human readable context identifier.
6915 * @param boolean $withprefix whether to prefix the name of the context with the
6916 * module name, e.g. Forum, Glossary, etc.
6917 * @param boolean $short does not apply to module context
6918 * @return string the human readable context name.
6920 public function get_context_name($withprefix = true, $short = false) {
6921 global $DB;
6923 $name = '';
6924 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6925 FROM {course_modules} cm
6926 JOIN {modules} md ON md.id = cm.module
6927 WHERE cm.id = ?", array($this->_instanceid))) {
6928 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6929 if ($withprefix){
6930 $name = get_string('modulename', $cm->modname).': ';
6932 $name .= format_string($mod->name, true, array('context' => $this));
6935 return $name;
6939 * Returns the most relevant URL for this context.
6941 * @return moodle_url
6943 public function get_url() {
6944 global $DB;
6946 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6947 FROM {course_modules} cm
6948 JOIN {modules} md ON md.id = cm.module
6949 WHERE cm.id = ?", array($this->_instanceid))) {
6950 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6953 return new moodle_url('/');
6957 * Returns array of relevant context capability records.
6959 * @return array
6961 public function get_capabilities() {
6962 global $DB, $CFG;
6964 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6966 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6967 $module = $DB->get_record('modules', array('id'=>$cm->module));
6969 $subcaps = array();
6970 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6971 if (file_exists($subpluginsfile)) {
6972 $subplugins = array(); // should be redefined in the file
6973 include($subpluginsfile);
6974 if (!empty($subplugins)) {
6975 foreach (array_keys($subplugins) as $subplugintype) {
6976 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
6977 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6983 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6984 $extracaps = array();
6985 if (file_exists($modfile)) {
6986 include_once($modfile);
6987 $modfunction = $module->name.'_get_extra_capabilities';
6988 if (function_exists($modfunction)) {
6989 $extracaps = $modfunction();
6993 $extracaps = array_merge($subcaps, $extracaps);
6994 $extra = '';
6995 list($extra, $params) = $DB->get_in_or_equal(
6996 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
6997 if (!empty($extra)) {
6998 $extra = "OR name $extra";
7000 $sql = "SELECT *
7001 FROM {capabilities}
7002 WHERE (contextlevel = ".CONTEXT_MODULE."
7003 AND (component = :component OR component = 'moodle'))
7004 $extra";
7005 $params['component'] = "mod_$module->name";
7007 return $DB->get_records_sql($sql.' '.$sort, $params);
7011 * Is this context part of any course? If yes return course context.
7013 * @param bool $strict true means throw exception if not found, false means return false if not found
7014 * @return context_course context of the enclosing course, null if not found or exception
7016 public function get_course_context($strict = true) {
7017 return $this->get_parent_context();
7021 * Returns module context instance.
7023 * @static
7024 * @param int $instanceid
7025 * @param int $strictness
7026 * @return context_module context instance
7028 public static function instance($instanceid, $strictness = MUST_EXIST) {
7029 global $DB;
7031 if ($context = context::cache_get(CONTEXT_MODULE, $instanceid)) {
7032 return $context;
7035 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$instanceid))) {
7036 if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), 'id,course', $strictness)) {
7037 $parentcontext = context_course::instance($cm->course);
7038 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
7042 if ($record) {
7043 $context = new context_module($record);
7044 context::cache_add($context);
7045 return $context;
7048 return false;
7052 * Create missing context instances at module context level
7053 * @static
7055 protected static function create_level_instances() {
7056 global $DB;
7058 $sql = "INSERT INTO {context} (contextlevel, instanceid)
7059 SELECT ".CONTEXT_MODULE.", cm.id
7060 FROM {course_modules} cm
7061 WHERE NOT EXISTS (SELECT 'x'
7062 FROM {context} cx
7063 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
7064 $DB->execute($sql);
7068 * Returns sql necessary for purging of stale context instances.
7070 * @static
7071 * @return string cleanup SQL
7073 protected static function get_cleanup_sql() {
7074 $sql = "
7075 SELECT c.*
7076 FROM {context} c
7077 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
7078 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
7081 return $sql;
7085 * Rebuild context paths and depths at module context level.
7087 * @static
7088 * @param bool $force
7090 protected static function build_paths($force) {
7091 global $DB;
7093 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
7094 if ($force) {
7095 $ctxemptyclause = '';
7096 } else {
7097 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7100 $sql = "INSERT INTO {context_temp} (id, path, depth)
7101 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7102 FROM {context} ctx
7103 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
7104 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
7105 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7106 $ctxemptyclause";
7107 $trans = $DB->start_delegated_transaction();
7108 $DB->delete_records('context_temp');
7109 $DB->execute($sql);
7110 context::merge_context_temp_table();
7111 $DB->delete_records('context_temp');
7112 $trans->allow_commit();
7119 * Block context class
7121 * @package core_access
7122 * @category access
7123 * @copyright Petr Skoda {@link http://skodak.org}
7124 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7125 * @since 2.2
7127 class context_block extends context {
7129 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
7130 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7132 * @param stdClass $record
7134 protected function __construct(stdClass $record) {
7135 parent::__construct($record);
7136 if ($record->contextlevel != CONTEXT_BLOCK) {
7137 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
7142 * Returns human readable context level name.
7144 * @static
7145 * @return string the human readable context level name.
7147 public static function get_level_name() {
7148 return get_string('block');
7152 * Returns human readable context identifier.
7154 * @param boolean $withprefix whether to prefix the name of the context with Block
7155 * @param boolean $short does not apply to block context
7156 * @return string the human readable context name.
7158 public function get_context_name($withprefix = true, $short = false) {
7159 global $DB, $CFG;
7161 $name = '';
7162 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
7163 global $CFG;
7164 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7165 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7166 $blockname = "block_$blockinstance->blockname";
7167 if ($blockobject = new $blockname()) {
7168 if ($withprefix){
7169 $name = get_string('block').': ';
7171 $name .= $blockobject->title;
7175 return $name;
7179 * Returns the most relevant URL for this context.
7181 * @return moodle_url
7183 public function get_url() {
7184 $parentcontexts = $this->get_parent_context();
7185 return $parentcontexts->get_url();
7189 * Returns array of relevant context capability records.
7191 * @return array
7193 public function get_capabilities() {
7194 global $DB;
7196 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7198 $params = array();
7199 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
7201 $extra = '';
7202 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7203 if ($extracaps) {
7204 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7205 $extra = "OR name $extra";
7208 $sql = "SELECT *
7209 FROM {capabilities}
7210 WHERE (contextlevel = ".CONTEXT_BLOCK."
7211 AND component = :component)
7212 $extra";
7213 $params['component'] = 'block_' . $bi->blockname;
7215 return $DB->get_records_sql($sql.' '.$sort, $params);
7219 * Is this context part of any course? If yes return course context.
7221 * @param bool $strict true means throw exception if not found, false means return false if not found
7222 * @return course_context context of the enclosing course, null if not found or exception
7224 public function get_course_context($strict = true) {
7225 $parentcontext = $this->get_parent_context();
7226 return $parentcontext->get_course_context($strict);
7230 * Returns block context instance.
7232 * @static
7233 * @param int $instanceid
7234 * @param int $strictness
7235 * @return context_block context instance
7237 public static function instance($instanceid, $strictness = MUST_EXIST) {
7238 global $DB;
7240 if ($context = context::cache_get(CONTEXT_BLOCK, $instanceid)) {
7241 return $context;
7244 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$instanceid))) {
7245 if ($bi = $DB->get_record('block_instances', array('id'=>$instanceid), 'id,parentcontextid', $strictness)) {
7246 $parentcontext = context::instance_by_id($bi->parentcontextid);
7247 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7251 if ($record) {
7252 $context = new context_block($record);
7253 context::cache_add($context);
7254 return $context;
7257 return false;
7261 * Block do not have child contexts...
7262 * @return array
7264 public function get_child_contexts() {
7265 return array();
7269 * Create missing context instances at block context level
7270 * @static
7272 protected static function create_level_instances() {
7273 global $DB;
7275 $sql = "INSERT INTO {context} (contextlevel, instanceid)
7276 SELECT ".CONTEXT_BLOCK.", bi.id
7277 FROM {block_instances} bi
7278 WHERE NOT EXISTS (SELECT 'x'
7279 FROM {context} cx
7280 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7281 $DB->execute($sql);
7285 * Returns sql necessary for purging of stale context instances.
7287 * @static
7288 * @return string cleanup SQL
7290 protected static function get_cleanup_sql() {
7291 $sql = "
7292 SELECT c.*
7293 FROM {context} c
7294 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7295 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7298 return $sql;
7302 * Rebuild context paths and depths at block context level.
7304 * @static
7305 * @param bool $force
7307 protected static function build_paths($force) {
7308 global $DB;
7310 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7311 if ($force) {
7312 $ctxemptyclause = '';
7313 } else {
7314 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7317 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7318 $sql = "INSERT INTO {context_temp} (id, path, depth)
7319 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7320 FROM {context} ctx
7321 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7322 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7323 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7324 $ctxemptyclause";
7325 $trans = $DB->start_delegated_transaction();
7326 $DB->delete_records('context_temp');
7327 $DB->execute($sql);
7328 context::merge_context_temp_table();
7329 $DB->delete_records('context_temp');
7330 $trans->allow_commit();
7336 // ============== DEPRECATED FUNCTIONS ==========================================
7337 // Old context related functions were deprecated in 2.0, it is recommended
7338 // to use context classes in new code. Old function can be used when
7339 // creating patches that are supposed to be backported to older stable branches.
7340 // These deprecated functions will not be removed in near future,
7341 // before removing devs will be warned with a debugging message first,
7342 // then we will add error message and only after that we can remove the functions
7343 // completely.
7346 * Runs get_records select on context table and returns the result
7347 * Does get_records_select on the context table, and returns the results ordered
7348 * by contextlevel, and then the natural sort order within each level.
7349 * for the purpose of $select, you need to know that the context table has been
7350 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7352 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7353 * @param array $params any parameters required by $select.
7354 * @return array the requested context records.
7356 function get_sorted_contexts($select, $params = array()) {
7358 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7360 global $DB;
7361 if ($select) {
7362 $select = 'WHERE ' . $select;
7364 return $DB->get_records_sql("
7365 SELECT ctx.*
7366 FROM {context} ctx
7367 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7368 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7369 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7370 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7371 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7372 $select
7373 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7374 ", $params);
7378 * Given context and array of users, returns array of users whose enrolment status is suspended,
7379 * or enrolment has expired or has not started. Also removes those users from the given array
7381 * @param context $context context in which suspended users should be extracted.
7382 * @param array $users list of users.
7383 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7384 * @return array list of suspended users.
7386 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7387 global $DB;
7389 // Get active enrolled users.
7390 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7391 $activeusers = $DB->get_records_sql($sql, $params);
7393 // Move suspended users to a separate array & remove from the initial one.
7394 $susers = array();
7395 if (sizeof($activeusers)) {
7396 foreach ($users as $userid => $user) {
7397 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7398 $susers[$userid] = $user;
7399 unset($users[$userid]);
7403 return $susers;
7407 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7408 * or enrolment has expired or not started.
7410 * @param context $context context in which user enrolment is checked.
7411 * @return array list of suspended user id's.
7413 function get_suspended_userids($context){
7414 global $DB;
7416 // Get all enrolled users.
7417 list($sql, $params) = get_enrolled_sql($context);
7418 $users = $DB->get_records_sql($sql, $params);
7420 // Get active enrolled users.
7421 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7422 $activeusers = $DB->get_records_sql($sql, $params);
7424 $susers = array();
7425 if (sizeof($activeusers) != sizeof($users)) {
7426 foreach ($users as $userid => $user) {
7427 if (!array_key_exists($userid, $activeusers)) {
7428 $susers[$userid] = $userid;
7432 return $susers;