MDL-51172 core_files: Using an invented file format
[moodle.git] / lib / accesslib.php
blobdfd3341d607f3dc5992a550b7131d17ddd074960
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
208 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
210 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
211 * accesslib's private caches. You need to do this before setting up test data,
212 * and also at the end of the tests.
214 * @access private
215 * @return void
217 function accesslib_clear_all_caches_for_unit_testing() {
218 global $USER;
219 if (!PHPUNIT_TEST) {
220 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
223 accesslib_clear_all_caches(true);
225 unset($USER->access);
229 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
231 * This reset does not touch global $USER.
233 * @access private
234 * @param bool $resetcontexts
235 * @return void
237 function accesslib_clear_all_caches($resetcontexts) {
238 global $ACCESSLIB_PRIVATE;
240 $ACCESSLIB_PRIVATE->dirtycontexts = null;
241 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
242 $ACCESSLIB_PRIVATE->rolepermissions = array();
244 if ($resetcontexts) {
245 context_helper::reset_caches();
250 * Gets the accessdata for role "sitewide" (system down to course)
252 * @access private
253 * @param int $roleid
254 * @return array
256 function get_role_access($roleid) {
257 global $DB, $ACCESSLIB_PRIVATE;
259 /* Get it in 1 DB query...
260 * - relevant role caps at the root and down
261 * to the course level - but not below
264 //TODO: MUC - this could be cached in shared memory to speed up first page loading, web crawlers, etc.
266 $accessdata = get_empty_accessdata();
268 $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
270 // Overrides for the role IN ANY CONTEXTS down to COURSE - not below -.
273 $sql = "SELECT ctx.path,
274 rc.capability, rc.permission
275 FROM {context} ctx
276 JOIN {role_capabilities} rc ON rc.contextid = ctx.id
277 LEFT JOIN {context} cctx
278 ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
279 WHERE rc.roleid = ? AND cctx.id IS NULL";
280 $params = array($roleid);
283 // Note: the commented out query is 100% accurate but slow, so let's cheat instead by hardcoding the blocks mess directly.
285 $sql = "SELECT COALESCE(ctx.path, bctx.path) AS path, rc.capability, rc.permission
286 FROM {role_capabilities} rc
287 LEFT JOIN {context} ctx ON (ctx.id = rc.contextid AND ctx.contextlevel <= ".CONTEXT_COURSE.")
288 LEFT JOIN ({context} bctx
289 JOIN {block_instances} bi ON (bi.id = bctx.instanceid)
290 JOIN {context} pctx ON (pctx.id = bi.parentcontextid AND pctx.contextlevel < ".CONTEXT_COURSE.")
291 ) ON (bctx.id = rc.contextid AND bctx.contextlevel = ".CONTEXT_BLOCK.")
292 WHERE rc.roleid = :roleid AND (ctx.id IS NOT NULL OR bctx.id IS NOT NULL)";
293 $params = array('roleid'=>$roleid);
295 // we need extra caching in CLI scripts and cron
296 $rs = $DB->get_recordset_sql($sql, $params);
297 foreach ($rs as $rd) {
298 $k = "{$rd->path}:{$roleid}";
299 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
301 $rs->close();
303 // share the role definitions
304 foreach ($accessdata['rdef'] as $k=>$unused) {
305 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
306 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
308 $accessdata['rdef_count']++;
309 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
312 return $accessdata;
316 * Get the default guest role, this is used for guest account,
317 * search engine spiders, etc.
319 * @return stdClass role record
321 function get_guest_role() {
322 global $CFG, $DB;
324 if (empty($CFG->guestroleid)) {
325 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
326 $guestrole = array_shift($roles); // Pick the first one
327 set_config('guestroleid', $guestrole->id);
328 return $guestrole;
329 } else {
330 debugging('Can not find any guest role!');
331 return false;
333 } else {
334 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
335 return $guestrole;
336 } else {
337 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
338 set_config('guestroleid', '');
339 return get_guest_role();
345 * Check whether a user has a particular capability in a given context.
347 * For example:
348 * $context = context_module::instance($cm->id);
349 * has_capability('mod/forum:replypost', $context)
351 * By default checks the capabilities of the current user, but you can pass a
352 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
354 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
355 * or capabilities with XSS, config or data loss risks.
357 * @category access
359 * @param string $capability the name of the capability to check. For example mod/forum:view
360 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
361 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
362 * @param boolean $doanything If false, ignores effect of admin role assignment
363 * @return boolean true if the user has this capability. Otherwise false.
365 function has_capability($capability, context $context, $user = null, $doanything = true) {
366 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
368 if (during_initial_install()) {
369 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cli/install.php" or $SCRIPT === "/$CFG->admin/cli/install_database.php") {
370 // we are in an installer - roles can not work yet
371 return true;
372 } else {
373 return false;
377 if (strpos($capability, 'moodle/legacy:') === 0) {
378 throw new coding_exception('Legacy capabilities can not be used any more!');
381 if (!is_bool($doanything)) {
382 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
385 // capability must exist
386 if (!$capinfo = get_capability_info($capability)) {
387 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
388 return false;
391 if (!isset($USER->id)) {
392 // should never happen
393 $USER->id = 0;
394 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER);
397 // make sure there is a real user specified
398 if ($user === null) {
399 $userid = $USER->id;
400 } else {
401 $userid = is_object($user) ? $user->id : $user;
404 // make sure forcelogin cuts off not-logged-in users if enabled
405 if (!empty($CFG->forcelogin) and $userid == 0) {
406 return false;
409 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
410 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
411 if (isguestuser($userid) or $userid == 0) {
412 return false;
416 // somehow make sure the user is not deleted and actually exists
417 if ($userid != 0) {
418 if ($userid == $USER->id and isset($USER->deleted)) {
419 // this prevents one query per page, it is a bit of cheating,
420 // but hopefully session is terminated properly once user is deleted
421 if ($USER->deleted) {
422 return false;
424 } else {
425 if (!context_user::instance($userid, IGNORE_MISSING)) {
426 // no user context == invalid userid
427 return false;
432 // context path/depth must be valid
433 if (empty($context->path) or $context->depth == 0) {
434 // this should not happen often, each upgrade tries to rebuild the context paths
435 debugging('Context id '.$context->id.' does not have valid path, please use context_helper::build_all_paths()');
436 if (is_siteadmin($userid)) {
437 return true;
438 } else {
439 return false;
443 // Find out if user is admin - it is not possible to override the doanything in any way
444 // and it is not possible to switch to admin role either.
445 if ($doanything) {
446 if (is_siteadmin($userid)) {
447 if ($userid != $USER->id) {
448 return true;
450 // make sure switchrole is not used in this context
451 if (empty($USER->access['rsw'])) {
452 return true;
454 $parts = explode('/', trim($context->path, '/'));
455 $path = '';
456 $switched = false;
457 foreach ($parts as $part) {
458 $path .= '/' . $part;
459 if (!empty($USER->access['rsw'][$path])) {
460 $switched = true;
461 break;
464 if (!$switched) {
465 return true;
467 //ok, admin switched role in this context, let's use normal access control rules
471 // Careful check for staleness...
472 $context->reload_if_dirty();
474 if ($USER->id == $userid) {
475 if (!isset($USER->access)) {
476 load_all_capabilities();
478 $access =& $USER->access;
480 } else {
481 // make sure user accessdata is really loaded
482 get_user_accessdata($userid, true);
483 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
487 // Load accessdata for below-the-course context if necessary,
488 // all contexts at and above all courses are already loaded
489 if ($context->contextlevel != CONTEXT_COURSE and $coursecontext = $context->get_course_context(false)) {
490 load_course_context($userid, $coursecontext, $access);
493 return has_capability_in_accessdata($capability, $context, $access);
497 * Check if the user has any one of several capabilities from a list.
499 * This is just a utility method that calls has_capability in a loop. Try to put
500 * the capabilities that most users are likely to have first in the list for best
501 * performance.
503 * @category access
504 * @see has_capability()
506 * @param array $capabilities an array of capability names.
507 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
508 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
509 * @param boolean $doanything If false, ignore effect of admin role assignment
510 * @return boolean true if the user has any of these capabilities. Otherwise false.
512 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
513 foreach ($capabilities as $capability) {
514 if (has_capability($capability, $context, $user, $doanything)) {
515 return true;
518 return false;
522 * Check if the user has all the capabilities in a list.
524 * This is just a utility method that calls has_capability in a loop. Try to put
525 * the capabilities that fewest users are likely to have first in the list for best
526 * performance.
528 * @category access
529 * @see has_capability()
531 * @param array $capabilities an array of capability names.
532 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
533 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
534 * @param boolean $doanything If false, ignore effect of admin role assignment
535 * @return boolean true if the user has all of these capabilities. Otherwise false.
537 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
538 foreach ($capabilities as $capability) {
539 if (!has_capability($capability, $context, $user, $doanything)) {
540 return false;
543 return true;
547 * Is course creator going to have capability in a new course?
549 * This is intended to be used in enrolment plugins before or during course creation,
550 * do not use after the course is fully created.
552 * @category access
554 * @param string $capability the name of the capability to check.
555 * @param context $context course or category context where is course going to be created
556 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
557 * @return boolean true if the user will have this capability.
559 * @throws coding_exception if different type of context submitted
561 function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) {
562 global $CFG;
564 if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) {
565 throw new coding_exception('Only course or course category context expected');
568 if (has_capability($capability, $context, $user)) {
569 // User already has the capability, it could be only removed if CAP_PROHIBIT
570 // was involved here, but we ignore that.
571 return true;
574 if (!has_capability('moodle/course:create', $context, $user)) {
575 return false;
578 if (!enrol_is_enabled('manual')) {
579 return false;
582 if (empty($CFG->creatornewroleid)) {
583 return false;
586 if ($context->contextlevel == CONTEXT_COURSE) {
587 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
588 return false;
590 } else {
591 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
592 return false;
596 // Most likely they will be enrolled after the course creation is finished,
597 // does the new role have the required capability?
598 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
599 return isset($neededroles[$CFG->creatornewroleid]);
603 * Check if the user is an admin at the site level.
605 * Please note that use of proper capabilities is always encouraged,
606 * this function is supposed to be used from core or for temporary hacks.
608 * @category access
610 * @param int|stdClass $user_or_id user id or user object
611 * @return bool true if user is one of the administrators, false otherwise
613 function is_siteadmin($user_or_id = null) {
614 global $CFG, $USER;
616 if ($user_or_id === null) {
617 $user_or_id = $USER;
620 if (empty($user_or_id)) {
621 return false;
623 if (!empty($user_or_id->id)) {
624 $userid = $user_or_id->id;
625 } else {
626 $userid = $user_or_id;
629 // Because this script is called many times (150+ for course page) with
630 // the same parameters, it is worth doing minor optimisations. This static
631 // cache stores the value for a single userid, saving about 2ms from course
632 // page load time without using significant memory. As the static cache
633 // also includes the value it depends on, this cannot break unit tests.
634 static $knownid, $knownresult, $knownsiteadmins;
635 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
636 return $knownresult;
638 $knownid = $userid;
639 $knownsiteadmins = $CFG->siteadmins;
641 $siteadmins = explode(',', $CFG->siteadmins);
642 $knownresult = in_array($userid, $siteadmins);
643 return $knownresult;
647 * Returns true if user has at least one role assign
648 * of 'coursecontact' role (is potentially listed in some course descriptions).
650 * @param int $userid
651 * @return bool
653 function has_coursecontact_role($userid) {
654 global $DB, $CFG;
656 if (empty($CFG->coursecontact)) {
657 return false;
659 $sql = "SELECT 1
660 FROM {role_assignments}
661 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
662 return $DB->record_exists_sql($sql, array('userid'=>$userid));
666 * Does the user have a capability to do something?
668 * Walk the accessdata array and return true/false.
669 * Deals with prohibits, role switching, aggregating
670 * capabilities, etc.
672 * The main feature of here is being FAST and with no
673 * side effects.
675 * Notes:
677 * Switch Role merges with default role
678 * ------------------------------------
679 * If you are a teacher in course X, you have at least
680 * teacher-in-X + defaultloggedinuser-sitewide. So in the
681 * course you'll have techer+defaultloggedinuser.
682 * We try to mimic that in switchrole.
684 * Permission evaluation
685 * ---------------------
686 * Originally there was an extremely complicated way
687 * to determine the user access that dealt with
688 * "locality" or role assignments and role overrides.
689 * Now we simply evaluate access for each role separately
690 * and then verify if user has at least one role with allow
691 * and at the same time no role with prohibit.
693 * @access private
694 * @param string $capability
695 * @param context $context
696 * @param array $accessdata
697 * @return bool
699 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
700 global $CFG;
702 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
703 $path = $context->path;
704 $paths = array($path);
705 while($path = rtrim($path, '0123456789')) {
706 $path = rtrim($path, '/');
707 if ($path === '') {
708 break;
710 $paths[] = $path;
713 $roles = array();
714 $switchedrole = false;
716 // Find out if role switched
717 if (!empty($accessdata['rsw'])) {
718 // From the bottom up...
719 foreach ($paths as $path) {
720 if (isset($accessdata['rsw'][$path])) {
721 // Found a switchrole assignment - check for that role _plus_ the default user role
722 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
723 $switchedrole = true;
724 break;
729 if (!$switchedrole) {
730 // get all users roles in this context and above
731 foreach ($paths as $path) {
732 if (isset($accessdata['ra'][$path])) {
733 foreach ($accessdata['ra'][$path] as $roleid) {
734 $roles[$roleid] = null;
740 // Now find out what access is given to each role, going bottom-->up direction
741 $allowed = false;
742 foreach ($roles as $roleid => $ignored) {
743 foreach ($paths as $path) {
744 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
745 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
746 if ($perm === CAP_PROHIBIT) {
747 // any CAP_PROHIBIT found means no permission for the user
748 return false;
750 if (is_null($roles[$roleid])) {
751 $roles[$roleid] = $perm;
755 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
756 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
759 return $allowed;
763 * A convenience function that tests has_capability, and displays an error if
764 * the user does not have that capability.
766 * NOTE before Moodle 2.0, this function attempted to make an appropriate
767 * require_login call before checking the capability. This is no longer the case.
768 * You must call require_login (or one of its variants) if you want to check the
769 * user is logged in, before you call this function.
771 * @see has_capability()
773 * @param string $capability the name of the capability to check. For example mod/forum:view
774 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
775 * @param int $userid A user id. By default (null) checks the permissions of the current user.
776 * @param bool $doanything If false, ignore effect of admin role assignment
777 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
778 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
779 * @return void terminates with an error if the user does not have the given capability.
781 function require_capability($capability, context $context, $userid = null, $doanything = true,
782 $errormessage = 'nopermissions', $stringfile = '') {
783 if (!has_capability($capability, $context, $userid, $doanything)) {
784 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
789 * Return a nested array showing role assignments
790 * all relevant role capabilities for the user at
791 * site/course_category/course levels
793 * We do _not_ delve deeper than courses because the number of
794 * overrides at the module/block levels can be HUGE.
796 * [ra] => [/path][roleid]=roleid
797 * [rdef] => [/path:roleid][capability]=permission
799 * @access private
800 * @param int $userid - the id of the user
801 * @return array access info array
803 function get_user_access_sitewide($userid) {
804 global $CFG, $DB, $ACCESSLIB_PRIVATE;
806 /* Get in a few cheap DB queries...
807 * - role assignments
808 * - relevant role caps
809 * - above and within this user's RAs
810 * - below this user's RAs - limited to course level
813 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
814 $raparents = array();
815 $accessdata = get_empty_accessdata();
817 // start with the default role
818 if (!empty($CFG->defaultuserroleid)) {
819 $syscontext = context_system::instance();
820 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
821 $raparents[$CFG->defaultuserroleid][$syscontext->id] = $syscontext->id;
824 // load the "default frontpage role"
825 if (!empty($CFG->defaultfrontpageroleid)) {
826 $frontpagecontext = context_course::instance(get_site()->id);
827 if ($frontpagecontext->path) {
828 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
829 $raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->id] = $frontpagecontext->id;
833 // preload every assigned role at and above course context
834 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
835 FROM {role_assignments} ra
836 JOIN {context} ctx
837 ON ctx.id = ra.contextid
838 LEFT JOIN {block_instances} bi
839 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
840 LEFT JOIN {context} bpctx
841 ON (bpctx.id = bi.parentcontextid)
842 WHERE ra.userid = :userid
843 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")";
844 $params = array('userid'=>$userid);
845 $rs = $DB->get_recordset_sql($sql, $params);
846 foreach ($rs as $ra) {
847 // RAs leafs are arrays to support multi-role assignments...
848 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
849 $raparents[$ra->roleid][$ra->contextid] = $ra->contextid;
851 $rs->close();
853 if (empty($raparents)) {
854 return $accessdata;
857 // now get overrides of interesting roles in all interesting child contexts
858 // hopefully we will not run out of SQL limits here,
859 // users would have to have very many roles at/above course context...
860 $sqls = array();
861 $params = array();
863 static $cp = 0;
864 foreach ($raparents as $roleid=>$ras) {
865 $cp++;
866 list($sqlcids, $cids) = $DB->get_in_or_equal($ras, SQL_PARAMS_NAMED, 'c'.$cp.'_');
867 $params = array_merge($params, $cids);
868 $params['r'.$cp] = $roleid;
869 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
870 FROM {role_capabilities} rc
871 JOIN {context} ctx
872 ON (ctx.id = rc.contextid)
873 JOIN {context} pctx
874 ON (pctx.id $sqlcids
875 AND (ctx.id = pctx.id
876 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
877 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
878 LEFT JOIN {block_instances} bi
879 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
880 LEFT JOIN {context} bpctx
881 ON (bpctx.id = bi.parentcontextid)
882 WHERE rc.roleid = :r{$cp}
883 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")
887 // fixed capability order is necessary for rdef dedupe
888 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
890 foreach ($rs as $rd) {
891 $k = $rd->path.':'.$rd->roleid;
892 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
894 $rs->close();
896 // share the role definitions
897 foreach ($accessdata['rdef'] as $k=>$unused) {
898 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
899 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
901 $accessdata['rdef_count']++;
902 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
905 return $accessdata;
909 * Add to the access ctrl array the data needed by a user for a given course.
911 * This function injects all course related access info into the accessdata array.
913 * @access private
914 * @param int $userid the id of the user
915 * @param context_course $coursecontext course context
916 * @param array $accessdata accessdata array (modified)
917 * @return void modifies $accessdata parameter
919 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
920 global $DB, $CFG, $ACCESSLIB_PRIVATE;
922 if (empty($coursecontext->path)) {
923 // weird, this should not happen
924 return;
927 if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
928 // already loaded, great!
929 return;
932 $roles = array();
934 if (empty($userid)) {
935 if (!empty($CFG->notloggedinroleid)) {
936 $roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
939 } else if (isguestuser($userid)) {
940 if ($guestrole = get_guest_role()) {
941 $roles[$guestrole->id] = $guestrole->id;
944 } else {
945 // Interesting role assignments at, above and below the course context
946 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
947 $params['userid'] = $userid;
948 $params['children'] = $coursecontext->path."/%";
949 $sql = "SELECT ra.*, ctx.path
950 FROM {role_assignments} ra
951 JOIN {context} ctx ON ra.contextid = ctx.id
952 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
953 $rs = $DB->get_recordset_sql($sql, $params);
955 // add missing role definitions
956 foreach ($rs as $ra) {
957 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
958 $roles[$ra->roleid] = $ra->roleid;
960 $rs->close();
962 // add the "default frontpage role" when on the frontpage
963 if (!empty($CFG->defaultfrontpageroleid)) {
964 $frontpagecontext = context_course::instance(get_site()->id);
965 if ($frontpagecontext->id == $coursecontext->id) {
966 $roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
970 // do not forget the default role
971 if (!empty($CFG->defaultuserroleid)) {
972 $roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
976 if (!$roles) {
977 // weird, default roles must be missing...
978 $accessdata['loaded'][$coursecontext->instanceid] = 1;
979 return;
982 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
983 $params = array('c'=>$coursecontext->id);
984 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
985 $params = array_merge($params, $rparams);
986 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
987 $params = array_merge($params, $rparams);
989 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
990 FROM {role_capabilities} rc
991 JOIN {context} ctx
992 ON (ctx.id = rc.contextid)
993 JOIN {context} cctx
994 ON (cctx.id = :c
995 AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
996 WHERE rc.roleid $roleids
997 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
998 $rs = $DB->get_recordset_sql($sql, $params);
1000 $newrdefs = array();
1001 foreach ($rs as $rd) {
1002 $k = $rd->path.':'.$rd->roleid;
1003 if (isset($accessdata['rdef'][$k])) {
1004 continue;
1006 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
1008 $rs->close();
1010 // share new role definitions
1011 foreach ($newrdefs as $k=>$unused) {
1012 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
1013 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
1015 $accessdata['rdef_count']++;
1016 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1019 $accessdata['loaded'][$coursecontext->instanceid] = 1;
1021 // we want to deduplicate the USER->access from time to time, this looks like a good place,
1022 // because we have to do it before the end of session
1023 dedupe_user_access();
1027 * Add to the access ctrl array the data needed by a role for a given context.
1029 * The data is added in the rdef key.
1030 * This role-centric function is useful for role_switching
1031 * and temporary course roles.
1033 * @access private
1034 * @param int $roleid the id of the user
1035 * @param context $context needs path!
1036 * @param array $accessdata accessdata array (is modified)
1037 * @return array
1039 function load_role_access_by_context($roleid, context $context, &$accessdata) {
1040 global $DB, $ACCESSLIB_PRIVATE;
1042 /* Get the relevant rolecaps into rdef
1043 * - relevant role caps
1044 * - at ctx and above
1045 * - below this ctx
1048 if (empty($context->path)) {
1049 // weird, this should not happen
1050 return;
1053 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
1054 $params['roleid'] = $roleid;
1055 $params['childpath'] = $context->path.'/%';
1057 $sql = "SELECT ctx.path, rc.capability, rc.permission
1058 FROM {role_capabilities} rc
1059 JOIN {context} ctx ON (rc.contextid = ctx.id)
1060 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
1061 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
1062 $rs = $DB->get_recordset_sql($sql, $params);
1064 $newrdefs = array();
1065 foreach ($rs as $rd) {
1066 $k = $rd->path.':'.$roleid;
1067 if (isset($accessdata['rdef'][$k])) {
1068 continue;
1070 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
1072 $rs->close();
1074 // share new role definitions
1075 foreach ($newrdefs as $k=>$unused) {
1076 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
1077 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
1079 $accessdata['rdef_count']++;
1080 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1085 * Returns empty accessdata structure.
1087 * @access private
1088 * @return array empt accessdata
1090 function get_empty_accessdata() {
1091 $accessdata = array(); // named list
1092 $accessdata['ra'] = array();
1093 $accessdata['rdef'] = array();
1094 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
1095 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
1096 $accessdata['loaded'] = array(); // loaded course contexts
1097 $accessdata['time'] = time();
1098 $accessdata['rsw'] = array();
1100 return $accessdata;
1104 * Get accessdata for a given user.
1106 * @access private
1107 * @param int $userid
1108 * @param bool $preloadonly true means do not return access array
1109 * @return array accessdata
1111 function get_user_accessdata($userid, $preloadonly=false) {
1112 global $CFG, $ACCESSLIB_PRIVATE, $USER;
1114 if (!empty($USER->access['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1115 // share rdef from USER session with rolepermissions cache in order to conserve memory
1116 foreach ($USER->access['rdef'] as $k=>$v) {
1117 $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->access['rdef'][$k];
1119 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->access;
1122 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
1123 if (empty($userid)) {
1124 if (!empty($CFG->notloggedinroleid)) {
1125 $accessdata = get_role_access($CFG->notloggedinroleid);
1126 } else {
1127 // weird
1128 return get_empty_accessdata();
1131 } else if (isguestuser($userid)) {
1132 if ($guestrole = get_guest_role()) {
1133 $accessdata = get_role_access($guestrole->id);
1134 } else {
1135 //weird
1136 return get_empty_accessdata();
1139 } else {
1140 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1143 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1146 if ($preloadonly) {
1147 return;
1148 } else {
1149 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1154 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1155 * this function looks for contexts with the same overrides and shares them.
1157 * @access private
1158 * @return void
1160 function dedupe_user_access() {
1161 global $USER;
1163 if (CLI_SCRIPT) {
1164 // no session in CLI --> no compression necessary
1165 return;
1168 if (empty($USER->access['rdef_count'])) {
1169 // weird, this should not happen
1170 return;
1173 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1174 if ($USER->access['rdef_count'] - $USER->access['rdef_lcc'] > 10) {
1175 // do not compress after each change, wait till there is more stuff to be done
1176 return;
1179 $hashmap = array();
1180 foreach ($USER->access['rdef'] as $k=>$def) {
1181 $hash = sha1(serialize($def));
1182 if (isset($hashmap[$hash])) {
1183 $USER->access['rdef'][$k] =& $hashmap[$hash];
1184 } else {
1185 $hashmap[$hash] =& $USER->access['rdef'][$k];
1189 $USER->access['rdef_lcc'] = $USER->access['rdef_count'];
1193 * A convenience function to completely load all the capabilities
1194 * for the current user. It is called from has_capability() and functions change permissions.
1196 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1197 * @see check_enrolment_plugins()
1199 * @access private
1200 * @return void
1202 function load_all_capabilities() {
1203 global $USER;
1205 // roles not installed yet - we are in the middle of installation
1206 if (during_initial_install()) {
1207 return;
1210 if (!isset($USER->id)) {
1211 // this should not happen
1212 $USER->id = 0;
1215 unset($USER->access);
1216 $USER->access = get_user_accessdata($USER->id);
1218 // deduplicate the overrides to minimize session size
1219 dedupe_user_access();
1221 // Clear to force a refresh
1222 unset($USER->mycourses);
1224 // init/reset internal enrol caches - active course enrolments and temp access
1225 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1229 * A convenience function to completely reload all the capabilities
1230 * for the current user when roles have been updated in a relevant
1231 * context -- but PRESERVING switchroles and loginas.
1232 * This function resets all accesslib and context caches.
1234 * That is - completely transparent to the user.
1236 * Note: reloads $USER->access completely.
1238 * @access private
1239 * @return void
1241 function reload_all_capabilities() {
1242 global $USER, $DB, $ACCESSLIB_PRIVATE;
1244 // copy switchroles
1245 $sw = array();
1246 if (!empty($USER->access['rsw'])) {
1247 $sw = $USER->access['rsw'];
1250 accesslib_clear_all_caches(true);
1251 unset($USER->access);
1252 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
1254 load_all_capabilities();
1256 foreach ($sw as $path => $roleid) {
1257 if ($record = $DB->get_record('context', array('path'=>$path))) {
1258 $context = context::instance_by_id($record->id);
1259 role_switch($roleid, $context);
1265 * Adds a temp role to current USER->access array.
1267 * Useful for the "temporary guest" access we grant to logged-in users.
1268 * This is useful for enrol plugins only.
1270 * @since Moodle 2.2
1271 * @param context_course $coursecontext
1272 * @param int $roleid
1273 * @return void
1275 function load_temp_course_role(context_course $coursecontext, $roleid) {
1276 global $USER, $SITE;
1278 if (empty($roleid)) {
1279 debugging('invalid role specified in load_temp_course_role()');
1280 return;
1283 if ($coursecontext->instanceid == $SITE->id) {
1284 debugging('Can not use temp roles on the frontpage');
1285 return;
1288 if (!isset($USER->access)) {
1289 load_all_capabilities();
1292 $coursecontext->reload_if_dirty();
1294 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1295 return;
1298 // load course stuff first
1299 load_course_context($USER->id, $coursecontext, $USER->access);
1301 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1303 load_role_access_by_context($roleid, $coursecontext, $USER->access);
1307 * Removes any extra guest roles from current USER->access array.
1308 * This is useful for enrol plugins only.
1310 * @since Moodle 2.2
1311 * @param context_course $coursecontext
1312 * @return void
1314 function remove_temp_course_roles(context_course $coursecontext) {
1315 global $DB, $USER, $SITE;
1317 if ($coursecontext->instanceid == $SITE->id) {
1318 debugging('Can not use temp roles on the frontpage');
1319 return;
1322 if (empty($USER->access['ra'][$coursecontext->path])) {
1323 //no roles here, weird
1324 return;
1327 $sql = "SELECT DISTINCT ra.roleid AS id
1328 FROM {role_assignments} ra
1329 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1330 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1332 $USER->access['ra'][$coursecontext->path] = array();
1333 foreach($ras as $r) {
1334 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1339 * Returns array of all role archetypes.
1341 * @return array
1343 function get_role_archetypes() {
1344 return array(
1345 'manager' => 'manager',
1346 'coursecreator' => 'coursecreator',
1347 'editingteacher' => 'editingteacher',
1348 'teacher' => 'teacher',
1349 'student' => 'student',
1350 'guest' => 'guest',
1351 'user' => 'user',
1352 'frontpage' => 'frontpage'
1357 * Assign the defaults found in this capability definition to roles that have
1358 * the corresponding legacy capabilities assigned to them.
1360 * @param string $capability
1361 * @param array $legacyperms an array in the format (example):
1362 * 'guest' => CAP_PREVENT,
1363 * 'student' => CAP_ALLOW,
1364 * 'teacher' => CAP_ALLOW,
1365 * 'editingteacher' => CAP_ALLOW,
1366 * 'coursecreator' => CAP_ALLOW,
1367 * 'manager' => CAP_ALLOW
1368 * @return boolean success or failure.
1370 function assign_legacy_capabilities($capability, $legacyperms) {
1372 $archetypes = get_role_archetypes();
1374 foreach ($legacyperms as $type => $perm) {
1376 $systemcontext = context_system::instance();
1377 if ($type === 'admin') {
1378 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1379 $type = 'manager';
1382 if (!array_key_exists($type, $archetypes)) {
1383 print_error('invalidlegacy', '', '', $type);
1386 if ($roles = get_archetype_roles($type)) {
1387 foreach ($roles as $role) {
1388 // Assign a site level capability.
1389 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1390 return false;
1395 return true;
1399 * Verify capability risks.
1401 * @param stdClass $capability a capability - a row from the capabilities table.
1402 * @return boolean whether this capability is safe - that is, whether people with the
1403 * safeoverrides capability should be allowed to change it.
1405 function is_safe_capability($capability) {
1406 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1410 * Get the local override (if any) for a given capability in a role in a context
1412 * @param int $roleid
1413 * @param int $contextid
1414 * @param string $capability
1415 * @return stdClass local capability override
1417 function get_local_override($roleid, $contextid, $capability) {
1418 global $DB;
1419 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1423 * Returns context instance plus related course and cm instances
1425 * @param int $contextid
1426 * @return array of ($context, $course, $cm)
1428 function get_context_info_array($contextid) {
1429 global $DB;
1431 $context = context::instance_by_id($contextid, MUST_EXIST);
1432 $course = null;
1433 $cm = null;
1435 if ($context->contextlevel == CONTEXT_COURSE) {
1436 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1438 } else if ($context->contextlevel == CONTEXT_MODULE) {
1439 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1440 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1442 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1443 $parent = $context->get_parent_context();
1445 if ($parent->contextlevel == CONTEXT_COURSE) {
1446 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1447 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1448 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1449 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1453 return array($context, $course, $cm);
1457 * Function that creates a role
1459 * @param string $name role name
1460 * @param string $shortname role short name
1461 * @param string $description role description
1462 * @param string $archetype
1463 * @return int id or dml_exception
1465 function create_role($name, $shortname, $description, $archetype = '') {
1466 global $DB;
1468 if (strpos($archetype, 'moodle/legacy:') !== false) {
1469 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1472 // verify role archetype actually exists
1473 $archetypes = get_role_archetypes();
1474 if (empty($archetypes[$archetype])) {
1475 $archetype = '';
1478 // Insert the role record.
1479 $role = new stdClass();
1480 $role->name = $name;
1481 $role->shortname = $shortname;
1482 $role->description = $description;
1483 $role->archetype = $archetype;
1485 //find free sortorder number
1486 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1487 if (empty($role->sortorder)) {
1488 $role->sortorder = 1;
1490 $id = $DB->insert_record('role', $role);
1492 return $id;
1496 * Function that deletes a role and cleanups up after it
1498 * @param int $roleid id of role to delete
1499 * @return bool always true
1501 function delete_role($roleid) {
1502 global $DB;
1504 // first unssign all users
1505 role_unassign_all(array('roleid'=>$roleid));
1507 // cleanup all references to this role, ignore errors
1508 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1509 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1510 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1511 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1512 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1513 $DB->delete_records('role_names', array('roleid'=>$roleid));
1514 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1516 // Get role record before it's deleted.
1517 $role = $DB->get_record('role', array('id'=>$roleid));
1519 // Finally delete the role itself.
1520 $DB->delete_records('role', array('id'=>$roleid));
1522 // Trigger event.
1523 $event = \core\event\role_deleted::create(
1524 array(
1525 'context' => context_system::instance(),
1526 'objectid' => $roleid,
1527 'other' =>
1528 array(
1529 'shortname' => $role->shortname,
1530 'description' => $role->description,
1531 'archetype' => $role->archetype
1535 $event->add_record_snapshot('role', $role);
1536 $event->trigger();
1538 return true;
1542 * Function to write context specific overrides, or default capabilities.
1544 * NOTE: use $context->mark_dirty() after this
1546 * @param string $capability string name
1547 * @param int $permission CAP_ constants
1548 * @param int $roleid role id
1549 * @param int|context $contextid context id
1550 * @param bool $overwrite
1551 * @return bool always true or exception
1553 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1554 global $USER, $DB;
1556 if ($contextid instanceof context) {
1557 $context = $contextid;
1558 } else {
1559 $context = context::instance_by_id($contextid);
1562 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1563 unassign_capability($capability, $roleid, $context->id);
1564 return true;
1567 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1569 if ($existing and !$overwrite) { // We want to keep whatever is there already
1570 return true;
1573 $cap = new stdClass();
1574 $cap->contextid = $context->id;
1575 $cap->roleid = $roleid;
1576 $cap->capability = $capability;
1577 $cap->permission = $permission;
1578 $cap->timemodified = time();
1579 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1581 if ($existing) {
1582 $cap->id = $existing->id;
1583 $DB->update_record('role_capabilities', $cap);
1584 } else {
1585 if ($DB->record_exists('context', array('id'=>$context->id))) {
1586 $DB->insert_record('role_capabilities', $cap);
1589 return true;
1593 * Unassign a capability from a role.
1595 * NOTE: use $context->mark_dirty() after this
1597 * @param string $capability the name of the capability
1598 * @param int $roleid the role id
1599 * @param int|context $contextid null means all contexts
1600 * @return boolean true or exception
1602 function unassign_capability($capability, $roleid, $contextid = null) {
1603 global $DB;
1605 if (!empty($contextid)) {
1606 if ($contextid instanceof context) {
1607 $context = $contextid;
1608 } else {
1609 $context = context::instance_by_id($contextid);
1611 // delete from context rel, if this is the last override in this context
1612 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1613 } else {
1614 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1616 return true;
1620 * Get the roles that have a given capability assigned to it
1622 * This function does not resolve the actual permission of the capability.
1623 * It just checks for permissions and overrides.
1624 * Use get_roles_with_cap_in_context() if resolution is required.
1626 * @param string $capability capability name (string)
1627 * @param string $permission optional, the permission defined for this capability
1628 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1629 * @param stdClass $context null means any
1630 * @return array of role records
1632 function get_roles_with_capability($capability, $permission = null, $context = null) {
1633 global $DB;
1635 if ($context) {
1636 $contexts = $context->get_parent_context_ids(true);
1637 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1638 $contextsql = "AND rc.contextid $insql";
1639 } else {
1640 $params = array();
1641 $contextsql = '';
1644 if ($permission) {
1645 $permissionsql = " AND rc.permission = :permission";
1646 $params['permission'] = $permission;
1647 } else {
1648 $permissionsql = '';
1651 $sql = "SELECT r.*
1652 FROM {role} r
1653 WHERE r.id IN (SELECT rc.roleid
1654 FROM {role_capabilities} rc
1655 WHERE rc.capability = :capname
1656 $contextsql
1657 $permissionsql)";
1658 $params['capname'] = $capability;
1661 return $DB->get_records_sql($sql, $params);
1665 * This function makes a role-assignment (a role for a user in a particular context)
1667 * @param int $roleid the role of the id
1668 * @param int $userid userid
1669 * @param int|context $contextid id of the context
1670 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1671 * @param int $itemid id of enrolment/auth plugin
1672 * @param string $timemodified defaults to current time
1673 * @return int new/existing id of the assignment
1675 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1676 global $USER, $DB;
1678 // first of all detect if somebody is using old style parameters
1679 if ($contextid === 0 or is_numeric($component)) {
1680 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1683 // now validate all parameters
1684 if (empty($roleid)) {
1685 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1688 if (empty($userid)) {
1689 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1692 if ($itemid) {
1693 if (strpos($component, '_') === false) {
1694 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1696 } else {
1697 $itemid = 0;
1698 if ($component !== '' and strpos($component, '_') === false) {
1699 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1703 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1704 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1707 if ($contextid instanceof context) {
1708 $context = $contextid;
1709 } else {
1710 $context = context::instance_by_id($contextid, MUST_EXIST);
1713 if (!$timemodified) {
1714 $timemodified = time();
1717 // Check for existing entry
1718 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1720 if ($ras) {
1721 // role already assigned - this should not happen
1722 if (count($ras) > 1) {
1723 // very weird - remove all duplicates!
1724 $ra = array_shift($ras);
1725 foreach ($ras as $r) {
1726 $DB->delete_records('role_assignments', array('id'=>$r->id));
1728 } else {
1729 $ra = reset($ras);
1732 // actually there is no need to update, reset anything or trigger any event, so just return
1733 return $ra->id;
1736 // Create a new entry
1737 $ra = new stdClass();
1738 $ra->roleid = $roleid;
1739 $ra->contextid = $context->id;
1740 $ra->userid = $userid;
1741 $ra->component = $component;
1742 $ra->itemid = $itemid;
1743 $ra->timemodified = $timemodified;
1744 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1745 $ra->sortorder = 0;
1747 $ra->id = $DB->insert_record('role_assignments', $ra);
1749 // mark context as dirty - again expensive, but needed
1750 $context->mark_dirty();
1752 if (!empty($USER->id) && $USER->id == $userid) {
1753 // If the user is the current user, then do full reload of capabilities too.
1754 reload_all_capabilities();
1757 $event = \core\event\role_assigned::create(array(
1758 'context' => $context,
1759 'objectid' => $ra->roleid,
1760 'relateduserid' => $ra->userid,
1761 'other' => array(
1762 'id' => $ra->id,
1763 'component' => $ra->component,
1764 'itemid' => $ra->itemid
1767 $event->add_record_snapshot('role_assignments', $ra);
1768 $event->trigger();
1770 return $ra->id;
1774 * Removes one role assignment
1776 * @param int $roleid
1777 * @param int $userid
1778 * @param int $contextid
1779 * @param string $component
1780 * @param int $itemid
1781 * @return void
1783 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1784 // first make sure the params make sense
1785 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1786 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1789 if ($itemid) {
1790 if (strpos($component, '_') === false) {
1791 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1793 } else {
1794 $itemid = 0;
1795 if ($component !== '' and strpos($component, '_') === false) {
1796 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1800 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1804 * Removes multiple role assignments, parameters may contain:
1805 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1807 * @param array $params role assignment parameters
1808 * @param bool $subcontexts unassign in subcontexts too
1809 * @param bool $includemanual include manual role assignments too
1810 * @return void
1812 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1813 global $USER, $CFG, $DB;
1815 if (!$params) {
1816 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1819 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1820 foreach ($params as $key=>$value) {
1821 if (!in_array($key, $allowed)) {
1822 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1826 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1827 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1830 if ($includemanual) {
1831 if (!isset($params['component']) or $params['component'] === '') {
1832 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1836 if ($subcontexts) {
1837 if (empty($params['contextid'])) {
1838 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1842 $ras = $DB->get_records('role_assignments', $params);
1843 foreach($ras as $ra) {
1844 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1845 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1846 // this is a bit expensive but necessary
1847 $context->mark_dirty();
1848 // If the user is the current user, then do full reload of capabilities too.
1849 if (!empty($USER->id) && $USER->id == $ra->userid) {
1850 reload_all_capabilities();
1852 $event = \core\event\role_unassigned::create(array(
1853 'context' => $context,
1854 'objectid' => $ra->roleid,
1855 'relateduserid' => $ra->userid,
1856 'other' => array(
1857 'id' => $ra->id,
1858 'component' => $ra->component,
1859 'itemid' => $ra->itemid
1862 $event->add_record_snapshot('role_assignments', $ra);
1863 $event->trigger();
1866 unset($ras);
1868 // process subcontexts
1869 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1870 if ($params['contextid'] instanceof context) {
1871 $context = $params['contextid'];
1872 } else {
1873 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1876 if ($context) {
1877 $contexts = $context->get_child_contexts();
1878 $mparams = $params;
1879 foreach($contexts as $context) {
1880 $mparams['contextid'] = $context->id;
1881 $ras = $DB->get_records('role_assignments', $mparams);
1882 foreach($ras as $ra) {
1883 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1884 // this is a bit expensive but necessary
1885 $context->mark_dirty();
1886 // If the user is the current user, then do full reload of capabilities too.
1887 if (!empty($USER->id) && $USER->id == $ra->userid) {
1888 reload_all_capabilities();
1890 $event = \core\event\role_unassigned::create(
1891 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1892 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1893 $event->add_record_snapshot('role_assignments', $ra);
1894 $event->trigger();
1900 // do this once more for all manual role assignments
1901 if ($includemanual) {
1902 $params['component'] = '';
1903 role_unassign_all($params, $subcontexts, false);
1908 * Determines if a user is currently logged in
1910 * @category access
1912 * @return bool
1914 function isloggedin() {
1915 global $USER;
1917 return (!empty($USER->id));
1921 * Determines if a user is logged in as real guest user with username 'guest'.
1923 * @category access
1925 * @param int|object $user mixed user object or id, $USER if not specified
1926 * @return bool true if user is the real guest user, false if not logged in or other user
1928 function isguestuser($user = null) {
1929 global $USER, $DB, $CFG;
1931 // make sure we have the user id cached in config table, because we are going to use it a lot
1932 if (empty($CFG->siteguest)) {
1933 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1934 // guest does not exist yet, weird
1935 return false;
1937 set_config('siteguest', $guestid);
1939 if ($user === null) {
1940 $user = $USER;
1943 if ($user === null) {
1944 // happens when setting the $USER
1945 return false;
1947 } else if (is_numeric($user)) {
1948 return ($CFG->siteguest == $user);
1950 } else if (is_object($user)) {
1951 if (empty($user->id)) {
1952 return false; // not logged in means is not be guest
1953 } else {
1954 return ($CFG->siteguest == $user->id);
1957 } else {
1958 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1963 * Does user have a (temporary or real) guest access to course?
1965 * @category access
1967 * @param context $context
1968 * @param stdClass|int $user
1969 * @return bool
1971 function is_guest(context $context, $user = null) {
1972 global $USER;
1974 // first find the course context
1975 $coursecontext = $context->get_course_context();
1977 // make sure there is a real user specified
1978 if ($user === null) {
1979 $userid = isset($USER->id) ? $USER->id : 0;
1980 } else {
1981 $userid = is_object($user) ? $user->id : $user;
1984 if (isguestuser($userid)) {
1985 // can not inspect or be enrolled
1986 return true;
1989 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1990 // viewing users appear out of nowhere, they are neither guests nor participants
1991 return false;
1994 // consider only real active enrolments here
1995 if (is_enrolled($coursecontext, $user, '', true)) {
1996 return false;
1999 return true;
2003 * Returns true if the user has moodle/course:view capability in the course,
2004 * this is intended for admins, managers (aka small admins), inspectors, etc.
2006 * @category access
2008 * @param context $context
2009 * @param int|stdClass $user if null $USER is used
2010 * @param string $withcapability extra capability name
2011 * @return bool
2013 function is_viewing(context $context, $user = null, $withcapability = '') {
2014 // first find the course context
2015 $coursecontext = $context->get_course_context();
2017 if (isguestuser($user)) {
2018 // can not inspect
2019 return false;
2022 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
2023 // admins are allowed to inspect courses
2024 return false;
2027 if ($withcapability and !has_capability($withcapability, $context, $user)) {
2028 // site admins always have the capability, but the enrolment above blocks
2029 return false;
2032 return true;
2036 * Returns true if user is enrolled (is participating) in course
2037 * this is intended for students and teachers.
2039 * Since 2.2 the result for active enrolments and current user are cached.
2041 * @package core_enrol
2042 * @category access
2044 * @param context $context
2045 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
2046 * @param string $withcapability extra capability name
2047 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2048 * @return bool
2050 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
2051 global $USER, $DB;
2053 // first find the course context
2054 $coursecontext = $context->get_course_context();
2056 // make sure there is a real user specified
2057 if ($user === null) {
2058 $userid = isset($USER->id) ? $USER->id : 0;
2059 } else {
2060 $userid = is_object($user) ? $user->id : $user;
2063 if (empty($userid)) {
2064 // not-logged-in!
2065 return false;
2066 } else if (isguestuser($userid)) {
2067 // guest account can not be enrolled anywhere
2068 return false;
2071 if ($coursecontext->instanceid == SITEID) {
2072 // everybody participates on frontpage
2073 } else {
2074 // try cached info first - the enrolled flag is set only when active enrolment present
2075 if ($USER->id == $userid) {
2076 $coursecontext->reload_if_dirty();
2077 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
2078 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
2079 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2080 return false;
2082 return true;
2087 if ($onlyactive) {
2088 // look for active enrolments only
2089 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
2091 if ($until === false) {
2092 return false;
2095 if ($USER->id == $userid) {
2096 if ($until == 0) {
2097 $until = ENROL_MAX_TIMESTAMP;
2099 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
2100 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
2101 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
2102 remove_temp_course_roles($coursecontext);
2106 } else {
2107 // any enrolment is good for us here, even outdated, disabled or inactive
2108 $sql = "SELECT 'x'
2109 FROM {user_enrolments} ue
2110 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2111 JOIN {user} u ON u.id = ue.userid
2112 WHERE ue.userid = :userid AND u.deleted = 0";
2113 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2114 if (!$DB->record_exists_sql($sql, $params)) {
2115 return false;
2120 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2121 return false;
2124 return true;
2128 * Returns true if the user is able to access the course.
2130 * This function is in no way, shape, or form a substitute for require_login.
2131 * It should only be used in circumstances where it is not possible to call require_login
2132 * such as the navigation.
2134 * This function checks many of the methods of access to a course such as the view
2135 * capability, enrollments, and guest access. It also makes use of the cache
2136 * generated by require_login for guest access.
2138 * The flags within the $USER object that are used here should NEVER be used outside
2139 * of this function can_access_course and require_login. Doing so WILL break future
2140 * versions.
2142 * @param stdClass $course record
2143 * @param stdClass|int|null $user user record or id, current user if null
2144 * @param string $withcapability Check for this capability as well.
2145 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2146 * @return boolean Returns true if the user is able to access the course
2148 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
2149 global $DB, $USER;
2151 // this function originally accepted $coursecontext parameter
2152 if ($course instanceof context) {
2153 if ($course instanceof context_course) {
2154 debugging('deprecated context parameter, please use $course record');
2155 $coursecontext = $course;
2156 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2157 } else {
2158 debugging('Invalid context parameter, please use $course record');
2159 return false;
2161 } else {
2162 $coursecontext = context_course::instance($course->id);
2165 if (!isset($USER->id)) {
2166 // should never happen
2167 $USER->id = 0;
2168 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
2171 // make sure there is a user specified
2172 if ($user === null) {
2173 $userid = $USER->id;
2174 } else {
2175 $userid = is_object($user) ? $user->id : $user;
2177 unset($user);
2179 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2180 return false;
2183 if ($userid == $USER->id) {
2184 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2185 // the fact that somebody switched role means they can access the course no matter to what role they switched
2186 return true;
2190 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2191 return false;
2194 if (is_viewing($coursecontext, $userid)) {
2195 return true;
2198 if ($userid != $USER->id) {
2199 // for performance reasons we do not verify temporary guest access for other users, sorry...
2200 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2203 // === from here we deal only with $USER ===
2205 $coursecontext->reload_if_dirty();
2207 if (isset($USER->enrol['enrolled'][$course->id])) {
2208 if ($USER->enrol['enrolled'][$course->id] > time()) {
2209 return true;
2212 if (isset($USER->enrol['tempguest'][$course->id])) {
2213 if ($USER->enrol['tempguest'][$course->id] > time()) {
2214 return true;
2218 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2219 return true;
2222 // if not enrolled try to gain temporary guest access
2223 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2224 $enrols = enrol_get_plugins(true);
2225 foreach($instances as $instance) {
2226 if (!isset($enrols[$instance->enrol])) {
2227 continue;
2229 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2230 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2231 if ($until !== false and $until > time()) {
2232 $USER->enrol['tempguest'][$course->id] = $until;
2233 return true;
2236 if (isset($USER->enrol['tempguest'][$course->id])) {
2237 unset($USER->enrol['tempguest'][$course->id]);
2238 remove_temp_course_roles($coursecontext);
2241 return false;
2245 * Returns array with sql code and parameters returning all ids
2246 * of users enrolled into course.
2248 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2250 * @package core_enrol
2251 * @category access
2253 * @param context $context
2254 * @param string $withcapability
2255 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2256 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2257 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
2258 * @return array list($sql, $params)
2260 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false, $onlysuspended = false) {
2261 global $DB, $CFG;
2263 // use unique prefix just in case somebody makes some SQL magic with the result
2264 static $i = 0;
2265 $i++;
2266 $prefix = 'eu'.$i.'_';
2268 // first find the course context
2269 $coursecontext = $context->get_course_context();
2271 $isfrontpage = ($coursecontext->instanceid == SITEID);
2273 if ($onlyactive && $onlysuspended) {
2274 throw new coding_exception("Both onlyactive and onlysuspended are set, this is probably not what you want!");
2276 if ($isfrontpage && $onlysuspended) {
2277 throw new coding_exception("onlysuspended is not supported on frontpage; please add your own early-exit!");
2280 $joins = array();
2281 $wheres = array();
2282 $params = array();
2284 list($contextids, $contextpaths) = get_context_info_list($context);
2286 // get all relevant capability info for all roles
2287 if ($withcapability) {
2288 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2289 $cparams['cap'] = $withcapability;
2291 $defs = array();
2292 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2293 FROM {role_capabilities} rc
2294 JOIN {context} ctx on rc.contextid = ctx.id
2295 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2296 $rcs = $DB->get_records_sql($sql, $cparams);
2297 foreach ($rcs as $rc) {
2298 $defs[$rc->path][$rc->roleid] = $rc->permission;
2301 $access = array();
2302 if (!empty($defs)) {
2303 foreach ($contextpaths as $path) {
2304 if (empty($defs[$path])) {
2305 continue;
2307 foreach($defs[$path] as $roleid => $perm) {
2308 if ($perm == CAP_PROHIBIT) {
2309 $access[$roleid] = CAP_PROHIBIT;
2310 continue;
2312 if (!isset($access[$roleid])) {
2313 $access[$roleid] = (int)$perm;
2319 unset($defs);
2321 // make lists of roles that are needed and prohibited
2322 $needed = array(); // one of these is enough
2323 $prohibited = array(); // must not have any of these
2324 foreach ($access as $roleid => $perm) {
2325 if ($perm == CAP_PROHIBIT) {
2326 unset($needed[$roleid]);
2327 $prohibited[$roleid] = true;
2328 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2329 $needed[$roleid] = true;
2333 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2334 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2336 $nobody = false;
2338 if ($isfrontpage) {
2339 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2340 $nobody = true;
2341 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2342 // everybody not having prohibit has the capability
2343 $needed = array();
2344 } else if (empty($needed)) {
2345 $nobody = true;
2347 } else {
2348 if (!empty($prohibited[$defaultuserroleid])) {
2349 $nobody = true;
2350 } else if (!empty($needed[$defaultuserroleid])) {
2351 // everybody not having prohibit has the capability
2352 $needed = array();
2353 } else if (empty($needed)) {
2354 $nobody = true;
2358 if ($nobody) {
2359 // nobody can match so return some SQL that does not return any results
2360 $wheres[] = "1 = 2";
2362 } else {
2364 if ($needed) {
2365 $ctxids = implode(',', $contextids);
2366 $roleids = implode(',', array_keys($needed));
2367 $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))";
2370 if ($prohibited) {
2371 $ctxids = implode(',', $contextids);
2372 $roleids = implode(',', array_keys($prohibited));
2373 $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))";
2374 $wheres[] = "{$prefix}ra4.id IS NULL";
2377 if ($groupid) {
2378 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2379 $params["{$prefix}gmid"] = $groupid;
2383 } else {
2384 if ($groupid) {
2385 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2386 $params["{$prefix}gmid"] = $groupid;
2390 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2391 $params["{$prefix}guestid"] = $CFG->siteguest;
2393 if ($isfrontpage) {
2394 // all users are "enrolled" on the frontpage
2395 } else {
2396 $where1 = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2397 $where2 = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2398 $ejoin = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2399 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2401 if (!$onlysuspended) {
2402 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2403 $joins[] = $ejoin;
2404 if ($onlyactive) {
2405 $wheres[] = "$where1 AND $where2";
2407 } else {
2408 // Suspended only where there is enrolment but ALL are suspended.
2409 // Consider multiple enrols where one is not suspended or plain role_assign.
2410 $enrolselect = "SELECT DISTINCT {$prefix}ue.userid FROM {user_enrolments} {$prefix}ue $ejoin WHERE $where1 AND $where2";
2411 $joins[] = "JOIN {user_enrolments} {$prefix}ue1 ON {$prefix}ue1.userid = {$prefix}u.id";
2412 $joins[] = "JOIN {enrol} {$prefix}e1 ON ({$prefix}e1.id = {$prefix}ue1.enrolid AND {$prefix}e1.courseid = :{$prefix}_e1_courseid)";
2413 $params["{$prefix}_e1_courseid"] = $coursecontext->instanceid;
2414 $wheres[] = "{$prefix}u.id NOT IN ($enrolselect)";
2417 if ($onlyactive || $onlysuspended) {
2418 $now = round(time(), -2); // rounding helps caching in DB
2419 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2420 $prefix.'active'=>ENROL_USER_ACTIVE,
2421 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2425 $joins = implode("\n", $joins);
2426 $wheres = "WHERE ".implode(" AND ", $wheres);
2428 $sql = "SELECT DISTINCT {$prefix}u.id
2429 FROM {user} {$prefix}u
2430 $joins
2431 $wheres";
2433 return array($sql, $params);
2437 * Returns list of users enrolled into course.
2439 * @package core_enrol
2440 * @category access
2442 * @param context $context
2443 * @param string $withcapability
2444 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2445 * @param string $userfields requested user record fields
2446 * @param string $orderby
2447 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2448 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2449 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2450 * @return array of user records
2452 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
2453 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
2454 global $DB;
2456 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2457 $sql = "SELECT $userfields
2458 FROM {user} u
2459 JOIN ($esql) je ON je.id = u.id
2460 WHERE u.deleted = 0";
2462 if ($orderby) {
2463 $sql = "$sql ORDER BY $orderby";
2464 } else {
2465 list($sort, $sortparams) = users_order_by_sql('u');
2466 $sql = "$sql ORDER BY $sort";
2467 $params = array_merge($params, $sortparams);
2470 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2474 * Counts list of users enrolled into course (as per above function)
2476 * @package core_enrol
2477 * @category access
2479 * @param context $context
2480 * @param string $withcapability
2481 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2482 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2483 * @return array of user records
2485 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2486 global $DB;
2488 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2489 $sql = "SELECT count(u.id)
2490 FROM {user} u
2491 JOIN ($esql) je ON je.id = u.id
2492 WHERE u.deleted = 0";
2494 return $DB->count_records_sql($sql, $params);
2498 * Loads the capability definitions for the component (from file).
2500 * Loads the capability definitions for the component (from file). If no
2501 * capabilities are defined for the component, we simply return an empty array.
2503 * @access private
2504 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2505 * @return array array of capabilities
2507 function load_capability_def($component) {
2508 $defpath = core_component::get_component_directory($component).'/db/access.php';
2510 $capabilities = array();
2511 if (file_exists($defpath)) {
2512 require($defpath);
2513 if (!empty(${$component.'_capabilities'})) {
2514 // BC capability array name
2515 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2516 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2517 $capabilities = ${$component.'_capabilities'};
2521 return $capabilities;
2525 * Gets the capabilities that have been cached in the database for this component.
2527 * @access private
2528 * @param string $component - examples: 'moodle', 'mod_forum'
2529 * @return array array of capabilities
2531 function get_cached_capabilities($component = 'moodle') {
2532 global $DB;
2533 $caps = get_all_capabilities();
2534 $componentcaps = array();
2535 foreach ($caps as $cap) {
2536 if ($cap['component'] == $component) {
2537 $componentcaps[] = (object) $cap;
2540 return $componentcaps;
2544 * Returns default capabilities for given role archetype.
2546 * @param string $archetype role archetype
2547 * @return array
2549 function get_default_capabilities($archetype) {
2550 global $DB;
2552 if (!$archetype) {
2553 return array();
2556 $alldefs = array();
2557 $defaults = array();
2558 $components = array();
2559 $allcaps = get_all_capabilities();
2561 foreach ($allcaps as $cap) {
2562 if (!in_array($cap['component'], $components)) {
2563 $components[] = $cap['component'];
2564 $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
2567 foreach($alldefs as $name=>$def) {
2568 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2569 if (isset($def['archetypes'])) {
2570 if (isset($def['archetypes'][$archetype])) {
2571 $defaults[$name] = $def['archetypes'][$archetype];
2573 // 'legacy' is for backward compatibility with 1.9 access.php
2574 } else {
2575 if (isset($def['legacy'][$archetype])) {
2576 $defaults[$name] = $def['legacy'][$archetype];
2581 return $defaults;
2585 * Return default roles that can be assigned, overridden or switched
2586 * by give role archetype.
2588 * @param string $type assign|override|switch
2589 * @param string $archetype
2590 * @return array of role ids
2592 function get_default_role_archetype_allows($type, $archetype) {
2593 global $DB;
2595 if (empty($archetype)) {
2596 return array();
2599 $roles = $DB->get_records('role');
2600 $archetypemap = array();
2601 foreach ($roles as $role) {
2602 if ($role->archetype) {
2603 $archetypemap[$role->archetype][$role->id] = $role->id;
2607 $defaults = array(
2608 'assign' => array(
2609 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2610 'coursecreator' => array(),
2611 'editingteacher' => array('teacher', 'student'),
2612 'teacher' => array(),
2613 'student' => array(),
2614 'guest' => array(),
2615 'user' => array(),
2616 'frontpage' => array(),
2618 'override' => array(
2619 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2620 'coursecreator' => array(),
2621 'editingteacher' => array('teacher', 'student', 'guest'),
2622 'teacher' => array(),
2623 'student' => array(),
2624 'guest' => array(),
2625 'user' => array(),
2626 'frontpage' => array(),
2628 'switch' => array(
2629 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2630 'coursecreator' => array(),
2631 'editingteacher' => array('teacher', 'student', 'guest'),
2632 'teacher' => array('student', 'guest'),
2633 'student' => array(),
2634 'guest' => array(),
2635 'user' => array(),
2636 'frontpage' => array(),
2640 if (!isset($defaults[$type][$archetype])) {
2641 debugging("Unknown type '$type'' or archetype '$archetype''");
2642 return array();
2645 $return = array();
2646 foreach ($defaults[$type][$archetype] as $at) {
2647 if (isset($archetypemap[$at])) {
2648 foreach ($archetypemap[$at] as $roleid) {
2649 $return[$roleid] = $roleid;
2654 return $return;
2658 * Reset role capabilities to default according to selected role archetype.
2659 * If no archetype selected, removes all capabilities.
2661 * This applies to capabilities that are assigned to the role (that you could
2662 * edit in the 'define roles' interface), and not to any capability overrides
2663 * in different locations.
2665 * @param int $roleid ID of role to reset capabilities for
2667 function reset_role_capabilities($roleid) {
2668 global $DB;
2670 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2671 $defaultcaps = get_default_capabilities($role->archetype);
2673 $systemcontext = context_system::instance();
2675 $DB->delete_records('role_capabilities',
2676 array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2678 foreach($defaultcaps as $cap=>$permission) {
2679 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2682 // Mark the system context dirty.
2683 context_system::instance()->mark_dirty();
2687 * Updates the capabilities table with the component capability definitions.
2688 * If no parameters are given, the function updates the core moodle
2689 * capabilities.
2691 * Note that the absence of the db/access.php capabilities definition file
2692 * will cause any stored capabilities for the component to be removed from
2693 * the database.
2695 * @access private
2696 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2697 * @return boolean true if success, exception in case of any problems
2699 function update_capabilities($component = 'moodle') {
2700 global $DB, $OUTPUT;
2702 $storedcaps = array();
2704 $filecaps = load_capability_def($component);
2705 foreach($filecaps as $capname=>$unused) {
2706 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2707 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2711 // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2712 // So ensure our updating is based on fresh data.
2713 cache::make('core', 'capabilities')->delete('core_capabilities');
2715 $cachedcaps = get_cached_capabilities($component);
2716 if ($cachedcaps) {
2717 foreach ($cachedcaps as $cachedcap) {
2718 array_push($storedcaps, $cachedcap->name);
2719 // update risk bitmasks and context levels in existing capabilities if needed
2720 if (array_key_exists($cachedcap->name, $filecaps)) {
2721 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2722 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2724 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2725 $updatecap = new stdClass();
2726 $updatecap->id = $cachedcap->id;
2727 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2728 $DB->update_record('capabilities', $updatecap);
2730 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2731 $updatecap = new stdClass();
2732 $updatecap->id = $cachedcap->id;
2733 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2734 $DB->update_record('capabilities', $updatecap);
2737 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2738 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2740 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2741 $updatecap = new stdClass();
2742 $updatecap->id = $cachedcap->id;
2743 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2744 $DB->update_record('capabilities', $updatecap);
2750 // Flush the cached again, as we have changed DB.
2751 cache::make('core', 'capabilities')->delete('core_capabilities');
2753 // Are there new capabilities in the file definition?
2754 $newcaps = array();
2756 foreach ($filecaps as $filecap => $def) {
2757 if (!$storedcaps ||
2758 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2759 if (!array_key_exists('riskbitmask', $def)) {
2760 $def['riskbitmask'] = 0; // no risk if not specified
2762 $newcaps[$filecap] = $def;
2765 // Add new capabilities to the stored definition.
2766 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2767 foreach ($newcaps as $capname => $capdef) {
2768 $capability = new stdClass();
2769 $capability->name = $capname;
2770 $capability->captype = $capdef['captype'];
2771 $capability->contextlevel = $capdef['contextlevel'];
2772 $capability->component = $component;
2773 $capability->riskbitmask = $capdef['riskbitmask'];
2775 $DB->insert_record('capabilities', $capability, false);
2777 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2778 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2779 foreach ($rolecapabilities as $rolecapability){
2780 //assign_capability will update rather than insert if capability exists
2781 if (!assign_capability($capname, $rolecapability->permission,
2782 $rolecapability->roleid, $rolecapability->contextid, true)){
2783 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2787 // we ignore archetype key if we have cloned permissions
2788 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2789 assign_legacy_capabilities($capname, $capdef['archetypes']);
2790 // 'legacy' is for backward compatibility with 1.9 access.php
2791 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2792 assign_legacy_capabilities($capname, $capdef['legacy']);
2795 // Are there any capabilities that have been removed from the file
2796 // definition that we need to delete from the stored capabilities and
2797 // role assignments?
2798 capabilities_cleanup($component, $filecaps);
2800 // reset static caches
2801 accesslib_clear_all_caches(false);
2803 // Flush the cached again, as we have changed DB.
2804 cache::make('core', 'capabilities')->delete('core_capabilities');
2806 return true;
2810 * Deletes cached capabilities that are no longer needed by the component.
2811 * Also unassigns these capabilities from any roles that have them.
2812 * NOTE: this function is called from lib/db/upgrade.php
2814 * @access private
2815 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2816 * @param array $newcapdef array of the new capability definitions that will be
2817 * compared with the cached capabilities
2818 * @return int number of deprecated capabilities that have been removed
2820 function capabilities_cleanup($component, $newcapdef = null) {
2821 global $DB;
2823 $removedcount = 0;
2825 if ($cachedcaps = get_cached_capabilities($component)) {
2826 foreach ($cachedcaps as $cachedcap) {
2827 if (empty($newcapdef) ||
2828 array_key_exists($cachedcap->name, $newcapdef) === false) {
2830 // Remove from capabilities cache.
2831 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2832 $removedcount++;
2833 // Delete from roles.
2834 if ($roles = get_roles_with_capability($cachedcap->name)) {
2835 foreach($roles as $role) {
2836 if (!unassign_capability($cachedcap->name, $role->id)) {
2837 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2841 } // End if.
2844 if ($removedcount) {
2845 cache::make('core', 'capabilities')->delete('core_capabilities');
2847 return $removedcount;
2851 * Returns an array of all the known types of risk
2852 * The array keys can be used, for example as CSS class names, or in calls to
2853 * print_risk_icon. The values are the corresponding RISK_ constants.
2855 * @return array all the known types of risk.
2857 function get_all_risks() {
2858 return array(
2859 'riskmanagetrust' => RISK_MANAGETRUST,
2860 'riskconfig' => RISK_CONFIG,
2861 'riskxss' => RISK_XSS,
2862 'riskpersonal' => RISK_PERSONAL,
2863 'riskspam' => RISK_SPAM,
2864 'riskdataloss' => RISK_DATALOSS,
2869 * Return a link to moodle docs for a given capability name
2871 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2872 * @return string the human-readable capability name as a link to Moodle Docs.
2874 function get_capability_docs_link($capability) {
2875 $url = get_docs_url('Capabilities/' . $capability->name);
2876 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2880 * This function pulls out all the resolved capabilities (overrides and
2881 * defaults) of a role used in capability overrides in contexts at a given
2882 * context.
2884 * @param int $roleid
2885 * @param context $context
2886 * @param string $cap capability, optional, defaults to ''
2887 * @return array Array of capabilities
2889 function role_context_capabilities($roleid, context $context, $cap = '') {
2890 global $DB;
2892 $contexts = $context->get_parent_context_ids(true);
2893 $contexts = '('.implode(',', $contexts).')';
2895 $params = array($roleid);
2897 if ($cap) {
2898 $search = " AND rc.capability = ? ";
2899 $params[] = $cap;
2900 } else {
2901 $search = '';
2904 $sql = "SELECT rc.*
2905 FROM {role_capabilities} rc, {context} c
2906 WHERE rc.contextid in $contexts
2907 AND rc.roleid = ?
2908 AND rc.contextid = c.id $search
2909 ORDER BY c.contextlevel DESC, rc.capability DESC";
2911 $capabilities = array();
2913 if ($records = $DB->get_records_sql($sql, $params)) {
2914 // We are traversing via reverse order.
2915 foreach ($records as $record) {
2916 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2917 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2918 $capabilities[$record->capability] = $record->permission;
2922 return $capabilities;
2926 * Constructs array with contextids as first parameter and context paths,
2927 * in both cases bottom top including self.
2929 * @access private
2930 * @param context $context
2931 * @return array
2933 function get_context_info_list(context $context) {
2934 $contextids = explode('/', ltrim($context->path, '/'));
2935 $contextpaths = array();
2936 $contextids2 = $contextids;
2937 while ($contextids2) {
2938 $contextpaths[] = '/' . implode('/', $contextids2);
2939 array_pop($contextids2);
2941 return array($contextids, $contextpaths);
2945 * Check if context is the front page context or a context inside it
2947 * Returns true if this context is the front page context, or a context inside it,
2948 * otherwise false.
2950 * @param context $context a context object.
2951 * @return bool
2953 function is_inside_frontpage(context $context) {
2954 $frontpagecontext = context_course::instance(SITEID);
2955 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2959 * Returns capability information (cached)
2961 * @param string $capabilityname
2962 * @return stdClass or null if capability not found
2964 function get_capability_info($capabilityname) {
2965 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2967 $caps = get_all_capabilities();
2969 if (!isset($caps[$capabilityname])) {
2970 return null;
2973 return (object) $caps[$capabilityname];
2977 * Returns all capabilitiy records, preferably from MUC and not database.
2979 * @return array All capability records indexed by capability name
2981 function get_all_capabilities() {
2982 global $DB;
2983 $cache = cache::make('core', 'capabilities');
2984 if (!$allcaps = $cache->get('core_capabilities')) {
2985 $rs = $DB->get_recordset('capabilities');
2986 $allcaps = array();
2987 foreach ($rs as $capability) {
2988 $capability->riskbitmask = (int) $capability->riskbitmask;
2989 $allcaps[$capability->name] = (array) $capability;
2991 $rs->close();
2992 $cache->set('core_capabilities', $allcaps);
2994 return $allcaps;
2998 * Returns the human-readable, translated version of the capability.
2999 * Basically a big switch statement.
3001 * @param string $capabilityname e.g. mod/choice:readresponses
3002 * @return string
3004 function get_capability_string($capabilityname) {
3006 // Typical capability name is 'plugintype/pluginname:capabilityname'
3007 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
3009 if ($type === 'moodle') {
3010 $component = 'core_role';
3011 } else if ($type === 'quizreport') {
3012 //ugly hack!!
3013 $component = 'quiz_'.$name;
3014 } else {
3015 $component = $type.'_'.$name;
3018 $stringname = $name.':'.$capname;
3020 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
3021 return get_string($stringname, $component);
3024 $dir = core_component::get_component_directory($component);
3025 if (!file_exists($dir)) {
3026 // plugin broken or does not exist, do not bother with printing of debug message
3027 return $capabilityname.' ???';
3030 // something is wrong in plugin, better print debug
3031 return get_string($stringname, $component);
3035 * This gets the mod/block/course/core etc strings.
3037 * @param string $component
3038 * @param int $contextlevel
3039 * @return string|bool String is success, false if failed
3041 function get_component_string($component, $contextlevel) {
3043 if ($component === 'moodle' or $component === 'core') {
3044 switch ($contextlevel) {
3045 // TODO MDL-46123: this should probably use context level names instead
3046 case CONTEXT_SYSTEM: return get_string('coresystem');
3047 case CONTEXT_USER: return get_string('users');
3048 case CONTEXT_COURSECAT: return get_string('categories');
3049 case CONTEXT_COURSE: return get_string('course');
3050 case CONTEXT_MODULE: return get_string('activities');
3051 case CONTEXT_BLOCK: return get_string('block');
3052 default: print_error('unknowncontext');
3056 list($type, $name) = core_component::normalize_component($component);
3057 $dir = core_component::get_plugin_directory($type, $name);
3058 if (!file_exists($dir)) {
3059 // plugin not installed, bad luck, there is no way to find the name
3060 return $component.' ???';
3063 switch ($type) {
3064 // TODO MDL-46123: this is really hacky and should be improved.
3065 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
3066 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
3067 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
3068 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
3069 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
3070 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
3071 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
3072 case 'mod':
3073 if (get_string_manager()->string_exists('pluginname', $component)) {
3074 return get_string('activity').': '.get_string('pluginname', $component);
3075 } else {
3076 return get_string('activity').': '.get_string('modulename', $component);
3078 default: return get_string('pluginname', $component);
3083 * Gets the list of roles assigned to this context and up (parents)
3084 * from the list of roles that are visible on user profile page
3085 * and participants page.
3087 * @param context $context
3088 * @return array
3090 function get_profile_roles(context $context) {
3091 global $CFG, $DB;
3093 if (empty($CFG->profileroles)) {
3094 return array();
3097 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
3098 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
3099 $params = array_merge($params, $cparams);
3101 if ($coursecontext = $context->get_course_context(false)) {
3102 $params['coursecontext'] = $coursecontext->id;
3103 } else {
3104 $params['coursecontext'] = 0;
3107 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3108 FROM {role_assignments} ra, {role} r
3109 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3110 WHERE r.id = ra.roleid
3111 AND ra.contextid $contextlist
3112 AND r.id $rallowed
3113 ORDER BY r.sortorder ASC";
3115 return $DB->get_records_sql($sql, $params);
3119 * Gets the list of roles assigned to this context and up (parents)
3121 * @param context $context
3122 * @return array
3124 function get_roles_used_in_context(context $context) {
3125 global $DB;
3127 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
3129 if ($coursecontext = $context->get_course_context(false)) {
3130 $params['coursecontext'] = $coursecontext->id;
3131 } else {
3132 $params['coursecontext'] = 0;
3135 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3136 FROM {role_assignments} ra, {role} r
3137 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3138 WHERE r.id = ra.roleid
3139 AND ra.contextid $contextlist
3140 ORDER BY r.sortorder ASC";
3142 return $DB->get_records_sql($sql, $params);
3146 * This function is used to print roles column in user profile page.
3147 * It is using the CFG->profileroles to limit the list to only interesting roles.
3148 * (The permission tab has full details of user role assignments.)
3150 * @param int $userid
3151 * @param int $courseid
3152 * @return string
3154 function get_user_roles_in_course($userid, $courseid) {
3155 global $CFG, $DB;
3157 if (empty($CFG->profileroles)) {
3158 return '';
3161 if ($courseid == SITEID) {
3162 $context = context_system::instance();
3163 } else {
3164 $context = context_course::instance($courseid);
3167 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
3168 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
3169 $params = array_merge($params, $cparams);
3171 if ($coursecontext = $context->get_course_context(false)) {
3172 $params['coursecontext'] = $coursecontext->id;
3173 } else {
3174 $params['coursecontext'] = 0;
3177 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3178 FROM {role_assignments} ra, {role} r
3179 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3180 WHERE r.id = ra.roleid
3181 AND ra.contextid $contextlist
3182 AND r.id $rallowed
3183 AND ra.userid = :userid
3184 ORDER BY r.sortorder ASC";
3185 $params['userid'] = $userid;
3187 $rolestring = '';
3189 if ($roles = $DB->get_records_sql($sql, $params)) {
3190 $rolenames = role_fix_names($roles, $context, ROLENAME_ALIAS, true); // Substitute aliases
3192 foreach ($rolenames as $roleid => $rolename) {
3193 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
3195 $rolestring = implode(',', $rolenames);
3198 return $rolestring;
3202 * Checks if a user can assign users to a particular role in this context
3204 * @param context $context
3205 * @param int $targetroleid - the id of the role you want to assign users to
3206 * @return boolean
3208 function user_can_assign(context $context, $targetroleid) {
3209 global $DB;
3211 // First check to see if the user is a site administrator.
3212 if (is_siteadmin()) {
3213 return true;
3216 // Check if user has override capability.
3217 // If not return false.
3218 if (!has_capability('moodle/role:assign', $context)) {
3219 return false;
3221 // pull out all active roles of this user from this context(or above)
3222 if ($userroles = get_user_roles($context)) {
3223 foreach ($userroles as $userrole) {
3224 // if any in the role_allow_override table, then it's ok
3225 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
3226 return true;
3231 return false;
3235 * Returns all site roles in correct sort order.
3237 * Note: this method does not localise role names or descriptions,
3238 * use role_get_names() if you need role names.
3240 * @param context $context optional context for course role name aliases
3241 * @return array of role records with optional coursealias property
3243 function get_all_roles(context $context = null) {
3244 global $DB;
3246 if (!$context or !$coursecontext = $context->get_course_context(false)) {
3247 $coursecontext = null;
3250 if ($coursecontext) {
3251 $sql = "SELECT r.*, rn.name AS coursealias
3252 FROM {role} r
3253 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3254 ORDER BY r.sortorder ASC";
3255 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
3257 } else {
3258 return $DB->get_records('role', array(), 'sortorder ASC');
3263 * Returns roles of a specified archetype
3265 * @param string $archetype
3266 * @return array of full role records
3268 function get_archetype_roles($archetype) {
3269 global $DB;
3270 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
3274 * Gets all the user roles assigned in this context, or higher contexts
3275 * this is mainly used when checking if a user can assign a role, or overriding a role
3276 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3277 * allow_override tables
3279 * @param context $context
3280 * @param int $userid
3281 * @param bool $checkparentcontexts defaults to true
3282 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
3283 * @return array
3285 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
3286 global $USER, $DB;
3288 if (empty($userid)) {
3289 if (empty($USER->id)) {
3290 return array();
3292 $userid = $USER->id;
3295 if ($checkparentcontexts) {
3296 $contextids = $context->get_parent_context_ids();
3297 } else {
3298 $contextids = array();
3300 $contextids[] = $context->id;
3302 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3304 array_unshift($params, $userid);
3306 $sql = "SELECT ra.*, r.name, r.shortname
3307 FROM {role_assignments} ra, {role} r, {context} c
3308 WHERE ra.userid = ?
3309 AND ra.roleid = r.id
3310 AND ra.contextid = c.id
3311 AND ra.contextid $contextids
3312 ORDER BY $order";
3314 return $DB->get_records_sql($sql ,$params);
3318 * Like get_user_roles, but adds in the authenticated user role, and the front
3319 * page roles, if applicable.
3321 * @param context $context the context.
3322 * @param int $userid optional. Defaults to $USER->id
3323 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3325 function get_user_roles_with_special(context $context, $userid = 0) {
3326 global $CFG, $USER;
3328 if (empty($userid)) {
3329 if (empty($USER->id)) {
3330 return array();
3332 $userid = $USER->id;
3335 $ras = get_user_roles($context, $userid);
3337 // Add front-page role if relevant.
3338 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3339 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3340 is_inside_frontpage($context);
3341 if ($defaultfrontpageroleid && $isfrontpage) {
3342 $frontpagecontext = context_course::instance(SITEID);
3343 $ra = new stdClass();
3344 $ra->userid = $userid;
3345 $ra->contextid = $frontpagecontext->id;
3346 $ra->roleid = $defaultfrontpageroleid;
3347 $ras[] = $ra;
3350 // Add authenticated user role if relevant.
3351 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3352 if ($defaultuserroleid && !isguestuser($userid)) {
3353 $systemcontext = context_system::instance();
3354 $ra = new stdClass();
3355 $ra->userid = $userid;
3356 $ra->contextid = $systemcontext->id;
3357 $ra->roleid = $defaultuserroleid;
3358 $ras[] = $ra;
3361 return $ras;
3365 * Creates a record in the role_allow_override table
3367 * @param int $sroleid source roleid
3368 * @param int $troleid target roleid
3369 * @return void
3371 function allow_override($sroleid, $troleid) {
3372 global $DB;
3374 $record = new stdClass();
3375 $record->roleid = $sroleid;
3376 $record->allowoverride = $troleid;
3377 $DB->insert_record('role_allow_override', $record);
3381 * Creates a record in the role_allow_assign table
3383 * @param int $fromroleid source roleid
3384 * @param int $targetroleid target roleid
3385 * @return void
3387 function allow_assign($fromroleid, $targetroleid) {
3388 global $DB;
3390 $record = new stdClass();
3391 $record->roleid = $fromroleid;
3392 $record->allowassign = $targetroleid;
3393 $DB->insert_record('role_allow_assign', $record);
3397 * Creates a record in the role_allow_switch table
3399 * @param int $fromroleid source roleid
3400 * @param int $targetroleid target roleid
3401 * @return void
3403 function allow_switch($fromroleid, $targetroleid) {
3404 global $DB;
3406 $record = new stdClass();
3407 $record->roleid = $fromroleid;
3408 $record->allowswitch = $targetroleid;
3409 $DB->insert_record('role_allow_switch', $record);
3413 * Gets a list of roles that this user can assign in this context
3415 * @param context $context the context.
3416 * @param int $rolenamedisplay the type of role name to display. One of the
3417 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3418 * @param bool $withusercounts if true, count the number of users with each role.
3419 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3420 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3421 * if $withusercounts is true, returns a list of three arrays,
3422 * $rolenames, $rolecounts, and $nameswithcounts.
3424 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3425 global $USER, $DB;
3427 // make sure there is a real user specified
3428 if ($user === null) {
3429 $userid = isset($USER->id) ? $USER->id : 0;
3430 } else {
3431 $userid = is_object($user) ? $user->id : $user;
3434 if (!has_capability('moodle/role:assign', $context, $userid)) {
3435 if ($withusercounts) {
3436 return array(array(), array(), array());
3437 } else {
3438 return array();
3442 $params = array();
3443 $extrafields = '';
3445 if ($withusercounts) {
3446 $extrafields = ', (SELECT count(u.id)
3447 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3448 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3449 ) AS usercount';
3450 $params['conid'] = $context->id;
3453 if (is_siteadmin($userid)) {
3454 // show all roles allowed in this context to admins
3455 $assignrestriction = "";
3456 } else {
3457 $parents = $context->get_parent_context_ids(true);
3458 $contexts = implode(',' , $parents);
3459 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3460 FROM {role_allow_assign} raa
3461 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3462 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3463 ) ar ON ar.id = r.id";
3464 $params['userid'] = $userid;
3466 $params['contextlevel'] = $context->contextlevel;
3468 if ($coursecontext = $context->get_course_context(false)) {
3469 $params['coursecontext'] = $coursecontext->id;
3470 } else {
3471 $params['coursecontext'] = 0; // no course aliases
3472 $coursecontext = null;
3474 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3475 FROM {role} r
3476 $assignrestriction
3477 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3478 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3479 ORDER BY r.sortorder ASC";
3480 $roles = $DB->get_records_sql($sql, $params);
3482 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3484 if (!$withusercounts) {
3485 return $rolenames;
3488 $rolecounts = array();
3489 $nameswithcounts = array();
3490 foreach ($roles as $role) {
3491 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3492 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3494 return array($rolenames, $rolecounts, $nameswithcounts);
3498 * Gets a list of roles that this user can switch to in a context
3500 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3501 * This function just process the contents of the role_allow_switch table. You also need to
3502 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3504 * @param context $context a context.
3505 * @return array an array $roleid => $rolename.
3507 function get_switchable_roles(context $context) {
3508 global $USER, $DB;
3510 $params = array();
3511 $extrajoins = '';
3512 $extrawhere = '';
3513 if (!is_siteadmin()) {
3514 // Admins are allowed to switch to any role with.
3515 // Others are subject to the additional constraint that the switch-to role must be allowed by
3516 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3517 $parents = $context->get_parent_context_ids(true);
3518 $contexts = implode(',' , $parents);
3520 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3521 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3522 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3523 $params['userid'] = $USER->id;
3526 if ($coursecontext = $context->get_course_context(false)) {
3527 $params['coursecontext'] = $coursecontext->id;
3528 } else {
3529 $params['coursecontext'] = 0; // no course aliases
3530 $coursecontext = null;
3533 $query = "
3534 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3535 FROM (SELECT DISTINCT rc.roleid
3536 FROM {role_capabilities} rc
3537 $extrajoins
3538 $extrawhere) idlist
3539 JOIN {role} r ON r.id = idlist.roleid
3540 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3541 ORDER BY r.sortorder";
3542 $roles = $DB->get_records_sql($query, $params);
3544 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3548 * Gets a list of roles that this user can override in this context.
3550 * @param context $context the context.
3551 * @param int $rolenamedisplay the type of role name to display. One of the
3552 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3553 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3554 * @return array if $withcounts is false, then an array $roleid => $rolename.
3555 * if $withusercounts is true, returns a list of three arrays,
3556 * $rolenames, $rolecounts, and $nameswithcounts.
3558 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3559 global $USER, $DB;
3561 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3562 if ($withcounts) {
3563 return array(array(), array(), array());
3564 } else {
3565 return array();
3569 $parents = $context->get_parent_context_ids(true);
3570 $contexts = implode(',' , $parents);
3572 $params = array();
3573 $extrafields = '';
3575 $params['userid'] = $USER->id;
3576 if ($withcounts) {
3577 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3578 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3579 $params['conid'] = $context->id;
3582 if ($coursecontext = $context->get_course_context(false)) {
3583 $params['coursecontext'] = $coursecontext->id;
3584 } else {
3585 $params['coursecontext'] = 0; // no course aliases
3586 $coursecontext = null;
3589 if (is_siteadmin()) {
3590 // show all roles to admins
3591 $roles = $DB->get_records_sql("
3592 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3593 FROM {role} ro
3594 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3595 ORDER BY ro.sortorder ASC", $params);
3597 } else {
3598 $roles = $DB->get_records_sql("
3599 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3600 FROM {role} ro
3601 JOIN (SELECT DISTINCT r.id
3602 FROM {role} r
3603 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3604 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3605 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3606 ) inline_view ON ro.id = inline_view.id
3607 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3608 ORDER BY ro.sortorder ASC", $params);
3611 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3613 if (!$withcounts) {
3614 return $rolenames;
3617 $rolecounts = array();
3618 $nameswithcounts = array();
3619 foreach ($roles as $role) {
3620 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3621 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3623 return array($rolenames, $rolecounts, $nameswithcounts);
3627 * Create a role menu suitable for default role selection in enrol plugins.
3629 * @package core_enrol
3631 * @param context $context
3632 * @param int $addroleid current or default role - always added to list
3633 * @return array roleid=>localised role name
3635 function get_default_enrol_roles(context $context, $addroleid = null) {
3636 global $DB;
3638 $params = array('contextlevel'=>CONTEXT_COURSE);
3640 if ($coursecontext = $context->get_course_context(false)) {
3641 $params['coursecontext'] = $coursecontext->id;
3642 } else {
3643 $params['coursecontext'] = 0; // no course names
3644 $coursecontext = null;
3647 if ($addroleid) {
3648 $addrole = "OR r.id = :addroleid";
3649 $params['addroleid'] = $addroleid;
3650 } else {
3651 $addrole = "";
3654 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3655 FROM {role} r
3656 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3657 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3658 WHERE rcl.id IS NOT NULL $addrole
3659 ORDER BY sortorder DESC";
3661 $roles = $DB->get_records_sql($sql, $params);
3663 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3667 * Return context levels where this role is assignable.
3669 * @param integer $roleid the id of a role.
3670 * @return array list of the context levels at which this role may be assigned.
3672 function get_role_contextlevels($roleid) {
3673 global $DB;
3674 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3675 'contextlevel', 'id,contextlevel');
3679 * Return roles suitable for assignment at the specified context level.
3681 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3683 * @param integer $contextlevel a contextlevel.
3684 * @return array list of role ids that are assignable at this context level.
3686 function get_roles_for_contextlevels($contextlevel) {
3687 global $DB;
3688 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3689 '', 'id,roleid');
3693 * Returns default context levels where roles can be assigned.
3695 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3696 * from the array returned by get_role_archetypes();
3697 * @return array list of the context levels at which this type of role may be assigned by default.
3699 function get_default_contextlevels($rolearchetype) {
3700 static $defaults = array(
3701 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3702 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3703 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3704 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3705 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3706 'guest' => array(),
3707 'user' => array(),
3708 'frontpage' => array());
3710 if (isset($defaults[$rolearchetype])) {
3711 return $defaults[$rolearchetype];
3712 } else {
3713 return array();
3718 * Set the context levels at which a particular role can be assigned.
3719 * Throws exceptions in case of error.
3721 * @param integer $roleid the id of a role.
3722 * @param array $contextlevels the context levels at which this role should be assignable,
3723 * duplicate levels are removed.
3724 * @return void
3726 function set_role_contextlevels($roleid, array $contextlevels) {
3727 global $DB;
3728 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3729 $rcl = new stdClass();
3730 $rcl->roleid = $roleid;
3731 $contextlevels = array_unique($contextlevels);
3732 foreach ($contextlevels as $level) {
3733 $rcl->contextlevel = $level;
3734 $DB->insert_record('role_context_levels', $rcl, false, true);
3739 * Who has this capability in this context?
3741 * This can be a very expensive call - use sparingly and keep
3742 * the results if you are going to need them again soon.
3744 * Note if $fields is empty this function attempts to get u.*
3745 * which can get rather large - and has a serious perf impact
3746 * on some DBs.
3748 * @param context $context
3749 * @param string|array $capability - capability name(s)
3750 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3751 * @param string $sort - the sort order. Default is lastaccess time.
3752 * @param mixed $limitfrom - number of records to skip (offset)
3753 * @param mixed $limitnum - number of records to fetch
3754 * @param string|array $groups - single group or array of groups - only return
3755 * users who are in one of these group(s).
3756 * @param string|array $exceptions - list of users to exclude, comma separated or array
3757 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3758 * @param bool $view_ignored - use get_enrolled_sql() instead
3759 * @param bool $useviewallgroups if $groups is set the return users who
3760 * have capability both $capability and moodle/site:accessallgroups
3761 * in this context, as well as users who have $capability and who are
3762 * in $groups.
3763 * @return array of user records
3765 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3766 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3767 global $CFG, $DB;
3769 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3770 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3772 $ctxids = trim($context->path, '/');
3773 $ctxids = str_replace('/', ',', $ctxids);
3775 // Context is the frontpage
3776 $iscoursepage = false; // coursepage other than fp
3777 $isfrontpage = false;
3778 if ($context->contextlevel == CONTEXT_COURSE) {
3779 if ($context->instanceid == SITEID) {
3780 $isfrontpage = true;
3781 } else {
3782 $iscoursepage = true;
3785 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3787 $caps = (array)$capability;
3789 // construct list of context paths bottom-->top
3790 list($contextids, $paths) = get_context_info_list($context);
3792 // we need to find out all roles that have these capabilities either in definition or in overrides
3793 $defs = array();
3794 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3795 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3796 $params = array_merge($params, $params2);
3797 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3798 FROM {role_capabilities} rc
3799 JOIN {context} ctx on rc.contextid = ctx.id
3800 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3802 $rcs = $DB->get_records_sql($sql, $params);
3803 foreach ($rcs as $rc) {
3804 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3807 // go through the permissions bottom-->top direction to evaluate the current permission,
3808 // first one wins (prohibit is an exception that always wins)
3809 $access = array();
3810 foreach ($caps as $cap) {
3811 foreach ($paths as $path) {
3812 if (empty($defs[$cap][$path])) {
3813 continue;
3815 foreach($defs[$cap][$path] as $roleid => $perm) {
3816 if ($perm == CAP_PROHIBIT) {
3817 $access[$cap][$roleid] = CAP_PROHIBIT;
3818 continue;
3820 if (!isset($access[$cap][$roleid])) {
3821 $access[$cap][$roleid] = (int)$perm;
3827 // make lists of roles that are needed and prohibited in this context
3828 $needed = array(); // one of these is enough
3829 $prohibited = array(); // must not have any of these
3830 foreach ($caps as $cap) {
3831 if (empty($access[$cap])) {
3832 continue;
3834 foreach ($access[$cap] as $roleid => $perm) {
3835 if ($perm == CAP_PROHIBIT) {
3836 unset($needed[$cap][$roleid]);
3837 $prohibited[$cap][$roleid] = true;
3838 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3839 $needed[$cap][$roleid] = true;
3842 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3843 // easy, nobody has the permission
3844 unset($needed[$cap]);
3845 unset($prohibited[$cap]);
3846 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3847 // everybody is disqualified on the frontpage
3848 unset($needed[$cap]);
3849 unset($prohibited[$cap]);
3851 if (empty($prohibited[$cap])) {
3852 unset($prohibited[$cap]);
3856 if (empty($needed)) {
3857 // there can not be anybody if no roles match this request
3858 return array();
3861 if (empty($prohibited)) {
3862 // we can compact the needed roles
3863 $n = array();
3864 foreach ($needed as $cap) {
3865 foreach ($cap as $roleid=>$unused) {
3866 $n[$roleid] = true;
3869 $needed = array('any'=>$n);
3870 unset($n);
3873 // ***** Set up default fields ******
3874 if (empty($fields)) {
3875 if ($iscoursepage) {
3876 $fields = 'u.*, ul.timeaccess AS lastaccess';
3877 } else {
3878 $fields = 'u.*';
3880 } else {
3881 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3882 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3886 // Set up default sort
3887 if (empty($sort)) { // default to course lastaccess or just lastaccess
3888 if ($iscoursepage) {
3889 $sort = 'ul.timeaccess';
3890 } else {
3891 $sort = 'u.lastaccess';
3895 // Prepare query clauses
3896 $wherecond = array();
3897 $params = array();
3898 $joins = array();
3900 // User lastaccess JOIN
3901 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3902 // user_lastaccess is not required MDL-13810
3903 } else {
3904 if ($iscoursepage) {
3905 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3906 } else {
3907 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3911 // We never return deleted users or guest account.
3912 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3913 $params['guestid'] = $CFG->siteguest;
3915 // Groups
3916 if ($groups) {
3917 $groups = (array)$groups;
3918 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3919 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3920 $params = array_merge($params, $grpparams);
3922 if ($useviewallgroups) {
3923 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3924 if (!empty($viewallgroupsusers)) {
3925 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3926 } else {
3927 $wherecond[] = "($grouptest)";
3929 } else {
3930 $wherecond[] = "($grouptest)";
3934 // User exceptions
3935 if (!empty($exceptions)) {
3936 $exceptions = (array)$exceptions;
3937 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3938 $params = array_merge($params, $exparams);
3939 $wherecond[] = "u.id $exsql";
3942 // now add the needed and prohibited roles conditions as joins
3943 if (!empty($needed['any'])) {
3944 // simple case - there are no prohibits involved
3945 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3946 // everybody
3947 } else {
3948 $joins[] = "JOIN (SELECT DISTINCT userid
3949 FROM {role_assignments}
3950 WHERE contextid IN ($ctxids)
3951 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3952 ) ra ON ra.userid = u.id";
3954 } else {
3955 $unions = array();
3956 $everybody = false;
3957 foreach ($needed as $cap=>$unused) {
3958 if (empty($prohibited[$cap])) {
3959 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3960 $everybody = true;
3961 break;
3962 } else {
3963 $unions[] = "SELECT userid
3964 FROM {role_assignments}
3965 WHERE contextid IN ($ctxids)
3966 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3968 } else {
3969 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3970 // nobody can have this cap because it is prevented in default roles
3971 continue;
3973 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3974 // everybody except the prohibitted - hiding does not matter
3975 $unions[] = "SELECT id AS userid
3976 FROM {user}
3977 WHERE id NOT IN (SELECT userid
3978 FROM {role_assignments}
3979 WHERE contextid IN ($ctxids)
3980 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3982 } else {
3983 $unions[] = "SELECT userid
3984 FROM {role_assignments}
3985 WHERE contextid IN ($ctxids)
3986 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3987 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3991 if (!$everybody) {
3992 if ($unions) {
3993 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3994 } else {
3995 // only prohibits found - nobody can be matched
3996 $wherecond[] = "1 = 2";
4001 // Collect WHERE conditions and needed joins
4002 $where = implode(' AND ', $wherecond);
4003 if ($where !== '') {
4004 $where = 'WHERE ' . $where;
4006 $joins = implode("\n", $joins);
4008 // Ok, let's get the users!
4009 $sql = "SELECT $fields
4010 FROM {user} u
4011 $joins
4012 $where
4013 ORDER BY $sort";
4015 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
4019 * Re-sort a users array based on a sorting policy
4021 * Will re-sort a $users results array (from get_users_by_capability(), usually)
4022 * based on a sorting policy. This is to support the odd practice of
4023 * sorting teachers by 'authority', where authority was "lowest id of the role
4024 * assignment".
4026 * Will execute 1 database query. Only suitable for small numbers of users, as it
4027 * uses an u.id IN() clause.
4029 * Notes about the sorting criteria.
4031 * As a default, we cannot rely on role.sortorder because then
4032 * admins/coursecreators will always win. That is why the sane
4033 * rule "is locality matters most", with sortorder as 2nd
4034 * consideration.
4036 * If you want role.sortorder, use the 'sortorder' policy, and
4037 * name explicitly what roles you want to cover. It's probably
4038 * a good idea to see what roles have the capabilities you want
4039 * (array_diff() them against roiles that have 'can-do-anything'
4040 * to weed out admin-ish roles. Or fetch a list of roles from
4041 * variables like $CFG->coursecontact .
4043 * @param array $users Users array, keyed on userid
4044 * @param context $context
4045 * @param array $roles ids of the roles to include, optional
4046 * @param string $sortpolicy defaults to locality, more about
4047 * @return array sorted copy of the array
4049 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
4050 global $DB;
4052 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
4053 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
4054 if (empty($roles)) {
4055 $roleswhere = '';
4056 } else {
4057 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
4060 $sql = "SELECT ra.userid
4061 FROM {role_assignments} ra
4062 JOIN {role} r
4063 ON ra.roleid=r.id
4064 JOIN {context} ctx
4065 ON ra.contextid=ctx.id
4066 WHERE $userswhere
4067 $contextwhere
4068 $roleswhere";
4070 // Default 'locality' policy -- read PHPDoc notes
4071 // about sort policies...
4072 $orderby = 'ORDER BY '
4073 .'ctx.depth DESC, ' /* locality wins */
4074 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
4075 .'ra.id'; /* role assignment order tie-breaker */
4076 if ($sortpolicy === 'sortorder') {
4077 $orderby = 'ORDER BY '
4078 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
4079 .'ra.id'; /* role assignment order tie-breaker */
4082 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
4083 $sortedusers = array();
4084 $seen = array();
4086 foreach ($sortedids as $id) {
4087 // Avoid duplicates
4088 if (isset($seen[$id])) {
4089 continue;
4091 $seen[$id] = true;
4093 // assign
4094 $sortedusers[$id] = $users[$id];
4096 return $sortedusers;
4100 * Gets all the users assigned this role in this context or higher
4102 * Note that moodle is based on capabilities and it is usually better
4103 * to check permissions than to check role ids as the capabilities
4104 * system is more flexible. If you really need, you can to use this
4105 * function but consider has_capability() as a possible substitute.
4107 * The caller function is responsible for including all the
4108 * $sort fields in $fields param.
4110 * If $roleid is an array or is empty (all roles) you need to set $fields
4111 * (and $sort by extension) params according to it, as the first field
4112 * returned by the database should be unique (ra.id is the best candidate).
4114 * @param int $roleid (can also be an array of ints!)
4115 * @param context $context
4116 * @param bool $parent if true, get list of users assigned in higher context too
4117 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
4118 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
4119 * null => use default sort from users_order_by_sql.
4120 * @param bool $all true means all, false means limit to enrolled users
4121 * @param string $group defaults to ''
4122 * @param mixed $limitfrom defaults to ''
4123 * @param mixed $limitnum defaults to ''
4124 * @param string $extrawheretest defaults to ''
4125 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
4126 * @return array
4128 function get_role_users($roleid, context $context, $parent = false, $fields = '',
4129 $sort = null, $all = true, $group = '',
4130 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
4131 global $DB;
4133 if (empty($fields)) {
4134 $allnames = get_all_user_name_fields(true, 'u');
4135 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
4136 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
4137 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
4138 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
4139 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
4142 // Prevent wrong function uses.
4143 if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
4144 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
4145 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
4147 if (!empty($roleid)) {
4148 // Solving partially the issue when specifying multiple roles.
4149 $users = array();
4150 foreach ($roleid as $id) {
4151 // Ignoring duplicated keys keeping the first user appearance.
4152 $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
4153 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
4155 return $users;
4159 $parentcontexts = '';
4160 if ($parent) {
4161 $parentcontexts = substr($context->path, 1); // kill leading slash
4162 $parentcontexts = str_replace('/', ',', $parentcontexts);
4163 if ($parentcontexts !== '') {
4164 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4168 if ($roleid) {
4169 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
4170 $roleselect = "AND ra.roleid $rids";
4171 } else {
4172 $params = array();
4173 $roleselect = '';
4176 if ($coursecontext = $context->get_course_context(false)) {
4177 $params['coursecontext'] = $coursecontext->id;
4178 } else {
4179 $params['coursecontext'] = 0;
4182 if ($group) {
4183 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
4184 $groupselect = " AND gm.groupid = :groupid ";
4185 $params['groupid'] = $group;
4186 } else {
4187 $groupjoin = '';
4188 $groupselect = '';
4191 $params['contextid'] = $context->id;
4193 if ($extrawheretest) {
4194 $extrawheretest = ' AND ' . $extrawheretest;
4197 if ($whereorsortparams) {
4198 $params = array_merge($params, $whereorsortparams);
4201 if (!$sort) {
4202 list($sort, $sortparams) = users_order_by_sql('u');
4203 $params = array_merge($params, $sortparams);
4206 if ($all === null) {
4207 // Previously null was used to indicate that parameter was not used.
4208 $all = true;
4210 if (!$all and $coursecontext) {
4211 // Do not use get_enrolled_sql() here for performance reasons.
4212 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
4213 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
4214 $params['ecourseid'] = $coursecontext->instanceid;
4215 } else {
4216 $ejoin = "";
4219 $sql = "SELECT DISTINCT $fields, ra.roleid
4220 FROM {role_assignments} ra
4221 JOIN {user} u ON u.id = ra.userid
4222 JOIN {role} r ON ra.roleid = r.id
4223 $ejoin
4224 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
4225 $groupjoin
4226 WHERE (ra.contextid = :contextid $parentcontexts)
4227 $roleselect
4228 $groupselect
4229 $extrawheretest
4230 ORDER BY $sort"; // join now so that we can just use fullname() later
4232 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
4236 * Counts all the users assigned this role in this context or higher
4238 * @param int|array $roleid either int or an array of ints
4239 * @param context $context
4240 * @param bool $parent if true, get list of users assigned in higher context too
4241 * @return int Returns the result count
4243 function count_role_users($roleid, context $context, $parent = false) {
4244 global $DB;
4246 if ($parent) {
4247 if ($contexts = $context->get_parent_context_ids()) {
4248 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4249 } else {
4250 $parentcontexts = '';
4252 } else {
4253 $parentcontexts = '';
4256 if ($roleid) {
4257 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
4258 $roleselect = "AND r.roleid $rids";
4259 } else {
4260 $params = array();
4261 $roleselect = '';
4264 array_unshift($params, $context->id);
4266 $sql = "SELECT COUNT(DISTINCT u.id)
4267 FROM {role_assignments} r
4268 JOIN {user} u ON u.id = r.userid
4269 WHERE (r.contextid = ? $parentcontexts)
4270 $roleselect
4271 AND u.deleted = 0";
4273 return $DB->count_records_sql($sql, $params);
4277 * This function gets the list of courses that this user has a particular capability in.
4278 * It is still not very efficient.
4280 * @param string $capability Capability in question
4281 * @param int $userid User ID or null for current user
4282 * @param bool $doanything True if 'doanything' is permitted (default)
4283 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4284 * otherwise use a comma-separated list of the fields you require, not including id
4285 * @param string $orderby If set, use a comma-separated list of fields from course
4286 * table with sql modifiers (DESC) if needed
4287 * @return array|bool Array of courses, if none found false is returned.
4289 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
4290 global $DB;
4292 // Convert fields list and ordering
4293 $fieldlist = '';
4294 if ($fieldsexceptid) {
4295 $fields = explode(',', $fieldsexceptid);
4296 foreach($fields as $field) {
4297 $fieldlist .= ',c.'.$field;
4300 if ($orderby) {
4301 $fields = explode(',', $orderby);
4302 $orderby = '';
4303 foreach($fields as $field) {
4304 if ($orderby) {
4305 $orderby .= ',';
4307 $orderby .= 'c.'.$field;
4309 $orderby = 'ORDER BY '.$orderby;
4312 // Obtain a list of everything relevant about all courses including context.
4313 // Note the result can be used directly as a context (we are going to), the course
4314 // fields are just appended.
4316 $contextpreload = context_helper::get_preload_record_columns_sql('x');
4318 $courses = array();
4319 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
4320 FROM {course} c
4321 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
4322 $orderby");
4323 // Check capability for each course in turn
4324 foreach ($rs as $course) {
4325 context_helper::preload_from_record($course);
4326 $context = context_course::instance($course->id);
4327 if (has_capability($capability, $context, $userid, $doanything)) {
4328 // We've got the capability. Make the record look like a course record
4329 // and store it
4330 $courses[] = $course;
4333 $rs->close();
4334 return empty($courses) ? false : $courses;
4338 * This function finds the roles assigned directly to this context only
4339 * i.e. no roles in parent contexts
4341 * @param context $context
4342 * @return array
4344 function get_roles_on_exact_context(context $context) {
4345 global $DB;
4347 return $DB->get_records_sql("SELECT r.*
4348 FROM {role_assignments} ra, {role} r
4349 WHERE ra.roleid = r.id AND ra.contextid = ?",
4350 array($context->id));
4354 * Switches the current user to another role for the current session and only
4355 * in the given context.
4357 * The caller *must* check
4358 * - that this op is allowed
4359 * - that the requested role can be switched to in this context (use get_switchable_roles)
4360 * - that the requested role is NOT $CFG->defaultuserroleid
4362 * To "unswitch" pass 0 as the roleid.
4364 * This function *will* modify $USER->access - beware
4366 * @param integer $roleid the role to switch to.
4367 * @param context $context the context in which to perform the switch.
4368 * @return bool success or failure.
4370 function role_switch($roleid, context $context) {
4371 global $USER;
4374 // Plan of action
4376 // - Add the ghost RA to $USER->access
4377 // as $USER->access['rsw'][$path] = $roleid
4379 // - Make sure $USER->access['rdef'] has the roledefs
4380 // it needs to honour the switcherole
4382 // Roledefs will get loaded "deep" here - down to the last child
4383 // context. Note that
4385 // - When visiting subcontexts, our selective accessdata loading
4386 // will still work fine - though those ra/rdefs will be ignored
4387 // appropriately while the switch is in place
4389 // - If a switcherole happens at a category with tons of courses
4390 // (that have many overrides for switched-to role), the session
4391 // will get... quite large. Sometimes you just can't win.
4393 // To un-switch just unset($USER->access['rsw'][$path])
4395 // Note: it is not possible to switch to roles that do not have course:view
4397 if (!isset($USER->access)) {
4398 load_all_capabilities();
4402 // Add the switch RA
4403 if ($roleid == 0) {
4404 unset($USER->access['rsw'][$context->path]);
4405 return true;
4408 $USER->access['rsw'][$context->path] = $roleid;
4410 // Load roledefs
4411 load_role_access_by_context($roleid, $context, $USER->access);
4413 return true;
4417 * Checks if the user has switched roles within the given course.
4419 * Note: You can only switch roles within the course, hence it takes a course id
4420 * rather than a context. On that note Petr volunteered to implement this across
4421 * all other contexts, all requests for this should be forwarded to him ;)
4423 * @param int $courseid The id of the course to check
4424 * @return bool True if the user has switched roles within the course.
4426 function is_role_switched($courseid) {
4427 global $USER;
4428 $context = context_course::instance($courseid, MUST_EXIST);
4429 return (!empty($USER->access['rsw'][$context->path]));
4433 * Get any role that has an override on exact context
4435 * @param context $context The context to check
4436 * @return array An array of roles
4438 function get_roles_with_override_on_context(context $context) {
4439 global $DB;
4441 return $DB->get_records_sql("SELECT r.*
4442 FROM {role_capabilities} rc, {role} r
4443 WHERE rc.roleid = r.id AND rc.contextid = ?",
4444 array($context->id));
4448 * Get all capabilities for this role on this context (overrides)
4450 * @param stdClass $role
4451 * @param context $context
4452 * @return array
4454 function get_capabilities_from_role_on_context($role, context $context) {
4455 global $DB;
4457 return $DB->get_records_sql("SELECT *
4458 FROM {role_capabilities}
4459 WHERE contextid = ? AND roleid = ?",
4460 array($context->id, $role->id));
4464 * Find out which roles has assignment on this context
4466 * @param context $context
4467 * @return array
4470 function get_roles_with_assignment_on_context(context $context) {
4471 global $DB;
4473 return $DB->get_records_sql("SELECT r.*
4474 FROM {role_assignments} ra, {role} r
4475 WHERE ra.roleid = r.id AND ra.contextid = ?",
4476 array($context->id));
4480 * Find all user assignment of users for this role, on this context
4482 * @param stdClass $role
4483 * @param context $context
4484 * @return array
4486 function get_users_from_role_on_context($role, context $context) {
4487 global $DB;
4489 return $DB->get_records_sql("SELECT *
4490 FROM {role_assignments}
4491 WHERE contextid = ? AND roleid = ?",
4492 array($context->id, $role->id));
4496 * Simple function returning a boolean true if user has roles
4497 * in context or parent contexts, otherwise false.
4499 * @param int $userid
4500 * @param int $roleid
4501 * @param int $contextid empty means any context
4502 * @return bool
4504 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4505 global $DB;
4507 if ($contextid) {
4508 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4509 return false;
4511 $parents = $context->get_parent_context_ids(true);
4512 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4513 $params['userid'] = $userid;
4514 $params['roleid'] = $roleid;
4516 $sql = "SELECT COUNT(ra.id)
4517 FROM {role_assignments} ra
4518 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4520 $count = $DB->get_field_sql($sql, $params);
4521 return ($count > 0);
4523 } else {
4524 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4529 * Get localised role name or alias if exists and format the text.
4531 * @param stdClass $role role object
4532 * - optional 'coursealias' property should be included for performance reasons if course context used
4533 * - description property is not required here
4534 * @param context|bool $context empty means system context
4535 * @param int $rolenamedisplay type of role name
4536 * @return string localised role name or course role name alias
4538 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4539 global $DB;
4541 if ($rolenamedisplay == ROLENAME_SHORT) {
4542 return $role->shortname;
4545 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4546 $coursecontext = null;
4549 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4550 $role = clone($role); // Do not modify parameters.
4551 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4552 $role->coursealias = $r->name;
4553 } else {
4554 $role->coursealias = null;
4558 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4559 if ($coursecontext) {
4560 return $role->coursealias;
4561 } else {
4562 return null;
4566 if (trim($role->name) !== '') {
4567 // For filtering always use context where was the thing defined - system for roles here.
4568 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4570 } else {
4571 // Empty role->name means we want to see localised role name based on shortname,
4572 // only default roles are supposed to be localised.
4573 switch ($role->shortname) {
4574 case 'manager': $original = get_string('manager', 'role'); break;
4575 case 'coursecreator': $original = get_string('coursecreators'); break;
4576 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4577 case 'teacher': $original = get_string('noneditingteacher'); break;
4578 case 'student': $original = get_string('defaultcoursestudent'); break;
4579 case 'guest': $original = get_string('guest'); break;
4580 case 'user': $original = get_string('authenticateduser'); break;
4581 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4582 // We should not get here, the role UI should require the name for custom roles!
4583 default: $original = $role->shortname; break;
4587 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4588 return $original;
4591 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4592 return "$original ($role->shortname)";
4595 if ($rolenamedisplay == ROLENAME_ALIAS) {
4596 if ($coursecontext and trim($role->coursealias) !== '') {
4597 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4598 } else {
4599 return $original;
4603 if ($rolenamedisplay == ROLENAME_BOTH) {
4604 if ($coursecontext and trim($role->coursealias) !== '') {
4605 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4606 } else {
4607 return $original;
4611 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4615 * Returns localised role description if available.
4616 * If the name is empty it tries to find the default role name using
4617 * hardcoded list of default role names or other methods in the future.
4619 * @param stdClass $role
4620 * @return string localised role name
4622 function role_get_description(stdClass $role) {
4623 if (!html_is_blank($role->description)) {
4624 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4627 switch ($role->shortname) {
4628 case 'manager': return get_string('managerdescription', 'role');
4629 case 'coursecreator': return get_string('coursecreatorsdescription');
4630 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4631 case 'teacher': return get_string('noneditingteacherdescription');
4632 case 'student': return get_string('defaultcoursestudentdescription');
4633 case 'guest': return get_string('guestdescription');
4634 case 'user': return get_string('authenticateduserdescription');
4635 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4636 default: return '';
4641 * Get all the localised role names for a context.
4643 * In new installs default roles have empty names, this function
4644 * add localised role names using current language pack.
4646 * @param context $context the context, null means system context
4647 * @param array of role objects with a ->localname field containing the context-specific role name.
4648 * @param int $rolenamedisplay
4649 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4650 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4652 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4653 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4657 * Prepare list of roles for display, apply aliases and localise default role names.
4659 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4660 * @param context $context the context, null means system context
4661 * @param int $rolenamedisplay
4662 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4663 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4665 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4666 global $DB;
4668 if (empty($roleoptions)) {
4669 return array();
4672 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4673 $coursecontext = null;
4676 // We usually need all role columns...
4677 $first = reset($roleoptions);
4678 if ($returnmenu === null) {
4679 $returnmenu = !is_object($first);
4682 if (!is_object($first) or !property_exists($first, 'shortname')) {
4683 $allroles = get_all_roles($context);
4684 foreach ($roleoptions as $rid => $unused) {
4685 $roleoptions[$rid] = $allroles[$rid];
4689 // Inject coursealias if necessary.
4690 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4691 $first = reset($roleoptions);
4692 if (!property_exists($first, 'coursealias')) {
4693 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4694 foreach ($aliasnames as $alias) {
4695 if (isset($roleoptions[$alias->roleid])) {
4696 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4702 // Add localname property.
4703 foreach ($roleoptions as $rid => $role) {
4704 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4707 if (!$returnmenu) {
4708 return $roleoptions;
4711 $menu = array();
4712 foreach ($roleoptions as $rid => $role) {
4713 $menu[$rid] = $role->localname;
4716 return $menu;
4720 * Aids in detecting if a new line is required when reading a new capability
4722 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4723 * when we read in a new capability.
4724 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4725 * but when we are in grade, all reports/import/export capabilities should be together
4727 * @param string $cap component string a
4728 * @param string $comp component string b
4729 * @param int $contextlevel
4730 * @return bool whether 2 component are in different "sections"
4732 function component_level_changed($cap, $comp, $contextlevel) {
4734 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4735 $compsa = explode('/', $cap->component);
4736 $compsb = explode('/', $comp);
4738 // list of system reports
4739 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4740 return false;
4743 // we are in gradebook, still
4744 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4745 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4746 return false;
4749 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4750 return false;
4754 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4758 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4759 * and return an array of roleids in order.
4761 * @param array $allroles array of roles, as returned by get_all_roles();
4762 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4764 function fix_role_sortorder($allroles) {
4765 global $DB;
4767 $rolesort = array();
4768 $i = 0;
4769 foreach ($allroles as $role) {
4770 $rolesort[$i] = $role->id;
4771 if ($role->sortorder != $i) {
4772 $r = new stdClass();
4773 $r->id = $role->id;
4774 $r->sortorder = $i;
4775 $DB->update_record('role', $r);
4776 $allroles[$role->id]->sortorder = $i;
4778 $i++;
4780 return $rolesort;
4784 * Switch the sort order of two roles (used in admin/roles/manage.php).
4786 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4787 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4788 * @return boolean success or failure
4790 function switch_roles($first, $second) {
4791 global $DB;
4792 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4793 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4794 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4795 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4796 return $result;
4800 * Duplicates all the base definitions of a role
4802 * @param stdClass $sourcerole role to copy from
4803 * @param int $targetrole id of role to copy to
4805 function role_cap_duplicate($sourcerole, $targetrole) {
4806 global $DB;
4808 $systemcontext = context_system::instance();
4809 $caps = $DB->get_records_sql("SELECT *
4810 FROM {role_capabilities}
4811 WHERE roleid = ? AND contextid = ?",
4812 array($sourcerole->id, $systemcontext->id));
4813 // adding capabilities
4814 foreach ($caps as $cap) {
4815 unset($cap->id);
4816 $cap->roleid = $targetrole;
4817 $DB->insert_record('role_capabilities', $cap);
4822 * Returns two lists, this can be used to find out if user has capability.
4823 * Having any needed role and no forbidden role in this context means
4824 * user has this capability in this context.
4825 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4827 * @param stdClass $context
4828 * @param string $capability
4829 * @return array($neededroles, $forbiddenroles)
4831 function get_roles_with_cap_in_context($context, $capability) {
4832 global $DB;
4834 $ctxids = trim($context->path, '/'); // kill leading slash
4835 $ctxids = str_replace('/', ',', $ctxids);
4837 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4838 FROM {role_capabilities} rc
4839 JOIN {context} ctx ON ctx.id = rc.contextid
4840 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4841 ORDER BY rc.roleid ASC, ctx.depth DESC";
4842 $params = array('cap'=>$capability);
4844 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4845 // no cap definitions --> no capability
4846 return array(array(), array());
4849 $forbidden = array();
4850 $needed = array();
4851 foreach($capdefs as $def) {
4852 if (isset($forbidden[$def->roleid])) {
4853 continue;
4855 if ($def->permission == CAP_PROHIBIT) {
4856 $forbidden[$def->roleid] = $def->roleid;
4857 unset($needed[$def->roleid]);
4858 continue;
4860 if (!isset($needed[$def->roleid])) {
4861 if ($def->permission == CAP_ALLOW) {
4862 $needed[$def->roleid] = true;
4863 } else if ($def->permission == CAP_PREVENT) {
4864 $needed[$def->roleid] = false;
4868 unset($capdefs);
4870 // remove all those roles not allowing
4871 foreach($needed as $key=>$value) {
4872 if (!$value) {
4873 unset($needed[$key]);
4874 } else {
4875 $needed[$key] = $key;
4879 return array($needed, $forbidden);
4883 * Returns an array of role IDs that have ALL of the the supplied capabilities
4884 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4886 * @param stdClass $context
4887 * @param array $capabilities An array of capabilities
4888 * @return array of roles with all of the required capabilities
4890 function get_roles_with_caps_in_context($context, $capabilities) {
4891 $neededarr = array();
4892 $forbiddenarr = array();
4893 foreach($capabilities as $caprequired) {
4894 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4897 $rolesthatcanrate = array();
4898 if (!empty($neededarr)) {
4899 foreach ($neededarr as $needed) {
4900 if (empty($rolesthatcanrate)) {
4901 $rolesthatcanrate = $needed;
4902 } else {
4903 //only want roles that have all caps
4904 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4908 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4909 foreach ($forbiddenarr as $forbidden) {
4910 //remove any roles that are forbidden any of the caps
4911 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4914 return $rolesthatcanrate;
4918 * Returns an array of role names that have ALL of the the supplied capabilities
4919 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4921 * @param stdClass $context
4922 * @param array $capabilities An array of capabilities
4923 * @return array of roles with all of the required capabilities
4925 function get_role_names_with_caps_in_context($context, $capabilities) {
4926 global $DB;
4928 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4929 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4931 $roles = array();
4932 foreach ($rolesthatcanrate as $r) {
4933 $roles[$r] = $allroles[$r];
4936 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4940 * This function verifies the prohibit comes from this context
4941 * and there are no more prohibits in parent contexts.
4943 * @param int $roleid
4944 * @param context $context
4945 * @param string $capability name
4946 * @return bool
4948 function prohibit_is_removable($roleid, context $context, $capability) {
4949 global $DB;
4951 $ctxids = trim($context->path, '/'); // kill leading slash
4952 $ctxids = str_replace('/', ',', $ctxids);
4954 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4956 $sql = "SELECT ctx.id
4957 FROM {role_capabilities} rc
4958 JOIN {context} ctx ON ctx.id = rc.contextid
4959 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4960 ORDER BY ctx.depth DESC";
4962 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4963 // no prohibits == nothing to remove
4964 return true;
4967 if (count($prohibits) > 1) {
4968 // more prohibits can not be removed
4969 return false;
4972 return !empty($prohibits[$context->id]);
4976 * More user friendly role permission changing,
4977 * it should produce as few overrides as possible.
4979 * @param int $roleid
4980 * @param stdClass $context
4981 * @param string $capname capability name
4982 * @param int $permission
4983 * @return void
4985 function role_change_permission($roleid, $context, $capname, $permission) {
4986 global $DB;
4988 if ($permission == CAP_INHERIT) {
4989 unassign_capability($capname, $roleid, $context->id);
4990 $context->mark_dirty();
4991 return;
4994 $ctxids = trim($context->path, '/'); // kill leading slash
4995 $ctxids = str_replace('/', ',', $ctxids);
4997 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4999 $sql = "SELECT ctx.id, rc.permission, ctx.depth
5000 FROM {role_capabilities} rc
5001 JOIN {context} ctx ON ctx.id = rc.contextid
5002 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
5003 ORDER BY ctx.depth DESC";
5005 if ($existing = $DB->get_records_sql($sql, $params)) {
5006 foreach($existing as $e) {
5007 if ($e->permission == CAP_PROHIBIT) {
5008 // prohibit can not be overridden, no point in changing anything
5009 return;
5012 $lowest = array_shift($existing);
5013 if ($lowest->permission == $permission) {
5014 // permission already set in this context or parent - nothing to do
5015 return;
5017 if ($existing) {
5018 $parent = array_shift($existing);
5019 if ($parent->permission == $permission) {
5020 // permission already set in parent context or parent - just unset in this context
5021 // we do this because we want as few overrides as possible for performance reasons
5022 unassign_capability($capname, $roleid, $context->id);
5023 $context->mark_dirty();
5024 return;
5028 } else {
5029 if ($permission == CAP_PREVENT) {
5030 // nothing means role does not have permission
5031 return;
5035 // assign the needed capability
5036 assign_capability($capname, $permission, $roleid, $context->id, true);
5038 // force cap reloading
5039 $context->mark_dirty();
5044 * Basic moodle context abstraction class.
5046 * Google confirms that no other important framework is using "context" class,
5047 * we could use something else like mcontext or moodle_context, but we need to type
5048 * this very often which would be annoying and it would take too much space...
5050 * This class is derived from stdClass for backwards compatibility with
5051 * odl $context record that was returned from DML $DB->get_record()
5053 * @package core_access
5054 * @category access
5055 * @copyright Petr Skoda {@link http://skodak.org}
5056 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5057 * @since Moodle 2.2
5059 * @property-read int $id context id
5060 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
5061 * @property-read int $instanceid id of related instance in each context
5062 * @property-read string $path path to context, starts with system context
5063 * @property-read int $depth
5065 abstract class context extends stdClass implements IteratorAggregate {
5068 * The context id
5069 * Can be accessed publicly through $context->id
5070 * @var int
5072 protected $_id;
5075 * The context level
5076 * Can be accessed publicly through $context->contextlevel
5077 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
5079 protected $_contextlevel;
5082 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
5083 * Can be accessed publicly through $context->instanceid
5084 * @var int
5086 protected $_instanceid;
5089 * The path to the context always starting from the system context
5090 * Can be accessed publicly through $context->path
5091 * @var string
5093 protected $_path;
5096 * The depth of the context in relation to parent contexts
5097 * Can be accessed publicly through $context->depth
5098 * @var int
5100 protected $_depth;
5103 * @var array Context caching info
5105 private static $cache_contextsbyid = array();
5108 * @var array Context caching info
5110 private static $cache_contexts = array();
5113 * Context count
5114 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
5115 * @var int
5117 protected static $cache_count = 0;
5120 * @var array Context caching info
5122 protected static $cache_preloaded = array();
5125 * @var context_system The system context once initialised
5127 protected static $systemcontext = null;
5130 * Resets the cache to remove all data.
5131 * @static
5133 protected static function reset_caches() {
5134 self::$cache_contextsbyid = array();
5135 self::$cache_contexts = array();
5136 self::$cache_count = 0;
5137 self::$cache_preloaded = array();
5139 self::$systemcontext = null;
5143 * Adds a context to the cache. If the cache is full, discards a batch of
5144 * older entries.
5146 * @static
5147 * @param context $context New context to add
5148 * @return void
5150 protected static function cache_add(context $context) {
5151 if (isset(self::$cache_contextsbyid[$context->id])) {
5152 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5153 return;
5156 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
5157 $i = 0;
5158 foreach(self::$cache_contextsbyid as $ctx) {
5159 $i++;
5160 if ($i <= 100) {
5161 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
5162 continue;
5164 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
5165 // we remove oldest third of the contexts to make room for more contexts
5166 break;
5168 unset(self::$cache_contextsbyid[$ctx->id]);
5169 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
5170 self::$cache_count--;
5174 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
5175 self::$cache_contextsbyid[$context->id] = $context;
5176 self::$cache_count++;
5180 * Removes a context from the cache.
5182 * @static
5183 * @param context $context Context object to remove
5184 * @return void
5186 protected static function cache_remove(context $context) {
5187 if (!isset(self::$cache_contextsbyid[$context->id])) {
5188 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5189 return;
5191 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
5192 unset(self::$cache_contextsbyid[$context->id]);
5194 self::$cache_count--;
5196 if (self::$cache_count < 0) {
5197 self::$cache_count = 0;
5202 * Gets a context from the cache.
5204 * @static
5205 * @param int $contextlevel Context level
5206 * @param int $instance Instance ID
5207 * @return context|bool Context or false if not in cache
5209 protected static function cache_get($contextlevel, $instance) {
5210 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
5211 return self::$cache_contexts[$contextlevel][$instance];
5213 return false;
5217 * Gets a context from the cache based on its id.
5219 * @static
5220 * @param int $id Context ID
5221 * @return context|bool Context or false if not in cache
5223 protected static function cache_get_by_id($id) {
5224 if (isset(self::$cache_contextsbyid[$id])) {
5225 return self::$cache_contextsbyid[$id];
5227 return false;
5231 * Preloads context information from db record and strips the cached info.
5233 * @static
5234 * @param stdClass $rec
5235 * @return void (modifies $rec)
5237 protected static function preload_from_record(stdClass $rec) {
5238 if (empty($rec->ctxid) or empty($rec->ctxlevel) or !isset($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
5239 // $rec does not have enough data, passed here repeatedly or context does not exist yet
5240 return;
5243 // note: in PHP5 the objects are passed by reference, no need to return $rec
5244 $record = new stdClass();
5245 $record->id = $rec->ctxid; unset($rec->ctxid);
5246 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
5247 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
5248 $record->path = $rec->ctxpath; unset($rec->ctxpath);
5249 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
5251 return context::create_instance_from_record($record);
5255 // ====== magic methods =======
5258 * Magic setter method, we do not want anybody to modify properties from the outside
5259 * @param string $name
5260 * @param mixed $value
5262 public function __set($name, $value) {
5263 debugging('Can not change context instance properties!');
5267 * Magic method getter, redirects to read only values.
5268 * @param string $name
5269 * @return mixed
5271 public function __get($name) {
5272 switch ($name) {
5273 case 'id': return $this->_id;
5274 case 'contextlevel': return $this->_contextlevel;
5275 case 'instanceid': return $this->_instanceid;
5276 case 'path': return $this->_path;
5277 case 'depth': return $this->_depth;
5279 default:
5280 debugging('Invalid context property accessed! '.$name);
5281 return null;
5286 * Full support for isset on our magic read only properties.
5287 * @param string $name
5288 * @return bool
5290 public function __isset($name) {
5291 switch ($name) {
5292 case 'id': return isset($this->_id);
5293 case 'contextlevel': return isset($this->_contextlevel);
5294 case 'instanceid': return isset($this->_instanceid);
5295 case 'path': return isset($this->_path);
5296 case 'depth': return isset($this->_depth);
5298 default: return false;
5304 * ALl properties are read only, sorry.
5305 * @param string $name
5307 public function __unset($name) {
5308 debugging('Can not unset context instance properties!');
5311 // ====== implementing method from interface IteratorAggregate ======
5314 * Create an iterator because magic vars can't be seen by 'foreach'.
5316 * Now we can convert context object to array using convert_to_array(),
5317 * and feed it properly to json_encode().
5319 public function getIterator() {
5320 $ret = array(
5321 'id' => $this->id,
5322 'contextlevel' => $this->contextlevel,
5323 'instanceid' => $this->instanceid,
5324 'path' => $this->path,
5325 'depth' => $this->depth
5327 return new ArrayIterator($ret);
5330 // ====== general context methods ======
5333 * Constructor is protected so that devs are forced to
5334 * use context_xxx::instance() or context::instance_by_id().
5336 * @param stdClass $record
5338 protected function __construct(stdClass $record) {
5339 $this->_id = (int)$record->id;
5340 $this->_contextlevel = (int)$record->contextlevel;
5341 $this->_instanceid = $record->instanceid;
5342 $this->_path = $record->path;
5343 $this->_depth = $record->depth;
5347 * This function is also used to work around 'protected' keyword problems in context_helper.
5348 * @static
5349 * @param stdClass $record
5350 * @return context instance
5352 protected static function create_instance_from_record(stdClass $record) {
5353 $classname = context_helper::get_class_for_level($record->contextlevel);
5355 if ($context = context::cache_get_by_id($record->id)) {
5356 return $context;
5359 $context = new $classname($record);
5360 context::cache_add($context);
5362 return $context;
5366 * Copy prepared new contexts from temp table to context table,
5367 * we do this in db specific way for perf reasons only.
5368 * @static
5370 protected static function merge_context_temp_table() {
5371 global $DB;
5373 /* MDL-11347:
5374 * - mysql does not allow to use FROM in UPDATE statements
5375 * - using two tables after UPDATE works in mysql, but might give unexpected
5376 * results in pg 8 (depends on configuration)
5377 * - using table alias in UPDATE does not work in pg < 8.2
5379 * Different code for each database - mostly for performance reasons
5382 $dbfamily = $DB->get_dbfamily();
5383 if ($dbfamily == 'mysql') {
5384 $updatesql = "UPDATE {context} ct, {context_temp} temp
5385 SET ct.path = temp.path,
5386 ct.depth = temp.depth
5387 WHERE ct.id = temp.id";
5388 } else if ($dbfamily == 'oracle') {
5389 $updatesql = "UPDATE {context} ct
5390 SET (ct.path, ct.depth) =
5391 (SELECT temp.path, temp.depth
5392 FROM {context_temp} temp
5393 WHERE temp.id=ct.id)
5394 WHERE EXISTS (SELECT 'x'
5395 FROM {context_temp} temp
5396 WHERE temp.id = ct.id)";
5397 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5398 $updatesql = "UPDATE {context}
5399 SET path = temp.path,
5400 depth = temp.depth
5401 FROM {context_temp} temp
5402 WHERE temp.id={context}.id";
5403 } else {
5404 // sqlite and others
5405 $updatesql = "UPDATE {context}
5406 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5407 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5408 WHERE id IN (SELECT id FROM {context_temp})";
5411 $DB->execute($updatesql);
5415 * Get a context instance as an object, from a given context id.
5417 * @static
5418 * @param int $id context id
5419 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5420 * MUST_EXIST means throw exception if no record found
5421 * @return context|bool the context object or false if not found
5423 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5424 global $DB;
5426 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5427 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5428 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5431 if ($id == SYSCONTEXTID) {
5432 return context_system::instance(0, $strictness);
5435 if (is_array($id) or is_object($id) or empty($id)) {
5436 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5439 if ($context = context::cache_get_by_id($id)) {
5440 return $context;
5443 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5444 return context::create_instance_from_record($record);
5447 return false;
5451 * Update context info after moving context in the tree structure.
5453 * @param context $newparent
5454 * @return void
5456 public function update_moved(context $newparent) {
5457 global $DB;
5459 $frompath = $this->_path;
5460 $newpath = $newparent->path . '/' . $this->_id;
5462 $trans = $DB->start_delegated_transaction();
5464 $this->mark_dirty();
5466 $setdepth = '';
5467 if (($newparent->depth +1) != $this->_depth) {
5468 $diff = $newparent->depth - $this->_depth + 1;
5469 $setdepth = ", depth = depth + $diff";
5471 $sql = "UPDATE {context}
5472 SET path = ?
5473 $setdepth
5474 WHERE id = ?";
5475 $params = array($newpath, $this->_id);
5476 $DB->execute($sql, $params);
5478 $this->_path = $newpath;
5479 $this->_depth = $newparent->depth + 1;
5481 $sql = "UPDATE {context}
5482 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5483 $setdepth
5484 WHERE path LIKE ?";
5485 $params = array($newpath, "{$frompath}/%");
5486 $DB->execute($sql, $params);
5488 $this->mark_dirty();
5490 context::reset_caches();
5492 $trans->allow_commit();
5496 * Remove all context path info and optionally rebuild it.
5498 * @param bool $rebuild
5499 * @return void
5501 public function reset_paths($rebuild = true) {
5502 global $DB;
5504 if ($this->_path) {
5505 $this->mark_dirty();
5507 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5508 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5509 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5510 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5511 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5512 $this->_depth = 0;
5513 $this->_path = null;
5516 if ($rebuild) {
5517 context_helper::build_all_paths(false);
5520 context::reset_caches();
5524 * Delete all data linked to content, do not delete the context record itself
5526 public function delete_content() {
5527 global $CFG, $DB;
5529 blocks_delete_all_for_context($this->_id);
5530 filter_delete_all_for_context($this->_id);
5532 require_once($CFG->dirroot . '/comment/lib.php');
5533 comment::delete_comments(array('contextid'=>$this->_id));
5535 require_once($CFG->dirroot.'/rating/lib.php');
5536 $delopt = new stdclass();
5537 $delopt->contextid = $this->_id;
5538 $rm = new rating_manager();
5539 $rm->delete_ratings($delopt);
5541 // delete all files attached to this context
5542 $fs = get_file_storage();
5543 $fs->delete_area_files($this->_id);
5545 // Delete all repository instances attached to this context.
5546 require_once($CFG->dirroot . '/repository/lib.php');
5547 repository::delete_all_for_context($this->_id);
5549 // delete all advanced grading data attached to this context
5550 require_once($CFG->dirroot.'/grade/grading/lib.php');
5551 grading_manager::delete_all_for_context($this->_id);
5553 // now delete stuff from role related tables, role_unassign_all
5554 // and unenrol should be called earlier to do proper cleanup
5555 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5556 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5557 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5561 * Delete the context content and the context record itself
5563 public function delete() {
5564 global $DB;
5566 if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5567 throw new coding_exception('Cannot delete system context');
5570 // double check the context still exists
5571 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5572 context::cache_remove($this);
5573 return;
5576 $this->delete_content();
5577 $DB->delete_records('context', array('id'=>$this->_id));
5578 // purge static context cache if entry present
5579 context::cache_remove($this);
5581 // do not mark dirty contexts if parents unknown
5582 if (!is_null($this->_path) and $this->_depth > 0) {
5583 $this->mark_dirty();
5587 // ====== context level related methods ======
5590 * Utility method for context creation
5592 * @static
5593 * @param int $contextlevel
5594 * @param int $instanceid
5595 * @param string $parentpath
5596 * @return stdClass context record
5598 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5599 global $DB;
5601 $record = new stdClass();
5602 $record->contextlevel = $contextlevel;
5603 $record->instanceid = $instanceid;
5604 $record->depth = 0;
5605 $record->path = null; //not known before insert
5607 $record->id = $DB->insert_record('context', $record);
5609 // now add path if known - it can be added later
5610 if (!is_null($parentpath)) {
5611 $record->path = $parentpath.'/'.$record->id;
5612 $record->depth = substr_count($record->path, '/');
5613 $DB->update_record('context', $record);
5616 return $record;
5620 * Returns human readable context identifier.
5622 * @param boolean $withprefix whether to prefix the name of the context with the
5623 * type of context, e.g. User, Course, Forum, etc.
5624 * @param boolean $short whether to use the short name of the thing. Only applies
5625 * to course contexts
5626 * @return string the human readable context name.
5628 public function get_context_name($withprefix = true, $short = false) {
5629 // must be implemented in all context levels
5630 throw new coding_exception('can not get name of abstract context');
5634 * Returns the most relevant URL for this context.
5636 * @return moodle_url
5638 public abstract function get_url();
5641 * Returns array of relevant context capability records.
5643 * @return array
5645 public abstract function get_capabilities();
5648 * Recursive function which, given a context, find all its children context ids.
5650 * For course category contexts it will return immediate children and all subcategory contexts.
5651 * It will NOT recurse into courses or subcategories categories.
5652 * If you want to do that, call it on the returned courses/categories.
5654 * When called for a course context, it will return the modules and blocks
5655 * displayed in the course page and blocks displayed on the module pages.
5657 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5658 * contexts ;-)
5660 * @return array Array of child records
5662 public function get_child_contexts() {
5663 global $DB;
5665 if (empty($this->_path) or empty($this->_depth)) {
5666 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5667 return array();
5670 $sql = "SELECT ctx.*
5671 FROM {context} ctx
5672 WHERE ctx.path LIKE ?";
5673 $params = array($this->_path.'/%');
5674 $records = $DB->get_records_sql($sql, $params);
5676 $result = array();
5677 foreach ($records as $record) {
5678 $result[$record->id] = context::create_instance_from_record($record);
5681 return $result;
5685 * Returns parent contexts of this context in reversed order, i.e. parent first,
5686 * then grand parent, etc.
5688 * @param bool $includeself tre means include self too
5689 * @return array of context instances
5691 public function get_parent_contexts($includeself = false) {
5692 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5693 return array();
5696 $result = array();
5697 foreach ($contextids as $contextid) {
5698 $parent = context::instance_by_id($contextid, MUST_EXIST);
5699 $result[$parent->id] = $parent;
5702 return $result;
5706 * Returns parent contexts of this context in reversed order, i.e. parent first,
5707 * then grand parent, etc.
5709 * @param bool $includeself tre means include self too
5710 * @return array of context ids
5712 public function get_parent_context_ids($includeself = false) {
5713 if (empty($this->_path)) {
5714 return array();
5717 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5718 $parentcontexts = explode('/', $parentcontexts);
5719 if (!$includeself) {
5720 array_pop($parentcontexts); // and remove its own id
5723 return array_reverse($parentcontexts);
5727 * Returns parent context
5729 * @return context
5731 public function get_parent_context() {
5732 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5733 return false;
5736 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5737 $parentcontexts = explode('/', $parentcontexts);
5738 array_pop($parentcontexts); // self
5739 $contextid = array_pop($parentcontexts); // immediate parent
5741 return context::instance_by_id($contextid, MUST_EXIST);
5745 * Is this context part of any course? If yes return course context.
5747 * @param bool $strict true means throw exception if not found, false means return false if not found
5748 * @return context_course context of the enclosing course, null if not found or exception
5750 public function get_course_context($strict = true) {
5751 if ($strict) {
5752 throw new coding_exception('Context does not belong to any course.');
5753 } else {
5754 return false;
5759 * Returns sql necessary for purging of stale context instances.
5761 * @static
5762 * @return string cleanup SQL
5764 protected static function get_cleanup_sql() {
5765 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5769 * Rebuild context paths and depths at context level.
5771 * @static
5772 * @param bool $force
5773 * @return void
5775 protected static function build_paths($force) {
5776 throw new coding_exception('build_paths() method must be implemented in all context levels');
5780 * Create missing context instances at given level
5782 * @static
5783 * @return void
5785 protected static function create_level_instances() {
5786 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5790 * Reset all cached permissions and definitions if the necessary.
5791 * @return void
5793 public function reload_if_dirty() {
5794 global $ACCESSLIB_PRIVATE, $USER;
5796 // Load dirty contexts list if needed
5797 if (CLI_SCRIPT) {
5798 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5799 // we do not load dirty flags in CLI and cron
5800 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5802 } else {
5803 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5804 if (!isset($USER->access['time'])) {
5805 // nothing was loaded yet, we do not need to check dirty contexts now
5806 return;
5808 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5809 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5813 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5814 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5815 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5816 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5817 reload_all_capabilities();
5818 break;
5824 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5826 public function mark_dirty() {
5827 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5829 if (during_initial_install()) {
5830 return;
5833 // only if it is a non-empty string
5834 if (is_string($this->_path) && $this->_path !== '') {
5835 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5836 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5837 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5838 } else {
5839 if (CLI_SCRIPT) {
5840 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5841 } else {
5842 if (isset($USER->access['time'])) {
5843 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5844 } else {
5845 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5847 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5856 * Context maintenance and helper methods.
5858 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5859 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5860 * level implementation from the rest of code, the code completion returns what developers need.
5862 * Thank you Tim Hunt for helping me with this nasty trick.
5864 * @package core_access
5865 * @category access
5866 * @copyright Petr Skoda {@link http://skodak.org}
5867 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5868 * @since Moodle 2.2
5870 class context_helper extends context {
5873 * @var array An array mapping context levels to classes
5875 private static $alllevels;
5878 * Instance does not make sense here, only static use
5880 protected function __construct() {
5884 * Reset internal context levels array.
5886 public static function reset_levels() {
5887 self::$alllevels = null;
5891 * Initialise context levels, call before using self::$alllevels.
5893 private static function init_levels() {
5894 global $CFG;
5896 if (isset(self::$alllevels)) {
5897 return;
5899 self::$alllevels = array(
5900 CONTEXT_SYSTEM => 'context_system',
5901 CONTEXT_USER => 'context_user',
5902 CONTEXT_COURSECAT => 'context_coursecat',
5903 CONTEXT_COURSE => 'context_course',
5904 CONTEXT_MODULE => 'context_module',
5905 CONTEXT_BLOCK => 'context_block',
5908 if (empty($CFG->custom_context_classes)) {
5909 return;
5912 $levels = $CFG->custom_context_classes;
5913 if (!is_array($levels)) {
5914 $levels = @unserialize($levels);
5916 if (!is_array($levels)) {
5917 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
5918 return;
5921 // Unsupported custom levels, use with care!!!
5922 foreach ($levels as $level => $classname) {
5923 self::$alllevels[$level] = $classname;
5925 ksort(self::$alllevels);
5929 * Returns a class name of the context level class
5931 * @static
5932 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5933 * @return string class name of the context class
5935 public static function get_class_for_level($contextlevel) {
5936 self::init_levels();
5937 if (isset(self::$alllevels[$contextlevel])) {
5938 return self::$alllevels[$contextlevel];
5939 } else {
5940 throw new coding_exception('Invalid context level specified');
5945 * Returns a list of all context levels
5947 * @static
5948 * @return array int=>string (level=>level class name)
5950 public static function get_all_levels() {
5951 self::init_levels();
5952 return self::$alllevels;
5956 * Remove stale contexts that belonged to deleted instances.
5957 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5959 * @static
5960 * @return void
5962 public static function cleanup_instances() {
5963 global $DB;
5964 self::init_levels();
5966 $sqls = array();
5967 foreach (self::$alllevels as $level=>$classname) {
5968 $sqls[] = $classname::get_cleanup_sql();
5971 $sql = implode(" UNION ", $sqls);
5973 // it is probably better to use transactions, it might be faster too
5974 $transaction = $DB->start_delegated_transaction();
5976 $rs = $DB->get_recordset_sql($sql);
5977 foreach ($rs as $record) {
5978 $context = context::create_instance_from_record($record);
5979 $context->delete();
5981 $rs->close();
5983 $transaction->allow_commit();
5987 * Create all context instances at the given level and above.
5989 * @static
5990 * @param int $contextlevel null means all levels
5991 * @param bool $buildpaths
5992 * @return void
5994 public static function create_instances($contextlevel = null, $buildpaths = true) {
5995 self::init_levels();
5996 foreach (self::$alllevels as $level=>$classname) {
5997 if ($contextlevel and $level > $contextlevel) {
5998 // skip potential sub-contexts
5999 continue;
6001 $classname::create_level_instances();
6002 if ($buildpaths) {
6003 $classname::build_paths(false);
6009 * Rebuild paths and depths in all context levels.
6011 * @static
6012 * @param bool $force false means add missing only
6013 * @return void
6015 public static function build_all_paths($force = false) {
6016 self::init_levels();
6017 foreach (self::$alllevels as $classname) {
6018 $classname::build_paths($force);
6021 // reset static course cache - it might have incorrect cached data
6022 accesslib_clear_all_caches(true);
6026 * Resets the cache to remove all data.
6027 * @static
6029 public static function reset_caches() {
6030 context::reset_caches();
6034 * Returns all fields necessary for context preloading from user $rec.
6036 * This helps with performance when dealing with hundreds of contexts.
6038 * @static
6039 * @param string $tablealias context table alias in the query
6040 * @return array (table.column=>alias, ...)
6042 public static function get_preload_record_columns($tablealias) {
6043 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
6047 * Returns all fields necessary for context preloading from user $rec.
6049 * This helps with performance when dealing with hundreds of contexts.
6051 * @static
6052 * @param string $tablealias context table alias in the query
6053 * @return string
6055 public static function get_preload_record_columns_sql($tablealias) {
6056 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
6060 * Preloads context information from db record and strips the cached info.
6062 * The db request has to contain all columns from context_helper::get_preload_record_columns().
6064 * @static
6065 * @param stdClass $rec
6066 * @return void (modifies $rec)
6068 public static function preload_from_record(stdClass $rec) {
6069 context::preload_from_record($rec);
6073 * Preload all contexts instances from course.
6075 * To be used if you expect multiple queries for course activities...
6077 * @static
6078 * @param int $courseid
6080 public static function preload_course($courseid) {
6081 // Users can call this multiple times without doing any harm
6082 if (isset(context::$cache_preloaded[$courseid])) {
6083 return;
6085 $coursecontext = context_course::instance($courseid);
6086 $coursecontext->get_child_contexts();
6088 context::$cache_preloaded[$courseid] = true;
6092 * Delete context instance
6094 * @static
6095 * @param int $contextlevel
6096 * @param int $instanceid
6097 * @return void
6099 public static function delete_instance($contextlevel, $instanceid) {
6100 global $DB;
6102 // double check the context still exists
6103 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
6104 $context = context::create_instance_from_record($record);
6105 $context->delete();
6106 } else {
6107 // we should try to purge the cache anyway
6112 * Returns the name of specified context level
6114 * @static
6115 * @param int $contextlevel
6116 * @return string name of the context level
6118 public static function get_level_name($contextlevel) {
6119 $classname = context_helper::get_class_for_level($contextlevel);
6120 return $classname::get_level_name();
6124 * not used
6126 public function get_url() {
6130 * not used
6132 public function get_capabilities() {
6138 * System context class
6140 * @package core_access
6141 * @category access
6142 * @copyright Petr Skoda {@link http://skodak.org}
6143 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6144 * @since Moodle 2.2
6146 class context_system extends context {
6148 * Please use context_system::instance() if you need the instance of context.
6150 * @param stdClass $record
6152 protected function __construct(stdClass $record) {
6153 parent::__construct($record);
6154 if ($record->contextlevel != CONTEXT_SYSTEM) {
6155 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
6160 * Returns human readable context level name.
6162 * @static
6163 * @return string the human readable context level name.
6165 public static function get_level_name() {
6166 return get_string('coresystem');
6170 * Returns human readable context identifier.
6172 * @param boolean $withprefix does not apply to system context
6173 * @param boolean $short does not apply to system context
6174 * @return string the human readable context name.
6176 public function get_context_name($withprefix = true, $short = false) {
6177 return self::get_level_name();
6181 * Returns the most relevant URL for this context.
6183 * @return moodle_url
6185 public function get_url() {
6186 return new moodle_url('/');
6190 * Returns array of relevant context capability records.
6192 * @return array
6194 public function get_capabilities() {
6195 global $DB;
6197 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6199 $params = array();
6200 $sql = "SELECT *
6201 FROM {capabilities}";
6203 return $DB->get_records_sql($sql.' '.$sort, $params);
6207 * Create missing context instances at system context
6208 * @static
6210 protected static function create_level_instances() {
6211 // nothing to do here, the system context is created automatically in installer
6212 self::instance(0);
6216 * Returns system context instance.
6218 * @static
6219 * @param int $instanceid
6220 * @param int $strictness
6221 * @param bool $cache
6222 * @return context_system context instance
6224 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
6225 global $DB;
6227 if ($instanceid != 0) {
6228 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
6231 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
6232 if (!isset(context::$systemcontext)) {
6233 $record = new stdClass();
6234 $record->id = SYSCONTEXTID;
6235 $record->contextlevel = CONTEXT_SYSTEM;
6236 $record->instanceid = 0;
6237 $record->path = '/'.SYSCONTEXTID;
6238 $record->depth = 1;
6239 context::$systemcontext = new context_system($record);
6241 return context::$systemcontext;
6245 try {
6246 // We ignore the strictness completely because system context must exist except during install.
6247 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6248 } catch (dml_exception $e) {
6249 //table or record does not exist
6250 if (!during_initial_install()) {
6251 // do not mess with system context after install, it simply must exist
6252 throw $e;
6254 $record = null;
6257 if (!$record) {
6258 $record = new stdClass();
6259 $record->contextlevel = CONTEXT_SYSTEM;
6260 $record->instanceid = 0;
6261 $record->depth = 1;
6262 $record->path = null; //not known before insert
6264 try {
6265 if ($DB->count_records('context')) {
6266 // contexts already exist, this is very weird, system must be first!!!
6267 return null;
6269 if (defined('SYSCONTEXTID')) {
6270 // this would happen only in unittest on sites that went through weird 1.7 upgrade
6271 $record->id = SYSCONTEXTID;
6272 $DB->import_record('context', $record);
6273 $DB->get_manager()->reset_sequence('context');
6274 } else {
6275 $record->id = $DB->insert_record('context', $record);
6277 } catch (dml_exception $e) {
6278 // can not create context - table does not exist yet, sorry
6279 return null;
6283 if ($record->instanceid != 0) {
6284 // this is very weird, somebody must be messing with context table
6285 debugging('Invalid system context detected');
6288 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6289 // fix path if necessary, initial install or path reset
6290 $record->depth = 1;
6291 $record->path = '/'.$record->id;
6292 $DB->update_record('context', $record);
6295 if (!defined('SYSCONTEXTID')) {
6296 define('SYSCONTEXTID', $record->id);
6299 context::$systemcontext = new context_system($record);
6300 return context::$systemcontext;
6304 * Returns all site contexts except the system context, DO NOT call on production servers!!
6306 * Contexts are not cached.
6308 * @return array
6310 public function get_child_contexts() {
6311 global $DB;
6313 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6315 // Just get all the contexts except for CONTEXT_SYSTEM level
6316 // and hope we don't OOM in the process - don't cache
6317 $sql = "SELECT c.*
6318 FROM {context} c
6319 WHERE contextlevel > ".CONTEXT_SYSTEM;
6320 $records = $DB->get_records_sql($sql);
6322 $result = array();
6323 foreach ($records as $record) {
6324 $result[$record->id] = context::create_instance_from_record($record);
6327 return $result;
6331 * Returns sql necessary for purging of stale context instances.
6333 * @static
6334 * @return string cleanup SQL
6336 protected static function get_cleanup_sql() {
6337 $sql = "
6338 SELECT c.*
6339 FROM {context} c
6340 WHERE 1=2
6343 return $sql;
6347 * Rebuild context paths and depths at system context level.
6349 * @static
6350 * @param bool $force
6352 protected static function build_paths($force) {
6353 global $DB;
6355 /* note: ignore $force here, we always do full test of system context */
6357 // exactly one record must exist
6358 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6360 if ($record->instanceid != 0) {
6361 debugging('Invalid system context detected');
6364 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6365 debugging('Invalid SYSCONTEXTID detected');
6368 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6369 // fix path if necessary, initial install or path reset
6370 $record->depth = 1;
6371 $record->path = '/'.$record->id;
6372 $DB->update_record('context', $record);
6379 * User context class
6381 * @package core_access
6382 * @category access
6383 * @copyright Petr Skoda {@link http://skodak.org}
6384 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6385 * @since Moodle 2.2
6387 class context_user extends context {
6389 * Please use context_user::instance($userid) if you need the instance of context.
6390 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6392 * @param stdClass $record
6394 protected function __construct(stdClass $record) {
6395 parent::__construct($record);
6396 if ($record->contextlevel != CONTEXT_USER) {
6397 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6402 * Returns human readable context level name.
6404 * @static
6405 * @return string the human readable context level name.
6407 public static function get_level_name() {
6408 return get_string('user');
6412 * Returns human readable context identifier.
6414 * @param boolean $withprefix whether to prefix the name of the context with User
6415 * @param boolean $short does not apply to user context
6416 * @return string the human readable context name.
6418 public function get_context_name($withprefix = true, $short = false) {
6419 global $DB;
6421 $name = '';
6422 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6423 if ($withprefix){
6424 $name = get_string('user').': ';
6426 $name .= fullname($user);
6428 return $name;
6432 * Returns the most relevant URL for this context.
6434 * @return moodle_url
6436 public function get_url() {
6437 global $COURSE;
6439 if ($COURSE->id == SITEID) {
6440 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6441 } else {
6442 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6444 return $url;
6448 * Returns array of relevant context capability records.
6450 * @return array
6452 public function get_capabilities() {
6453 global $DB;
6455 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6457 $extracaps = array('moodle/grade:viewall');
6458 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6459 $sql = "SELECT *
6460 FROM {capabilities}
6461 WHERE contextlevel = ".CONTEXT_USER."
6462 OR name $extra";
6464 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6468 * Returns user context instance.
6470 * @static
6471 * @param int $instanceid
6472 * @param int $strictness
6473 * @return context_user context instance
6475 public static function instance($instanceid, $strictness = MUST_EXIST) {
6476 global $DB;
6478 if ($context = context::cache_get(CONTEXT_USER, $instanceid)) {
6479 return $context;
6482 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_USER, 'instanceid'=>$instanceid))) {
6483 if ($user = $DB->get_record('user', array('id'=>$instanceid, 'deleted'=>0), 'id', $strictness)) {
6484 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6488 if ($record) {
6489 $context = new context_user($record);
6490 context::cache_add($context);
6491 return $context;
6494 return false;
6498 * Create missing context instances at user context level
6499 * @static
6501 protected static function create_level_instances() {
6502 global $DB;
6504 $sql = "SELECT ".CONTEXT_USER.", u.id
6505 FROM {user} u
6506 WHERE u.deleted = 0
6507 AND NOT EXISTS (SELECT 'x'
6508 FROM {context} cx
6509 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6510 $contextdata = $DB->get_recordset_sql($sql);
6511 foreach ($contextdata as $context) {
6512 context::insert_context_record(CONTEXT_USER, $context->id, null);
6514 $contextdata->close();
6518 * Returns sql necessary for purging of stale context instances.
6520 * @static
6521 * @return string cleanup SQL
6523 protected static function get_cleanup_sql() {
6524 $sql = "
6525 SELECT c.*
6526 FROM {context} c
6527 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6528 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6531 return $sql;
6535 * Rebuild context paths and depths at user context level.
6537 * @static
6538 * @param bool $force
6540 protected static function build_paths($force) {
6541 global $DB;
6543 // First update normal users.
6544 $path = $DB->sql_concat('?', 'id');
6545 $pathstart = '/' . SYSCONTEXTID . '/';
6546 $params = array($pathstart);
6548 if ($force) {
6549 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6550 $params[] = $pathstart;
6551 } else {
6552 $where = "depth = 0 OR path IS NULL";
6555 $sql = "UPDATE {context}
6556 SET depth = 2,
6557 path = {$path}
6558 WHERE contextlevel = " . CONTEXT_USER . "
6559 AND ($where)";
6560 $DB->execute($sql, $params);
6566 * Course category context class
6568 * @package core_access
6569 * @category access
6570 * @copyright Petr Skoda {@link http://skodak.org}
6571 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6572 * @since Moodle 2.2
6574 class context_coursecat extends context {
6576 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6577 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6579 * @param stdClass $record
6581 protected function __construct(stdClass $record) {
6582 parent::__construct($record);
6583 if ($record->contextlevel != CONTEXT_COURSECAT) {
6584 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6589 * Returns human readable context level name.
6591 * @static
6592 * @return string the human readable context level name.
6594 public static function get_level_name() {
6595 return get_string('category');
6599 * Returns human readable context identifier.
6601 * @param boolean $withprefix whether to prefix the name of the context with Category
6602 * @param boolean $short does not apply to course categories
6603 * @return string the human readable context name.
6605 public function get_context_name($withprefix = true, $short = false) {
6606 global $DB;
6608 $name = '';
6609 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6610 if ($withprefix){
6611 $name = get_string('category').': ';
6613 $name .= format_string($category->name, true, array('context' => $this));
6615 return $name;
6619 * Returns the most relevant URL for this context.
6621 * @return moodle_url
6623 public function get_url() {
6624 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6628 * Returns array of relevant context capability records.
6630 * @return array
6632 public function get_capabilities() {
6633 global $DB;
6635 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6637 $params = array();
6638 $sql = "SELECT *
6639 FROM {capabilities}
6640 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6642 return $DB->get_records_sql($sql.' '.$sort, $params);
6646 * Returns course category context instance.
6648 * @static
6649 * @param int $instanceid
6650 * @param int $strictness
6651 * @return context_coursecat context instance
6653 public static function instance($instanceid, $strictness = MUST_EXIST) {
6654 global $DB;
6656 if ($context = context::cache_get(CONTEXT_COURSECAT, $instanceid)) {
6657 return $context;
6660 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSECAT, 'instanceid'=>$instanceid))) {
6661 if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), 'id,parent', $strictness)) {
6662 if ($category->parent) {
6663 $parentcontext = context_coursecat::instance($category->parent);
6664 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6665 } else {
6666 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6671 if ($record) {
6672 $context = new context_coursecat($record);
6673 context::cache_add($context);
6674 return $context;
6677 return false;
6681 * Returns immediate child contexts of category and all subcategories,
6682 * children of subcategories and courses are not returned.
6684 * @return array
6686 public function get_child_contexts() {
6687 global $DB;
6689 if (empty($this->_path) or empty($this->_depth)) {
6690 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6691 return array();
6694 $sql = "SELECT ctx.*
6695 FROM {context} ctx
6696 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6697 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6698 $records = $DB->get_records_sql($sql, $params);
6700 $result = array();
6701 foreach ($records as $record) {
6702 $result[$record->id] = context::create_instance_from_record($record);
6705 return $result;
6709 * Create missing context instances at course category context level
6710 * @static
6712 protected static function create_level_instances() {
6713 global $DB;
6715 $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6716 FROM {course_categories} cc
6717 WHERE NOT EXISTS (SELECT 'x'
6718 FROM {context} cx
6719 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6720 $contextdata = $DB->get_recordset_sql($sql);
6721 foreach ($contextdata as $context) {
6722 context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6724 $contextdata->close();
6728 * Returns sql necessary for purging of stale context instances.
6730 * @static
6731 * @return string cleanup SQL
6733 protected static function get_cleanup_sql() {
6734 $sql = "
6735 SELECT c.*
6736 FROM {context} c
6737 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6738 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6741 return $sql;
6745 * Rebuild context paths and depths at course category context level.
6747 * @static
6748 * @param bool $force
6750 protected static function build_paths($force) {
6751 global $DB;
6753 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6754 if ($force) {
6755 $ctxemptyclause = $emptyclause = '';
6756 } else {
6757 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6758 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6761 $base = '/'.SYSCONTEXTID;
6763 // Normal top level categories
6764 $sql = "UPDATE {context}
6765 SET depth=2,
6766 path=".$DB->sql_concat("'$base/'", 'id')."
6767 WHERE contextlevel=".CONTEXT_COURSECAT."
6768 AND EXISTS (SELECT 'x'
6769 FROM {course_categories} cc
6770 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6771 $emptyclause";
6772 $DB->execute($sql);
6774 // Deeper categories - one query per depthlevel
6775 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6776 for ($n=2; $n<=$maxdepth; $n++) {
6777 $sql = "INSERT INTO {context_temp} (id, path, depth)
6778 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6779 FROM {context} ctx
6780 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6781 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6782 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6783 $ctxemptyclause";
6784 $trans = $DB->start_delegated_transaction();
6785 $DB->delete_records('context_temp');
6786 $DB->execute($sql);
6787 context::merge_context_temp_table();
6788 $DB->delete_records('context_temp');
6789 $trans->allow_commit();
6798 * Course context class
6800 * @package core_access
6801 * @category access
6802 * @copyright Petr Skoda {@link http://skodak.org}
6803 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6804 * @since Moodle 2.2
6806 class context_course extends context {
6808 * Please use context_course::instance($courseid) if you need the instance of context.
6809 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6811 * @param stdClass $record
6813 protected function __construct(stdClass $record) {
6814 parent::__construct($record);
6815 if ($record->contextlevel != CONTEXT_COURSE) {
6816 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6821 * Returns human readable context level name.
6823 * @static
6824 * @return string the human readable context level name.
6826 public static function get_level_name() {
6827 return get_string('course');
6831 * Returns human readable context identifier.
6833 * @param boolean $withprefix whether to prefix the name of the context with Course
6834 * @param boolean $short whether to use the short name of the thing.
6835 * @return string the human readable context name.
6837 public function get_context_name($withprefix = true, $short = false) {
6838 global $DB;
6840 $name = '';
6841 if ($this->_instanceid == SITEID) {
6842 $name = get_string('frontpage', 'admin');
6843 } else {
6844 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6845 if ($withprefix){
6846 $name = get_string('course').': ';
6848 if ($short){
6849 $name .= format_string($course->shortname, true, array('context' => $this));
6850 } else {
6851 $name .= format_string(get_course_display_name_for_list($course));
6855 return $name;
6859 * Returns the most relevant URL for this context.
6861 * @return moodle_url
6863 public function get_url() {
6864 if ($this->_instanceid != SITEID) {
6865 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6868 return new moodle_url('/');
6872 * Returns array of relevant context capability records.
6874 * @return array
6876 public function get_capabilities() {
6877 global $DB;
6879 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6881 $params = array();
6882 $sql = "SELECT *
6883 FROM {capabilities}
6884 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6886 return $DB->get_records_sql($sql.' '.$sort, $params);
6890 * Is this context part of any course? If yes return course context.
6892 * @param bool $strict true means throw exception if not found, false means return false if not found
6893 * @return context_course context of the enclosing course, null if not found or exception
6895 public function get_course_context($strict = true) {
6896 return $this;
6900 * Returns course context instance.
6902 * @static
6903 * @param int $instanceid
6904 * @param int $strictness
6905 * @return context_course context instance
6907 public static function instance($instanceid, $strictness = MUST_EXIST) {
6908 global $DB;
6910 if ($context = context::cache_get(CONTEXT_COURSE, $instanceid)) {
6911 return $context;
6914 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$instanceid))) {
6915 if ($course = $DB->get_record('course', array('id'=>$instanceid), 'id,category', $strictness)) {
6916 if ($course->category) {
6917 $parentcontext = context_coursecat::instance($course->category);
6918 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6919 } else {
6920 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6925 if ($record) {
6926 $context = new context_course($record);
6927 context::cache_add($context);
6928 return $context;
6931 return false;
6935 * Create missing context instances at course context level
6936 * @static
6938 protected static function create_level_instances() {
6939 global $DB;
6941 $sql = "SELECT ".CONTEXT_COURSE.", c.id
6942 FROM {course} c
6943 WHERE NOT EXISTS (SELECT 'x'
6944 FROM {context} cx
6945 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6946 $contextdata = $DB->get_recordset_sql($sql);
6947 foreach ($contextdata as $context) {
6948 context::insert_context_record(CONTEXT_COURSE, $context->id, null);
6950 $contextdata->close();
6954 * Returns sql necessary for purging of stale context instances.
6956 * @static
6957 * @return string cleanup SQL
6959 protected static function get_cleanup_sql() {
6960 $sql = "
6961 SELECT c.*
6962 FROM {context} c
6963 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6964 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6967 return $sql;
6971 * Rebuild context paths and depths at course context level.
6973 * @static
6974 * @param bool $force
6976 protected static function build_paths($force) {
6977 global $DB;
6979 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6980 if ($force) {
6981 $ctxemptyclause = $emptyclause = '';
6982 } else {
6983 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6984 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6987 $base = '/'.SYSCONTEXTID;
6989 // Standard frontpage
6990 $sql = "UPDATE {context}
6991 SET depth = 2,
6992 path = ".$DB->sql_concat("'$base/'", 'id')."
6993 WHERE contextlevel = ".CONTEXT_COURSE."
6994 AND EXISTS (SELECT 'x'
6995 FROM {course} c
6996 WHERE c.id = {context}.instanceid AND c.category = 0)
6997 $emptyclause";
6998 $DB->execute($sql);
7000 // standard courses
7001 $sql = "INSERT INTO {context_temp} (id, path, depth)
7002 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7003 FROM {context} ctx
7004 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
7005 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
7006 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7007 $ctxemptyclause";
7008 $trans = $DB->start_delegated_transaction();
7009 $DB->delete_records('context_temp');
7010 $DB->execute($sql);
7011 context::merge_context_temp_table();
7012 $DB->delete_records('context_temp');
7013 $trans->allow_commit();
7020 * Course module context class
7022 * @package core_access
7023 * @category access
7024 * @copyright Petr Skoda {@link http://skodak.org}
7025 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7026 * @since Moodle 2.2
7028 class context_module extends context {
7030 * Please use context_module::instance($cmid) if you need the instance of context.
7031 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7033 * @param stdClass $record
7035 protected function __construct(stdClass $record) {
7036 parent::__construct($record);
7037 if ($record->contextlevel != CONTEXT_MODULE) {
7038 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
7043 * Returns human readable context level name.
7045 * @static
7046 * @return string the human readable context level name.
7048 public static function get_level_name() {
7049 return get_string('activitymodule');
7053 * Returns human readable context identifier.
7055 * @param boolean $withprefix whether to prefix the name of the context with the
7056 * module name, e.g. Forum, Glossary, etc.
7057 * @param boolean $short does not apply to module context
7058 * @return string the human readable context name.
7060 public function get_context_name($withprefix = true, $short = false) {
7061 global $DB;
7063 $name = '';
7064 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
7065 FROM {course_modules} cm
7066 JOIN {modules} md ON md.id = cm.module
7067 WHERE cm.id = ?", array($this->_instanceid))) {
7068 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
7069 if ($withprefix){
7070 $name = get_string('modulename', $cm->modname).': ';
7072 $name .= format_string($mod->name, true, array('context' => $this));
7075 return $name;
7079 * Returns the most relevant URL for this context.
7081 * @return moodle_url
7083 public function get_url() {
7084 global $DB;
7086 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
7087 FROM {course_modules} cm
7088 JOIN {modules} md ON md.id = cm.module
7089 WHERE cm.id = ?", array($this->_instanceid))) {
7090 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
7093 return new moodle_url('/');
7097 * Returns array of relevant context capability records.
7099 * @return array
7101 public function get_capabilities() {
7102 global $DB, $CFG;
7104 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7106 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
7107 $module = $DB->get_record('modules', array('id'=>$cm->module));
7109 $subcaps = array();
7110 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
7111 if (file_exists($subpluginsfile)) {
7112 $subplugins = array(); // should be redefined in the file
7113 include($subpluginsfile);
7114 if (!empty($subplugins)) {
7115 foreach (array_keys($subplugins) as $subplugintype) {
7116 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
7117 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
7123 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
7124 $extracaps = array();
7125 if (file_exists($modfile)) {
7126 include_once($modfile);
7127 $modfunction = $module->name.'_get_extra_capabilities';
7128 if (function_exists($modfunction)) {
7129 $extracaps = $modfunction();
7133 $extracaps = array_merge($subcaps, $extracaps);
7134 $extra = '';
7135 list($extra, $params) = $DB->get_in_or_equal(
7136 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
7137 if (!empty($extra)) {
7138 $extra = "OR name $extra";
7140 $sql = "SELECT *
7141 FROM {capabilities}
7142 WHERE (contextlevel = ".CONTEXT_MODULE."
7143 AND (component = :component OR component = 'moodle'))
7144 $extra";
7145 $params['component'] = "mod_$module->name";
7147 return $DB->get_records_sql($sql.' '.$sort, $params);
7151 * Is this context part of any course? If yes return course context.
7153 * @param bool $strict true means throw exception if not found, false means return false if not found
7154 * @return context_course context of the enclosing course, null if not found or exception
7156 public function get_course_context($strict = true) {
7157 return $this->get_parent_context();
7161 * Returns module context instance.
7163 * @static
7164 * @param int $instanceid
7165 * @param int $strictness
7166 * @return context_module context instance
7168 public static function instance($instanceid, $strictness = MUST_EXIST) {
7169 global $DB;
7171 if ($context = context::cache_get(CONTEXT_MODULE, $instanceid)) {
7172 return $context;
7175 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$instanceid))) {
7176 if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), 'id,course', $strictness)) {
7177 $parentcontext = context_course::instance($cm->course);
7178 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
7182 if ($record) {
7183 $context = new context_module($record);
7184 context::cache_add($context);
7185 return $context;
7188 return false;
7192 * Create missing context instances at module context level
7193 * @static
7195 protected static function create_level_instances() {
7196 global $DB;
7198 $sql = "SELECT ".CONTEXT_MODULE.", cm.id
7199 FROM {course_modules} cm
7200 WHERE NOT EXISTS (SELECT 'x'
7201 FROM {context} cx
7202 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
7203 $contextdata = $DB->get_recordset_sql($sql);
7204 foreach ($contextdata as $context) {
7205 context::insert_context_record(CONTEXT_MODULE, $context->id, null);
7207 $contextdata->close();
7211 * Returns sql necessary for purging of stale context instances.
7213 * @static
7214 * @return string cleanup SQL
7216 protected static function get_cleanup_sql() {
7217 $sql = "
7218 SELECT c.*
7219 FROM {context} c
7220 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
7221 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
7224 return $sql;
7228 * Rebuild context paths and depths at module context level.
7230 * @static
7231 * @param bool $force
7233 protected static function build_paths($force) {
7234 global $DB;
7236 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
7237 if ($force) {
7238 $ctxemptyclause = '';
7239 } else {
7240 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7243 $sql = "INSERT INTO {context_temp} (id, path, depth)
7244 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7245 FROM {context} ctx
7246 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
7247 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
7248 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7249 $ctxemptyclause";
7250 $trans = $DB->start_delegated_transaction();
7251 $DB->delete_records('context_temp');
7252 $DB->execute($sql);
7253 context::merge_context_temp_table();
7254 $DB->delete_records('context_temp');
7255 $trans->allow_commit();
7262 * Block context class
7264 * @package core_access
7265 * @category access
7266 * @copyright Petr Skoda {@link http://skodak.org}
7267 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7268 * @since Moodle 2.2
7270 class context_block extends context {
7272 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
7273 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7275 * @param stdClass $record
7277 protected function __construct(stdClass $record) {
7278 parent::__construct($record);
7279 if ($record->contextlevel != CONTEXT_BLOCK) {
7280 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
7285 * Returns human readable context level name.
7287 * @static
7288 * @return string the human readable context level name.
7290 public static function get_level_name() {
7291 return get_string('block');
7295 * Returns human readable context identifier.
7297 * @param boolean $withprefix whether to prefix the name of the context with Block
7298 * @param boolean $short does not apply to block context
7299 * @return string the human readable context name.
7301 public function get_context_name($withprefix = true, $short = false) {
7302 global $DB, $CFG;
7304 $name = '';
7305 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
7306 global $CFG;
7307 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7308 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7309 $blockname = "block_$blockinstance->blockname";
7310 if ($blockobject = new $blockname()) {
7311 if ($withprefix){
7312 $name = get_string('block').': ';
7314 $name .= $blockobject->title;
7318 return $name;
7322 * Returns the most relevant URL for this context.
7324 * @return moodle_url
7326 public function get_url() {
7327 $parentcontexts = $this->get_parent_context();
7328 return $parentcontexts->get_url();
7332 * Returns array of relevant context capability records.
7334 * @return array
7336 public function get_capabilities() {
7337 global $DB;
7339 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7341 $params = array();
7342 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
7344 $extra = '';
7345 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7346 if ($extracaps) {
7347 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7348 $extra = "OR name $extra";
7351 $sql = "SELECT *
7352 FROM {capabilities}
7353 WHERE (contextlevel = ".CONTEXT_BLOCK."
7354 AND component = :component)
7355 $extra";
7356 $params['component'] = 'block_' . $bi->blockname;
7358 return $DB->get_records_sql($sql.' '.$sort, $params);
7362 * Is this context part of any course? If yes return course context.
7364 * @param bool $strict true means throw exception if not found, false means return false if not found
7365 * @return context_course context of the enclosing course, null if not found or exception
7367 public function get_course_context($strict = true) {
7368 $parentcontext = $this->get_parent_context();
7369 return $parentcontext->get_course_context($strict);
7373 * Returns block context instance.
7375 * @static
7376 * @param int $instanceid
7377 * @param int $strictness
7378 * @return context_block context instance
7380 public static function instance($instanceid, $strictness = MUST_EXIST) {
7381 global $DB;
7383 if ($context = context::cache_get(CONTEXT_BLOCK, $instanceid)) {
7384 return $context;
7387 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$instanceid))) {
7388 if ($bi = $DB->get_record('block_instances', array('id'=>$instanceid), 'id,parentcontextid', $strictness)) {
7389 $parentcontext = context::instance_by_id($bi->parentcontextid);
7390 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7394 if ($record) {
7395 $context = new context_block($record);
7396 context::cache_add($context);
7397 return $context;
7400 return false;
7404 * Block do not have child contexts...
7405 * @return array
7407 public function get_child_contexts() {
7408 return array();
7412 * Create missing context instances at block context level
7413 * @static
7415 protected static function create_level_instances() {
7416 global $DB;
7418 $sql = "SELECT ".CONTEXT_BLOCK.", bi.id
7419 FROM {block_instances} bi
7420 WHERE NOT EXISTS (SELECT 'x'
7421 FROM {context} cx
7422 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7423 $contextdata = $DB->get_recordset_sql($sql);
7424 foreach ($contextdata as $context) {
7425 context::insert_context_record(CONTEXT_BLOCK, $context->id, null);
7427 $contextdata->close();
7431 * Returns sql necessary for purging of stale context instances.
7433 * @static
7434 * @return string cleanup SQL
7436 protected static function get_cleanup_sql() {
7437 $sql = "
7438 SELECT c.*
7439 FROM {context} c
7440 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7441 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7444 return $sql;
7448 * Rebuild context paths and depths at block context level.
7450 * @static
7451 * @param bool $force
7453 protected static function build_paths($force) {
7454 global $DB;
7456 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7457 if ($force) {
7458 $ctxemptyclause = '';
7459 } else {
7460 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7463 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7464 $sql = "INSERT INTO {context_temp} (id, path, depth)
7465 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7466 FROM {context} ctx
7467 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7468 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7469 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7470 $ctxemptyclause";
7471 $trans = $DB->start_delegated_transaction();
7472 $DB->delete_records('context_temp');
7473 $DB->execute($sql);
7474 context::merge_context_temp_table();
7475 $DB->delete_records('context_temp');
7476 $trans->allow_commit();
7482 // ============== DEPRECATED FUNCTIONS ==========================================
7483 // Old context related functions were deprecated in 2.0, it is recommended
7484 // to use context classes in new code. Old function can be used when
7485 // creating patches that are supposed to be backported to older stable branches.
7486 // These deprecated functions will not be removed in near future,
7487 // before removing devs will be warned with a debugging message first,
7488 // then we will add error message and only after that we can remove the functions
7489 // completely.
7492 * Runs get_records select on context table and returns the result
7493 * Does get_records_select on the context table, and returns the results ordered
7494 * by contextlevel, and then the natural sort order within each level.
7495 * for the purpose of $select, you need to know that the context table has been
7496 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7498 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7499 * @param array $params any parameters required by $select.
7500 * @return array the requested context records.
7502 function get_sorted_contexts($select, $params = array()) {
7504 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7506 global $DB;
7507 if ($select) {
7508 $select = 'WHERE ' . $select;
7510 return $DB->get_records_sql("
7511 SELECT ctx.*
7512 FROM {context} ctx
7513 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7514 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7515 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7516 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7517 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7518 $select
7519 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7520 ", $params);
7524 * Given context and array of users, returns array of users whose enrolment status is suspended,
7525 * or enrolment has expired or has not started. Also removes those users from the given array
7527 * @param context $context context in which suspended users should be extracted.
7528 * @param array $users list of users.
7529 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7530 * @return array list of suspended users.
7532 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7533 global $DB;
7535 // Get active enrolled users.
7536 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7537 $activeusers = $DB->get_records_sql($sql, $params);
7539 // Move suspended users to a separate array & remove from the initial one.
7540 $susers = array();
7541 if (sizeof($activeusers)) {
7542 foreach ($users as $userid => $user) {
7543 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7544 $susers[$userid] = $user;
7545 unset($users[$userid]);
7549 return $susers;
7553 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7554 * or enrolment has expired or not started.
7556 * @param context $context context in which user enrolment is checked.
7557 * @param bool $usecache Enable or disable (default) the request cache
7558 * @return array list of suspended user id's.
7560 function get_suspended_userids(context $context, $usecache = false) {
7561 global $DB;
7563 if ($usecache) {
7564 $cache = cache::make('core', 'suspended_userids');
7565 $susers = $cache->get($context->id);
7566 if ($susers !== false) {
7567 return $susers;
7571 $coursecontext = $context->get_course_context();
7572 $susers = array();
7574 // Front page users are always enrolled, so suspended list is empty.
7575 if ($coursecontext->instanceid != SITEID) {
7576 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7577 $susers = $DB->get_fieldset_sql($sql, $params);
7578 $susers = array_combine($susers, $susers);
7581 // Cache results for the remainder of this request.
7582 if ($usecache) {
7583 $cache->set($context->id, $susers);
7586 return $susers;