MDL-41197 normalize ascii text conversion
[moodle.git] / lib / accesslib.php
blob7d7bb69d70e854e48c2acd9cb909fbdec738289a
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 'name' => $role->name,
1532 'shortname' => $role->shortname,
1533 'description' => $role->description,
1534 'archetype' => $role->archetype
1538 $event->add_record_snapshot('role', $role);
1539 $event->trigger();
1541 return true;
1545 * Function to write context specific overrides, or default capabilities.
1547 * NOTE: use $context->mark_dirty() after this
1549 * @param string $capability string name
1550 * @param int $permission CAP_ constants
1551 * @param int $roleid role id
1552 * @param int|context $contextid context id
1553 * @param bool $overwrite
1554 * @return bool always true or exception
1556 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1557 global $USER, $DB;
1559 if ($contextid instanceof context) {
1560 $context = $contextid;
1561 } else {
1562 $context = context::instance_by_id($contextid);
1565 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1566 unassign_capability($capability, $roleid, $context->id);
1567 return true;
1570 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1572 if ($existing and !$overwrite) { // We want to keep whatever is there already
1573 return true;
1576 $cap = new stdClass();
1577 $cap->contextid = $context->id;
1578 $cap->roleid = $roleid;
1579 $cap->capability = $capability;
1580 $cap->permission = $permission;
1581 $cap->timemodified = time();
1582 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1584 if ($existing) {
1585 $cap->id = $existing->id;
1586 $DB->update_record('role_capabilities', $cap);
1587 } else {
1588 if ($DB->record_exists('context', array('id'=>$context->id))) {
1589 $DB->insert_record('role_capabilities', $cap);
1592 return true;
1596 * Unassign a capability from a role.
1598 * NOTE: use $context->mark_dirty() after this
1600 * @param string $capability the name of the capability
1601 * @param int $roleid the role id
1602 * @param int|context $contextid null means all contexts
1603 * @return boolean true or exception
1605 function unassign_capability($capability, $roleid, $contextid = null) {
1606 global $DB;
1608 if (!empty($contextid)) {
1609 if ($contextid instanceof context) {
1610 $context = $contextid;
1611 } else {
1612 $context = context::instance_by_id($contextid);
1614 // delete from context rel, if this is the last override in this context
1615 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1616 } else {
1617 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1619 return true;
1623 * Get the roles that have a given capability assigned to it
1625 * This function does not resolve the actual permission of the capability.
1626 * It just checks for permissions and overrides.
1627 * Use get_roles_with_cap_in_context() if resolution is required.
1629 * @param string $capability capability name (string)
1630 * @param string $permission optional, the permission defined for this capability
1631 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1632 * @param stdClass $context null means any
1633 * @return array of role records
1635 function get_roles_with_capability($capability, $permission = null, $context = null) {
1636 global $DB;
1638 if ($context) {
1639 $contexts = $context->get_parent_context_ids(true);
1640 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1641 $contextsql = "AND rc.contextid $insql";
1642 } else {
1643 $params = array();
1644 $contextsql = '';
1647 if ($permission) {
1648 $permissionsql = " AND rc.permission = :permission";
1649 $params['permission'] = $permission;
1650 } else {
1651 $permissionsql = '';
1654 $sql = "SELECT r.*
1655 FROM {role} r
1656 WHERE r.id IN (SELECT rc.roleid
1657 FROM {role_capabilities} rc
1658 WHERE rc.capability = :capname
1659 $contextsql
1660 $permissionsql)";
1661 $params['capname'] = $capability;
1664 return $DB->get_records_sql($sql, $params);
1668 * This function makes a role-assignment (a role for a user in a particular context)
1670 * @param int $roleid the role of the id
1671 * @param int $userid userid
1672 * @param int|context $contextid id of the context
1673 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1674 * @param int $itemid id of enrolment/auth plugin
1675 * @param string $timemodified defaults to current time
1676 * @return int new/existing id of the assignment
1678 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1679 global $USER, $DB;
1681 // first of all detect if somebody is using old style parameters
1682 if ($contextid === 0 or is_numeric($component)) {
1683 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1686 // now validate all parameters
1687 if (empty($roleid)) {
1688 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1691 if (empty($userid)) {
1692 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1695 if ($itemid) {
1696 if (strpos($component, '_') === false) {
1697 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1699 } else {
1700 $itemid = 0;
1701 if ($component !== '' and strpos($component, '_') === false) {
1702 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1706 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1707 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1710 if ($contextid instanceof context) {
1711 $context = $contextid;
1712 } else {
1713 $context = context::instance_by_id($contextid, MUST_EXIST);
1716 if (!$timemodified) {
1717 $timemodified = time();
1720 // Check for existing entry
1721 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1723 if ($ras) {
1724 // role already assigned - this should not happen
1725 if (count($ras) > 1) {
1726 // very weird - remove all duplicates!
1727 $ra = array_shift($ras);
1728 foreach ($ras as $r) {
1729 $DB->delete_records('role_assignments', array('id'=>$r->id));
1731 } else {
1732 $ra = reset($ras);
1735 // actually there is no need to update, reset anything or trigger any event, so just return
1736 return $ra->id;
1739 // Create a new entry
1740 $ra = new stdClass();
1741 $ra->roleid = $roleid;
1742 $ra->contextid = $context->id;
1743 $ra->userid = $userid;
1744 $ra->component = $component;
1745 $ra->itemid = $itemid;
1746 $ra->timemodified = $timemodified;
1747 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1749 $ra->id = $DB->insert_record('role_assignments', $ra);
1751 // mark context as dirty - again expensive, but needed
1752 $context->mark_dirty();
1754 if (!empty($USER->id) && $USER->id == $userid) {
1755 // If the user is the current user, then do full reload of capabilities too.
1756 reload_all_capabilities();
1759 $event = \core\event\role_assigned::create(
1760 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1761 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1762 $event->add_record_snapshot('role_assignments', $ra);
1763 $event->trigger();
1765 return $ra->id;
1769 * Removes one role assignment
1771 * @param int $roleid
1772 * @param int $userid
1773 * @param int $contextid
1774 * @param string $component
1775 * @param int $itemid
1776 * @return void
1778 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1779 // first make sure the params make sense
1780 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1781 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1784 if ($itemid) {
1785 if (strpos($component, '_') === false) {
1786 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1788 } else {
1789 $itemid = 0;
1790 if ($component !== '' and strpos($component, '_') === false) {
1791 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1795 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1799 * Removes multiple role assignments, parameters may contain:
1800 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1802 * @param array $params role assignment parameters
1803 * @param bool $subcontexts unassign in subcontexts too
1804 * @param bool $includemanual include manual role assignments too
1805 * @return void
1807 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1808 global $USER, $CFG, $DB;
1810 if (!$params) {
1811 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1814 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1815 foreach ($params as $key=>$value) {
1816 if (!in_array($key, $allowed)) {
1817 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1821 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1822 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1825 if ($includemanual) {
1826 if (!isset($params['component']) or $params['component'] === '') {
1827 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1831 if ($subcontexts) {
1832 if (empty($params['contextid'])) {
1833 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1837 $ras = $DB->get_records('role_assignments', $params);
1838 foreach($ras as $ra) {
1839 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1840 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1841 // this is a bit expensive but necessary
1842 $context->mark_dirty();
1843 // If the user is the current user, then do full reload of capabilities too.
1844 if (!empty($USER->id) && $USER->id == $ra->userid) {
1845 reload_all_capabilities();
1847 $event = \core\event\role_unassigned::create(
1848 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1849 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1850 $event->add_record_snapshot('role_assignments', $ra);
1851 $event->trigger();
1854 unset($ras);
1856 // process subcontexts
1857 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1858 if ($params['contextid'] instanceof context) {
1859 $context = $params['contextid'];
1860 } else {
1861 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1864 if ($context) {
1865 $contexts = $context->get_child_contexts();
1866 $mparams = $params;
1867 foreach($contexts as $context) {
1868 $mparams['contextid'] = $context->id;
1869 $ras = $DB->get_records('role_assignments', $mparams);
1870 foreach($ras as $ra) {
1871 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1872 // this is a bit expensive but necessary
1873 $context->mark_dirty();
1874 // If the user is the current user, then do full reload of capabilities too.
1875 if (!empty($USER->id) && $USER->id == $ra->userid) {
1876 reload_all_capabilities();
1878 $event = \core\event\role_unassigned::create(
1879 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1880 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1881 $event->add_record_snapshot('role_assignments', $ra);
1882 $event->trigger();
1888 // do this once more for all manual role assignments
1889 if ($includemanual) {
1890 $params['component'] = '';
1891 role_unassign_all($params, $subcontexts, false);
1896 * Determines if a user is currently logged in
1898 * @category access
1900 * @return bool
1902 function isloggedin() {
1903 global $USER;
1905 return (!empty($USER->id));
1909 * Determines if a user is logged in as real guest user with username 'guest'.
1911 * @category access
1913 * @param int|object $user mixed user object or id, $USER if not specified
1914 * @return bool true if user is the real guest user, false if not logged in or other user
1916 function isguestuser($user = null) {
1917 global $USER, $DB, $CFG;
1919 // make sure we have the user id cached in config table, because we are going to use it a lot
1920 if (empty($CFG->siteguest)) {
1921 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1922 // guest does not exist yet, weird
1923 return false;
1925 set_config('siteguest', $guestid);
1927 if ($user === null) {
1928 $user = $USER;
1931 if ($user === null) {
1932 // happens when setting the $USER
1933 return false;
1935 } else if (is_numeric($user)) {
1936 return ($CFG->siteguest == $user);
1938 } else if (is_object($user)) {
1939 if (empty($user->id)) {
1940 return false; // not logged in means is not be guest
1941 } else {
1942 return ($CFG->siteguest == $user->id);
1945 } else {
1946 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1951 * Does user have a (temporary or real) guest access to course?
1953 * @category access
1955 * @param context $context
1956 * @param stdClass|int $user
1957 * @return bool
1959 function is_guest(context $context, $user = null) {
1960 global $USER;
1962 // first find the course context
1963 $coursecontext = $context->get_course_context();
1965 // make sure there is a real user specified
1966 if ($user === null) {
1967 $userid = isset($USER->id) ? $USER->id : 0;
1968 } else {
1969 $userid = is_object($user) ? $user->id : $user;
1972 if (isguestuser($userid)) {
1973 // can not inspect or be enrolled
1974 return true;
1977 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1978 // viewing users appear out of nowhere, they are neither guests nor participants
1979 return false;
1982 // consider only real active enrolments here
1983 if (is_enrolled($coursecontext, $user, '', true)) {
1984 return false;
1987 return true;
1991 * Returns true if the user has moodle/course:view capability in the course,
1992 * this is intended for admins, managers (aka small admins), inspectors, etc.
1994 * @category access
1996 * @param context $context
1997 * @param int|stdClass $user if null $USER is used
1998 * @param string $withcapability extra capability name
1999 * @return bool
2001 function is_viewing(context $context, $user = null, $withcapability = '') {
2002 // first find the course context
2003 $coursecontext = $context->get_course_context();
2005 if (isguestuser($user)) {
2006 // can not inspect
2007 return false;
2010 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
2011 // admins are allowed to inspect courses
2012 return false;
2015 if ($withcapability and !has_capability($withcapability, $context, $user)) {
2016 // site admins always have the capability, but the enrolment above blocks
2017 return false;
2020 return true;
2024 * Returns true if user is enrolled (is participating) in course
2025 * this is intended for students and teachers.
2027 * Since 2.2 the result for active enrolments and current user are cached.
2029 * @package core_enrol
2030 * @category access
2032 * @param context $context
2033 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
2034 * @param string $withcapability extra capability name
2035 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2036 * @return bool
2038 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
2039 global $USER, $DB;
2041 // first find the course context
2042 $coursecontext = $context->get_course_context();
2044 // make sure there is a real user specified
2045 if ($user === null) {
2046 $userid = isset($USER->id) ? $USER->id : 0;
2047 } else {
2048 $userid = is_object($user) ? $user->id : $user;
2051 if (empty($userid)) {
2052 // not-logged-in!
2053 return false;
2054 } else if (isguestuser($userid)) {
2055 // guest account can not be enrolled anywhere
2056 return false;
2059 if ($coursecontext->instanceid == SITEID) {
2060 // everybody participates on frontpage
2061 } else {
2062 // try cached info first - the enrolled flag is set only when active enrolment present
2063 if ($USER->id == $userid) {
2064 $coursecontext->reload_if_dirty();
2065 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
2066 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
2067 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2068 return false;
2070 return true;
2075 if ($onlyactive) {
2076 // look for active enrolments only
2077 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
2079 if ($until === false) {
2080 return false;
2083 if ($USER->id == $userid) {
2084 if ($until == 0) {
2085 $until = ENROL_MAX_TIMESTAMP;
2087 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
2088 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
2089 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
2090 remove_temp_course_roles($coursecontext);
2094 } else {
2095 // any enrolment is good for us here, even outdated, disabled or inactive
2096 $sql = "SELECT 'x'
2097 FROM {user_enrolments} ue
2098 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2099 JOIN {user} u ON u.id = ue.userid
2100 WHERE ue.userid = :userid AND u.deleted = 0";
2101 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2102 if (!$DB->record_exists_sql($sql, $params)) {
2103 return false;
2108 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2109 return false;
2112 return true;
2116 * Returns true if the user is able to access the course.
2118 * This function is in no way, shape, or form a substitute for require_login.
2119 * It should only be used in circumstances where it is not possible to call require_login
2120 * such as the navigation.
2122 * This function checks many of the methods of access to a course such as the view
2123 * capability, enrollments, and guest access. It also makes use of the cache
2124 * generated by require_login for guest access.
2126 * The flags within the $USER object that are used here should NEVER be used outside
2127 * of this function can_access_course and require_login. Doing so WILL break future
2128 * versions.
2130 * @param stdClass $course record
2131 * @param stdClass|int|null $user user record or id, current user if null
2132 * @param string $withcapability Check for this capability as well.
2133 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2134 * @return boolean Returns true if the user is able to access the course
2136 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
2137 global $DB, $USER;
2139 // this function originally accepted $coursecontext parameter
2140 if ($course instanceof context) {
2141 if ($course instanceof context_course) {
2142 debugging('deprecated context parameter, please use $course record');
2143 $coursecontext = $course;
2144 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2145 } else {
2146 debugging('Invalid context parameter, please use $course record');
2147 return false;
2149 } else {
2150 $coursecontext = context_course::instance($course->id);
2153 if (!isset($USER->id)) {
2154 // should never happen
2155 $USER->id = 0;
2156 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
2159 // make sure there is a user specified
2160 if ($user === null) {
2161 $userid = $USER->id;
2162 } else {
2163 $userid = is_object($user) ? $user->id : $user;
2165 unset($user);
2167 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2168 return false;
2171 if ($userid == $USER->id) {
2172 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2173 // the fact that somebody switched role means they can access the course no matter to what role they switched
2174 return true;
2178 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2179 return false;
2182 if (is_viewing($coursecontext, $userid)) {
2183 return true;
2186 if ($userid != $USER->id) {
2187 // for performance reasons we do not verify temporary guest access for other users, sorry...
2188 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2191 // === from here we deal only with $USER ===
2193 $coursecontext->reload_if_dirty();
2195 if (isset($USER->enrol['enrolled'][$course->id])) {
2196 if ($USER->enrol['enrolled'][$course->id] > time()) {
2197 return true;
2200 if (isset($USER->enrol['tempguest'][$course->id])) {
2201 if ($USER->enrol['tempguest'][$course->id] > time()) {
2202 return true;
2206 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2207 return true;
2210 // if not enrolled try to gain temporary guest access
2211 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2212 $enrols = enrol_get_plugins(true);
2213 foreach($instances as $instance) {
2214 if (!isset($enrols[$instance->enrol])) {
2215 continue;
2217 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2218 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2219 if ($until !== false and $until > time()) {
2220 $USER->enrol['tempguest'][$course->id] = $until;
2221 return true;
2224 if (isset($USER->enrol['tempguest'][$course->id])) {
2225 unset($USER->enrol['tempguest'][$course->id]);
2226 remove_temp_course_roles($coursecontext);
2229 return false;
2233 * Returns array with sql code and parameters returning all ids
2234 * of users enrolled into course.
2236 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2238 * @package core_enrol
2239 * @category access
2241 * @param context $context
2242 * @param string $withcapability
2243 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2244 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2245 * @return array list($sql, $params)
2247 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2248 global $DB, $CFG;
2250 // use unique prefix just in case somebody makes some SQL magic with the result
2251 static $i = 0;
2252 $i++;
2253 $prefix = 'eu'.$i.'_';
2255 // first find the course context
2256 $coursecontext = $context->get_course_context();
2258 $isfrontpage = ($coursecontext->instanceid == SITEID);
2260 $joins = array();
2261 $wheres = array();
2262 $params = array();
2264 list($contextids, $contextpaths) = get_context_info_list($context);
2266 // get all relevant capability info for all roles
2267 if ($withcapability) {
2268 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2269 $cparams['cap'] = $withcapability;
2271 $defs = array();
2272 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2273 FROM {role_capabilities} rc
2274 JOIN {context} ctx on rc.contextid = ctx.id
2275 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2276 $rcs = $DB->get_records_sql($sql, $cparams);
2277 foreach ($rcs as $rc) {
2278 $defs[$rc->path][$rc->roleid] = $rc->permission;
2281 $access = array();
2282 if (!empty($defs)) {
2283 foreach ($contextpaths as $path) {
2284 if (empty($defs[$path])) {
2285 continue;
2287 foreach($defs[$path] as $roleid => $perm) {
2288 if ($perm == CAP_PROHIBIT) {
2289 $access[$roleid] = CAP_PROHIBIT;
2290 continue;
2292 if (!isset($access[$roleid])) {
2293 $access[$roleid] = (int)$perm;
2299 unset($defs);
2301 // make lists of roles that are needed and prohibited
2302 $needed = array(); // one of these is enough
2303 $prohibited = array(); // must not have any of these
2304 foreach ($access as $roleid => $perm) {
2305 if ($perm == CAP_PROHIBIT) {
2306 unset($needed[$roleid]);
2307 $prohibited[$roleid] = true;
2308 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2309 $needed[$roleid] = true;
2313 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2314 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2316 $nobody = false;
2318 if ($isfrontpage) {
2319 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2320 $nobody = true;
2321 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2322 // everybody not having prohibit has the capability
2323 $needed = array();
2324 } else if (empty($needed)) {
2325 $nobody = true;
2327 } else {
2328 if (!empty($prohibited[$defaultuserroleid])) {
2329 $nobody = true;
2330 } else if (!empty($needed[$defaultuserroleid])) {
2331 // everybody not having prohibit has the capability
2332 $needed = array();
2333 } else if (empty($needed)) {
2334 $nobody = true;
2338 if ($nobody) {
2339 // nobody can match so return some SQL that does not return any results
2340 $wheres[] = "1 = 2";
2342 } else {
2344 if ($needed) {
2345 $ctxids = implode(',', $contextids);
2346 $roleids = implode(',', array_keys($needed));
2347 $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))";
2350 if ($prohibited) {
2351 $ctxids = implode(',', $contextids);
2352 $roleids = implode(',', array_keys($prohibited));
2353 $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))";
2354 $wheres[] = "{$prefix}ra4.id IS NULL";
2357 if ($groupid) {
2358 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2359 $params["{$prefix}gmid"] = $groupid;
2363 } else {
2364 if ($groupid) {
2365 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2366 $params["{$prefix}gmid"] = $groupid;
2370 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2371 $params["{$prefix}guestid"] = $CFG->siteguest;
2373 if ($isfrontpage) {
2374 // all users are "enrolled" on the frontpage
2375 } else {
2376 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2377 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2378 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2380 if ($onlyactive) {
2381 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2382 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2383 $now = round(time(), -2); // rounding helps caching in DB
2384 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2385 $prefix.'active'=>ENROL_USER_ACTIVE,
2386 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2390 $joins = implode("\n", $joins);
2391 $wheres = "WHERE ".implode(" AND ", $wheres);
2393 $sql = "SELECT DISTINCT {$prefix}u.id
2394 FROM {user} {$prefix}u
2395 $joins
2396 $wheres";
2398 return array($sql, $params);
2402 * Returns list of users enrolled into course.
2404 * @package core_enrol
2405 * @category access
2407 * @param context $context
2408 * @param string $withcapability
2409 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2410 * @param string $userfields requested user record fields
2411 * @param string $orderby
2412 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2413 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2414 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2415 * @return array of user records
2417 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
2418 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
2419 global $DB;
2421 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2422 $sql = "SELECT $userfields
2423 FROM {user} u
2424 JOIN ($esql) je ON je.id = u.id
2425 WHERE u.deleted = 0";
2427 if ($orderby) {
2428 $sql = "$sql ORDER BY $orderby";
2429 } else {
2430 list($sort, $sortparams) = users_order_by_sql('u');
2431 $sql = "$sql ORDER BY $sort";
2432 $params = array_merge($params, $sortparams);
2435 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2439 * Counts list of users enrolled into course (as per above function)
2441 * @package core_enrol
2442 * @category access
2444 * @param context $context
2445 * @param string $withcapability
2446 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2447 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2448 * @return array of user records
2450 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2451 global $DB;
2453 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2454 $sql = "SELECT count(u.id)
2455 FROM {user} u
2456 JOIN ($esql) je ON je.id = u.id
2457 WHERE u.deleted = 0";
2459 return $DB->count_records_sql($sql, $params);
2463 * Loads the capability definitions for the component (from file).
2465 * Loads the capability definitions for the component (from file). If no
2466 * capabilities are defined for the component, we simply return an empty array.
2468 * @access private
2469 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2470 * @return array array of capabilities
2472 function load_capability_def($component) {
2473 $defpath = core_component::get_component_directory($component).'/db/access.php';
2475 $capabilities = array();
2476 if (file_exists($defpath)) {
2477 require($defpath);
2478 if (!empty(${$component.'_capabilities'})) {
2479 // BC capability array name
2480 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2481 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2482 $capabilities = ${$component.'_capabilities'};
2486 return $capabilities;
2490 * Gets the capabilities that have been cached in the database for this component.
2492 * @access private
2493 * @param string $component - examples: 'moodle', 'mod_forum'
2494 * @return array array of capabilities
2496 function get_cached_capabilities($component = 'moodle') {
2497 global $DB;
2498 return $DB->get_records('capabilities', array('component'=>$component));
2502 * Returns default capabilities for given role archetype.
2504 * @param string $archetype role archetype
2505 * @return array
2507 function get_default_capabilities($archetype) {
2508 global $DB;
2510 if (!$archetype) {
2511 return array();
2514 $alldefs = array();
2515 $defaults = array();
2516 $components = array();
2517 $allcaps = $DB->get_records('capabilities');
2519 foreach ($allcaps as $cap) {
2520 if (!in_array($cap->component, $components)) {
2521 $components[] = $cap->component;
2522 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2525 foreach($alldefs as $name=>$def) {
2526 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2527 if (isset($def['archetypes'])) {
2528 if (isset($def['archetypes'][$archetype])) {
2529 $defaults[$name] = $def['archetypes'][$archetype];
2531 // 'legacy' is for backward compatibility with 1.9 access.php
2532 } else {
2533 if (isset($def['legacy'][$archetype])) {
2534 $defaults[$name] = $def['legacy'][$archetype];
2539 return $defaults;
2543 * Return default roles that can be assigned, overridden or switched
2544 * by give role archetype.
2546 * @param string $type assign|override|switch
2547 * @param string $archetype
2548 * @return array of role ids
2550 function get_default_role_archetype_allows($type, $archetype) {
2551 global $DB;
2553 if (empty($archetype)) {
2554 return array();
2557 $roles = $DB->get_records('role');
2558 $archetypemap = array();
2559 foreach ($roles as $role) {
2560 if ($role->archetype) {
2561 $archetypemap[$role->archetype][$role->id] = $role->id;
2565 $defaults = array(
2566 'assign' => array(
2567 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2568 'coursecreator' => array(),
2569 'editingteacher' => array('teacher', 'student'),
2570 'teacher' => array(),
2571 'student' => array(),
2572 'guest' => array(),
2573 'user' => array(),
2574 'frontpage' => array(),
2576 'override' => array(
2577 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2578 'coursecreator' => array(),
2579 'editingteacher' => array('teacher', 'student', 'guest'),
2580 'teacher' => array(),
2581 'student' => array(),
2582 'guest' => array(),
2583 'user' => array(),
2584 'frontpage' => array(),
2586 'switch' => array(
2587 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2588 'coursecreator' => array(),
2589 'editingteacher' => array('teacher', 'student', 'guest'),
2590 'teacher' => array('student', 'guest'),
2591 'student' => array(),
2592 'guest' => array(),
2593 'user' => array(),
2594 'frontpage' => array(),
2598 if (!isset($defaults[$type][$archetype])) {
2599 debugging("Unknown type '$type'' or archetype '$archetype''");
2600 return array();
2603 $return = array();
2604 foreach ($defaults[$type][$archetype] as $at) {
2605 if (isset($archetypemap[$at])) {
2606 foreach ($archetypemap[$at] as $roleid) {
2607 $return[$roleid] = $roleid;
2612 return $return;
2616 * Reset role capabilities to default according to selected role archetype.
2617 * If no archetype selected, removes all capabilities.
2619 * @param int $roleid
2620 * @return void
2622 function reset_role_capabilities($roleid) {
2623 global $DB;
2625 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2626 $defaultcaps = get_default_capabilities($role->archetype);
2628 $systemcontext = context_system::instance();
2630 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2632 foreach($defaultcaps as $cap=>$permission) {
2633 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2638 * Updates the capabilities table with the component capability definitions.
2639 * If no parameters are given, the function updates the core moodle
2640 * capabilities.
2642 * Note that the absence of the db/access.php capabilities definition file
2643 * will cause any stored capabilities for the component to be removed from
2644 * the database.
2646 * @access private
2647 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2648 * @return boolean true if success, exception in case of any problems
2650 function update_capabilities($component = 'moodle') {
2651 global $DB, $OUTPUT;
2653 $storedcaps = array();
2655 $filecaps = load_capability_def($component);
2656 foreach($filecaps as $capname=>$unused) {
2657 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2658 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2662 $cachedcaps = get_cached_capabilities($component);
2663 if ($cachedcaps) {
2664 foreach ($cachedcaps as $cachedcap) {
2665 array_push($storedcaps, $cachedcap->name);
2666 // update risk bitmasks and context levels in existing capabilities if needed
2667 if (array_key_exists($cachedcap->name, $filecaps)) {
2668 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2669 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2671 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2672 $updatecap = new stdClass();
2673 $updatecap->id = $cachedcap->id;
2674 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2675 $DB->update_record('capabilities', $updatecap);
2677 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2678 $updatecap = new stdClass();
2679 $updatecap->id = $cachedcap->id;
2680 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2681 $DB->update_record('capabilities', $updatecap);
2684 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2685 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2687 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2688 $updatecap = new stdClass();
2689 $updatecap->id = $cachedcap->id;
2690 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2691 $DB->update_record('capabilities', $updatecap);
2697 // Are there new capabilities in the file definition?
2698 $newcaps = array();
2700 foreach ($filecaps as $filecap => $def) {
2701 if (!$storedcaps ||
2702 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2703 if (!array_key_exists('riskbitmask', $def)) {
2704 $def['riskbitmask'] = 0; // no risk if not specified
2706 $newcaps[$filecap] = $def;
2709 // Add new capabilities to the stored definition.
2710 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2711 foreach ($newcaps as $capname => $capdef) {
2712 $capability = new stdClass();
2713 $capability->name = $capname;
2714 $capability->captype = $capdef['captype'];
2715 $capability->contextlevel = $capdef['contextlevel'];
2716 $capability->component = $component;
2717 $capability->riskbitmask = $capdef['riskbitmask'];
2719 $DB->insert_record('capabilities', $capability, false);
2721 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2722 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2723 foreach ($rolecapabilities as $rolecapability){
2724 //assign_capability will update rather than insert if capability exists
2725 if (!assign_capability($capname, $rolecapability->permission,
2726 $rolecapability->roleid, $rolecapability->contextid, true)){
2727 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2731 // we ignore archetype key if we have cloned permissions
2732 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2733 assign_legacy_capabilities($capname, $capdef['archetypes']);
2734 // 'legacy' is for backward compatibility with 1.9 access.php
2735 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2736 assign_legacy_capabilities($capname, $capdef['legacy']);
2739 // Are there any capabilities that have been removed from the file
2740 // definition that we need to delete from the stored capabilities and
2741 // role assignments?
2742 capabilities_cleanup($component, $filecaps);
2744 // reset static caches
2745 accesslib_clear_all_caches(false);
2747 return true;
2751 * Deletes cached capabilities that are no longer needed by the component.
2752 * Also unassigns these capabilities from any roles that have them.
2753 * NOTE: this function is called from lib/db/upgrade.php
2755 * @access private
2756 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2757 * @param array $newcapdef array of the new capability definitions that will be
2758 * compared with the cached capabilities
2759 * @return int number of deprecated capabilities that have been removed
2761 function capabilities_cleanup($component, $newcapdef = null) {
2762 global $DB;
2764 $removedcount = 0;
2766 if ($cachedcaps = get_cached_capabilities($component)) {
2767 foreach ($cachedcaps as $cachedcap) {
2768 if (empty($newcapdef) ||
2769 array_key_exists($cachedcap->name, $newcapdef) === false) {
2771 // Remove from capabilities cache.
2772 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2773 $removedcount++;
2774 // Delete from roles.
2775 if ($roles = get_roles_with_capability($cachedcap->name)) {
2776 foreach($roles as $role) {
2777 if (!unassign_capability($cachedcap->name, $role->id)) {
2778 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2782 } // End if.
2785 return $removedcount;
2789 * Returns an array of all the known types of risk
2790 * The array keys can be used, for example as CSS class names, or in calls to
2791 * print_risk_icon. The values are the corresponding RISK_ constants.
2793 * @return array all the known types of risk.
2795 function get_all_risks() {
2796 return array(
2797 'riskmanagetrust' => RISK_MANAGETRUST,
2798 'riskconfig' => RISK_CONFIG,
2799 'riskxss' => RISK_XSS,
2800 'riskpersonal' => RISK_PERSONAL,
2801 'riskspam' => RISK_SPAM,
2802 'riskdataloss' => RISK_DATALOSS,
2807 * Return a link to moodle docs for a given capability name
2809 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2810 * @return string the human-readable capability name as a link to Moodle Docs.
2812 function get_capability_docs_link($capability) {
2813 $url = get_docs_url('Capabilities/' . $capability->name);
2814 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2818 * This function pulls out all the resolved capabilities (overrides and
2819 * defaults) of a role used in capability overrides in contexts at a given
2820 * context.
2822 * @param int $roleid
2823 * @param context $context
2824 * @param string $cap capability, optional, defaults to ''
2825 * @return array Array of capabilities
2827 function role_context_capabilities($roleid, context $context, $cap = '') {
2828 global $DB;
2830 $contexts = $context->get_parent_context_ids(true);
2831 $contexts = '('.implode(',', $contexts).')';
2833 $params = array($roleid);
2835 if ($cap) {
2836 $search = " AND rc.capability = ? ";
2837 $params[] = $cap;
2838 } else {
2839 $search = '';
2842 $sql = "SELECT rc.*
2843 FROM {role_capabilities} rc, {context} c
2844 WHERE rc.contextid in $contexts
2845 AND rc.roleid = ?
2846 AND rc.contextid = c.id $search
2847 ORDER BY c.contextlevel DESC, rc.capability DESC";
2849 $capabilities = array();
2851 if ($records = $DB->get_records_sql($sql, $params)) {
2852 // We are traversing via reverse order.
2853 foreach ($records as $record) {
2854 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2855 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2856 $capabilities[$record->capability] = $record->permission;
2860 return $capabilities;
2864 * Constructs array with contextids as first parameter and context paths,
2865 * in both cases bottom top including self.
2867 * @access private
2868 * @param context $context
2869 * @return array
2871 function get_context_info_list(context $context) {
2872 $contextids = explode('/', ltrim($context->path, '/'));
2873 $contextpaths = array();
2874 $contextids2 = $contextids;
2875 while ($contextids2) {
2876 $contextpaths[] = '/' . implode('/', $contextids2);
2877 array_pop($contextids2);
2879 return array($contextids, $contextpaths);
2883 * Check if context is the front page context or a context inside it
2885 * Returns true if this context is the front page context, or a context inside it,
2886 * otherwise false.
2888 * @param context $context a context object.
2889 * @return bool
2891 function is_inside_frontpage(context $context) {
2892 $frontpagecontext = context_course::instance(SITEID);
2893 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2897 * Returns capability information (cached)
2899 * @param string $capabilityname
2900 * @return stdClass or null if capability not found
2902 function get_capability_info($capabilityname) {
2903 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2905 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2907 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2908 $ACCESSLIB_PRIVATE->capabilities = array();
2909 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2910 foreach ($caps as $cap) {
2911 $capname = $cap->name;
2912 unset($cap->id);
2913 unset($cap->name);
2914 $cap->riskbitmask = (int)$cap->riskbitmask;
2915 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2919 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2923 * Returns the human-readable, translated version of the capability.
2924 * Basically a big switch statement.
2926 * @param string $capabilityname e.g. mod/choice:readresponses
2927 * @return string
2929 function get_capability_string($capabilityname) {
2931 // Typical capability name is 'plugintype/pluginname:capabilityname'
2932 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2934 if ($type === 'moodle') {
2935 $component = 'core_role';
2936 } else if ($type === 'quizreport') {
2937 //ugly hack!!
2938 $component = 'quiz_'.$name;
2939 } else {
2940 $component = $type.'_'.$name;
2943 $stringname = $name.':'.$capname;
2945 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2946 return get_string($stringname, $component);
2949 $dir = core_component::get_component_directory($component);
2950 if (!file_exists($dir)) {
2951 // plugin broken or does not exist, do not bother with printing of debug message
2952 return $capabilityname.' ???';
2955 // something is wrong in plugin, better print debug
2956 return get_string($stringname, $component);
2960 * This gets the mod/block/course/core etc strings.
2962 * @param string $component
2963 * @param int $contextlevel
2964 * @return string|bool String is success, false if failed
2966 function get_component_string($component, $contextlevel) {
2968 if ($component === 'moodle' or $component === 'core') {
2969 switch ($contextlevel) {
2970 // TODO: this should probably use context level names instead
2971 case CONTEXT_SYSTEM: return get_string('coresystem');
2972 case CONTEXT_USER: return get_string('users');
2973 case CONTEXT_COURSECAT: return get_string('categories');
2974 case CONTEXT_COURSE: return get_string('course');
2975 case CONTEXT_MODULE: return get_string('activities');
2976 case CONTEXT_BLOCK: return get_string('block');
2977 default: print_error('unknowncontext');
2981 list($type, $name) = core_component::normalize_component($component);
2982 $dir = core_component::get_plugin_directory($type, $name);
2983 if (!file_exists($dir)) {
2984 // plugin not installed, bad luck, there is no way to find the name
2985 return $component.' ???';
2988 switch ($type) {
2989 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2990 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2991 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2992 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2993 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2994 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2995 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2996 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2997 case 'mod':
2998 if (get_string_manager()->string_exists('pluginname', $component)) {
2999 return get_string('activity').': '.get_string('pluginname', $component);
3000 } else {
3001 return get_string('activity').': '.get_string('modulename', $component);
3003 default: return get_string('pluginname', $component);
3008 * Gets the list of roles assigned to this context and up (parents)
3009 * from the list of roles that are visible on user profile page
3010 * and participants page.
3012 * @param context $context
3013 * @return array
3015 function get_profile_roles(context $context) {
3016 global $CFG, $DB;
3018 if (empty($CFG->profileroles)) {
3019 return array();
3022 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
3023 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
3024 $params = array_merge($params, $cparams);
3026 if ($coursecontext = $context->get_course_context(false)) {
3027 $params['coursecontext'] = $coursecontext->id;
3028 } else {
3029 $params['coursecontext'] = 0;
3032 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3033 FROM {role_assignments} ra, {role} r
3034 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3035 WHERE r.id = ra.roleid
3036 AND ra.contextid $contextlist
3037 AND r.id $rallowed
3038 ORDER BY r.sortorder ASC";
3040 return $DB->get_records_sql($sql, $params);
3044 * Gets the list of roles assigned to this context and up (parents)
3046 * @param context $context
3047 * @return array
3049 function get_roles_used_in_context(context $context) {
3050 global $DB;
3052 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
3054 if ($coursecontext = $context->get_course_context(false)) {
3055 $params['coursecontext'] = $coursecontext->id;
3056 } else {
3057 $params['coursecontext'] = 0;
3060 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3061 FROM {role_assignments} ra, {role} r
3062 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3063 WHERE r.id = ra.roleid
3064 AND ra.contextid $contextlist
3065 ORDER BY r.sortorder ASC";
3067 return $DB->get_records_sql($sql, $params);
3071 * This function is used to print roles column in user profile page.
3072 * It is using the CFG->profileroles to limit the list to only interesting roles.
3073 * (The permission tab has full details of user role assignments.)
3075 * @param int $userid
3076 * @param int $courseid
3077 * @return string
3079 function get_user_roles_in_course($userid, $courseid) {
3080 global $CFG, $DB;
3082 if (empty($CFG->profileroles)) {
3083 return '';
3086 if ($courseid == SITEID) {
3087 $context = context_system::instance();
3088 } else {
3089 $context = context_course::instance($courseid);
3092 if (empty($CFG->profileroles)) {
3093 return array();
3096 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
3097 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
3098 $params = array_merge($params, $cparams);
3100 if ($coursecontext = $context->get_course_context(false)) {
3101 $params['coursecontext'] = $coursecontext->id;
3102 } else {
3103 $params['coursecontext'] = 0;
3106 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3107 FROM {role_assignments} ra, {role} r
3108 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3109 WHERE r.id = ra.roleid
3110 AND ra.contextid $contextlist
3111 AND r.id $rallowed
3112 AND ra.userid = :userid
3113 ORDER BY r.sortorder ASC";
3114 $params['userid'] = $userid;
3116 $rolestring = '';
3118 if ($roles = $DB->get_records_sql($sql, $params)) {
3119 $rolenames = role_fix_names($roles, $context, ROLENAME_ALIAS, true); // Substitute aliases
3121 foreach ($rolenames as $roleid => $rolename) {
3122 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
3124 $rolestring = implode(',', $rolenames);
3127 return $rolestring;
3131 * Checks if a user can assign users to a particular role in this context
3133 * @param context $context
3134 * @param int $targetroleid - the id of the role you want to assign users to
3135 * @return boolean
3137 function user_can_assign(context $context, $targetroleid) {
3138 global $DB;
3140 // First check to see if the user is a site administrator.
3141 if (is_siteadmin()) {
3142 return true;
3145 // Check if user has override capability.
3146 // If not return false.
3147 if (!has_capability('moodle/role:assign', $context)) {
3148 return false;
3150 // pull out all active roles of this user from this context(or above)
3151 if ($userroles = get_user_roles($context)) {
3152 foreach ($userroles as $userrole) {
3153 // if any in the role_allow_override table, then it's ok
3154 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
3155 return true;
3160 return false;
3164 * Returns all site roles in correct sort order.
3166 * Note: this method does not localise role names or descriptions,
3167 * use role_get_names() if you need role names.
3169 * @param context $context optional context for course role name aliases
3170 * @return array of role records with optional coursealias property
3172 function get_all_roles(context $context = null) {
3173 global $DB;
3175 if (!$context or !$coursecontext = $context->get_course_context(false)) {
3176 $coursecontext = null;
3179 if ($coursecontext) {
3180 $sql = "SELECT r.*, rn.name AS coursealias
3181 FROM {role} r
3182 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3183 ORDER BY r.sortorder ASC";
3184 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
3186 } else {
3187 return $DB->get_records('role', array(), 'sortorder ASC');
3192 * Returns roles of a specified archetype
3194 * @param string $archetype
3195 * @return array of full role records
3197 function get_archetype_roles($archetype) {
3198 global $DB;
3199 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
3203 * Gets all the user roles assigned in this context, or higher contexts
3204 * this is mainly used when checking if a user can assign a role, or overriding a role
3205 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3206 * allow_override tables
3208 * @param context $context
3209 * @param int $userid
3210 * @param bool $checkparentcontexts defaults to true
3211 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
3212 * @return array
3214 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
3215 global $USER, $DB;
3217 if (empty($userid)) {
3218 if (empty($USER->id)) {
3219 return array();
3221 $userid = $USER->id;
3224 if ($checkparentcontexts) {
3225 $contextids = $context->get_parent_context_ids();
3226 } else {
3227 $contextids = array();
3229 $contextids[] = $context->id;
3231 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3233 array_unshift($params, $userid);
3235 $sql = "SELECT ra.*, r.name, r.shortname
3236 FROM {role_assignments} ra, {role} r, {context} c
3237 WHERE ra.userid = ?
3238 AND ra.roleid = r.id
3239 AND ra.contextid = c.id
3240 AND ra.contextid $contextids
3241 ORDER BY $order";
3243 return $DB->get_records_sql($sql ,$params);
3247 * Like get_user_roles, but adds in the authenticated user role, and the front
3248 * page roles, if applicable.
3250 * @param context $context the context.
3251 * @param int $userid optional. Defaults to $USER->id
3252 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3254 function get_user_roles_with_special(context $context, $userid = 0) {
3255 global $CFG, $USER;
3257 if (empty($userid)) {
3258 if (empty($USER->id)) {
3259 return array();
3261 $userid = $USER->id;
3264 $ras = get_user_roles($context, $userid);
3266 // Add front-page role if relevant.
3267 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3268 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3269 is_inside_frontpage($context);
3270 if ($defaultfrontpageroleid && $isfrontpage) {
3271 $frontpagecontext = context_course::instance(SITEID);
3272 $ra = new stdClass();
3273 $ra->userid = $userid;
3274 $ra->contextid = $frontpagecontext->id;
3275 $ra->roleid = $defaultfrontpageroleid;
3276 $ras[] = $ra;
3279 // Add authenticated user role if relevant.
3280 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3281 if ($defaultuserroleid && !isguestuser($userid)) {
3282 $systemcontext = context_system::instance();
3283 $ra = new stdClass();
3284 $ra->userid = $userid;
3285 $ra->contextid = $systemcontext->id;
3286 $ra->roleid = $defaultuserroleid;
3287 $ras[] = $ra;
3290 return $ras;
3294 * Creates a record in the role_allow_override table
3296 * @param int $sroleid source roleid
3297 * @param int $troleid target roleid
3298 * @return void
3300 function allow_override($sroleid, $troleid) {
3301 global $DB;
3303 $record = new stdClass();
3304 $record->roleid = $sroleid;
3305 $record->allowoverride = $troleid;
3306 $DB->insert_record('role_allow_override', $record);
3310 * Creates a record in the role_allow_assign table
3312 * @param int $fromroleid source roleid
3313 * @param int $targetroleid target roleid
3314 * @return void
3316 function allow_assign($fromroleid, $targetroleid) {
3317 global $DB;
3319 $record = new stdClass();
3320 $record->roleid = $fromroleid;
3321 $record->allowassign = $targetroleid;
3322 $DB->insert_record('role_allow_assign', $record);
3326 * Creates a record in the role_allow_switch table
3328 * @param int $fromroleid source roleid
3329 * @param int $targetroleid target roleid
3330 * @return void
3332 function allow_switch($fromroleid, $targetroleid) {
3333 global $DB;
3335 $record = new stdClass();
3336 $record->roleid = $fromroleid;
3337 $record->allowswitch = $targetroleid;
3338 $DB->insert_record('role_allow_switch', $record);
3342 * Gets a list of roles that this user can assign in this context
3344 * @param context $context the context.
3345 * @param int $rolenamedisplay the type of role name to display. One of the
3346 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3347 * @param bool $withusercounts if true, count the number of users with each role.
3348 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3349 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3350 * if $withusercounts is true, returns a list of three arrays,
3351 * $rolenames, $rolecounts, and $nameswithcounts.
3353 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3354 global $USER, $DB;
3356 // make sure there is a real user specified
3357 if ($user === null) {
3358 $userid = isset($USER->id) ? $USER->id : 0;
3359 } else {
3360 $userid = is_object($user) ? $user->id : $user;
3363 if (!has_capability('moodle/role:assign', $context, $userid)) {
3364 if ($withusercounts) {
3365 return array(array(), array(), array());
3366 } else {
3367 return array();
3371 $params = array();
3372 $extrafields = '';
3374 if ($withusercounts) {
3375 $extrafields = ', (SELECT count(u.id)
3376 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3377 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3378 ) AS usercount';
3379 $params['conid'] = $context->id;
3382 if (is_siteadmin($userid)) {
3383 // show all roles allowed in this context to admins
3384 $assignrestriction = "";
3385 } else {
3386 $parents = $context->get_parent_context_ids(true);
3387 $contexts = implode(',' , $parents);
3388 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3389 FROM {role_allow_assign} raa
3390 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3391 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3392 ) ar ON ar.id = r.id";
3393 $params['userid'] = $userid;
3395 $params['contextlevel'] = $context->contextlevel;
3397 if ($coursecontext = $context->get_course_context(false)) {
3398 $params['coursecontext'] = $coursecontext->id;
3399 } else {
3400 $params['coursecontext'] = 0; // no course aliases
3401 $coursecontext = null;
3403 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3404 FROM {role} r
3405 $assignrestriction
3406 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3407 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3408 ORDER BY r.sortorder ASC";
3409 $roles = $DB->get_records_sql($sql, $params);
3411 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3413 if (!$withusercounts) {
3414 return $rolenames;
3417 $rolecounts = array();
3418 $nameswithcounts = array();
3419 foreach ($roles as $role) {
3420 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3421 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3423 return array($rolenames, $rolecounts, $nameswithcounts);
3427 * Gets a list of roles that this user can switch to in a context
3429 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3430 * This function just process the contents of the role_allow_switch table. You also need to
3431 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3433 * @param context $context a context.
3434 * @return array an array $roleid => $rolename.
3436 function get_switchable_roles(context $context) {
3437 global $USER, $DB;
3439 $params = array();
3440 $extrajoins = '';
3441 $extrawhere = '';
3442 if (!is_siteadmin()) {
3443 // Admins are allowed to switch to any role with.
3444 // Others are subject to the additional constraint that the switch-to role must be allowed by
3445 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3446 $parents = $context->get_parent_context_ids(true);
3447 $contexts = implode(',' , $parents);
3449 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3450 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3451 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3452 $params['userid'] = $USER->id;
3455 if ($coursecontext = $context->get_course_context(false)) {
3456 $params['coursecontext'] = $coursecontext->id;
3457 } else {
3458 $params['coursecontext'] = 0; // no course aliases
3459 $coursecontext = null;
3462 $query = "
3463 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3464 FROM (SELECT DISTINCT rc.roleid
3465 FROM {role_capabilities} rc
3466 $extrajoins
3467 $extrawhere) idlist
3468 JOIN {role} r ON r.id = idlist.roleid
3469 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3470 ORDER BY r.sortorder";
3471 $roles = $DB->get_records_sql($query, $params);
3473 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3477 * Gets a list of roles that this user can override in this context.
3479 * @param context $context the context.
3480 * @param int $rolenamedisplay the type of role name to display. One of the
3481 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3482 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3483 * @return array if $withcounts is false, then an array $roleid => $rolename.
3484 * if $withusercounts is true, returns a list of three arrays,
3485 * $rolenames, $rolecounts, and $nameswithcounts.
3487 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3488 global $USER, $DB;
3490 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3491 if ($withcounts) {
3492 return array(array(), array(), array());
3493 } else {
3494 return array();
3498 $parents = $context->get_parent_context_ids(true);
3499 $contexts = implode(',' , $parents);
3501 $params = array();
3502 $extrafields = '';
3504 $params['userid'] = $USER->id;
3505 if ($withcounts) {
3506 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3507 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3508 $params['conid'] = $context->id;
3511 if ($coursecontext = $context->get_course_context(false)) {
3512 $params['coursecontext'] = $coursecontext->id;
3513 } else {
3514 $params['coursecontext'] = 0; // no course aliases
3515 $coursecontext = null;
3518 if (is_siteadmin()) {
3519 // show all roles to admins
3520 $roles = $DB->get_records_sql("
3521 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3522 FROM {role} ro
3523 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3524 ORDER BY ro.sortorder ASC", $params);
3526 } else {
3527 $roles = $DB->get_records_sql("
3528 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3529 FROM {role} ro
3530 JOIN (SELECT DISTINCT r.id
3531 FROM {role} r
3532 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3533 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3534 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3535 ) inline_view ON ro.id = inline_view.id
3536 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3537 ORDER BY ro.sortorder ASC", $params);
3540 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3542 if (!$withcounts) {
3543 return $rolenames;
3546 $rolecounts = array();
3547 $nameswithcounts = array();
3548 foreach ($roles as $role) {
3549 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3550 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3552 return array($rolenames, $rolecounts, $nameswithcounts);
3556 * Create a role menu suitable for default role selection in enrol plugins.
3558 * @package core_enrol
3560 * @param context $context
3561 * @param int $addroleid current or default role - always added to list
3562 * @return array roleid=>localised role name
3564 function get_default_enrol_roles(context $context, $addroleid = null) {
3565 global $DB;
3567 $params = array('contextlevel'=>CONTEXT_COURSE);
3569 if ($coursecontext = $context->get_course_context(false)) {
3570 $params['coursecontext'] = $coursecontext->id;
3571 } else {
3572 $params['coursecontext'] = 0; // no course names
3573 $coursecontext = null;
3576 if ($addroleid) {
3577 $addrole = "OR r.id = :addroleid";
3578 $params['addroleid'] = $addroleid;
3579 } else {
3580 $addrole = "";
3583 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3584 FROM {role} r
3585 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3586 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3587 WHERE rcl.id IS NOT NULL $addrole
3588 ORDER BY sortorder DESC";
3590 $roles = $DB->get_records_sql($sql, $params);
3592 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3596 * Return context levels where this role is assignable.
3598 * @param integer $roleid the id of a role.
3599 * @return array list of the context levels at which this role may be assigned.
3601 function get_role_contextlevels($roleid) {
3602 global $DB;
3603 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3604 'contextlevel', 'id,contextlevel');
3608 * Return roles suitable for assignment at the specified context level.
3610 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3612 * @param integer $contextlevel a contextlevel.
3613 * @return array list of role ids that are assignable at this context level.
3615 function get_roles_for_contextlevels($contextlevel) {
3616 global $DB;
3617 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3618 '', 'id,roleid');
3622 * Returns default context levels where roles can be assigned.
3624 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3625 * from the array returned by get_role_archetypes();
3626 * @return array list of the context levels at which this type of role may be assigned by default.
3628 function get_default_contextlevels($rolearchetype) {
3629 static $defaults = array(
3630 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3631 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3632 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3633 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3634 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3635 'guest' => array(),
3636 'user' => array(),
3637 'frontpage' => array());
3639 if (isset($defaults[$rolearchetype])) {
3640 return $defaults[$rolearchetype];
3641 } else {
3642 return array();
3647 * Set the context levels at which a particular role can be assigned.
3648 * Throws exceptions in case of error.
3650 * @param integer $roleid the id of a role.
3651 * @param array $contextlevels the context levels at which this role should be assignable,
3652 * duplicate levels are removed.
3653 * @return void
3655 function set_role_contextlevels($roleid, array $contextlevels) {
3656 global $DB;
3657 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3658 $rcl = new stdClass();
3659 $rcl->roleid = $roleid;
3660 $contextlevels = array_unique($contextlevels);
3661 foreach ($contextlevels as $level) {
3662 $rcl->contextlevel = $level;
3663 $DB->insert_record('role_context_levels', $rcl, false, true);
3668 * Who has this capability in this context?
3670 * This can be a very expensive call - use sparingly and keep
3671 * the results if you are going to need them again soon.
3673 * Note if $fields is empty this function attempts to get u.*
3674 * which can get rather large - and has a serious perf impact
3675 * on some DBs.
3677 * @param context $context
3678 * @param string|array $capability - capability name(s)
3679 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3680 * @param string $sort - the sort order. Default is lastaccess time.
3681 * @param mixed $limitfrom - number of records to skip (offset)
3682 * @param mixed $limitnum - number of records to fetch
3683 * @param string|array $groups - single group or array of groups - only return
3684 * users who are in one of these group(s).
3685 * @param string|array $exceptions - list of users to exclude, comma separated or array
3686 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3687 * @param bool $view_ignored - use get_enrolled_sql() instead
3688 * @param bool $useviewallgroups if $groups is set the return users who
3689 * have capability both $capability and moodle/site:accessallgroups
3690 * in this context, as well as users who have $capability and who are
3691 * in $groups.
3692 * @return array of user records
3694 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3695 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3696 global $CFG, $DB;
3698 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3699 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3701 $ctxids = trim($context->path, '/');
3702 $ctxids = str_replace('/', ',', $ctxids);
3704 // Context is the frontpage
3705 $iscoursepage = false; // coursepage other than fp
3706 $isfrontpage = false;
3707 if ($context->contextlevel == CONTEXT_COURSE) {
3708 if ($context->instanceid == SITEID) {
3709 $isfrontpage = true;
3710 } else {
3711 $iscoursepage = true;
3714 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3716 $caps = (array)$capability;
3718 // construct list of context paths bottom-->top
3719 list($contextids, $paths) = get_context_info_list($context);
3721 // we need to find out all roles that have these capabilities either in definition or in overrides
3722 $defs = array();
3723 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3724 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3725 $params = array_merge($params, $params2);
3726 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3727 FROM {role_capabilities} rc
3728 JOIN {context} ctx on rc.contextid = ctx.id
3729 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3731 $rcs = $DB->get_records_sql($sql, $params);
3732 foreach ($rcs as $rc) {
3733 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3736 // go through the permissions bottom-->top direction to evaluate the current permission,
3737 // first one wins (prohibit is an exception that always wins)
3738 $access = array();
3739 foreach ($caps as $cap) {
3740 foreach ($paths as $path) {
3741 if (empty($defs[$cap][$path])) {
3742 continue;
3744 foreach($defs[$cap][$path] as $roleid => $perm) {
3745 if ($perm == CAP_PROHIBIT) {
3746 $access[$cap][$roleid] = CAP_PROHIBIT;
3747 continue;
3749 if (!isset($access[$cap][$roleid])) {
3750 $access[$cap][$roleid] = (int)$perm;
3756 // make lists of roles that are needed and prohibited in this context
3757 $needed = array(); // one of these is enough
3758 $prohibited = array(); // must not have any of these
3759 foreach ($caps as $cap) {
3760 if (empty($access[$cap])) {
3761 continue;
3763 foreach ($access[$cap] as $roleid => $perm) {
3764 if ($perm == CAP_PROHIBIT) {
3765 unset($needed[$cap][$roleid]);
3766 $prohibited[$cap][$roleid] = true;
3767 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3768 $needed[$cap][$roleid] = true;
3771 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3772 // easy, nobody has the permission
3773 unset($needed[$cap]);
3774 unset($prohibited[$cap]);
3775 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3776 // everybody is disqualified on the frontpage
3777 unset($needed[$cap]);
3778 unset($prohibited[$cap]);
3780 if (empty($prohibited[$cap])) {
3781 unset($prohibited[$cap]);
3785 if (empty($needed)) {
3786 // there can not be anybody if no roles match this request
3787 return array();
3790 if (empty($prohibited)) {
3791 // we can compact the needed roles
3792 $n = array();
3793 foreach ($needed as $cap) {
3794 foreach ($cap as $roleid=>$unused) {
3795 $n[$roleid] = true;
3798 $needed = array('any'=>$n);
3799 unset($n);
3802 // ***** Set up default fields ******
3803 if (empty($fields)) {
3804 if ($iscoursepage) {
3805 $fields = 'u.*, ul.timeaccess AS lastaccess';
3806 } else {
3807 $fields = 'u.*';
3809 } else {
3810 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3811 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3815 // Set up default sort
3816 if (empty($sort)) { // default to course lastaccess or just lastaccess
3817 if ($iscoursepage) {
3818 $sort = 'ul.timeaccess';
3819 } else {
3820 $sort = 'u.lastaccess';
3824 // Prepare query clauses
3825 $wherecond = array();
3826 $params = array();
3827 $joins = array();
3829 // User lastaccess JOIN
3830 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3831 // user_lastaccess is not required MDL-13810
3832 } else {
3833 if ($iscoursepage) {
3834 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3835 } else {
3836 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3840 // We never return deleted users or guest account.
3841 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3842 $params['guestid'] = $CFG->siteguest;
3844 // Groups
3845 if ($groups) {
3846 $groups = (array)$groups;
3847 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3848 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3849 $params = array_merge($params, $grpparams);
3851 if ($useviewallgroups) {
3852 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3853 if (!empty($viewallgroupsusers)) {
3854 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3855 } else {
3856 $wherecond[] = "($grouptest)";
3858 } else {
3859 $wherecond[] = "($grouptest)";
3863 // User exceptions
3864 if (!empty($exceptions)) {
3865 $exceptions = (array)$exceptions;
3866 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3867 $params = array_merge($params, $exparams);
3868 $wherecond[] = "u.id $exsql";
3871 // now add the needed and prohibited roles conditions as joins
3872 if (!empty($needed['any'])) {
3873 // simple case - there are no prohibits involved
3874 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3875 // everybody
3876 } else {
3877 $joins[] = "JOIN (SELECT DISTINCT userid
3878 FROM {role_assignments}
3879 WHERE contextid IN ($ctxids)
3880 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3881 ) ra ON ra.userid = u.id";
3883 } else {
3884 $unions = array();
3885 $everybody = false;
3886 foreach ($needed as $cap=>$unused) {
3887 if (empty($prohibited[$cap])) {
3888 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3889 $everybody = true;
3890 break;
3891 } else {
3892 $unions[] = "SELECT userid
3893 FROM {role_assignments}
3894 WHERE contextid IN ($ctxids)
3895 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3897 } else {
3898 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3899 // nobody can have this cap because it is prevented in default roles
3900 continue;
3902 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3903 // everybody except the prohibitted - hiding does not matter
3904 $unions[] = "SELECT id AS userid
3905 FROM {user}
3906 WHERE id NOT IN (SELECT userid
3907 FROM {role_assignments}
3908 WHERE contextid IN ($ctxids)
3909 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3911 } else {
3912 $unions[] = "SELECT userid
3913 FROM {role_assignments}
3914 WHERE contextid IN ($ctxids)
3915 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3916 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3920 if (!$everybody) {
3921 if ($unions) {
3922 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3923 } else {
3924 // only prohibits found - nobody can be matched
3925 $wherecond[] = "1 = 2";
3930 // Collect WHERE conditions and needed joins
3931 $where = implode(' AND ', $wherecond);
3932 if ($where !== '') {
3933 $where = 'WHERE ' . $where;
3935 $joins = implode("\n", $joins);
3937 // Ok, let's get the users!
3938 $sql = "SELECT $fields
3939 FROM {user} u
3940 $joins
3941 $where
3942 ORDER BY $sort";
3944 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3948 * Re-sort a users array based on a sorting policy
3950 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3951 * based on a sorting policy. This is to support the odd practice of
3952 * sorting teachers by 'authority', where authority was "lowest id of the role
3953 * assignment".
3955 * Will execute 1 database query. Only suitable for small numbers of users, as it
3956 * uses an u.id IN() clause.
3958 * Notes about the sorting criteria.
3960 * As a default, we cannot rely on role.sortorder because then
3961 * admins/coursecreators will always win. That is why the sane
3962 * rule "is locality matters most", with sortorder as 2nd
3963 * consideration.
3965 * If you want role.sortorder, use the 'sortorder' policy, and
3966 * name explicitly what roles you want to cover. It's probably
3967 * a good idea to see what roles have the capabilities you want
3968 * (array_diff() them against roiles that have 'can-do-anything'
3969 * to weed out admin-ish roles. Or fetch a list of roles from
3970 * variables like $CFG->coursecontact .
3972 * @param array $users Users array, keyed on userid
3973 * @param context $context
3974 * @param array $roles ids of the roles to include, optional
3975 * @param string $sortpolicy defaults to locality, more about
3976 * @return array sorted copy of the array
3978 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3979 global $DB;
3981 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3982 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3983 if (empty($roles)) {
3984 $roleswhere = '';
3985 } else {
3986 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3989 $sql = "SELECT ra.userid
3990 FROM {role_assignments} ra
3991 JOIN {role} r
3992 ON ra.roleid=r.id
3993 JOIN {context} ctx
3994 ON ra.contextid=ctx.id
3995 WHERE $userswhere
3996 $contextwhere
3997 $roleswhere";
3999 // Default 'locality' policy -- read PHPDoc notes
4000 // about sort policies...
4001 $orderby = 'ORDER BY '
4002 .'ctx.depth DESC, ' /* locality wins */
4003 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
4004 .'ra.id'; /* role assignment order tie-breaker */
4005 if ($sortpolicy === 'sortorder') {
4006 $orderby = 'ORDER BY '
4007 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
4008 .'ra.id'; /* role assignment order tie-breaker */
4011 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
4012 $sortedusers = array();
4013 $seen = array();
4015 foreach ($sortedids as $id) {
4016 // Avoid duplicates
4017 if (isset($seen[$id])) {
4018 continue;
4020 $seen[$id] = true;
4022 // assign
4023 $sortedusers[$id] = $users[$id];
4025 return $sortedusers;
4029 * Gets all the users assigned this role in this context or higher
4031 * @param int $roleid (can also be an array of ints!)
4032 * @param context $context
4033 * @param bool $parent if true, get list of users assigned in higher context too
4034 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
4035 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
4036 * null => use default sort from users_order_by_sql.
4037 * @param bool $all true means all, false means limit to enrolled users
4038 * @param string $group defaults to ''
4039 * @param mixed $limitfrom defaults to ''
4040 * @param mixed $limitnum defaults to ''
4041 * @param string $extrawheretest defaults to ''
4042 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
4043 * @return array
4045 function get_role_users($roleid, context $context, $parent = false, $fields = '',
4046 $sort = null, $all = true, $group = '',
4047 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
4048 global $DB;
4050 if (empty($fields)) {
4051 $allnames = get_all_user_name_fields(true, 'u');
4052 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
4053 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
4054 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
4055 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
4056 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
4059 $parentcontexts = '';
4060 if ($parent) {
4061 $parentcontexts = substr($context->path, 1); // kill leading slash
4062 $parentcontexts = str_replace('/', ',', $parentcontexts);
4063 if ($parentcontexts !== '') {
4064 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4068 if ($roleid) {
4069 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
4070 $roleselect = "AND ra.roleid $rids";
4071 } else {
4072 $params = array();
4073 $roleselect = '';
4076 if ($coursecontext = $context->get_course_context(false)) {
4077 $params['coursecontext'] = $coursecontext->id;
4078 } else {
4079 $params['coursecontext'] = 0;
4082 if ($group) {
4083 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
4084 $groupselect = " AND gm.groupid = :groupid ";
4085 $params['groupid'] = $group;
4086 } else {
4087 $groupjoin = '';
4088 $groupselect = '';
4091 $params['contextid'] = $context->id;
4093 if ($extrawheretest) {
4094 $extrawheretest = ' AND ' . $extrawheretest;
4097 if ($whereorsortparams) {
4098 $params = array_merge($params, $whereorsortparams);
4101 if (!$sort) {
4102 list($sort, $sortparams) = users_order_by_sql('u');
4103 $params = array_merge($params, $sortparams);
4106 if ($all === null) {
4107 // Previously null was used to indicate that parameter was not used.
4108 $all = true;
4110 if (!$all and $coursecontext) {
4111 // Do not use get_enrolled_sql() here for performance reasons.
4112 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
4113 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
4114 $params['ecourseid'] = $coursecontext->instanceid;
4115 } else {
4116 $ejoin = "";
4119 $sql = "SELECT DISTINCT $fields, ra.roleid
4120 FROM {role_assignments} ra
4121 JOIN {user} u ON u.id = ra.userid
4122 JOIN {role} r ON ra.roleid = r.id
4123 $ejoin
4124 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
4125 $groupjoin
4126 WHERE (ra.contextid = :contextid $parentcontexts)
4127 $roleselect
4128 $groupselect
4129 $extrawheretest
4130 ORDER BY $sort"; // join now so that we can just use fullname() later
4132 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
4136 * Counts all the users assigned this role in this context or higher
4138 * @param int|array $roleid either int or an array of ints
4139 * @param context $context
4140 * @param bool $parent if true, get list of users assigned in higher context too
4141 * @return int Returns the result count
4143 function count_role_users($roleid, context $context, $parent = false) {
4144 global $DB;
4146 if ($parent) {
4147 if ($contexts = $context->get_parent_context_ids()) {
4148 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4149 } else {
4150 $parentcontexts = '';
4152 } else {
4153 $parentcontexts = '';
4156 if ($roleid) {
4157 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
4158 $roleselect = "AND r.roleid $rids";
4159 } else {
4160 $params = array();
4161 $roleselect = '';
4164 array_unshift($params, $context->id);
4166 $sql = "SELECT COUNT(u.id)
4167 FROM {role_assignments} r
4168 JOIN {user} u ON u.id = r.userid
4169 WHERE (r.contextid = ? $parentcontexts)
4170 $roleselect
4171 AND u.deleted = 0";
4173 return $DB->count_records_sql($sql, $params);
4177 * This function gets the list of courses that this user has a particular capability in.
4178 * It is still not very efficient.
4180 * @param string $capability Capability in question
4181 * @param int $userid User ID or null for current user
4182 * @param bool $doanything True if 'doanything' is permitted (default)
4183 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4184 * otherwise use a comma-separated list of the fields you require, not including id
4185 * @param string $orderby If set, use a comma-separated list of fields from course
4186 * table with sql modifiers (DESC) if needed
4187 * @return array Array of courses, may have zero entries. Or false if query failed.
4189 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
4190 global $DB;
4192 // Convert fields list and ordering
4193 $fieldlist = '';
4194 if ($fieldsexceptid) {
4195 $fields = explode(',', $fieldsexceptid);
4196 foreach($fields as $field) {
4197 $fieldlist .= ',c.'.$field;
4200 if ($orderby) {
4201 $fields = explode(',', $orderby);
4202 $orderby = '';
4203 foreach($fields as $field) {
4204 if ($orderby) {
4205 $orderby .= ',';
4207 $orderby .= 'c.'.$field;
4209 $orderby = 'ORDER BY '.$orderby;
4212 // Obtain a list of everything relevant about all courses including context.
4213 // Note the result can be used directly as a context (we are going to), the course
4214 // fields are just appended.
4216 $contextpreload = context_helper::get_preload_record_columns_sql('x');
4218 $courses = array();
4219 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
4220 FROM {course} c
4221 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
4222 $orderby");
4223 // Check capability for each course in turn
4224 foreach ($rs as $course) {
4225 context_helper::preload_from_record($course);
4226 $context = context_course::instance($course->id);
4227 if (has_capability($capability, $context, $userid, $doanything)) {
4228 // We've got the capability. Make the record look like a course record
4229 // and store it
4230 $courses[] = $course;
4233 $rs->close();
4234 return empty($courses) ? false : $courses;
4238 * This function finds the roles assigned directly to this context only
4239 * i.e. no roles in parent contexts
4241 * @param context $context
4242 * @return array
4244 function get_roles_on_exact_context(context $context) {
4245 global $DB;
4247 return $DB->get_records_sql("SELECT r.*
4248 FROM {role_assignments} ra, {role} r
4249 WHERE ra.roleid = r.id AND ra.contextid = ?",
4250 array($context->id));
4254 * Switches the current user to another role for the current session and only
4255 * in the given context.
4257 * The caller *must* check
4258 * - that this op is allowed
4259 * - that the requested role can be switched to in this context (use get_switchable_roles)
4260 * - that the requested role is NOT $CFG->defaultuserroleid
4262 * To "unswitch" pass 0 as the roleid.
4264 * This function *will* modify $USER->access - beware
4266 * @param integer $roleid the role to switch to.
4267 * @param context $context the context in which to perform the switch.
4268 * @return bool success or failure.
4270 function role_switch($roleid, context $context) {
4271 global $USER;
4274 // Plan of action
4276 // - Add the ghost RA to $USER->access
4277 // as $USER->access['rsw'][$path] = $roleid
4279 // - Make sure $USER->access['rdef'] has the roledefs
4280 // it needs to honour the switcherole
4282 // Roledefs will get loaded "deep" here - down to the last child
4283 // context. Note that
4285 // - When visiting subcontexts, our selective accessdata loading
4286 // will still work fine - though those ra/rdefs will be ignored
4287 // appropriately while the switch is in place
4289 // - If a switcherole happens at a category with tons of courses
4290 // (that have many overrides for switched-to role), the session
4291 // will get... quite large. Sometimes you just can't win.
4293 // To un-switch just unset($USER->access['rsw'][$path])
4295 // Note: it is not possible to switch to roles that do not have course:view
4297 if (!isset($USER->access)) {
4298 load_all_capabilities();
4302 // Add the switch RA
4303 if ($roleid == 0) {
4304 unset($USER->access['rsw'][$context->path]);
4305 return true;
4308 $USER->access['rsw'][$context->path] = $roleid;
4310 // Load roledefs
4311 load_role_access_by_context($roleid, $context, $USER->access);
4313 return true;
4317 * Checks if the user has switched roles within the given course.
4319 * Note: You can only switch roles within the course, hence it takes a course id
4320 * rather than a context. On that note Petr volunteered to implement this across
4321 * all other contexts, all requests for this should be forwarded to him ;)
4323 * @param int $courseid The id of the course to check
4324 * @return bool True if the user has switched roles within the course.
4326 function is_role_switched($courseid) {
4327 global $USER;
4328 $context = context_course::instance($courseid, MUST_EXIST);
4329 return (!empty($USER->access['rsw'][$context->path]));
4333 * Get any role that has an override on exact context
4335 * @param context $context The context to check
4336 * @return array An array of roles
4338 function get_roles_with_override_on_context(context $context) {
4339 global $DB;
4341 return $DB->get_records_sql("SELECT r.*
4342 FROM {role_capabilities} rc, {role} r
4343 WHERE rc.roleid = r.id AND rc.contextid = ?",
4344 array($context->id));
4348 * Get all capabilities for this role on this context (overrides)
4350 * @param stdClass $role
4351 * @param context $context
4352 * @return array
4354 function get_capabilities_from_role_on_context($role, context $context) {
4355 global $DB;
4357 return $DB->get_records_sql("SELECT *
4358 FROM {role_capabilities}
4359 WHERE contextid = ? AND roleid = ?",
4360 array($context->id, $role->id));
4364 * Find out which roles has assignment on this context
4366 * @param context $context
4367 * @return array
4370 function get_roles_with_assignment_on_context(context $context) {
4371 global $DB;
4373 return $DB->get_records_sql("SELECT r.*
4374 FROM {role_assignments} ra, {role} r
4375 WHERE ra.roleid = r.id AND ra.contextid = ?",
4376 array($context->id));
4380 * Find all user assignment of users for this role, on this context
4382 * @param stdClass $role
4383 * @param context $context
4384 * @return array
4386 function get_users_from_role_on_context($role, context $context) {
4387 global $DB;
4389 return $DB->get_records_sql("SELECT *
4390 FROM {role_assignments}
4391 WHERE contextid = ? AND roleid = ?",
4392 array($context->id, $role->id));
4396 * Simple function returning a boolean true if user has roles
4397 * in context or parent contexts, otherwise false.
4399 * @param int $userid
4400 * @param int $roleid
4401 * @param int $contextid empty means any context
4402 * @return bool
4404 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4405 global $DB;
4407 if ($contextid) {
4408 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4409 return false;
4411 $parents = $context->get_parent_context_ids(true);
4412 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4413 $params['userid'] = $userid;
4414 $params['roleid'] = $roleid;
4416 $sql = "SELECT COUNT(ra.id)
4417 FROM {role_assignments} ra
4418 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4420 $count = $DB->get_field_sql($sql, $params);
4421 return ($count > 0);
4423 } else {
4424 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4429 * Get localised role name or alias if exists and format the text.
4431 * @param stdClass $role role object
4432 * - optional 'coursealias' property should be included for performance reasons if course context used
4433 * - description property is not required here
4434 * @param context|bool $context empty means system context
4435 * @param int $rolenamedisplay type of role name
4436 * @return string localised role name or course role name alias
4438 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4439 global $DB;
4441 if ($rolenamedisplay == ROLENAME_SHORT) {
4442 return $role->shortname;
4445 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4446 $coursecontext = null;
4449 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4450 $role = clone($role); // Do not modify parameters.
4451 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4452 $role->coursealias = $r->name;
4453 } else {
4454 $role->coursealias = null;
4458 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4459 if ($coursecontext) {
4460 return $role->coursealias;
4461 } else {
4462 return null;
4466 if (trim($role->name) !== '') {
4467 // For filtering always use context where was the thing defined - system for roles here.
4468 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4470 } else {
4471 // Empty role->name means we want to see localised role name based on shortname,
4472 // only default roles are supposed to be localised.
4473 switch ($role->shortname) {
4474 case 'manager': $original = get_string('manager', 'role'); break;
4475 case 'coursecreator': $original = get_string('coursecreators'); break;
4476 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4477 case 'teacher': $original = get_string('noneditingteacher'); break;
4478 case 'student': $original = get_string('defaultcoursestudent'); break;
4479 case 'guest': $original = get_string('guest'); break;
4480 case 'user': $original = get_string('authenticateduser'); break;
4481 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4482 // We should not get here, the role UI should require the name for custom roles!
4483 default: $original = $role->shortname; break;
4487 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4488 return $original;
4491 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4492 return "$original ($role->shortname)";
4495 if ($rolenamedisplay == ROLENAME_ALIAS) {
4496 if ($coursecontext and trim($role->coursealias) !== '') {
4497 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4498 } else {
4499 return $original;
4503 if ($rolenamedisplay == ROLENAME_BOTH) {
4504 if ($coursecontext and trim($role->coursealias) !== '') {
4505 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4506 } else {
4507 return $original;
4511 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4515 * Returns localised role description if available.
4516 * If the name is empty it tries to find the default role name using
4517 * hardcoded list of default role names or other methods in the future.
4519 * @param stdClass $role
4520 * @return string localised role name
4522 function role_get_description(stdClass $role) {
4523 if (!html_is_blank($role->description)) {
4524 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4527 switch ($role->shortname) {
4528 case 'manager': return get_string('managerdescription', 'role');
4529 case 'coursecreator': return get_string('coursecreatorsdescription');
4530 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4531 case 'teacher': return get_string('noneditingteacherdescription');
4532 case 'student': return get_string('defaultcoursestudentdescription');
4533 case 'guest': return get_string('guestdescription');
4534 case 'user': return get_string('authenticateduserdescription');
4535 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4536 default: return '';
4541 * Get all the localised role names for a context.
4543 * In new installs default roles have empty names, this function
4544 * add localised role names using current language pack.
4546 * @param context $context the context, null means system context
4547 * @param array of role objects with a ->localname field containing the context-specific role name.
4548 * @param int $rolenamedisplay
4549 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4550 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4552 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4553 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4557 * Prepare list of roles for display, apply aliases and localise default role names.
4559 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4560 * @param context $context the context, null means system context
4561 * @param int $rolenamedisplay
4562 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4563 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4565 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4566 global $DB;
4568 if (empty($roleoptions)) {
4569 return array();
4572 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4573 $coursecontext = null;
4576 // We usually need all role columns...
4577 $first = reset($roleoptions);
4578 if ($returnmenu === null) {
4579 $returnmenu = !is_object($first);
4582 if (!is_object($first) or !property_exists($first, 'shortname')) {
4583 $allroles = get_all_roles($context);
4584 foreach ($roleoptions as $rid => $unused) {
4585 $roleoptions[$rid] = $allroles[$rid];
4589 // Inject coursealias if necessary.
4590 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4591 $first = reset($roleoptions);
4592 if (!property_exists($first, 'coursealias')) {
4593 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4594 foreach ($aliasnames as $alias) {
4595 if (isset($roleoptions[$alias->roleid])) {
4596 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4602 // Add localname property.
4603 foreach ($roleoptions as $rid => $role) {
4604 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4607 if (!$returnmenu) {
4608 return $roleoptions;
4611 $menu = array();
4612 foreach ($roleoptions as $rid => $role) {
4613 $menu[$rid] = $role->localname;
4616 return $menu;
4620 * Aids in detecting if a new line is required when reading a new capability
4622 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4623 * when we read in a new capability.
4624 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4625 * but when we are in grade, all reports/import/export capabilities should be together
4627 * @param string $cap component string a
4628 * @param string $comp component string b
4629 * @param int $contextlevel
4630 * @return bool whether 2 component are in different "sections"
4632 function component_level_changed($cap, $comp, $contextlevel) {
4634 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4635 $compsa = explode('/', $cap->component);
4636 $compsb = explode('/', $comp);
4638 // list of system reports
4639 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4640 return false;
4643 // we are in gradebook, still
4644 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4645 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4646 return false;
4649 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4650 return false;
4654 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4658 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4659 * and return an array of roleids in order.
4661 * @param array $allroles array of roles, as returned by get_all_roles();
4662 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4664 function fix_role_sortorder($allroles) {
4665 global $DB;
4667 $rolesort = array();
4668 $i = 0;
4669 foreach ($allroles as $role) {
4670 $rolesort[$i] = $role->id;
4671 if ($role->sortorder != $i) {
4672 $r = new stdClass();
4673 $r->id = $role->id;
4674 $r->sortorder = $i;
4675 $DB->update_record('role', $r);
4676 $allroles[$role->id]->sortorder = $i;
4678 $i++;
4680 return $rolesort;
4684 * Switch the sort order of two roles (used in admin/roles/manage.php).
4686 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4687 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4688 * @return boolean success or failure
4690 function switch_roles($first, $second) {
4691 global $DB;
4692 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4693 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4694 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4695 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4696 return $result;
4700 * Duplicates all the base definitions of a role
4702 * @param stdClass $sourcerole role to copy from
4703 * @param int $targetrole id of role to copy to
4705 function role_cap_duplicate($sourcerole, $targetrole) {
4706 global $DB;
4708 $systemcontext = context_system::instance();
4709 $caps = $DB->get_records_sql("SELECT *
4710 FROM {role_capabilities}
4711 WHERE roleid = ? AND contextid = ?",
4712 array($sourcerole->id, $systemcontext->id));
4713 // adding capabilities
4714 foreach ($caps as $cap) {
4715 unset($cap->id);
4716 $cap->roleid = $targetrole;
4717 $DB->insert_record('role_capabilities', $cap);
4722 * Returns two lists, this can be used to find out if user has capability.
4723 * Having any needed role and no forbidden role in this context means
4724 * user has this capability in this context.
4725 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4727 * @param stdClass $context
4728 * @param string $capability
4729 * @return array($neededroles, $forbiddenroles)
4731 function get_roles_with_cap_in_context($context, $capability) {
4732 global $DB;
4734 $ctxids = trim($context->path, '/'); // kill leading slash
4735 $ctxids = str_replace('/', ',', $ctxids);
4737 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4738 FROM {role_capabilities} rc
4739 JOIN {context} ctx ON ctx.id = rc.contextid
4740 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4741 ORDER BY rc.roleid ASC, ctx.depth DESC";
4742 $params = array('cap'=>$capability);
4744 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4745 // no cap definitions --> no capability
4746 return array(array(), array());
4749 $forbidden = array();
4750 $needed = array();
4751 foreach($capdefs as $def) {
4752 if (isset($forbidden[$def->roleid])) {
4753 continue;
4755 if ($def->permission == CAP_PROHIBIT) {
4756 $forbidden[$def->roleid] = $def->roleid;
4757 unset($needed[$def->roleid]);
4758 continue;
4760 if (!isset($needed[$def->roleid])) {
4761 if ($def->permission == CAP_ALLOW) {
4762 $needed[$def->roleid] = true;
4763 } else if ($def->permission == CAP_PREVENT) {
4764 $needed[$def->roleid] = false;
4768 unset($capdefs);
4770 // remove all those roles not allowing
4771 foreach($needed as $key=>$value) {
4772 if (!$value) {
4773 unset($needed[$key]);
4774 } else {
4775 $needed[$key] = $key;
4779 return array($needed, $forbidden);
4783 * Returns an array of role IDs that have ALL of the the supplied capabilities
4784 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4786 * @param stdClass $context
4787 * @param array $capabilities An array of capabilities
4788 * @return array of roles with all of the required capabilities
4790 function get_roles_with_caps_in_context($context, $capabilities) {
4791 $neededarr = array();
4792 $forbiddenarr = array();
4793 foreach($capabilities as $caprequired) {
4794 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4797 $rolesthatcanrate = array();
4798 if (!empty($neededarr)) {
4799 foreach ($neededarr as $needed) {
4800 if (empty($rolesthatcanrate)) {
4801 $rolesthatcanrate = $needed;
4802 } else {
4803 //only want roles that have all caps
4804 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4808 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4809 foreach ($forbiddenarr as $forbidden) {
4810 //remove any roles that are forbidden any of the caps
4811 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4814 return $rolesthatcanrate;
4818 * Returns an array of role names that have ALL of the the supplied capabilities
4819 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4821 * @param stdClass $context
4822 * @param array $capabilities An array of capabilities
4823 * @return array of roles with all of the required capabilities
4825 function get_role_names_with_caps_in_context($context, $capabilities) {
4826 global $DB;
4828 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4829 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4831 $roles = array();
4832 foreach ($rolesthatcanrate as $r) {
4833 $roles[$r] = $allroles[$r];
4836 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4840 * This function verifies the prohibit comes from this context
4841 * and there are no more prohibits in parent contexts.
4843 * @param int $roleid
4844 * @param context $context
4845 * @param string $capability name
4846 * @return bool
4848 function prohibit_is_removable($roleid, context $context, $capability) {
4849 global $DB;
4851 $ctxids = trim($context->path, '/'); // kill leading slash
4852 $ctxids = str_replace('/', ',', $ctxids);
4854 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4856 $sql = "SELECT ctx.id
4857 FROM {role_capabilities} rc
4858 JOIN {context} ctx ON ctx.id = rc.contextid
4859 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4860 ORDER BY ctx.depth DESC";
4862 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4863 // no prohibits == nothing to remove
4864 return true;
4867 if (count($prohibits) > 1) {
4868 // more prohibits can not be removed
4869 return false;
4872 return !empty($prohibits[$context->id]);
4876 * More user friendly role permission changing,
4877 * it should produce as few overrides as possible.
4879 * @param int $roleid
4880 * @param stdClass $context
4881 * @param string $capname capability name
4882 * @param int $permission
4883 * @return void
4885 function role_change_permission($roleid, $context, $capname, $permission) {
4886 global $DB;
4888 if ($permission == CAP_INHERIT) {
4889 unassign_capability($capname, $roleid, $context->id);
4890 $context->mark_dirty();
4891 return;
4894 $ctxids = trim($context->path, '/'); // kill leading slash
4895 $ctxids = str_replace('/', ',', $ctxids);
4897 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4899 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4900 FROM {role_capabilities} rc
4901 JOIN {context} ctx ON ctx.id = rc.contextid
4902 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4903 ORDER BY ctx.depth DESC";
4905 if ($existing = $DB->get_records_sql($sql, $params)) {
4906 foreach($existing as $e) {
4907 if ($e->permission == CAP_PROHIBIT) {
4908 // prohibit can not be overridden, no point in changing anything
4909 return;
4912 $lowest = array_shift($existing);
4913 if ($lowest->permission == $permission) {
4914 // permission already set in this context or parent - nothing to do
4915 return;
4917 if ($existing) {
4918 $parent = array_shift($existing);
4919 if ($parent->permission == $permission) {
4920 // permission already set in parent context or parent - just unset in this context
4921 // we do this because we want as few overrides as possible for performance reasons
4922 unassign_capability($capname, $roleid, $context->id);
4923 $context->mark_dirty();
4924 return;
4928 } else {
4929 if ($permission == CAP_PREVENT) {
4930 // nothing means role does not have permission
4931 return;
4935 // assign the needed capability
4936 assign_capability($capname, $permission, $roleid, $context->id, true);
4938 // force cap reloading
4939 $context->mark_dirty();
4944 * Basic moodle context abstraction class.
4946 * Google confirms that no other important framework is using "context" class,
4947 * we could use something else like mcontext or moodle_context, but we need to type
4948 * this very often which would be annoying and it would take too much space...
4950 * This class is derived from stdClass for backwards compatibility with
4951 * odl $context record that was returned from DML $DB->get_record()
4953 * @package core_access
4954 * @category access
4955 * @copyright Petr Skoda {@link http://skodak.org}
4956 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4957 * @since 2.2
4959 * @property-read int $id context id
4960 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4961 * @property-read int $instanceid id of related instance in each context
4962 * @property-read string $path path to context, starts with system context
4963 * @property-read int $depth
4965 abstract class context extends stdClass implements IteratorAggregate {
4968 * The context id
4969 * Can be accessed publicly through $context->id
4970 * @var int
4972 protected $_id;
4975 * The context level
4976 * Can be accessed publicly through $context->contextlevel
4977 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4979 protected $_contextlevel;
4982 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4983 * Can be accessed publicly through $context->instanceid
4984 * @var int
4986 protected $_instanceid;
4989 * The path to the context always starting from the system context
4990 * Can be accessed publicly through $context->path
4991 * @var string
4993 protected $_path;
4996 * The depth of the context in relation to parent contexts
4997 * Can be accessed publicly through $context->depth
4998 * @var int
5000 protected $_depth;
5003 * @var array Context caching info
5005 private static $cache_contextsbyid = array();
5008 * @var array Context caching info
5010 private static $cache_contexts = array();
5013 * Context count
5014 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
5015 * @var int
5017 protected static $cache_count = 0;
5020 * @var array Context caching info
5022 protected static $cache_preloaded = array();
5025 * @var context_system The system context once initialised
5027 protected static $systemcontext = null;
5030 * Resets the cache to remove all data.
5031 * @static
5033 protected static function reset_caches() {
5034 self::$cache_contextsbyid = array();
5035 self::$cache_contexts = array();
5036 self::$cache_count = 0;
5037 self::$cache_preloaded = array();
5039 self::$systemcontext = null;
5043 * Adds a context to the cache. If the cache is full, discards a batch of
5044 * older entries.
5046 * @static
5047 * @param context $context New context to add
5048 * @return void
5050 protected static function cache_add(context $context) {
5051 if (isset(self::$cache_contextsbyid[$context->id])) {
5052 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5053 return;
5056 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
5057 $i = 0;
5058 foreach(self::$cache_contextsbyid as $ctx) {
5059 $i++;
5060 if ($i <= 100) {
5061 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
5062 continue;
5064 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
5065 // we remove oldest third of the contexts to make room for more contexts
5066 break;
5068 unset(self::$cache_contextsbyid[$ctx->id]);
5069 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
5070 self::$cache_count--;
5074 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
5075 self::$cache_contextsbyid[$context->id] = $context;
5076 self::$cache_count++;
5080 * Removes a context from the cache.
5082 * @static
5083 * @param context $context Context object to remove
5084 * @return void
5086 protected static function cache_remove(context $context) {
5087 if (!isset(self::$cache_contextsbyid[$context->id])) {
5088 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5089 return;
5091 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
5092 unset(self::$cache_contextsbyid[$context->id]);
5094 self::$cache_count--;
5096 if (self::$cache_count < 0) {
5097 self::$cache_count = 0;
5102 * Gets a context from the cache.
5104 * @static
5105 * @param int $contextlevel Context level
5106 * @param int $instance Instance ID
5107 * @return context|bool Context or false if not in cache
5109 protected static function cache_get($contextlevel, $instance) {
5110 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
5111 return self::$cache_contexts[$contextlevel][$instance];
5113 return false;
5117 * Gets a context from the cache based on its id.
5119 * @static
5120 * @param int $id Context ID
5121 * @return context|bool Context or false if not in cache
5123 protected static function cache_get_by_id($id) {
5124 if (isset(self::$cache_contextsbyid[$id])) {
5125 return self::$cache_contextsbyid[$id];
5127 return false;
5131 * Preloads context information from db record and strips the cached info.
5133 * @static
5134 * @param stdClass $rec
5135 * @return void (modifies $rec)
5137 protected static function preload_from_record(stdClass $rec) {
5138 if (empty($rec->ctxid) or empty($rec->ctxlevel) or empty($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
5139 // $rec does not have enough data, passed here repeatedly or context does not exist yet
5140 return;
5143 // note: in PHP5 the objects are passed by reference, no need to return $rec
5144 $record = new stdClass();
5145 $record->id = $rec->ctxid; unset($rec->ctxid);
5146 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
5147 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
5148 $record->path = $rec->ctxpath; unset($rec->ctxpath);
5149 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
5151 return context::create_instance_from_record($record);
5155 // ====== magic methods =======
5158 * Magic setter method, we do not want anybody to modify properties from the outside
5159 * @param string $name
5160 * @param mixed $value
5162 public function __set($name, $value) {
5163 debugging('Can not change context instance properties!');
5167 * Magic method getter, redirects to read only values.
5168 * @param string $name
5169 * @return mixed
5171 public function __get($name) {
5172 switch ($name) {
5173 case 'id': return $this->_id;
5174 case 'contextlevel': return $this->_contextlevel;
5175 case 'instanceid': return $this->_instanceid;
5176 case 'path': return $this->_path;
5177 case 'depth': return $this->_depth;
5179 default:
5180 debugging('Invalid context property accessed! '.$name);
5181 return null;
5186 * Full support for isset on our magic read only properties.
5187 * @param string $name
5188 * @return bool
5190 public function __isset($name) {
5191 switch ($name) {
5192 case 'id': return isset($this->_id);
5193 case 'contextlevel': return isset($this->_contextlevel);
5194 case 'instanceid': return isset($this->_instanceid);
5195 case 'path': return isset($this->_path);
5196 case 'depth': return isset($this->_depth);
5198 default: return false;
5204 * ALl properties are read only, sorry.
5205 * @param string $name
5207 public function __unset($name) {
5208 debugging('Can not unset context instance properties!');
5211 // ====== implementing method from interface IteratorAggregate ======
5214 * Create an iterator because magic vars can't be seen by 'foreach'.
5216 * Now we can convert context object to array using convert_to_array(),
5217 * and feed it properly to json_encode().
5219 public function getIterator() {
5220 $ret = array(
5221 'id' => $this->id,
5222 'contextlevel' => $this->contextlevel,
5223 'instanceid' => $this->instanceid,
5224 'path' => $this->path,
5225 'depth' => $this->depth
5227 return new ArrayIterator($ret);
5230 // ====== general context methods ======
5233 * Constructor is protected so that devs are forced to
5234 * use context_xxx::instance() or context::instance_by_id().
5236 * @param stdClass $record
5238 protected function __construct(stdClass $record) {
5239 $this->_id = $record->id;
5240 $this->_contextlevel = (int)$record->contextlevel;
5241 $this->_instanceid = $record->instanceid;
5242 $this->_path = $record->path;
5243 $this->_depth = $record->depth;
5247 * This function is also used to work around 'protected' keyword problems in context_helper.
5248 * @static
5249 * @param stdClass $record
5250 * @return context instance
5252 protected static function create_instance_from_record(stdClass $record) {
5253 $classname = context_helper::get_class_for_level($record->contextlevel);
5255 if ($context = context::cache_get_by_id($record->id)) {
5256 return $context;
5259 $context = new $classname($record);
5260 context::cache_add($context);
5262 return $context;
5266 * Copy prepared new contexts from temp table to context table,
5267 * we do this in db specific way for perf reasons only.
5268 * @static
5270 protected static function merge_context_temp_table() {
5271 global $DB;
5273 /* MDL-11347:
5274 * - mysql does not allow to use FROM in UPDATE statements
5275 * - using two tables after UPDATE works in mysql, but might give unexpected
5276 * results in pg 8 (depends on configuration)
5277 * - using table alias in UPDATE does not work in pg < 8.2
5279 * Different code for each database - mostly for performance reasons
5282 $dbfamily = $DB->get_dbfamily();
5283 if ($dbfamily == 'mysql') {
5284 $updatesql = "UPDATE {context} ct, {context_temp} temp
5285 SET ct.path = temp.path,
5286 ct.depth = temp.depth
5287 WHERE ct.id = temp.id";
5288 } else if ($dbfamily == 'oracle') {
5289 $updatesql = "UPDATE {context} ct
5290 SET (ct.path, ct.depth) =
5291 (SELECT temp.path, temp.depth
5292 FROM {context_temp} temp
5293 WHERE temp.id=ct.id)
5294 WHERE EXISTS (SELECT 'x'
5295 FROM {context_temp} temp
5296 WHERE temp.id = ct.id)";
5297 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5298 $updatesql = "UPDATE {context}
5299 SET path = temp.path,
5300 depth = temp.depth
5301 FROM {context_temp} temp
5302 WHERE temp.id={context}.id";
5303 } else {
5304 // sqlite and others
5305 $updatesql = "UPDATE {context}
5306 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5307 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5308 WHERE id IN (SELECT id FROM {context_temp})";
5311 $DB->execute($updatesql);
5315 * Get a context instance as an object, from a given context id.
5317 * @static
5318 * @param int $id context id
5319 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5320 * MUST_EXIST means throw exception if no record found
5321 * @return context|bool the context object or false if not found
5323 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5324 global $DB;
5326 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5327 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5328 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5331 if ($id == SYSCONTEXTID) {
5332 return context_system::instance(0, $strictness);
5335 if (is_array($id) or is_object($id) or empty($id)) {
5336 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5339 if ($context = context::cache_get_by_id($id)) {
5340 return $context;
5343 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5344 return context::create_instance_from_record($record);
5347 return false;
5351 * Update context info after moving context in the tree structure.
5353 * @param context $newparent
5354 * @return void
5356 public function update_moved(context $newparent) {
5357 global $DB;
5359 $frompath = $this->_path;
5360 $newpath = $newparent->path . '/' . $this->_id;
5362 $trans = $DB->start_delegated_transaction();
5364 $this->mark_dirty();
5366 $setdepth = '';
5367 if (($newparent->depth +1) != $this->_depth) {
5368 $diff = $newparent->depth - $this->_depth + 1;
5369 $setdepth = ", depth = depth + $diff";
5371 $sql = "UPDATE {context}
5372 SET path = ?
5373 $setdepth
5374 WHERE id = ?";
5375 $params = array($newpath, $this->_id);
5376 $DB->execute($sql, $params);
5378 $this->_path = $newpath;
5379 $this->_depth = $newparent->depth + 1;
5381 $sql = "UPDATE {context}
5382 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5383 $setdepth
5384 WHERE path LIKE ?";
5385 $params = array($newpath, "{$frompath}/%");
5386 $DB->execute($sql, $params);
5388 $this->mark_dirty();
5390 context::reset_caches();
5392 $trans->allow_commit();
5396 * Remove all context path info and optionally rebuild it.
5398 * @param bool $rebuild
5399 * @return void
5401 public function reset_paths($rebuild = true) {
5402 global $DB;
5404 if ($this->_path) {
5405 $this->mark_dirty();
5407 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5408 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5409 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5410 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5411 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5412 $this->_depth = 0;
5413 $this->_path = null;
5416 if ($rebuild) {
5417 context_helper::build_all_paths(false);
5420 context::reset_caches();
5424 * Delete all data linked to content, do not delete the context record itself
5426 public function delete_content() {
5427 global $CFG, $DB;
5429 blocks_delete_all_for_context($this->_id);
5430 filter_delete_all_for_context($this->_id);
5432 require_once($CFG->dirroot . '/comment/lib.php');
5433 comment::delete_comments(array('contextid'=>$this->_id));
5435 require_once($CFG->dirroot.'/rating/lib.php');
5436 $delopt = new stdclass();
5437 $delopt->contextid = $this->_id;
5438 $rm = new rating_manager();
5439 $rm->delete_ratings($delopt);
5441 // delete all files attached to this context
5442 $fs = get_file_storage();
5443 $fs->delete_area_files($this->_id);
5445 // Delete all repository instances attached to this context.
5446 require_once($CFG->dirroot . '/repository/lib.php');
5447 repository::delete_all_for_context($this->_id);
5449 // delete all advanced grading data attached to this context
5450 require_once($CFG->dirroot.'/grade/grading/lib.php');
5451 grading_manager::delete_all_for_context($this->_id);
5453 // now delete stuff from role related tables, role_unassign_all
5454 // and unenrol should be called earlier to do proper cleanup
5455 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5456 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5457 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5461 * Delete the context content and the context record itself
5463 public function delete() {
5464 global $DB;
5466 // double check the context still exists
5467 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5468 context::cache_remove($this);
5469 return;
5472 $this->delete_content();
5473 $DB->delete_records('context', array('id'=>$this->_id));
5474 // purge static context cache if entry present
5475 context::cache_remove($this);
5477 // do not mark dirty contexts if parents unknown
5478 if (!is_null($this->_path) and $this->_depth > 0) {
5479 $this->mark_dirty();
5483 // ====== context level related methods ======
5486 * Utility method for context creation
5488 * @static
5489 * @param int $contextlevel
5490 * @param int $instanceid
5491 * @param string $parentpath
5492 * @return stdClass context record
5494 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5495 global $DB;
5497 $record = new stdClass();
5498 $record->contextlevel = $contextlevel;
5499 $record->instanceid = $instanceid;
5500 $record->depth = 0;
5501 $record->path = null; //not known before insert
5503 $record->id = $DB->insert_record('context', $record);
5505 // now add path if known - it can be added later
5506 if (!is_null($parentpath)) {
5507 $record->path = $parentpath.'/'.$record->id;
5508 $record->depth = substr_count($record->path, '/');
5509 $DB->update_record('context', $record);
5512 return $record;
5516 * Returns human readable context identifier.
5518 * @param boolean $withprefix whether to prefix the name of the context with the
5519 * type of context, e.g. User, Course, Forum, etc.
5520 * @param boolean $short whether to use the short name of the thing. Only applies
5521 * to course contexts
5522 * @return string the human readable context name.
5524 public function get_context_name($withprefix = true, $short = false) {
5525 // must be implemented in all context levels
5526 throw new coding_exception('can not get name of abstract context');
5530 * Returns the most relevant URL for this context.
5532 * @return moodle_url
5534 public abstract function get_url();
5537 * Returns array of relevant context capability records.
5539 * @return array
5541 public abstract function get_capabilities();
5544 * Recursive function which, given a context, find all its children context ids.
5546 * For course category contexts it will return immediate children and all subcategory contexts.
5547 * It will NOT recurse into courses or subcategories categories.
5548 * If you want to do that, call it on the returned courses/categories.
5550 * When called for a course context, it will return the modules and blocks
5551 * displayed in the course page and blocks displayed on the module pages.
5553 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5554 * contexts ;-)
5556 * @return array Array of child records
5558 public function get_child_contexts() {
5559 global $DB;
5561 $sql = "SELECT ctx.*
5562 FROM {context} ctx
5563 WHERE ctx.path LIKE ?";
5564 $params = array($this->_path.'/%');
5565 $records = $DB->get_records_sql($sql, $params);
5567 $result = array();
5568 foreach ($records as $record) {
5569 $result[$record->id] = context::create_instance_from_record($record);
5572 return $result;
5576 * Returns parent contexts of this context in reversed order, i.e. parent first,
5577 * then grand parent, etc.
5579 * @param bool $includeself tre means include self too
5580 * @return array of context instances
5582 public function get_parent_contexts($includeself = false) {
5583 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5584 return array();
5587 $result = array();
5588 foreach ($contextids as $contextid) {
5589 $parent = context::instance_by_id($contextid, MUST_EXIST);
5590 $result[$parent->id] = $parent;
5593 return $result;
5597 * Returns parent contexts of this context in reversed order, i.e. parent first,
5598 * then grand parent, etc.
5600 * @param bool $includeself tre means include self too
5601 * @return array of context ids
5603 public function get_parent_context_ids($includeself = false) {
5604 if (empty($this->_path)) {
5605 return array();
5608 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5609 $parentcontexts = explode('/', $parentcontexts);
5610 if (!$includeself) {
5611 array_pop($parentcontexts); // and remove its own id
5614 return array_reverse($parentcontexts);
5618 * Returns parent context
5620 * @return context
5622 public function get_parent_context() {
5623 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5624 return false;
5627 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5628 $parentcontexts = explode('/', $parentcontexts);
5629 array_pop($parentcontexts); // self
5630 $contextid = array_pop($parentcontexts); // immediate parent
5632 return context::instance_by_id($contextid, MUST_EXIST);
5636 * Is this context part of any course? If yes return course context.
5638 * @param bool $strict true means throw exception if not found, false means return false if not found
5639 * @return course_context context of the enclosing course, null if not found or exception
5641 public function get_course_context($strict = true) {
5642 if ($strict) {
5643 throw new coding_exception('Context does not belong to any course.');
5644 } else {
5645 return false;
5650 * Returns sql necessary for purging of stale context instances.
5652 * @static
5653 * @return string cleanup SQL
5655 protected static function get_cleanup_sql() {
5656 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5660 * Rebuild context paths and depths at context level.
5662 * @static
5663 * @param bool $force
5664 * @return void
5666 protected static function build_paths($force) {
5667 throw new coding_exception('build_paths() method must be implemented in all context levels');
5671 * Create missing context instances at given level
5673 * @static
5674 * @return void
5676 protected static function create_level_instances() {
5677 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5681 * Reset all cached permissions and definitions if the necessary.
5682 * @return void
5684 public function reload_if_dirty() {
5685 global $ACCESSLIB_PRIVATE, $USER;
5687 // Load dirty contexts list if needed
5688 if (CLI_SCRIPT) {
5689 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5690 // we do not load dirty flags in CLI and cron
5691 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5693 } else {
5694 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5695 if (!isset($USER->access['time'])) {
5696 // nothing was loaded yet, we do not need to check dirty contexts now
5697 return;
5699 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5700 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5704 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5705 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5706 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5707 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5708 reload_all_capabilities();
5709 break;
5715 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5717 public function mark_dirty() {
5718 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5720 if (during_initial_install()) {
5721 return;
5724 // only if it is a non-empty string
5725 if (is_string($this->_path) && $this->_path !== '') {
5726 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5727 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5728 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5729 } else {
5730 if (CLI_SCRIPT) {
5731 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5732 } else {
5733 if (isset($USER->access['time'])) {
5734 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5735 } else {
5736 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5738 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5747 * Context maintenance and helper methods.
5749 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5750 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5751 * level implementation from the rest of code, the code completion returns what developers need.
5753 * Thank you Tim Hunt for helping me with this nasty trick.
5755 * @package core_access
5756 * @category access
5757 * @copyright Petr Skoda {@link http://skodak.org}
5758 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5759 * @since 2.2
5761 class context_helper extends context {
5764 * @var array An array mapping context levels to classes
5766 private static $alllevels;
5769 * Instance does not make sense here, only static use
5771 protected function __construct() {
5775 * Initialise context levels, call before using self::$alllevels.
5777 private static function init_levels() {
5778 global $CFG;
5780 if (isset(self::$alllevels)) {
5781 return;
5783 self::$alllevels = array(
5784 CONTEXT_SYSTEM => 'context_system',
5785 CONTEXT_USER => 'context_user',
5786 CONTEXT_COURSECAT => 'context_coursecat',
5787 CONTEXT_COURSE => 'context_course',
5788 CONTEXT_MODULE => 'context_module',
5789 CONTEXT_BLOCK => 'context_block',
5792 if (empty($CFG->custom_context_classes)) {
5793 return;
5796 // Unsupported custom levels, use with care!!!
5797 foreach ($CFG->custom_context_classes as $level => $classname) {
5798 self::$alllevels[$level] = $classname;
5800 ksort(self::$alllevels);
5804 * Returns a class name of the context level class
5806 * @static
5807 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5808 * @return string class name of the context class
5810 public static function get_class_for_level($contextlevel) {
5811 self::init_levels();
5812 if (isset(self::$alllevels[$contextlevel])) {
5813 return self::$alllevels[$contextlevel];
5814 } else {
5815 throw new coding_exception('Invalid context level specified');
5820 * Returns a list of all context levels
5822 * @static
5823 * @return array int=>string (level=>level class name)
5825 public static function get_all_levels() {
5826 self::init_levels();
5827 return self::$alllevels;
5831 * Remove stale contexts that belonged to deleted instances.
5832 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5834 * @static
5835 * @return void
5837 public static function cleanup_instances() {
5838 global $DB;
5839 self::init_levels();
5841 $sqls = array();
5842 foreach (self::$alllevels as $level=>$classname) {
5843 $sqls[] = $classname::get_cleanup_sql();
5846 $sql = implode(" UNION ", $sqls);
5848 // it is probably better to use transactions, it might be faster too
5849 $transaction = $DB->start_delegated_transaction();
5851 $rs = $DB->get_recordset_sql($sql);
5852 foreach ($rs as $record) {
5853 $context = context::create_instance_from_record($record);
5854 $context->delete();
5856 $rs->close();
5858 $transaction->allow_commit();
5862 * Create all context instances at the given level and above.
5864 * @static
5865 * @param int $contextlevel null means all levels
5866 * @param bool $buildpaths
5867 * @return void
5869 public static function create_instances($contextlevel = null, $buildpaths = true) {
5870 self::init_levels();
5871 foreach (self::$alllevels as $level=>$classname) {
5872 if ($contextlevel and $level > $contextlevel) {
5873 // skip potential sub-contexts
5874 continue;
5876 $classname::create_level_instances();
5877 if ($buildpaths) {
5878 $classname::build_paths(false);
5884 * Rebuild paths and depths in all context levels.
5886 * @static
5887 * @param bool $force false means add missing only
5888 * @return void
5890 public static function build_all_paths($force = false) {
5891 self::init_levels();
5892 foreach (self::$alllevels as $classname) {
5893 $classname::build_paths($force);
5896 // reset static course cache - it might have incorrect cached data
5897 accesslib_clear_all_caches(true);
5901 * Resets the cache to remove all data.
5902 * @static
5904 public static function reset_caches() {
5905 context::reset_caches();
5909 * Returns all fields necessary for context preloading from user $rec.
5911 * This helps with performance when dealing with hundreds of contexts.
5913 * @static
5914 * @param string $tablealias context table alias in the query
5915 * @return array (table.column=>alias, ...)
5917 public static function get_preload_record_columns($tablealias) {
5918 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5922 * Returns all fields necessary for context preloading from user $rec.
5924 * This helps with performance when dealing with hundreds of contexts.
5926 * @static
5927 * @param string $tablealias context table alias in the query
5928 * @return string
5930 public static function get_preload_record_columns_sql($tablealias) {
5931 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5935 * Preloads context information from db record and strips the cached info.
5937 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5939 * @static
5940 * @param stdClass $rec
5941 * @return void (modifies $rec)
5943 public static function preload_from_record(stdClass $rec) {
5944 context::preload_from_record($rec);
5948 * Preload all contexts instances from course.
5950 * To be used if you expect multiple queries for course activities...
5952 * @static
5953 * @param int $courseid
5955 public static function preload_course($courseid) {
5956 // Users can call this multiple times without doing any harm
5957 if (isset(context::$cache_preloaded[$courseid])) {
5958 return;
5960 $coursecontext = context_course::instance($courseid);
5961 $coursecontext->get_child_contexts();
5963 context::$cache_preloaded[$courseid] = true;
5967 * Delete context instance
5969 * @static
5970 * @param int $contextlevel
5971 * @param int $instanceid
5972 * @return void
5974 public static function delete_instance($contextlevel, $instanceid) {
5975 global $DB;
5977 // double check the context still exists
5978 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5979 $context = context::create_instance_from_record($record);
5980 $context->delete();
5981 } else {
5982 // we should try to purge the cache anyway
5987 * Returns the name of specified context level
5989 * @static
5990 * @param int $contextlevel
5991 * @return string name of the context level
5993 public static function get_level_name($contextlevel) {
5994 $classname = context_helper::get_class_for_level($contextlevel);
5995 return $classname::get_level_name();
5999 * not used
6001 public function get_url() {
6005 * not used
6007 public function get_capabilities() {
6013 * System context class
6015 * @package core_access
6016 * @category access
6017 * @copyright Petr Skoda {@link http://skodak.org}
6018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6019 * @since 2.2
6021 class context_system extends context {
6023 * Please use context_system::instance() if you need the instance of context.
6025 * @param stdClass $record
6027 protected function __construct(stdClass $record) {
6028 parent::__construct($record);
6029 if ($record->contextlevel != CONTEXT_SYSTEM) {
6030 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
6035 * Returns human readable context level name.
6037 * @static
6038 * @return string the human readable context level name.
6040 public static function get_level_name() {
6041 return get_string('coresystem');
6045 * Returns human readable context identifier.
6047 * @param boolean $withprefix does not apply to system context
6048 * @param boolean $short does not apply to system context
6049 * @return string the human readable context name.
6051 public function get_context_name($withprefix = true, $short = false) {
6052 return self::get_level_name();
6056 * Returns the most relevant URL for this context.
6058 * @return moodle_url
6060 public function get_url() {
6061 return new moodle_url('/');
6065 * Returns array of relevant context capability records.
6067 * @return array
6069 public function get_capabilities() {
6070 global $DB;
6072 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6074 $params = array();
6075 $sql = "SELECT *
6076 FROM {capabilities}";
6078 return $DB->get_records_sql($sql.' '.$sort, $params);
6082 * Create missing context instances at system context
6083 * @static
6085 protected static function create_level_instances() {
6086 // nothing to do here, the system context is created automatically in installer
6087 self::instance(0);
6091 * Returns system context instance.
6093 * @static
6094 * @param int $instanceid
6095 * @param int $strictness
6096 * @param bool $cache
6097 * @return context_system context instance
6099 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
6100 global $DB;
6102 if ($instanceid != 0) {
6103 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
6106 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
6107 if (!isset(context::$systemcontext)) {
6108 $record = new stdClass();
6109 $record->id = SYSCONTEXTID;
6110 $record->contextlevel = CONTEXT_SYSTEM;
6111 $record->instanceid = 0;
6112 $record->path = '/'.SYSCONTEXTID;
6113 $record->depth = 1;
6114 context::$systemcontext = new context_system($record);
6116 return context::$systemcontext;
6120 try {
6121 // We ignore the strictness completely because system context must exist except during install.
6122 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6123 } catch (dml_exception $e) {
6124 //table or record does not exist
6125 if (!during_initial_install()) {
6126 // do not mess with system context after install, it simply must exist
6127 throw $e;
6129 $record = null;
6132 if (!$record) {
6133 $record = new stdClass();
6134 $record->contextlevel = CONTEXT_SYSTEM;
6135 $record->instanceid = 0;
6136 $record->depth = 1;
6137 $record->path = null; //not known before insert
6139 try {
6140 if ($DB->count_records('context')) {
6141 // contexts already exist, this is very weird, system must be first!!!
6142 return null;
6144 if (defined('SYSCONTEXTID')) {
6145 // this would happen only in unittest on sites that went through weird 1.7 upgrade
6146 $record->id = SYSCONTEXTID;
6147 $DB->import_record('context', $record);
6148 $DB->get_manager()->reset_sequence('context');
6149 } else {
6150 $record->id = $DB->insert_record('context', $record);
6152 } catch (dml_exception $e) {
6153 // can not create context - table does not exist yet, sorry
6154 return null;
6158 if ($record->instanceid != 0) {
6159 // this is very weird, somebody must be messing with context table
6160 debugging('Invalid system context detected');
6163 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6164 // fix path if necessary, initial install or path reset
6165 $record->depth = 1;
6166 $record->path = '/'.$record->id;
6167 $DB->update_record('context', $record);
6170 if (!defined('SYSCONTEXTID')) {
6171 define('SYSCONTEXTID', $record->id);
6174 context::$systemcontext = new context_system($record);
6175 return context::$systemcontext;
6179 * Returns all site contexts except the system context, DO NOT call on production servers!!
6181 * Contexts are not cached.
6183 * @return array
6185 public function get_child_contexts() {
6186 global $DB;
6188 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6190 // Just get all the contexts except for CONTEXT_SYSTEM level
6191 // and hope we don't OOM in the process - don't cache
6192 $sql = "SELECT c.*
6193 FROM {context} c
6194 WHERE contextlevel > ".CONTEXT_SYSTEM;
6195 $records = $DB->get_records_sql($sql);
6197 $result = array();
6198 foreach ($records as $record) {
6199 $result[$record->id] = context::create_instance_from_record($record);
6202 return $result;
6206 * Returns sql necessary for purging of stale context instances.
6208 * @static
6209 * @return string cleanup SQL
6211 protected static function get_cleanup_sql() {
6212 $sql = "
6213 SELECT c.*
6214 FROM {context} c
6215 WHERE 1=2
6218 return $sql;
6222 * Rebuild context paths and depths at system context level.
6224 * @static
6225 * @param bool $force
6227 protected static function build_paths($force) {
6228 global $DB;
6230 /* note: ignore $force here, we always do full test of system context */
6232 // exactly one record must exist
6233 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6235 if ($record->instanceid != 0) {
6236 debugging('Invalid system context detected');
6239 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6240 debugging('Invalid SYSCONTEXTID detected');
6243 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6244 // fix path if necessary, initial install or path reset
6245 $record->depth = 1;
6246 $record->path = '/'.$record->id;
6247 $DB->update_record('context', $record);
6254 * User context class
6256 * @package core_access
6257 * @category access
6258 * @copyright Petr Skoda {@link http://skodak.org}
6259 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6260 * @since 2.2
6262 class context_user extends context {
6264 * Please use context_user::instance($userid) if you need the instance of context.
6265 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6267 * @param stdClass $record
6269 protected function __construct(stdClass $record) {
6270 parent::__construct($record);
6271 if ($record->contextlevel != CONTEXT_USER) {
6272 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6277 * Returns human readable context level name.
6279 * @static
6280 * @return string the human readable context level name.
6282 public static function get_level_name() {
6283 return get_string('user');
6287 * Returns human readable context identifier.
6289 * @param boolean $withprefix whether to prefix the name of the context with User
6290 * @param boolean $short does not apply to user context
6291 * @return string the human readable context name.
6293 public function get_context_name($withprefix = true, $short = false) {
6294 global $DB;
6296 $name = '';
6297 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6298 if ($withprefix){
6299 $name = get_string('user').': ';
6301 $name .= fullname($user);
6303 return $name;
6307 * Returns the most relevant URL for this context.
6309 * @return moodle_url
6311 public function get_url() {
6312 global $COURSE;
6314 if ($COURSE->id == SITEID) {
6315 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6316 } else {
6317 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6319 return $url;
6323 * Returns array of relevant context capability records.
6325 * @return array
6327 public function get_capabilities() {
6328 global $DB;
6330 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6332 $extracaps = array('moodle/grade:viewall');
6333 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6334 $sql = "SELECT *
6335 FROM {capabilities}
6336 WHERE contextlevel = ".CONTEXT_USER."
6337 OR name $extra";
6339 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6343 * Returns user context instance.
6345 * @static
6346 * @param int $instanceid
6347 * @param int $strictness
6348 * @return context_user context instance
6350 public static function instance($instanceid, $strictness = MUST_EXIST) {
6351 global $DB;
6353 if ($context = context::cache_get(CONTEXT_USER, $instanceid)) {
6354 return $context;
6357 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_USER, 'instanceid'=>$instanceid))) {
6358 if ($user = $DB->get_record('user', array('id'=>$instanceid, 'deleted'=>0), 'id', $strictness)) {
6359 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6363 if ($record) {
6364 $context = new context_user($record);
6365 context::cache_add($context);
6366 return $context;
6369 return false;
6373 * Create missing context instances at user context level
6374 * @static
6376 protected static function create_level_instances() {
6377 global $DB;
6379 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6380 SELECT ".CONTEXT_USER.", u.id
6381 FROM {user} u
6382 WHERE u.deleted = 0
6383 AND NOT EXISTS (SELECT 'x'
6384 FROM {context} cx
6385 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6386 $DB->execute($sql);
6390 * Returns sql necessary for purging of stale context instances.
6392 * @static
6393 * @return string cleanup SQL
6395 protected static function get_cleanup_sql() {
6396 $sql = "
6397 SELECT c.*
6398 FROM {context} c
6399 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6400 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6403 return $sql;
6407 * Rebuild context paths and depths at user context level.
6409 * @static
6410 * @param bool $force
6412 protected static function build_paths($force) {
6413 global $DB;
6415 // First update normal users.
6416 $path = $DB->sql_concat('?', 'id');
6417 $pathstart = '/' . SYSCONTEXTID . '/';
6418 $params = array($pathstart);
6420 if ($force) {
6421 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6422 $params[] = $pathstart;
6423 } else {
6424 $where = "depth = 0 OR path IS NULL";
6427 $sql = "UPDATE {context}
6428 SET depth = 2,
6429 path = {$path}
6430 WHERE contextlevel = " . CONTEXT_USER . "
6431 AND ($where)";
6432 $DB->execute($sql, $params);
6438 * Course category context class
6440 * @package core_access
6441 * @category access
6442 * @copyright Petr Skoda {@link http://skodak.org}
6443 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6444 * @since 2.2
6446 class context_coursecat extends context {
6448 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6449 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6451 * @param stdClass $record
6453 protected function __construct(stdClass $record) {
6454 parent::__construct($record);
6455 if ($record->contextlevel != CONTEXT_COURSECAT) {
6456 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6461 * Returns human readable context level name.
6463 * @static
6464 * @return string the human readable context level name.
6466 public static function get_level_name() {
6467 return get_string('category');
6471 * Returns human readable context identifier.
6473 * @param boolean $withprefix whether to prefix the name of the context with Category
6474 * @param boolean $short does not apply to course categories
6475 * @return string the human readable context name.
6477 public function get_context_name($withprefix = true, $short = false) {
6478 global $DB;
6480 $name = '';
6481 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6482 if ($withprefix){
6483 $name = get_string('category').': ';
6485 $name .= format_string($category->name, true, array('context' => $this));
6487 return $name;
6491 * Returns the most relevant URL for this context.
6493 * @return moodle_url
6495 public function get_url() {
6496 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6500 * Returns array of relevant context capability records.
6502 * @return array
6504 public function get_capabilities() {
6505 global $DB;
6507 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6509 $params = array();
6510 $sql = "SELECT *
6511 FROM {capabilities}
6512 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6514 return $DB->get_records_sql($sql.' '.$sort, $params);
6518 * Returns course category context instance.
6520 * @static
6521 * @param int $instanceid
6522 * @param int $strictness
6523 * @return context_coursecat context instance
6525 public static function instance($instanceid, $strictness = MUST_EXIST) {
6526 global $DB;
6528 if ($context = context::cache_get(CONTEXT_COURSECAT, $instanceid)) {
6529 return $context;
6532 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSECAT, 'instanceid'=>$instanceid))) {
6533 if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), 'id,parent', $strictness)) {
6534 if ($category->parent) {
6535 $parentcontext = context_coursecat::instance($category->parent);
6536 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6537 } else {
6538 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6543 if ($record) {
6544 $context = new context_coursecat($record);
6545 context::cache_add($context);
6546 return $context;
6549 return false;
6553 * Returns immediate child contexts of category and all subcategories,
6554 * children of subcategories and courses are not returned.
6556 * @return array
6558 public function get_child_contexts() {
6559 global $DB;
6561 $sql = "SELECT ctx.*
6562 FROM {context} ctx
6563 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6564 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6565 $records = $DB->get_records_sql($sql, $params);
6567 $result = array();
6568 foreach ($records as $record) {
6569 $result[$record->id] = context::create_instance_from_record($record);
6572 return $result;
6576 * Create missing context instances at course category context level
6577 * @static
6579 protected static function create_level_instances() {
6580 global $DB;
6582 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6583 SELECT ".CONTEXT_COURSECAT.", cc.id
6584 FROM {course_categories} cc
6585 WHERE NOT EXISTS (SELECT 'x'
6586 FROM {context} cx
6587 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6588 $DB->execute($sql);
6592 * Returns sql necessary for purging of stale context instances.
6594 * @static
6595 * @return string cleanup SQL
6597 protected static function get_cleanup_sql() {
6598 $sql = "
6599 SELECT c.*
6600 FROM {context} c
6601 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6602 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6605 return $sql;
6609 * Rebuild context paths and depths at course category context level.
6611 * @static
6612 * @param bool $force
6614 protected static function build_paths($force) {
6615 global $DB;
6617 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6618 if ($force) {
6619 $ctxemptyclause = $emptyclause = '';
6620 } else {
6621 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6622 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6625 $base = '/'.SYSCONTEXTID;
6627 // Normal top level categories
6628 $sql = "UPDATE {context}
6629 SET depth=2,
6630 path=".$DB->sql_concat("'$base/'", 'id')."
6631 WHERE contextlevel=".CONTEXT_COURSECAT."
6632 AND EXISTS (SELECT 'x'
6633 FROM {course_categories} cc
6634 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6635 $emptyclause";
6636 $DB->execute($sql);
6638 // Deeper categories - one query per depthlevel
6639 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6640 for ($n=2; $n<=$maxdepth; $n++) {
6641 $sql = "INSERT INTO {context_temp} (id, path, depth)
6642 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6643 FROM {context} ctx
6644 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6645 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6646 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6647 $ctxemptyclause";
6648 $trans = $DB->start_delegated_transaction();
6649 $DB->delete_records('context_temp');
6650 $DB->execute($sql);
6651 context::merge_context_temp_table();
6652 $DB->delete_records('context_temp');
6653 $trans->allow_commit();
6662 * Course context class
6664 * @package core_access
6665 * @category access
6666 * @copyright Petr Skoda {@link http://skodak.org}
6667 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6668 * @since 2.2
6670 class context_course extends context {
6672 * Please use context_course::instance($courseid) if you need the instance of context.
6673 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6675 * @param stdClass $record
6677 protected function __construct(stdClass $record) {
6678 parent::__construct($record);
6679 if ($record->contextlevel != CONTEXT_COURSE) {
6680 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6685 * Returns human readable context level name.
6687 * @static
6688 * @return string the human readable context level name.
6690 public static function get_level_name() {
6691 return get_string('course');
6695 * Returns human readable context identifier.
6697 * @param boolean $withprefix whether to prefix the name of the context with Course
6698 * @param boolean $short whether to use the short name of the thing.
6699 * @return string the human readable context name.
6701 public function get_context_name($withprefix = true, $short = false) {
6702 global $DB;
6704 $name = '';
6705 if ($this->_instanceid == SITEID) {
6706 $name = get_string('frontpage', 'admin');
6707 } else {
6708 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6709 if ($withprefix){
6710 $name = get_string('course').': ';
6712 if ($short){
6713 $name .= format_string($course->shortname, true, array('context' => $this));
6714 } else {
6715 $name .= format_string(get_course_display_name_for_list($course));
6719 return $name;
6723 * Returns the most relevant URL for this context.
6725 * @return moodle_url
6727 public function get_url() {
6728 if ($this->_instanceid != SITEID) {
6729 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6732 return new moodle_url('/');
6736 * Returns array of relevant context capability records.
6738 * @return array
6740 public function get_capabilities() {
6741 global $DB;
6743 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6745 $params = array();
6746 $sql = "SELECT *
6747 FROM {capabilities}
6748 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6750 return $DB->get_records_sql($sql.' '.$sort, $params);
6754 * Is this context part of any course? If yes return course context.
6756 * @param bool $strict true means throw exception if not found, false means return false if not found
6757 * @return course_context context of the enclosing course, null if not found or exception
6759 public function get_course_context($strict = true) {
6760 return $this;
6764 * Returns course context instance.
6766 * @static
6767 * @param int $instanceid
6768 * @param int $strictness
6769 * @return context_course context instance
6771 public static function instance($instanceid, $strictness = MUST_EXIST) {
6772 global $DB;
6774 if ($context = context::cache_get(CONTEXT_COURSE, $instanceid)) {
6775 return $context;
6778 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$instanceid))) {
6779 if ($course = $DB->get_record('course', array('id'=>$instanceid), 'id,category', $strictness)) {
6780 if ($course->category) {
6781 $parentcontext = context_coursecat::instance($course->category);
6782 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6783 } else {
6784 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6789 if ($record) {
6790 $context = new context_course($record);
6791 context::cache_add($context);
6792 return $context;
6795 return false;
6799 * Create missing context instances at course context level
6800 * @static
6802 protected static function create_level_instances() {
6803 global $DB;
6805 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6806 SELECT ".CONTEXT_COURSE.", c.id
6807 FROM {course} c
6808 WHERE NOT EXISTS (SELECT 'x'
6809 FROM {context} cx
6810 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6811 $DB->execute($sql);
6815 * Returns sql necessary for purging of stale context instances.
6817 * @static
6818 * @return string cleanup SQL
6820 protected static function get_cleanup_sql() {
6821 $sql = "
6822 SELECT c.*
6823 FROM {context} c
6824 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6825 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6828 return $sql;
6832 * Rebuild context paths and depths at course context level.
6834 * @static
6835 * @param bool $force
6837 protected static function build_paths($force) {
6838 global $DB;
6840 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6841 if ($force) {
6842 $ctxemptyclause = $emptyclause = '';
6843 } else {
6844 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6845 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6848 $base = '/'.SYSCONTEXTID;
6850 // Standard frontpage
6851 $sql = "UPDATE {context}
6852 SET depth = 2,
6853 path = ".$DB->sql_concat("'$base/'", 'id')."
6854 WHERE contextlevel = ".CONTEXT_COURSE."
6855 AND EXISTS (SELECT 'x'
6856 FROM {course} c
6857 WHERE c.id = {context}.instanceid AND c.category = 0)
6858 $emptyclause";
6859 $DB->execute($sql);
6861 // standard courses
6862 $sql = "INSERT INTO {context_temp} (id, path, depth)
6863 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6864 FROM {context} ctx
6865 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6866 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6867 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6868 $ctxemptyclause";
6869 $trans = $DB->start_delegated_transaction();
6870 $DB->delete_records('context_temp');
6871 $DB->execute($sql);
6872 context::merge_context_temp_table();
6873 $DB->delete_records('context_temp');
6874 $trans->allow_commit();
6881 * Course module context class
6883 * @package core_access
6884 * @category access
6885 * @copyright Petr Skoda {@link http://skodak.org}
6886 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6887 * @since 2.2
6889 class context_module extends context {
6891 * Please use context_module::instance($cmid) if you need the instance of context.
6892 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6894 * @param stdClass $record
6896 protected function __construct(stdClass $record) {
6897 parent::__construct($record);
6898 if ($record->contextlevel != CONTEXT_MODULE) {
6899 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6904 * Returns human readable context level name.
6906 * @static
6907 * @return string the human readable context level name.
6909 public static function get_level_name() {
6910 return get_string('activitymodule');
6914 * Returns human readable context identifier.
6916 * @param boolean $withprefix whether to prefix the name of the context with the
6917 * module name, e.g. Forum, Glossary, etc.
6918 * @param boolean $short does not apply to module context
6919 * @return string the human readable context name.
6921 public function get_context_name($withprefix = true, $short = false) {
6922 global $DB;
6924 $name = '';
6925 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6926 FROM {course_modules} cm
6927 JOIN {modules} md ON md.id = cm.module
6928 WHERE cm.id = ?", array($this->_instanceid))) {
6929 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6930 if ($withprefix){
6931 $name = get_string('modulename', $cm->modname).': ';
6933 $name .= format_string($mod->name, true, array('context' => $this));
6936 return $name;
6940 * Returns the most relevant URL for this context.
6942 * @return moodle_url
6944 public function get_url() {
6945 global $DB;
6947 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6948 FROM {course_modules} cm
6949 JOIN {modules} md ON md.id = cm.module
6950 WHERE cm.id = ?", array($this->_instanceid))) {
6951 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6954 return new moodle_url('/');
6958 * Returns array of relevant context capability records.
6960 * @return array
6962 public function get_capabilities() {
6963 global $DB, $CFG;
6965 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6967 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6968 $module = $DB->get_record('modules', array('id'=>$cm->module));
6970 $subcaps = array();
6971 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6972 if (file_exists($subpluginsfile)) {
6973 $subplugins = array(); // should be redefined in the file
6974 include($subpluginsfile);
6975 if (!empty($subplugins)) {
6976 foreach (array_keys($subplugins) as $subplugintype) {
6977 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
6978 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6984 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6985 $extracaps = array();
6986 if (file_exists($modfile)) {
6987 include_once($modfile);
6988 $modfunction = $module->name.'_get_extra_capabilities';
6989 if (function_exists($modfunction)) {
6990 $extracaps = $modfunction();
6994 $extracaps = array_merge($subcaps, $extracaps);
6995 $extra = '';
6996 list($extra, $params) = $DB->get_in_or_equal(
6997 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
6998 if (!empty($extra)) {
6999 $extra = "OR name $extra";
7001 $sql = "SELECT *
7002 FROM {capabilities}
7003 WHERE (contextlevel = ".CONTEXT_MODULE."
7004 AND (component = :component OR component = 'moodle'))
7005 $extra";
7006 $params['component'] = "mod_$module->name";
7008 return $DB->get_records_sql($sql.' '.$sort, $params);
7012 * Is this context part of any course? If yes return course context.
7014 * @param bool $strict true means throw exception if not found, false means return false if not found
7015 * @return context_course context of the enclosing course, null if not found or exception
7017 public function get_course_context($strict = true) {
7018 return $this->get_parent_context();
7022 * Returns module context instance.
7024 * @static
7025 * @param int $instanceid
7026 * @param int $strictness
7027 * @return context_module context instance
7029 public static function instance($instanceid, $strictness = MUST_EXIST) {
7030 global $DB;
7032 if ($context = context::cache_get(CONTEXT_MODULE, $instanceid)) {
7033 return $context;
7036 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$instanceid))) {
7037 if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), 'id,course', $strictness)) {
7038 $parentcontext = context_course::instance($cm->course);
7039 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
7043 if ($record) {
7044 $context = new context_module($record);
7045 context::cache_add($context);
7046 return $context;
7049 return false;
7053 * Create missing context instances at module context level
7054 * @static
7056 protected static function create_level_instances() {
7057 global $DB;
7059 $sql = "INSERT INTO {context} (contextlevel, instanceid)
7060 SELECT ".CONTEXT_MODULE.", cm.id
7061 FROM {course_modules} cm
7062 WHERE NOT EXISTS (SELECT 'x'
7063 FROM {context} cx
7064 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
7065 $DB->execute($sql);
7069 * Returns sql necessary for purging of stale context instances.
7071 * @static
7072 * @return string cleanup SQL
7074 protected static function get_cleanup_sql() {
7075 $sql = "
7076 SELECT c.*
7077 FROM {context} c
7078 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
7079 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
7082 return $sql;
7086 * Rebuild context paths and depths at module context level.
7088 * @static
7089 * @param bool $force
7091 protected static function build_paths($force) {
7092 global $DB;
7094 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
7095 if ($force) {
7096 $ctxemptyclause = '';
7097 } else {
7098 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7101 $sql = "INSERT INTO {context_temp} (id, path, depth)
7102 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7103 FROM {context} ctx
7104 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
7105 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
7106 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7107 $ctxemptyclause";
7108 $trans = $DB->start_delegated_transaction();
7109 $DB->delete_records('context_temp');
7110 $DB->execute($sql);
7111 context::merge_context_temp_table();
7112 $DB->delete_records('context_temp');
7113 $trans->allow_commit();
7120 * Block context class
7122 * @package core_access
7123 * @category access
7124 * @copyright Petr Skoda {@link http://skodak.org}
7125 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7126 * @since 2.2
7128 class context_block extends context {
7130 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
7131 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7133 * @param stdClass $record
7135 protected function __construct(stdClass $record) {
7136 parent::__construct($record);
7137 if ($record->contextlevel != CONTEXT_BLOCK) {
7138 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
7143 * Returns human readable context level name.
7145 * @static
7146 * @return string the human readable context level name.
7148 public static function get_level_name() {
7149 return get_string('block');
7153 * Returns human readable context identifier.
7155 * @param boolean $withprefix whether to prefix the name of the context with Block
7156 * @param boolean $short does not apply to block context
7157 * @return string the human readable context name.
7159 public function get_context_name($withprefix = true, $short = false) {
7160 global $DB, $CFG;
7162 $name = '';
7163 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
7164 global $CFG;
7165 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7166 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7167 $blockname = "block_$blockinstance->blockname";
7168 if ($blockobject = new $blockname()) {
7169 if ($withprefix){
7170 $name = get_string('block').': ';
7172 $name .= $blockobject->title;
7176 return $name;
7180 * Returns the most relevant URL for this context.
7182 * @return moodle_url
7184 public function get_url() {
7185 $parentcontexts = $this->get_parent_context();
7186 return $parentcontexts->get_url();
7190 * Returns array of relevant context capability records.
7192 * @return array
7194 public function get_capabilities() {
7195 global $DB;
7197 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7199 $params = array();
7200 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
7202 $extra = '';
7203 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7204 if ($extracaps) {
7205 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7206 $extra = "OR name $extra";
7209 $sql = "SELECT *
7210 FROM {capabilities}
7211 WHERE (contextlevel = ".CONTEXT_BLOCK."
7212 AND component = :component)
7213 $extra";
7214 $params['component'] = 'block_' . $bi->blockname;
7216 return $DB->get_records_sql($sql.' '.$sort, $params);
7220 * Is this context part of any course? If yes return course context.
7222 * @param bool $strict true means throw exception if not found, false means return false if not found
7223 * @return course_context context of the enclosing course, null if not found or exception
7225 public function get_course_context($strict = true) {
7226 $parentcontext = $this->get_parent_context();
7227 return $parentcontext->get_course_context($strict);
7231 * Returns block context instance.
7233 * @static
7234 * @param int $instanceid
7235 * @param int $strictness
7236 * @return context_block context instance
7238 public static function instance($instanceid, $strictness = MUST_EXIST) {
7239 global $DB;
7241 if ($context = context::cache_get(CONTEXT_BLOCK, $instanceid)) {
7242 return $context;
7245 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$instanceid))) {
7246 if ($bi = $DB->get_record('block_instances', array('id'=>$instanceid), 'id,parentcontextid', $strictness)) {
7247 $parentcontext = context::instance_by_id($bi->parentcontextid);
7248 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7252 if ($record) {
7253 $context = new context_block($record);
7254 context::cache_add($context);
7255 return $context;
7258 return false;
7262 * Block do not have child contexts...
7263 * @return array
7265 public function get_child_contexts() {
7266 return array();
7270 * Create missing context instances at block context level
7271 * @static
7273 protected static function create_level_instances() {
7274 global $DB;
7276 $sql = "INSERT INTO {context} (contextlevel, instanceid)
7277 SELECT ".CONTEXT_BLOCK.", bi.id
7278 FROM {block_instances} bi
7279 WHERE NOT EXISTS (SELECT 'x'
7280 FROM {context} cx
7281 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7282 $DB->execute($sql);
7286 * Returns sql necessary for purging of stale context instances.
7288 * @static
7289 * @return string cleanup SQL
7291 protected static function get_cleanup_sql() {
7292 $sql = "
7293 SELECT c.*
7294 FROM {context} c
7295 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7296 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7299 return $sql;
7303 * Rebuild context paths and depths at block context level.
7305 * @static
7306 * @param bool $force
7308 protected static function build_paths($force) {
7309 global $DB;
7311 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7312 if ($force) {
7313 $ctxemptyclause = '';
7314 } else {
7315 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7318 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7319 $sql = "INSERT INTO {context_temp} (id, path, depth)
7320 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7321 FROM {context} ctx
7322 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7323 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7324 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7325 $ctxemptyclause";
7326 $trans = $DB->start_delegated_transaction();
7327 $DB->delete_records('context_temp');
7328 $DB->execute($sql);
7329 context::merge_context_temp_table();
7330 $DB->delete_records('context_temp');
7331 $trans->allow_commit();
7337 // ============== DEPRECATED FUNCTIONS ==========================================
7338 // Old context related functions were deprecated in 2.0, it is recommended
7339 // to use context classes in new code. Old function can be used when
7340 // creating patches that are supposed to be backported to older stable branches.
7341 // These deprecated functions will not be removed in near future,
7342 // before removing devs will be warned with a debugging message first,
7343 // then we will add error message and only after that we can remove the functions
7344 // completely.
7347 * Runs get_records select on context table and returns the result
7348 * Does get_records_select on the context table, and returns the results ordered
7349 * by contextlevel, and then the natural sort order within each level.
7350 * for the purpose of $select, you need to know that the context table has been
7351 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7353 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7354 * @param array $params any parameters required by $select.
7355 * @return array the requested context records.
7357 function get_sorted_contexts($select, $params = array()) {
7359 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7361 global $DB;
7362 if ($select) {
7363 $select = 'WHERE ' . $select;
7365 return $DB->get_records_sql("
7366 SELECT ctx.*
7367 FROM {context} ctx
7368 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7369 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7370 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7371 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7372 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7373 $select
7374 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7375 ", $params);
7379 * Given context and array of users, returns array of users whose enrolment status is suspended,
7380 * or enrolment has expired or has not started. Also removes those users from the given array
7382 * @param context $context context in which suspended users should be extracted.
7383 * @param array $users list of users.
7384 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7385 * @return array list of suspended users.
7387 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7388 global $DB;
7390 // Get active enrolled users.
7391 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7392 $activeusers = $DB->get_records_sql($sql, $params);
7394 // Move suspended users to a separate array & remove from the initial one.
7395 $susers = array();
7396 if (sizeof($activeusers)) {
7397 foreach ($users as $userid => $user) {
7398 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7399 $susers[$userid] = $user;
7400 unset($users[$userid]);
7404 return $susers;
7408 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7409 * or enrolment has expired or not started.
7411 * @param context $context context in which user enrolment is checked.
7412 * @return array list of suspended user id's.
7414 function get_suspended_userids($context){
7415 global $DB;
7417 // Get all enrolled users.
7418 list($sql, $params) = get_enrolled_sql($context);
7419 $users = $DB->get_records_sql($sql, $params);
7421 // Get active enrolled users.
7422 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7423 $activeusers = $DB->get_records_sql($sql, $params);
7425 $susers = array();
7426 if (sizeof($activeusers) != sizeof($users)) {
7427 foreach ($users as $userid => $user) {
7428 if (!array_key_exists($userid, $activeusers)) {
7429 $susers[$userid] = $userid;
7433 return $susers;