Merge branch 'MDL-52610_30' of git://github.com/dmonllao/moodle into MOODLE_30_STABLE
[moodle.git] / lib / accesslib.php
blob447535704a594cbd5454e03b6cd5564e73094b29
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, $CFG;
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 require_once($CFG->libdir . '/coursecatlib.php');
1758 coursecat::role_assignment_changed($roleid, $context);
1760 $event = \core\event\role_assigned::create(array(
1761 'context' => $context,
1762 'objectid' => $ra->roleid,
1763 'relateduserid' => $ra->userid,
1764 'other' => array(
1765 'id' => $ra->id,
1766 'component' => $ra->component,
1767 'itemid' => $ra->itemid
1770 $event->add_record_snapshot('role_assignments', $ra);
1771 $event->trigger();
1773 return $ra->id;
1777 * Removes one role assignment
1779 * @param int $roleid
1780 * @param int $userid
1781 * @param int $contextid
1782 * @param string $component
1783 * @param int $itemid
1784 * @return void
1786 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1787 // first make sure the params make sense
1788 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1789 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1792 if ($itemid) {
1793 if (strpos($component, '_') === false) {
1794 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1796 } else {
1797 $itemid = 0;
1798 if ($component !== '' and strpos($component, '_') === false) {
1799 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1803 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1807 * Removes multiple role assignments, parameters may contain:
1808 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1810 * @param array $params role assignment parameters
1811 * @param bool $subcontexts unassign in subcontexts too
1812 * @param bool $includemanual include manual role assignments too
1813 * @return void
1815 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1816 global $USER, $CFG, $DB;
1817 require_once($CFG->libdir . '/coursecatlib.php');
1819 if (!$params) {
1820 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1823 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1824 foreach ($params as $key=>$value) {
1825 if (!in_array($key, $allowed)) {
1826 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1830 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1831 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1834 if ($includemanual) {
1835 if (!isset($params['component']) or $params['component'] === '') {
1836 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1840 if ($subcontexts) {
1841 if (empty($params['contextid'])) {
1842 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1846 $ras = $DB->get_records('role_assignments', $params);
1847 foreach($ras as $ra) {
1848 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1849 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1850 // this is a bit expensive but necessary
1851 $context->mark_dirty();
1852 // If the user is the current user, then do full reload of capabilities too.
1853 if (!empty($USER->id) && $USER->id == $ra->userid) {
1854 reload_all_capabilities();
1856 $event = \core\event\role_unassigned::create(array(
1857 'context' => $context,
1858 'objectid' => $ra->roleid,
1859 'relateduserid' => $ra->userid,
1860 'other' => array(
1861 'id' => $ra->id,
1862 'component' => $ra->component,
1863 'itemid' => $ra->itemid
1866 $event->add_record_snapshot('role_assignments', $ra);
1867 $event->trigger();
1868 coursecat::role_assignment_changed($ra->roleid, $context);
1871 unset($ras);
1873 // process subcontexts
1874 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1875 if ($params['contextid'] instanceof context) {
1876 $context = $params['contextid'];
1877 } else {
1878 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1881 if ($context) {
1882 $contexts = $context->get_child_contexts();
1883 $mparams = $params;
1884 foreach($contexts as $context) {
1885 $mparams['contextid'] = $context->id;
1886 $ras = $DB->get_records('role_assignments', $mparams);
1887 foreach($ras as $ra) {
1888 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1889 // this is a bit expensive but necessary
1890 $context->mark_dirty();
1891 // If the user is the current user, then do full reload of capabilities too.
1892 if (!empty($USER->id) && $USER->id == $ra->userid) {
1893 reload_all_capabilities();
1895 $event = \core\event\role_unassigned::create(
1896 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1897 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1898 $event->add_record_snapshot('role_assignments', $ra);
1899 $event->trigger();
1900 coursecat::role_assignment_changed($ra->roleid, $context);
1906 // do this once more for all manual role assignments
1907 if ($includemanual) {
1908 $params['component'] = '';
1909 role_unassign_all($params, $subcontexts, false);
1914 * Determines if a user is currently logged in
1916 * @category access
1918 * @return bool
1920 function isloggedin() {
1921 global $USER;
1923 return (!empty($USER->id));
1927 * Determines if a user is logged in as real guest user with username 'guest'.
1929 * @category access
1931 * @param int|object $user mixed user object or id, $USER if not specified
1932 * @return bool true if user is the real guest user, false if not logged in or other user
1934 function isguestuser($user = null) {
1935 global $USER, $DB, $CFG;
1937 // make sure we have the user id cached in config table, because we are going to use it a lot
1938 if (empty($CFG->siteguest)) {
1939 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1940 // guest does not exist yet, weird
1941 return false;
1943 set_config('siteguest', $guestid);
1945 if ($user === null) {
1946 $user = $USER;
1949 if ($user === null) {
1950 // happens when setting the $USER
1951 return false;
1953 } else if (is_numeric($user)) {
1954 return ($CFG->siteguest == $user);
1956 } else if (is_object($user)) {
1957 if (empty($user->id)) {
1958 return false; // not logged in means is not be guest
1959 } else {
1960 return ($CFG->siteguest == $user->id);
1963 } else {
1964 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1969 * Does user have a (temporary or real) guest access to course?
1971 * @category access
1973 * @param context $context
1974 * @param stdClass|int $user
1975 * @return bool
1977 function is_guest(context $context, $user = null) {
1978 global $USER;
1980 // first find the course context
1981 $coursecontext = $context->get_course_context();
1983 // make sure there is a real user specified
1984 if ($user === null) {
1985 $userid = isset($USER->id) ? $USER->id : 0;
1986 } else {
1987 $userid = is_object($user) ? $user->id : $user;
1990 if (isguestuser($userid)) {
1991 // can not inspect or be enrolled
1992 return true;
1995 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1996 // viewing users appear out of nowhere, they are neither guests nor participants
1997 return false;
2000 // consider only real active enrolments here
2001 if (is_enrolled($coursecontext, $user, '', true)) {
2002 return false;
2005 return true;
2009 * Returns true if the user has moodle/course:view capability in the course,
2010 * this is intended for admins, managers (aka small admins), inspectors, etc.
2012 * @category access
2014 * @param context $context
2015 * @param int|stdClass $user if null $USER is used
2016 * @param string $withcapability extra capability name
2017 * @return bool
2019 function is_viewing(context $context, $user = null, $withcapability = '') {
2020 // first find the course context
2021 $coursecontext = $context->get_course_context();
2023 if (isguestuser($user)) {
2024 // can not inspect
2025 return false;
2028 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
2029 // admins are allowed to inspect courses
2030 return false;
2033 if ($withcapability and !has_capability($withcapability, $context, $user)) {
2034 // site admins always have the capability, but the enrolment above blocks
2035 return false;
2038 return true;
2042 * Returns true if user is enrolled (is participating) in course
2043 * this is intended for students and teachers.
2045 * Since 2.2 the result for active enrolments and current user are cached.
2047 * @package core_enrol
2048 * @category access
2050 * @param context $context
2051 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
2052 * @param string $withcapability extra capability name
2053 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2054 * @return bool
2056 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
2057 global $USER, $DB;
2059 // first find the course context
2060 $coursecontext = $context->get_course_context();
2062 // make sure there is a real user specified
2063 if ($user === null) {
2064 $userid = isset($USER->id) ? $USER->id : 0;
2065 } else {
2066 $userid = is_object($user) ? $user->id : $user;
2069 if (empty($userid)) {
2070 // not-logged-in!
2071 return false;
2072 } else if (isguestuser($userid)) {
2073 // guest account can not be enrolled anywhere
2074 return false;
2077 if ($coursecontext->instanceid == SITEID) {
2078 // everybody participates on frontpage
2079 } else {
2080 // try cached info first - the enrolled flag is set only when active enrolment present
2081 if ($USER->id == $userid) {
2082 $coursecontext->reload_if_dirty();
2083 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
2084 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
2085 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2086 return false;
2088 return true;
2093 if ($onlyactive) {
2094 // look for active enrolments only
2095 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
2097 if ($until === false) {
2098 return false;
2101 if ($USER->id == $userid) {
2102 if ($until == 0) {
2103 $until = ENROL_MAX_TIMESTAMP;
2105 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
2106 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
2107 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
2108 remove_temp_course_roles($coursecontext);
2112 } else {
2113 // any enrolment is good for us here, even outdated, disabled or inactive
2114 $sql = "SELECT 'x'
2115 FROM {user_enrolments} ue
2116 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2117 JOIN {user} u ON u.id = ue.userid
2118 WHERE ue.userid = :userid AND u.deleted = 0";
2119 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2120 if (!$DB->record_exists_sql($sql, $params)) {
2121 return false;
2126 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2127 return false;
2130 return true;
2134 * Returns true if the user is able to access the course.
2136 * This function is in no way, shape, or form a substitute for require_login.
2137 * It should only be used in circumstances where it is not possible to call require_login
2138 * such as the navigation.
2140 * This function checks many of the methods of access to a course such as the view
2141 * capability, enrollments, and guest access. It also makes use of the cache
2142 * generated by require_login for guest access.
2144 * The flags within the $USER object that are used here should NEVER be used outside
2145 * of this function can_access_course and require_login. Doing so WILL break future
2146 * versions.
2148 * @param stdClass $course record
2149 * @param stdClass|int|null $user user record or id, current user if null
2150 * @param string $withcapability Check for this capability as well.
2151 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2152 * @return boolean Returns true if the user is able to access the course
2154 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
2155 global $DB, $USER;
2157 // this function originally accepted $coursecontext parameter
2158 if ($course instanceof context) {
2159 if ($course instanceof context_course) {
2160 debugging('deprecated context parameter, please use $course record');
2161 $coursecontext = $course;
2162 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2163 } else {
2164 debugging('Invalid context parameter, please use $course record');
2165 return false;
2167 } else {
2168 $coursecontext = context_course::instance($course->id);
2171 if (!isset($USER->id)) {
2172 // should never happen
2173 $USER->id = 0;
2174 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
2177 // make sure there is a user specified
2178 if ($user === null) {
2179 $userid = $USER->id;
2180 } else {
2181 $userid = is_object($user) ? $user->id : $user;
2183 unset($user);
2185 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2186 return false;
2189 if ($userid == $USER->id) {
2190 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2191 // the fact that somebody switched role means they can access the course no matter to what role they switched
2192 return true;
2196 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2197 return false;
2200 if (is_viewing($coursecontext, $userid)) {
2201 return true;
2204 if ($userid != $USER->id) {
2205 // for performance reasons we do not verify temporary guest access for other users, sorry...
2206 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2209 // === from here we deal only with $USER ===
2211 $coursecontext->reload_if_dirty();
2213 if (isset($USER->enrol['enrolled'][$course->id])) {
2214 if ($USER->enrol['enrolled'][$course->id] > time()) {
2215 return true;
2218 if (isset($USER->enrol['tempguest'][$course->id])) {
2219 if ($USER->enrol['tempguest'][$course->id] > time()) {
2220 return true;
2224 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2225 return true;
2228 // if not enrolled try to gain temporary guest access
2229 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2230 $enrols = enrol_get_plugins(true);
2231 foreach($instances as $instance) {
2232 if (!isset($enrols[$instance->enrol])) {
2233 continue;
2235 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2236 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2237 if ($until !== false and $until > time()) {
2238 $USER->enrol['tempguest'][$course->id] = $until;
2239 return true;
2242 if (isset($USER->enrol['tempguest'][$course->id])) {
2243 unset($USER->enrol['tempguest'][$course->id]);
2244 remove_temp_course_roles($coursecontext);
2247 return false;
2251 * Returns array with sql code and parameters returning all ids
2252 * of users enrolled into course.
2254 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2256 * @package core_enrol
2257 * @category access
2259 * @param context $context
2260 * @param string $withcapability
2261 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2262 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2263 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
2264 * @return array list($sql, $params)
2266 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false, $onlysuspended = false) {
2267 global $DB, $CFG;
2269 // use unique prefix just in case somebody makes some SQL magic with the result
2270 static $i = 0;
2271 $i++;
2272 $prefix = 'eu'.$i.'_';
2274 // first find the course context
2275 $coursecontext = $context->get_course_context();
2277 $isfrontpage = ($coursecontext->instanceid == SITEID);
2279 if ($onlyactive && $onlysuspended) {
2280 throw new coding_exception("Both onlyactive and onlysuspended are set, this is probably not what you want!");
2282 if ($isfrontpage && $onlysuspended) {
2283 throw new coding_exception("onlysuspended is not supported on frontpage; please add your own early-exit!");
2286 $joins = array();
2287 $wheres = array();
2288 $params = array();
2290 list($contextids, $contextpaths) = get_context_info_list($context);
2292 // get all relevant capability info for all roles
2293 if ($withcapability) {
2294 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2295 $cparams['cap'] = $withcapability;
2297 $defs = array();
2298 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2299 FROM {role_capabilities} rc
2300 JOIN {context} ctx on rc.contextid = ctx.id
2301 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2302 $rcs = $DB->get_records_sql($sql, $cparams);
2303 foreach ($rcs as $rc) {
2304 $defs[$rc->path][$rc->roleid] = $rc->permission;
2307 $access = array();
2308 if (!empty($defs)) {
2309 foreach ($contextpaths as $path) {
2310 if (empty($defs[$path])) {
2311 continue;
2313 foreach($defs[$path] as $roleid => $perm) {
2314 if ($perm == CAP_PROHIBIT) {
2315 $access[$roleid] = CAP_PROHIBIT;
2316 continue;
2318 if (!isset($access[$roleid])) {
2319 $access[$roleid] = (int)$perm;
2325 unset($defs);
2327 // make lists of roles that are needed and prohibited
2328 $needed = array(); // one of these is enough
2329 $prohibited = array(); // must not have any of these
2330 foreach ($access as $roleid => $perm) {
2331 if ($perm == CAP_PROHIBIT) {
2332 unset($needed[$roleid]);
2333 $prohibited[$roleid] = true;
2334 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2335 $needed[$roleid] = true;
2339 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2340 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2342 $nobody = false;
2344 if ($isfrontpage) {
2345 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2346 $nobody = true;
2347 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2348 // everybody not having prohibit has the capability
2349 $needed = array();
2350 } else if (empty($needed)) {
2351 $nobody = true;
2353 } else {
2354 if (!empty($prohibited[$defaultuserroleid])) {
2355 $nobody = true;
2356 } else if (!empty($needed[$defaultuserroleid])) {
2357 // everybody not having prohibit has the capability
2358 $needed = array();
2359 } else if (empty($needed)) {
2360 $nobody = true;
2364 if ($nobody) {
2365 // nobody can match so return some SQL that does not return any results
2366 $wheres[] = "1 = 2";
2368 } else {
2370 if ($needed) {
2371 $ctxids = implode(',', $contextids);
2372 $roleids = implode(',', array_keys($needed));
2373 $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))";
2376 if ($prohibited) {
2377 $ctxids = implode(',', $contextids);
2378 $roleids = implode(',', array_keys($prohibited));
2379 $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))";
2380 $wheres[] = "{$prefix}ra4.id IS NULL";
2383 if ($groupid) {
2384 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2385 $params["{$prefix}gmid"] = $groupid;
2389 } else {
2390 if ($groupid) {
2391 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2392 $params["{$prefix}gmid"] = $groupid;
2396 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2397 $params["{$prefix}guestid"] = $CFG->siteguest;
2399 if ($isfrontpage) {
2400 // all users are "enrolled" on the frontpage
2401 } else {
2402 $where1 = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2403 $where2 = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2404 $ejoin = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2405 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2407 if (!$onlysuspended) {
2408 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2409 $joins[] = $ejoin;
2410 if ($onlyactive) {
2411 $wheres[] = "$where1 AND $where2";
2413 } else {
2414 // Suspended only where there is enrolment but ALL are suspended.
2415 // Consider multiple enrols where one is not suspended or plain role_assign.
2416 $enrolselect = "SELECT DISTINCT {$prefix}ue.userid FROM {user_enrolments} {$prefix}ue $ejoin WHERE $where1 AND $where2";
2417 $joins[] = "JOIN {user_enrolments} {$prefix}ue1 ON {$prefix}ue1.userid = {$prefix}u.id";
2418 $joins[] = "JOIN {enrol} {$prefix}e1 ON ({$prefix}e1.id = {$prefix}ue1.enrolid AND {$prefix}e1.courseid = :{$prefix}_e1_courseid)";
2419 $params["{$prefix}_e1_courseid"] = $coursecontext->instanceid;
2420 $wheres[] = "{$prefix}u.id NOT IN ($enrolselect)";
2423 if ($onlyactive || $onlysuspended) {
2424 $now = round(time(), -2); // rounding helps caching in DB
2425 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2426 $prefix.'active'=>ENROL_USER_ACTIVE,
2427 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2431 $joins = implode("\n", $joins);
2432 $wheres = "WHERE ".implode(" AND ", $wheres);
2434 $sql = "SELECT DISTINCT {$prefix}u.id
2435 FROM {user} {$prefix}u
2436 $joins
2437 $wheres";
2439 return array($sql, $params);
2443 * Returns list of users enrolled into course.
2445 * @package core_enrol
2446 * @category access
2448 * @param context $context
2449 * @param string $withcapability
2450 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2451 * @param string $userfields requested user record fields
2452 * @param string $orderby
2453 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2454 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2455 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2456 * @return array of user records
2458 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
2459 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
2460 global $DB;
2462 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2463 $sql = "SELECT $userfields
2464 FROM {user} u
2465 JOIN ($esql) je ON je.id = u.id
2466 WHERE u.deleted = 0";
2468 if ($orderby) {
2469 $sql = "$sql ORDER BY $orderby";
2470 } else {
2471 list($sort, $sortparams) = users_order_by_sql('u');
2472 $sql = "$sql ORDER BY $sort";
2473 $params = array_merge($params, $sortparams);
2476 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2480 * Counts list of users enrolled into course (as per above function)
2482 * @package core_enrol
2483 * @category access
2485 * @param context $context
2486 * @param string $withcapability
2487 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2488 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2489 * @return array of user records
2491 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2492 global $DB;
2494 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2495 $sql = "SELECT count(u.id)
2496 FROM {user} u
2497 JOIN ($esql) je ON je.id = u.id
2498 WHERE u.deleted = 0";
2500 return $DB->count_records_sql($sql, $params);
2504 * Loads the capability definitions for the component (from file).
2506 * Loads the capability definitions for the component (from file). If no
2507 * capabilities are defined for the component, we simply return an empty array.
2509 * @access private
2510 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2511 * @return array array of capabilities
2513 function load_capability_def($component) {
2514 $defpath = core_component::get_component_directory($component).'/db/access.php';
2516 $capabilities = array();
2517 if (file_exists($defpath)) {
2518 require($defpath);
2519 if (!empty(${$component.'_capabilities'})) {
2520 // BC capability array name
2521 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2522 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2523 $capabilities = ${$component.'_capabilities'};
2527 return $capabilities;
2531 * Gets the capabilities that have been cached in the database for this component.
2533 * @access private
2534 * @param string $component - examples: 'moodle', 'mod_forum'
2535 * @return array array of capabilities
2537 function get_cached_capabilities($component = 'moodle') {
2538 global $DB;
2539 $caps = get_all_capabilities();
2540 $componentcaps = array();
2541 foreach ($caps as $cap) {
2542 if ($cap['component'] == $component) {
2543 $componentcaps[] = (object) $cap;
2546 return $componentcaps;
2550 * Returns default capabilities for given role archetype.
2552 * @param string $archetype role archetype
2553 * @return array
2555 function get_default_capabilities($archetype) {
2556 global $DB;
2558 if (!$archetype) {
2559 return array();
2562 $alldefs = array();
2563 $defaults = array();
2564 $components = array();
2565 $allcaps = get_all_capabilities();
2567 foreach ($allcaps as $cap) {
2568 if (!in_array($cap['component'], $components)) {
2569 $components[] = $cap['component'];
2570 $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
2573 foreach($alldefs as $name=>$def) {
2574 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2575 if (isset($def['archetypes'])) {
2576 if (isset($def['archetypes'][$archetype])) {
2577 $defaults[$name] = $def['archetypes'][$archetype];
2579 // 'legacy' is for backward compatibility with 1.9 access.php
2580 } else {
2581 if (isset($def['legacy'][$archetype])) {
2582 $defaults[$name] = $def['legacy'][$archetype];
2587 return $defaults;
2591 * Return default roles that can be assigned, overridden or switched
2592 * by give role archetype.
2594 * @param string $type assign|override|switch
2595 * @param string $archetype
2596 * @return array of role ids
2598 function get_default_role_archetype_allows($type, $archetype) {
2599 global $DB;
2601 if (empty($archetype)) {
2602 return array();
2605 $roles = $DB->get_records('role');
2606 $archetypemap = array();
2607 foreach ($roles as $role) {
2608 if ($role->archetype) {
2609 $archetypemap[$role->archetype][$role->id] = $role->id;
2613 $defaults = array(
2614 'assign' => array(
2615 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2616 'coursecreator' => array(),
2617 'editingteacher' => array('teacher', 'student'),
2618 'teacher' => array(),
2619 'student' => array(),
2620 'guest' => array(),
2621 'user' => array(),
2622 'frontpage' => array(),
2624 'override' => array(
2625 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2626 'coursecreator' => array(),
2627 'editingteacher' => array('teacher', 'student', 'guest'),
2628 'teacher' => array(),
2629 'student' => array(),
2630 'guest' => array(),
2631 'user' => array(),
2632 'frontpage' => array(),
2634 'switch' => array(
2635 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2636 'coursecreator' => array(),
2637 'editingteacher' => array('teacher', 'student', 'guest'),
2638 'teacher' => array('student', 'guest'),
2639 'student' => array(),
2640 'guest' => array(),
2641 'user' => array(),
2642 'frontpage' => array(),
2646 if (!isset($defaults[$type][$archetype])) {
2647 debugging("Unknown type '$type'' or archetype '$archetype''");
2648 return array();
2651 $return = array();
2652 foreach ($defaults[$type][$archetype] as $at) {
2653 if (isset($archetypemap[$at])) {
2654 foreach ($archetypemap[$at] as $roleid) {
2655 $return[$roleid] = $roleid;
2660 return $return;
2664 * Reset role capabilities to default according to selected role archetype.
2665 * If no archetype selected, removes all capabilities.
2667 * This applies to capabilities that are assigned to the role (that you could
2668 * edit in the 'define roles' interface), and not to any capability overrides
2669 * in different locations.
2671 * @param int $roleid ID of role to reset capabilities for
2673 function reset_role_capabilities($roleid) {
2674 global $DB;
2676 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2677 $defaultcaps = get_default_capabilities($role->archetype);
2679 $systemcontext = context_system::instance();
2681 $DB->delete_records('role_capabilities',
2682 array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2684 foreach($defaultcaps as $cap=>$permission) {
2685 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2688 // Mark the system context dirty.
2689 context_system::instance()->mark_dirty();
2693 * Updates the capabilities table with the component capability definitions.
2694 * If no parameters are given, the function updates the core moodle
2695 * capabilities.
2697 * Note that the absence of the db/access.php capabilities definition file
2698 * will cause any stored capabilities for the component to be removed from
2699 * the database.
2701 * @access private
2702 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2703 * @return boolean true if success, exception in case of any problems
2705 function update_capabilities($component = 'moodle') {
2706 global $DB, $OUTPUT;
2708 $storedcaps = array();
2710 $filecaps = load_capability_def($component);
2711 foreach($filecaps as $capname=>$unused) {
2712 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2713 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2717 // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2718 // So ensure our updating is based on fresh data.
2719 cache::make('core', 'capabilities')->delete('core_capabilities');
2721 $cachedcaps = get_cached_capabilities($component);
2722 if ($cachedcaps) {
2723 foreach ($cachedcaps as $cachedcap) {
2724 array_push($storedcaps, $cachedcap->name);
2725 // update risk bitmasks and context levels in existing capabilities if needed
2726 if (array_key_exists($cachedcap->name, $filecaps)) {
2727 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2728 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2730 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2731 $updatecap = new stdClass();
2732 $updatecap->id = $cachedcap->id;
2733 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2734 $DB->update_record('capabilities', $updatecap);
2736 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2737 $updatecap = new stdClass();
2738 $updatecap->id = $cachedcap->id;
2739 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2740 $DB->update_record('capabilities', $updatecap);
2743 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2744 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2746 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2747 $updatecap = new stdClass();
2748 $updatecap->id = $cachedcap->id;
2749 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2750 $DB->update_record('capabilities', $updatecap);
2756 // Flush the cached again, as we have changed DB.
2757 cache::make('core', 'capabilities')->delete('core_capabilities');
2759 // Are there new capabilities in the file definition?
2760 $newcaps = array();
2762 foreach ($filecaps as $filecap => $def) {
2763 if (!$storedcaps ||
2764 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2765 if (!array_key_exists('riskbitmask', $def)) {
2766 $def['riskbitmask'] = 0; // no risk if not specified
2768 $newcaps[$filecap] = $def;
2771 // Add new capabilities to the stored definition.
2772 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2773 foreach ($newcaps as $capname => $capdef) {
2774 $capability = new stdClass();
2775 $capability->name = $capname;
2776 $capability->captype = $capdef['captype'];
2777 $capability->contextlevel = $capdef['contextlevel'];
2778 $capability->component = $component;
2779 $capability->riskbitmask = $capdef['riskbitmask'];
2781 $DB->insert_record('capabilities', $capability, false);
2783 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2784 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2785 foreach ($rolecapabilities as $rolecapability){
2786 //assign_capability will update rather than insert if capability exists
2787 if (!assign_capability($capname, $rolecapability->permission,
2788 $rolecapability->roleid, $rolecapability->contextid, true)){
2789 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2793 // we ignore archetype key if we have cloned permissions
2794 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2795 assign_legacy_capabilities($capname, $capdef['archetypes']);
2796 // 'legacy' is for backward compatibility with 1.9 access.php
2797 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2798 assign_legacy_capabilities($capname, $capdef['legacy']);
2801 // Are there any capabilities that have been removed from the file
2802 // definition that we need to delete from the stored capabilities and
2803 // role assignments?
2804 capabilities_cleanup($component, $filecaps);
2806 // reset static caches
2807 accesslib_clear_all_caches(false);
2809 // Flush the cached again, as we have changed DB.
2810 cache::make('core', 'capabilities')->delete('core_capabilities');
2812 return true;
2816 * Deletes cached capabilities that are no longer needed by the component.
2817 * Also unassigns these capabilities from any roles that have them.
2818 * NOTE: this function is called from lib/db/upgrade.php
2820 * @access private
2821 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2822 * @param array $newcapdef array of the new capability definitions that will be
2823 * compared with the cached capabilities
2824 * @return int number of deprecated capabilities that have been removed
2826 function capabilities_cleanup($component, $newcapdef = null) {
2827 global $DB;
2829 $removedcount = 0;
2831 if ($cachedcaps = get_cached_capabilities($component)) {
2832 foreach ($cachedcaps as $cachedcap) {
2833 if (empty($newcapdef) ||
2834 array_key_exists($cachedcap->name, $newcapdef) === false) {
2836 // Remove from capabilities cache.
2837 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2838 $removedcount++;
2839 // Delete from roles.
2840 if ($roles = get_roles_with_capability($cachedcap->name)) {
2841 foreach($roles as $role) {
2842 if (!unassign_capability($cachedcap->name, $role->id)) {
2843 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2847 } // End if.
2850 if ($removedcount) {
2851 cache::make('core', 'capabilities')->delete('core_capabilities');
2853 return $removedcount;
2857 * Returns an array of all the known types of risk
2858 * The array keys can be used, for example as CSS class names, or in calls to
2859 * print_risk_icon. The values are the corresponding RISK_ constants.
2861 * @return array all the known types of risk.
2863 function get_all_risks() {
2864 return array(
2865 'riskmanagetrust' => RISK_MANAGETRUST,
2866 'riskconfig' => RISK_CONFIG,
2867 'riskxss' => RISK_XSS,
2868 'riskpersonal' => RISK_PERSONAL,
2869 'riskspam' => RISK_SPAM,
2870 'riskdataloss' => RISK_DATALOSS,
2875 * Return a link to moodle docs for a given capability name
2877 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2878 * @return string the human-readable capability name as a link to Moodle Docs.
2880 function get_capability_docs_link($capability) {
2881 $url = get_docs_url('Capabilities/' . $capability->name);
2882 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2886 * This function pulls out all the resolved capabilities (overrides and
2887 * defaults) of a role used in capability overrides in contexts at a given
2888 * context.
2890 * @param int $roleid
2891 * @param context $context
2892 * @param string $cap capability, optional, defaults to ''
2893 * @return array Array of capabilities
2895 function role_context_capabilities($roleid, context $context, $cap = '') {
2896 global $DB;
2898 $contexts = $context->get_parent_context_ids(true);
2899 $contexts = '('.implode(',', $contexts).')';
2901 $params = array($roleid);
2903 if ($cap) {
2904 $search = " AND rc.capability = ? ";
2905 $params[] = $cap;
2906 } else {
2907 $search = '';
2910 $sql = "SELECT rc.*
2911 FROM {role_capabilities} rc, {context} c
2912 WHERE rc.contextid in $contexts
2913 AND rc.roleid = ?
2914 AND rc.contextid = c.id $search
2915 ORDER BY c.contextlevel DESC, rc.capability DESC";
2917 $capabilities = array();
2919 if ($records = $DB->get_records_sql($sql, $params)) {
2920 // We are traversing via reverse order.
2921 foreach ($records as $record) {
2922 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2923 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2924 $capabilities[$record->capability] = $record->permission;
2928 return $capabilities;
2932 * Constructs array with contextids as first parameter and context paths,
2933 * in both cases bottom top including self.
2935 * @access private
2936 * @param context $context
2937 * @return array
2939 function get_context_info_list(context $context) {
2940 $contextids = explode('/', ltrim($context->path, '/'));
2941 $contextpaths = array();
2942 $contextids2 = $contextids;
2943 while ($contextids2) {
2944 $contextpaths[] = '/' . implode('/', $contextids2);
2945 array_pop($contextids2);
2947 return array($contextids, $contextpaths);
2951 * Check if context is the front page context or a context inside it
2953 * Returns true if this context is the front page context, or a context inside it,
2954 * otherwise false.
2956 * @param context $context a context object.
2957 * @return bool
2959 function is_inside_frontpage(context $context) {
2960 $frontpagecontext = context_course::instance(SITEID);
2961 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2965 * Returns capability information (cached)
2967 * @param string $capabilityname
2968 * @return stdClass or null if capability not found
2970 function get_capability_info($capabilityname) {
2971 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2973 $caps = get_all_capabilities();
2975 if (!isset($caps[$capabilityname])) {
2976 return null;
2979 return (object) $caps[$capabilityname];
2983 * Returns all capabilitiy records, preferably from MUC and not database.
2985 * @return array All capability records indexed by capability name
2987 function get_all_capabilities() {
2988 global $DB;
2989 $cache = cache::make('core', 'capabilities');
2990 if (!$allcaps = $cache->get('core_capabilities')) {
2991 $rs = $DB->get_recordset('capabilities');
2992 $allcaps = array();
2993 foreach ($rs as $capability) {
2994 $capability->riskbitmask = (int) $capability->riskbitmask;
2995 $allcaps[$capability->name] = (array) $capability;
2997 $rs->close();
2998 $cache->set('core_capabilities', $allcaps);
3000 return $allcaps;
3004 * Returns the human-readable, translated version of the capability.
3005 * Basically a big switch statement.
3007 * @param string $capabilityname e.g. mod/choice:readresponses
3008 * @return string
3010 function get_capability_string($capabilityname) {
3012 // Typical capability name is 'plugintype/pluginname:capabilityname'
3013 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
3015 if ($type === 'moodle') {
3016 $component = 'core_role';
3017 } else if ($type === 'quizreport') {
3018 //ugly hack!!
3019 $component = 'quiz_'.$name;
3020 } else {
3021 $component = $type.'_'.$name;
3024 $stringname = $name.':'.$capname;
3026 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
3027 return get_string($stringname, $component);
3030 $dir = core_component::get_component_directory($component);
3031 if (!file_exists($dir)) {
3032 // plugin broken or does not exist, do not bother with printing of debug message
3033 return $capabilityname.' ???';
3036 // something is wrong in plugin, better print debug
3037 return get_string($stringname, $component);
3041 * This gets the mod/block/course/core etc strings.
3043 * @param string $component
3044 * @param int $contextlevel
3045 * @return string|bool String is success, false if failed
3047 function get_component_string($component, $contextlevel) {
3049 if ($component === 'moodle' or $component === 'core') {
3050 switch ($contextlevel) {
3051 // TODO MDL-46123: this should probably use context level names instead
3052 case CONTEXT_SYSTEM: return get_string('coresystem');
3053 case CONTEXT_USER: return get_string('users');
3054 case CONTEXT_COURSECAT: return get_string('categories');
3055 case CONTEXT_COURSE: return get_string('course');
3056 case CONTEXT_MODULE: return get_string('activities');
3057 case CONTEXT_BLOCK: return get_string('block');
3058 default: print_error('unknowncontext');
3062 list($type, $name) = core_component::normalize_component($component);
3063 $dir = core_component::get_plugin_directory($type, $name);
3064 if (!file_exists($dir)) {
3065 // plugin not installed, bad luck, there is no way to find the name
3066 return $component.' ???';
3069 switch ($type) {
3070 // TODO MDL-46123: this is really hacky and should be improved.
3071 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
3072 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
3073 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
3074 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
3075 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
3076 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
3077 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
3078 case 'mod':
3079 if (get_string_manager()->string_exists('pluginname', $component)) {
3080 return get_string('activity').': '.get_string('pluginname', $component);
3081 } else {
3082 return get_string('activity').': '.get_string('modulename', $component);
3084 default: return get_string('pluginname', $component);
3089 * Gets the list of roles assigned to this context and up (parents)
3090 * from the list of roles that are visible on user profile page
3091 * and participants page.
3093 * @param context $context
3094 * @return array
3096 function get_profile_roles(context $context) {
3097 global $CFG, $DB;
3099 if (empty($CFG->profileroles)) {
3100 return array();
3103 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
3104 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
3105 $params = array_merge($params, $cparams);
3107 if ($coursecontext = $context->get_course_context(false)) {
3108 $params['coursecontext'] = $coursecontext->id;
3109 } else {
3110 $params['coursecontext'] = 0;
3113 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3114 FROM {role_assignments} ra, {role} r
3115 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3116 WHERE r.id = ra.roleid
3117 AND ra.contextid $contextlist
3118 AND r.id $rallowed
3119 ORDER BY r.sortorder ASC";
3121 return $DB->get_records_sql($sql, $params);
3125 * Gets the list of roles assigned to this context and up (parents)
3127 * @param context $context
3128 * @return array
3130 function get_roles_used_in_context(context $context) {
3131 global $DB;
3133 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
3135 if ($coursecontext = $context->get_course_context(false)) {
3136 $params['coursecontext'] = $coursecontext->id;
3137 } else {
3138 $params['coursecontext'] = 0;
3141 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3142 FROM {role_assignments} ra, {role} r
3143 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3144 WHERE r.id = ra.roleid
3145 AND ra.contextid $contextlist
3146 ORDER BY r.sortorder ASC";
3148 return $DB->get_records_sql($sql, $params);
3152 * This function is used to print roles column in user profile page.
3153 * It is using the CFG->profileroles to limit the list to only interesting roles.
3154 * (The permission tab has full details of user role assignments.)
3156 * @param int $userid
3157 * @param int $courseid
3158 * @return string
3160 function get_user_roles_in_course($userid, $courseid) {
3161 global $CFG, $DB;
3163 if (empty($CFG->profileroles)) {
3164 return '';
3167 if ($courseid == SITEID) {
3168 $context = context_system::instance();
3169 } else {
3170 $context = context_course::instance($courseid);
3173 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
3174 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
3175 $params = array_merge($params, $cparams);
3177 if ($coursecontext = $context->get_course_context(false)) {
3178 $params['coursecontext'] = $coursecontext->id;
3179 } else {
3180 $params['coursecontext'] = 0;
3183 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3184 FROM {role_assignments} ra, {role} r
3185 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3186 WHERE r.id = ra.roleid
3187 AND ra.contextid $contextlist
3188 AND r.id $rallowed
3189 AND ra.userid = :userid
3190 ORDER BY r.sortorder ASC";
3191 $params['userid'] = $userid;
3193 $rolestring = '';
3195 if ($roles = $DB->get_records_sql($sql, $params)) {
3196 $rolenames = role_fix_names($roles, $context, ROLENAME_ALIAS, true); // Substitute aliases
3198 foreach ($rolenames as $roleid => $rolename) {
3199 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
3201 $rolestring = implode(',', $rolenames);
3204 return $rolestring;
3208 * Checks if a user can assign users to a particular role in this context
3210 * @param context $context
3211 * @param int $targetroleid - the id of the role you want to assign users to
3212 * @return boolean
3214 function user_can_assign(context $context, $targetroleid) {
3215 global $DB;
3217 // First check to see if the user is a site administrator.
3218 if (is_siteadmin()) {
3219 return true;
3222 // Check if user has override capability.
3223 // If not return false.
3224 if (!has_capability('moodle/role:assign', $context)) {
3225 return false;
3227 // pull out all active roles of this user from this context(or above)
3228 if ($userroles = get_user_roles($context)) {
3229 foreach ($userroles as $userrole) {
3230 // if any in the role_allow_override table, then it's ok
3231 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
3232 return true;
3237 return false;
3241 * Returns all site roles in correct sort order.
3243 * Note: this method does not localise role names or descriptions,
3244 * use role_get_names() if you need role names.
3246 * @param context $context optional context for course role name aliases
3247 * @return array of role records with optional coursealias property
3249 function get_all_roles(context $context = null) {
3250 global $DB;
3252 if (!$context or !$coursecontext = $context->get_course_context(false)) {
3253 $coursecontext = null;
3256 if ($coursecontext) {
3257 $sql = "SELECT r.*, rn.name AS coursealias
3258 FROM {role} r
3259 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3260 ORDER BY r.sortorder ASC";
3261 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
3263 } else {
3264 return $DB->get_records('role', array(), 'sortorder ASC');
3269 * Returns roles of a specified archetype
3271 * @param string $archetype
3272 * @return array of full role records
3274 function get_archetype_roles($archetype) {
3275 global $DB;
3276 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
3280 * Gets all the user roles assigned in this context, or higher contexts
3281 * this is mainly used when checking if a user can assign a role, or overriding a role
3282 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3283 * allow_override tables
3285 * @param context $context
3286 * @param int $userid
3287 * @param bool $checkparentcontexts defaults to true
3288 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
3289 * @return array
3291 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
3292 global $USER, $DB;
3294 if (empty($userid)) {
3295 if (empty($USER->id)) {
3296 return array();
3298 $userid = $USER->id;
3301 if ($checkparentcontexts) {
3302 $contextids = $context->get_parent_context_ids();
3303 } else {
3304 $contextids = array();
3306 $contextids[] = $context->id;
3308 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3310 array_unshift($params, $userid);
3312 $sql = "SELECT ra.*, r.name, r.shortname
3313 FROM {role_assignments} ra, {role} r, {context} c
3314 WHERE ra.userid = ?
3315 AND ra.roleid = r.id
3316 AND ra.contextid = c.id
3317 AND ra.contextid $contextids
3318 ORDER BY $order";
3320 return $DB->get_records_sql($sql ,$params);
3324 * Like get_user_roles, but adds in the authenticated user role, and the front
3325 * page roles, if applicable.
3327 * @param context $context the context.
3328 * @param int $userid optional. Defaults to $USER->id
3329 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3331 function get_user_roles_with_special(context $context, $userid = 0) {
3332 global $CFG, $USER;
3334 if (empty($userid)) {
3335 if (empty($USER->id)) {
3336 return array();
3338 $userid = $USER->id;
3341 $ras = get_user_roles($context, $userid);
3343 // Add front-page role if relevant.
3344 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3345 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3346 is_inside_frontpage($context);
3347 if ($defaultfrontpageroleid && $isfrontpage) {
3348 $frontpagecontext = context_course::instance(SITEID);
3349 $ra = new stdClass();
3350 $ra->userid = $userid;
3351 $ra->contextid = $frontpagecontext->id;
3352 $ra->roleid = $defaultfrontpageroleid;
3353 $ras[] = $ra;
3356 // Add authenticated user role if relevant.
3357 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3358 if ($defaultuserroleid && !isguestuser($userid)) {
3359 $systemcontext = context_system::instance();
3360 $ra = new stdClass();
3361 $ra->userid = $userid;
3362 $ra->contextid = $systemcontext->id;
3363 $ra->roleid = $defaultuserroleid;
3364 $ras[] = $ra;
3367 return $ras;
3371 * Creates a record in the role_allow_override table
3373 * @param int $sroleid source roleid
3374 * @param int $troleid target roleid
3375 * @return void
3377 function allow_override($sroleid, $troleid) {
3378 global $DB;
3380 $record = new stdClass();
3381 $record->roleid = $sroleid;
3382 $record->allowoverride = $troleid;
3383 $DB->insert_record('role_allow_override', $record);
3387 * Creates a record in the role_allow_assign table
3389 * @param int $fromroleid source roleid
3390 * @param int $targetroleid target roleid
3391 * @return void
3393 function allow_assign($fromroleid, $targetroleid) {
3394 global $DB;
3396 $record = new stdClass();
3397 $record->roleid = $fromroleid;
3398 $record->allowassign = $targetroleid;
3399 $DB->insert_record('role_allow_assign', $record);
3403 * Creates a record in the role_allow_switch table
3405 * @param int $fromroleid source roleid
3406 * @param int $targetroleid target roleid
3407 * @return void
3409 function allow_switch($fromroleid, $targetroleid) {
3410 global $DB;
3412 $record = new stdClass();
3413 $record->roleid = $fromroleid;
3414 $record->allowswitch = $targetroleid;
3415 $DB->insert_record('role_allow_switch', $record);
3419 * Gets a list of roles that this user can assign in this context
3421 * @param context $context the context.
3422 * @param int $rolenamedisplay the type of role name to display. One of the
3423 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3424 * @param bool $withusercounts if true, count the number of users with each role.
3425 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3426 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3427 * if $withusercounts is true, returns a list of three arrays,
3428 * $rolenames, $rolecounts, and $nameswithcounts.
3430 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3431 global $USER, $DB;
3433 // make sure there is a real user specified
3434 if ($user === null) {
3435 $userid = isset($USER->id) ? $USER->id : 0;
3436 } else {
3437 $userid = is_object($user) ? $user->id : $user;
3440 if (!has_capability('moodle/role:assign', $context, $userid)) {
3441 if ($withusercounts) {
3442 return array(array(), array(), array());
3443 } else {
3444 return array();
3448 $params = array();
3449 $extrafields = '';
3451 if ($withusercounts) {
3452 $extrafields = ', (SELECT count(u.id)
3453 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3454 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3455 ) AS usercount';
3456 $params['conid'] = $context->id;
3459 if (is_siteadmin($userid)) {
3460 // show all roles allowed in this context to admins
3461 $assignrestriction = "";
3462 } else {
3463 $parents = $context->get_parent_context_ids(true);
3464 $contexts = implode(',' , $parents);
3465 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3466 FROM {role_allow_assign} raa
3467 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3468 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3469 ) ar ON ar.id = r.id";
3470 $params['userid'] = $userid;
3472 $params['contextlevel'] = $context->contextlevel;
3474 if ($coursecontext = $context->get_course_context(false)) {
3475 $params['coursecontext'] = $coursecontext->id;
3476 } else {
3477 $params['coursecontext'] = 0; // no course aliases
3478 $coursecontext = null;
3480 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3481 FROM {role} r
3482 $assignrestriction
3483 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3484 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3485 ORDER BY r.sortorder ASC";
3486 $roles = $DB->get_records_sql($sql, $params);
3488 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3490 if (!$withusercounts) {
3491 return $rolenames;
3494 $rolecounts = array();
3495 $nameswithcounts = array();
3496 foreach ($roles as $role) {
3497 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3498 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3500 return array($rolenames, $rolecounts, $nameswithcounts);
3504 * Gets a list of roles that this user can switch to in a context
3506 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3507 * This function just process the contents of the role_allow_switch table. You also need to
3508 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3510 * @param context $context a context.
3511 * @return array an array $roleid => $rolename.
3513 function get_switchable_roles(context $context) {
3514 global $USER, $DB;
3516 $params = array();
3517 $extrajoins = '';
3518 $extrawhere = '';
3519 if (!is_siteadmin()) {
3520 // Admins are allowed to switch to any role with.
3521 // Others are subject to the additional constraint that the switch-to role must be allowed by
3522 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3523 $parents = $context->get_parent_context_ids(true);
3524 $contexts = implode(',' , $parents);
3526 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3527 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3528 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3529 $params['userid'] = $USER->id;
3532 if ($coursecontext = $context->get_course_context(false)) {
3533 $params['coursecontext'] = $coursecontext->id;
3534 } else {
3535 $params['coursecontext'] = 0; // no course aliases
3536 $coursecontext = null;
3539 $query = "
3540 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3541 FROM (SELECT DISTINCT rc.roleid
3542 FROM {role_capabilities} rc
3543 $extrajoins
3544 $extrawhere) idlist
3545 JOIN {role} r ON r.id = idlist.roleid
3546 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3547 ORDER BY r.sortorder";
3548 $roles = $DB->get_records_sql($query, $params);
3550 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3554 * Gets a list of roles that this user can override in this context.
3556 * @param context $context the context.
3557 * @param int $rolenamedisplay the type of role name to display. One of the
3558 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3559 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3560 * @return array if $withcounts is false, then an array $roleid => $rolename.
3561 * if $withusercounts is true, returns a list of three arrays,
3562 * $rolenames, $rolecounts, and $nameswithcounts.
3564 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3565 global $USER, $DB;
3567 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3568 if ($withcounts) {
3569 return array(array(), array(), array());
3570 } else {
3571 return array();
3575 $parents = $context->get_parent_context_ids(true);
3576 $contexts = implode(',' , $parents);
3578 $params = array();
3579 $extrafields = '';
3581 $params['userid'] = $USER->id;
3582 if ($withcounts) {
3583 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3584 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3585 $params['conid'] = $context->id;
3588 if ($coursecontext = $context->get_course_context(false)) {
3589 $params['coursecontext'] = $coursecontext->id;
3590 } else {
3591 $params['coursecontext'] = 0; // no course aliases
3592 $coursecontext = null;
3595 if (is_siteadmin()) {
3596 // show all roles to admins
3597 $roles = $DB->get_records_sql("
3598 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3599 FROM {role} ro
3600 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3601 ORDER BY ro.sortorder ASC", $params);
3603 } else {
3604 $roles = $DB->get_records_sql("
3605 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3606 FROM {role} ro
3607 JOIN (SELECT DISTINCT r.id
3608 FROM {role} r
3609 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3610 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3611 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3612 ) inline_view ON ro.id = inline_view.id
3613 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3614 ORDER BY ro.sortorder ASC", $params);
3617 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3619 if (!$withcounts) {
3620 return $rolenames;
3623 $rolecounts = array();
3624 $nameswithcounts = array();
3625 foreach ($roles as $role) {
3626 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3627 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3629 return array($rolenames, $rolecounts, $nameswithcounts);
3633 * Create a role menu suitable for default role selection in enrol plugins.
3635 * @package core_enrol
3637 * @param context $context
3638 * @param int $addroleid current or default role - always added to list
3639 * @return array roleid=>localised role name
3641 function get_default_enrol_roles(context $context, $addroleid = null) {
3642 global $DB;
3644 $params = array('contextlevel'=>CONTEXT_COURSE);
3646 if ($coursecontext = $context->get_course_context(false)) {
3647 $params['coursecontext'] = $coursecontext->id;
3648 } else {
3649 $params['coursecontext'] = 0; // no course names
3650 $coursecontext = null;
3653 if ($addroleid) {
3654 $addrole = "OR r.id = :addroleid";
3655 $params['addroleid'] = $addroleid;
3656 } else {
3657 $addrole = "";
3660 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3661 FROM {role} r
3662 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3663 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3664 WHERE rcl.id IS NOT NULL $addrole
3665 ORDER BY sortorder DESC";
3667 $roles = $DB->get_records_sql($sql, $params);
3669 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3673 * Return context levels where this role is assignable.
3675 * @param integer $roleid the id of a role.
3676 * @return array list of the context levels at which this role may be assigned.
3678 function get_role_contextlevels($roleid) {
3679 global $DB;
3680 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3681 'contextlevel', 'id,contextlevel');
3685 * Return roles suitable for assignment at the specified context level.
3687 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3689 * @param integer $contextlevel a contextlevel.
3690 * @return array list of role ids that are assignable at this context level.
3692 function get_roles_for_contextlevels($contextlevel) {
3693 global $DB;
3694 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3695 '', 'id,roleid');
3699 * Returns default context levels where roles can be assigned.
3701 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3702 * from the array returned by get_role_archetypes();
3703 * @return array list of the context levels at which this type of role may be assigned by default.
3705 function get_default_contextlevels($rolearchetype) {
3706 static $defaults = array(
3707 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3708 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3709 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3710 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3711 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3712 'guest' => array(),
3713 'user' => array(),
3714 'frontpage' => array());
3716 if (isset($defaults[$rolearchetype])) {
3717 return $defaults[$rolearchetype];
3718 } else {
3719 return array();
3724 * Set the context levels at which a particular role can be assigned.
3725 * Throws exceptions in case of error.
3727 * @param integer $roleid the id of a role.
3728 * @param array $contextlevels the context levels at which this role should be assignable,
3729 * duplicate levels are removed.
3730 * @return void
3732 function set_role_contextlevels($roleid, array $contextlevels) {
3733 global $DB;
3734 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3735 $rcl = new stdClass();
3736 $rcl->roleid = $roleid;
3737 $contextlevels = array_unique($contextlevels);
3738 foreach ($contextlevels as $level) {
3739 $rcl->contextlevel = $level;
3740 $DB->insert_record('role_context_levels', $rcl, false, true);
3745 * Who has this capability in this context?
3747 * This can be a very expensive call - use sparingly and keep
3748 * the results if you are going to need them again soon.
3750 * Note if $fields is empty this function attempts to get u.*
3751 * which can get rather large - and has a serious perf impact
3752 * on some DBs.
3754 * @param context $context
3755 * @param string|array $capability - capability name(s)
3756 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3757 * @param string $sort - the sort order. Default is lastaccess time.
3758 * @param mixed $limitfrom - number of records to skip (offset)
3759 * @param mixed $limitnum - number of records to fetch
3760 * @param string|array $groups - single group or array of groups - only return
3761 * users who are in one of these group(s).
3762 * @param string|array $exceptions - list of users to exclude, comma separated or array
3763 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3764 * @param bool $view_ignored - use get_enrolled_sql() instead
3765 * @param bool $useviewallgroups if $groups is set the return users who
3766 * have capability both $capability and moodle/site:accessallgroups
3767 * in this context, as well as users who have $capability and who are
3768 * in $groups.
3769 * @return array of user records
3771 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3772 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3773 global $CFG, $DB;
3775 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3776 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3778 $ctxids = trim($context->path, '/');
3779 $ctxids = str_replace('/', ',', $ctxids);
3781 // Context is the frontpage
3782 $iscoursepage = false; // coursepage other than fp
3783 $isfrontpage = false;
3784 if ($context->contextlevel == CONTEXT_COURSE) {
3785 if ($context->instanceid == SITEID) {
3786 $isfrontpage = true;
3787 } else {
3788 $iscoursepage = true;
3791 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3793 $caps = (array)$capability;
3795 // construct list of context paths bottom-->top
3796 list($contextids, $paths) = get_context_info_list($context);
3798 // we need to find out all roles that have these capabilities either in definition or in overrides
3799 $defs = array();
3800 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3801 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3802 $params = array_merge($params, $params2);
3803 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3804 FROM {role_capabilities} rc
3805 JOIN {context} ctx on rc.contextid = ctx.id
3806 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3808 $rcs = $DB->get_records_sql($sql, $params);
3809 foreach ($rcs as $rc) {
3810 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3813 // go through the permissions bottom-->top direction to evaluate the current permission,
3814 // first one wins (prohibit is an exception that always wins)
3815 $access = array();
3816 foreach ($caps as $cap) {
3817 foreach ($paths as $path) {
3818 if (empty($defs[$cap][$path])) {
3819 continue;
3821 foreach($defs[$cap][$path] as $roleid => $perm) {
3822 if ($perm == CAP_PROHIBIT) {
3823 $access[$cap][$roleid] = CAP_PROHIBIT;
3824 continue;
3826 if (!isset($access[$cap][$roleid])) {
3827 $access[$cap][$roleid] = (int)$perm;
3833 // make lists of roles that are needed and prohibited in this context
3834 $needed = array(); // one of these is enough
3835 $prohibited = array(); // must not have any of these
3836 foreach ($caps as $cap) {
3837 if (empty($access[$cap])) {
3838 continue;
3840 foreach ($access[$cap] as $roleid => $perm) {
3841 if ($perm == CAP_PROHIBIT) {
3842 unset($needed[$cap][$roleid]);
3843 $prohibited[$cap][$roleid] = true;
3844 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3845 $needed[$cap][$roleid] = true;
3848 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3849 // easy, nobody has the permission
3850 unset($needed[$cap]);
3851 unset($prohibited[$cap]);
3852 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3853 // everybody is disqualified on the frontpage
3854 unset($needed[$cap]);
3855 unset($prohibited[$cap]);
3857 if (empty($prohibited[$cap])) {
3858 unset($prohibited[$cap]);
3862 if (empty($needed)) {
3863 // there can not be anybody if no roles match this request
3864 return array();
3867 if (empty($prohibited)) {
3868 // we can compact the needed roles
3869 $n = array();
3870 foreach ($needed as $cap) {
3871 foreach ($cap as $roleid=>$unused) {
3872 $n[$roleid] = true;
3875 $needed = array('any'=>$n);
3876 unset($n);
3879 // ***** Set up default fields ******
3880 if (empty($fields)) {
3881 if ($iscoursepage) {
3882 $fields = 'u.*, ul.timeaccess AS lastaccess';
3883 } else {
3884 $fields = 'u.*';
3886 } else {
3887 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3888 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3892 // Set up default sort
3893 if (empty($sort)) { // default to course lastaccess or just lastaccess
3894 if ($iscoursepage) {
3895 $sort = 'ul.timeaccess';
3896 } else {
3897 $sort = 'u.lastaccess';
3901 // Prepare query clauses
3902 $wherecond = array();
3903 $params = array();
3904 $joins = array();
3906 // User lastaccess JOIN
3907 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3908 // user_lastaccess is not required MDL-13810
3909 } else {
3910 if ($iscoursepage) {
3911 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3912 } else {
3913 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3917 // We never return deleted users or guest account.
3918 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3919 $params['guestid'] = $CFG->siteguest;
3921 // Groups
3922 if ($groups) {
3923 $groups = (array)$groups;
3924 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3925 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3926 $params = array_merge($params, $grpparams);
3928 if ($useviewallgroups) {
3929 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3930 if (!empty($viewallgroupsusers)) {
3931 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3932 } else {
3933 $wherecond[] = "($grouptest)";
3935 } else {
3936 $wherecond[] = "($grouptest)";
3940 // User exceptions
3941 if (!empty($exceptions)) {
3942 $exceptions = (array)$exceptions;
3943 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3944 $params = array_merge($params, $exparams);
3945 $wherecond[] = "u.id $exsql";
3948 // now add the needed and prohibited roles conditions as joins
3949 if (!empty($needed['any'])) {
3950 // simple case - there are no prohibits involved
3951 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3952 // everybody
3953 } else {
3954 $joins[] = "JOIN (SELECT DISTINCT userid
3955 FROM {role_assignments}
3956 WHERE contextid IN ($ctxids)
3957 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3958 ) ra ON ra.userid = u.id";
3960 } else {
3961 $unions = array();
3962 $everybody = false;
3963 foreach ($needed as $cap=>$unused) {
3964 if (empty($prohibited[$cap])) {
3965 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3966 $everybody = true;
3967 break;
3968 } else {
3969 $unions[] = "SELECT userid
3970 FROM {role_assignments}
3971 WHERE contextid IN ($ctxids)
3972 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3974 } else {
3975 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3976 // nobody can have this cap because it is prevented in default roles
3977 continue;
3979 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3980 // everybody except the prohibitted - hiding does not matter
3981 $unions[] = "SELECT id AS userid
3982 FROM {user}
3983 WHERE id NOT IN (SELECT userid
3984 FROM {role_assignments}
3985 WHERE contextid IN ($ctxids)
3986 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3988 } else {
3989 $unions[] = "SELECT userid
3990 FROM {role_assignments}
3991 WHERE contextid IN ($ctxids)
3992 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3993 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3997 if (!$everybody) {
3998 if ($unions) {
3999 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
4000 } else {
4001 // only prohibits found - nobody can be matched
4002 $wherecond[] = "1 = 2";
4007 // Collect WHERE conditions and needed joins
4008 $where = implode(' AND ', $wherecond);
4009 if ($where !== '') {
4010 $where = 'WHERE ' . $where;
4012 $joins = implode("\n", $joins);
4014 // Ok, let's get the users!
4015 $sql = "SELECT $fields
4016 FROM {user} u
4017 $joins
4018 $where
4019 ORDER BY $sort";
4021 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
4025 * Re-sort a users array based on a sorting policy
4027 * Will re-sort a $users results array (from get_users_by_capability(), usually)
4028 * based on a sorting policy. This is to support the odd practice of
4029 * sorting teachers by 'authority', where authority was "lowest id of the role
4030 * assignment".
4032 * Will execute 1 database query. Only suitable for small numbers of users, as it
4033 * uses an u.id IN() clause.
4035 * Notes about the sorting criteria.
4037 * As a default, we cannot rely on role.sortorder because then
4038 * admins/coursecreators will always win. That is why the sane
4039 * rule "is locality matters most", with sortorder as 2nd
4040 * consideration.
4042 * If you want role.sortorder, use the 'sortorder' policy, and
4043 * name explicitly what roles you want to cover. It's probably
4044 * a good idea to see what roles have the capabilities you want
4045 * (array_diff() them against roiles that have 'can-do-anything'
4046 * to weed out admin-ish roles. Or fetch a list of roles from
4047 * variables like $CFG->coursecontact .
4049 * @param array $users Users array, keyed on userid
4050 * @param context $context
4051 * @param array $roles ids of the roles to include, optional
4052 * @param string $sortpolicy defaults to locality, more about
4053 * @return array sorted copy of the array
4055 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
4056 global $DB;
4058 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
4059 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
4060 if (empty($roles)) {
4061 $roleswhere = '';
4062 } else {
4063 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
4066 $sql = "SELECT ra.userid
4067 FROM {role_assignments} ra
4068 JOIN {role} r
4069 ON ra.roleid=r.id
4070 JOIN {context} ctx
4071 ON ra.contextid=ctx.id
4072 WHERE $userswhere
4073 $contextwhere
4074 $roleswhere";
4076 // Default 'locality' policy -- read PHPDoc notes
4077 // about sort policies...
4078 $orderby = 'ORDER BY '
4079 .'ctx.depth DESC, ' /* locality wins */
4080 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
4081 .'ra.id'; /* role assignment order tie-breaker */
4082 if ($sortpolicy === 'sortorder') {
4083 $orderby = 'ORDER BY '
4084 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
4085 .'ra.id'; /* role assignment order tie-breaker */
4088 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
4089 $sortedusers = array();
4090 $seen = array();
4092 foreach ($sortedids as $id) {
4093 // Avoid duplicates
4094 if (isset($seen[$id])) {
4095 continue;
4097 $seen[$id] = true;
4099 // assign
4100 $sortedusers[$id] = $users[$id];
4102 return $sortedusers;
4106 * Gets all the users assigned this role in this context or higher
4108 * Note that moodle is based on capabilities and it is usually better
4109 * to check permissions than to check role ids as the capabilities
4110 * system is more flexible. If you really need, you can to use this
4111 * function but consider has_capability() as a possible substitute.
4113 * The caller function is responsible for including all the
4114 * $sort fields in $fields param.
4116 * If $roleid is an array or is empty (all roles) you need to set $fields
4117 * (and $sort by extension) params according to it, as the first field
4118 * returned by the database should be unique (ra.id is the best candidate).
4120 * @param int $roleid (can also be an array of ints!)
4121 * @param context $context
4122 * @param bool $parent if true, get list of users assigned in higher context too
4123 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
4124 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
4125 * null => use default sort from users_order_by_sql.
4126 * @param bool $all true means all, false means limit to enrolled users
4127 * @param string $group defaults to ''
4128 * @param mixed $limitfrom defaults to ''
4129 * @param mixed $limitnum defaults to ''
4130 * @param string $extrawheretest defaults to ''
4131 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
4132 * @return array
4134 function get_role_users($roleid, context $context, $parent = false, $fields = '',
4135 $sort = null, $all = true, $group = '',
4136 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
4137 global $DB;
4139 if (empty($fields)) {
4140 $allnames = get_all_user_name_fields(true, 'u');
4141 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
4142 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
4143 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
4144 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
4145 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
4148 // Prevent wrong function uses.
4149 if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
4150 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
4151 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
4153 if (!empty($roleid)) {
4154 // Solving partially the issue when specifying multiple roles.
4155 $users = array();
4156 foreach ($roleid as $id) {
4157 // Ignoring duplicated keys keeping the first user appearance.
4158 $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
4159 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
4161 return $users;
4165 $parentcontexts = '';
4166 if ($parent) {
4167 $parentcontexts = substr($context->path, 1); // kill leading slash
4168 $parentcontexts = str_replace('/', ',', $parentcontexts);
4169 if ($parentcontexts !== '') {
4170 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4174 if ($roleid) {
4175 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
4176 $roleselect = "AND ra.roleid $rids";
4177 } else {
4178 $params = array();
4179 $roleselect = '';
4182 if ($coursecontext = $context->get_course_context(false)) {
4183 $params['coursecontext'] = $coursecontext->id;
4184 } else {
4185 $params['coursecontext'] = 0;
4188 if ($group) {
4189 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
4190 $groupselect = " AND gm.groupid = :groupid ";
4191 $params['groupid'] = $group;
4192 } else {
4193 $groupjoin = '';
4194 $groupselect = '';
4197 $params['contextid'] = $context->id;
4199 if ($extrawheretest) {
4200 $extrawheretest = ' AND ' . $extrawheretest;
4203 if ($whereorsortparams) {
4204 $params = array_merge($params, $whereorsortparams);
4207 if (!$sort) {
4208 list($sort, $sortparams) = users_order_by_sql('u');
4209 $params = array_merge($params, $sortparams);
4212 if ($all === null) {
4213 // Previously null was used to indicate that parameter was not used.
4214 $all = true;
4216 if (!$all and $coursecontext) {
4217 // Do not use get_enrolled_sql() here for performance reasons.
4218 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
4219 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
4220 $params['ecourseid'] = $coursecontext->instanceid;
4221 } else {
4222 $ejoin = "";
4225 $sql = "SELECT DISTINCT $fields, ra.roleid
4226 FROM {role_assignments} ra
4227 JOIN {user} u ON u.id = ra.userid
4228 JOIN {role} r ON ra.roleid = r.id
4229 $ejoin
4230 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
4231 $groupjoin
4232 WHERE (ra.contextid = :contextid $parentcontexts)
4233 $roleselect
4234 $groupselect
4235 $extrawheretest
4236 ORDER BY $sort"; // join now so that we can just use fullname() later
4238 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
4242 * Counts all the users assigned this role in this context or higher
4244 * @param int|array $roleid either int or an array of ints
4245 * @param context $context
4246 * @param bool $parent if true, get list of users assigned in higher context too
4247 * @return int Returns the result count
4249 function count_role_users($roleid, context $context, $parent = false) {
4250 global $DB;
4252 if ($parent) {
4253 if ($contexts = $context->get_parent_context_ids()) {
4254 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4255 } else {
4256 $parentcontexts = '';
4258 } else {
4259 $parentcontexts = '';
4262 if ($roleid) {
4263 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
4264 $roleselect = "AND r.roleid $rids";
4265 } else {
4266 $params = array();
4267 $roleselect = '';
4270 array_unshift($params, $context->id);
4272 $sql = "SELECT COUNT(DISTINCT u.id)
4273 FROM {role_assignments} r
4274 JOIN {user} u ON u.id = r.userid
4275 WHERE (r.contextid = ? $parentcontexts)
4276 $roleselect
4277 AND u.deleted = 0";
4279 return $DB->count_records_sql($sql, $params);
4283 * This function gets the list of courses that this user has a particular capability in.
4284 * It is still not very efficient.
4286 * @param string $capability Capability in question
4287 * @param int $userid User ID or null for current user
4288 * @param bool $doanything True if 'doanything' is permitted (default)
4289 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4290 * otherwise use a comma-separated list of the fields you require, not including id
4291 * @param string $orderby If set, use a comma-separated list of fields from course
4292 * table with sql modifiers (DESC) if needed
4293 * @return array|bool Array of courses, if none found false is returned.
4295 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
4296 global $DB;
4298 // Convert fields list and ordering
4299 $fieldlist = '';
4300 if ($fieldsexceptid) {
4301 $fields = explode(',', $fieldsexceptid);
4302 foreach($fields as $field) {
4303 $fieldlist .= ',c.'.$field;
4306 if ($orderby) {
4307 $fields = explode(',', $orderby);
4308 $orderby = '';
4309 foreach($fields as $field) {
4310 if ($orderby) {
4311 $orderby .= ',';
4313 $orderby .= 'c.'.$field;
4315 $orderby = 'ORDER BY '.$orderby;
4318 // Obtain a list of everything relevant about all courses including context.
4319 // Note the result can be used directly as a context (we are going to), the course
4320 // fields are just appended.
4322 $contextpreload = context_helper::get_preload_record_columns_sql('x');
4324 $courses = array();
4325 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
4326 FROM {course} c
4327 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
4328 $orderby");
4329 // Check capability for each course in turn
4330 foreach ($rs as $course) {
4331 context_helper::preload_from_record($course);
4332 $context = context_course::instance($course->id);
4333 if (has_capability($capability, $context, $userid, $doanything)) {
4334 // We've got the capability. Make the record look like a course record
4335 // and store it
4336 $courses[] = $course;
4339 $rs->close();
4340 return empty($courses) ? false : $courses;
4344 * This function finds the roles assigned directly to this context only
4345 * i.e. no roles in parent contexts
4347 * @param context $context
4348 * @return array
4350 function get_roles_on_exact_context(context $context) {
4351 global $DB;
4353 return $DB->get_records_sql("SELECT r.*
4354 FROM {role_assignments} ra, {role} r
4355 WHERE ra.roleid = r.id AND ra.contextid = ?",
4356 array($context->id));
4360 * Switches the current user to another role for the current session and only
4361 * in the given context.
4363 * The caller *must* check
4364 * - that this op is allowed
4365 * - that the requested role can be switched to in this context (use get_switchable_roles)
4366 * - that the requested role is NOT $CFG->defaultuserroleid
4368 * To "unswitch" pass 0 as the roleid.
4370 * This function *will* modify $USER->access - beware
4372 * @param integer $roleid the role to switch to.
4373 * @param context $context the context in which to perform the switch.
4374 * @return bool success or failure.
4376 function role_switch($roleid, context $context) {
4377 global $USER;
4380 // Plan of action
4382 // - Add the ghost RA to $USER->access
4383 // as $USER->access['rsw'][$path] = $roleid
4385 // - Make sure $USER->access['rdef'] has the roledefs
4386 // it needs to honour the switcherole
4388 // Roledefs will get loaded "deep" here - down to the last child
4389 // context. Note that
4391 // - When visiting subcontexts, our selective accessdata loading
4392 // will still work fine - though those ra/rdefs will be ignored
4393 // appropriately while the switch is in place
4395 // - If a switcherole happens at a category with tons of courses
4396 // (that have many overrides for switched-to role), the session
4397 // will get... quite large. Sometimes you just can't win.
4399 // To un-switch just unset($USER->access['rsw'][$path])
4401 // Note: it is not possible to switch to roles that do not have course:view
4403 if (!isset($USER->access)) {
4404 load_all_capabilities();
4408 // Add the switch RA
4409 if ($roleid == 0) {
4410 unset($USER->access['rsw'][$context->path]);
4411 return true;
4414 $USER->access['rsw'][$context->path] = $roleid;
4416 // Load roledefs
4417 load_role_access_by_context($roleid, $context, $USER->access);
4419 return true;
4423 * Checks if the user has switched roles within the given course.
4425 * Note: You can only switch roles within the course, hence it takes a course id
4426 * rather than a context. On that note Petr volunteered to implement this across
4427 * all other contexts, all requests for this should be forwarded to him ;)
4429 * @param int $courseid The id of the course to check
4430 * @return bool True if the user has switched roles within the course.
4432 function is_role_switched($courseid) {
4433 global $USER;
4434 $context = context_course::instance($courseid, MUST_EXIST);
4435 return (!empty($USER->access['rsw'][$context->path]));
4439 * Get any role that has an override on exact context
4441 * @param context $context The context to check
4442 * @return array An array of roles
4444 function get_roles_with_override_on_context(context $context) {
4445 global $DB;
4447 return $DB->get_records_sql("SELECT r.*
4448 FROM {role_capabilities} rc, {role} r
4449 WHERE rc.roleid = r.id AND rc.contextid = ?",
4450 array($context->id));
4454 * Get all capabilities for this role on this context (overrides)
4456 * @param stdClass $role
4457 * @param context $context
4458 * @return array
4460 function get_capabilities_from_role_on_context($role, context $context) {
4461 global $DB;
4463 return $DB->get_records_sql("SELECT *
4464 FROM {role_capabilities}
4465 WHERE contextid = ? AND roleid = ?",
4466 array($context->id, $role->id));
4470 * Find out which roles has assignment on this context
4472 * @param context $context
4473 * @return array
4476 function get_roles_with_assignment_on_context(context $context) {
4477 global $DB;
4479 return $DB->get_records_sql("SELECT r.*
4480 FROM {role_assignments} ra, {role} r
4481 WHERE ra.roleid = r.id AND ra.contextid = ?",
4482 array($context->id));
4486 * Find all user assignment of users for this role, on this context
4488 * @param stdClass $role
4489 * @param context $context
4490 * @return array
4492 function get_users_from_role_on_context($role, context $context) {
4493 global $DB;
4495 return $DB->get_records_sql("SELECT *
4496 FROM {role_assignments}
4497 WHERE contextid = ? AND roleid = ?",
4498 array($context->id, $role->id));
4502 * Simple function returning a boolean true if user has roles
4503 * in context or parent contexts, otherwise false.
4505 * @param int $userid
4506 * @param int $roleid
4507 * @param int $contextid empty means any context
4508 * @return bool
4510 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4511 global $DB;
4513 if ($contextid) {
4514 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4515 return false;
4517 $parents = $context->get_parent_context_ids(true);
4518 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4519 $params['userid'] = $userid;
4520 $params['roleid'] = $roleid;
4522 $sql = "SELECT COUNT(ra.id)
4523 FROM {role_assignments} ra
4524 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4526 $count = $DB->get_field_sql($sql, $params);
4527 return ($count > 0);
4529 } else {
4530 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4535 * Get localised role name or alias if exists and format the text.
4537 * @param stdClass $role role object
4538 * - optional 'coursealias' property should be included for performance reasons if course context used
4539 * - description property is not required here
4540 * @param context|bool $context empty means system context
4541 * @param int $rolenamedisplay type of role name
4542 * @return string localised role name or course role name alias
4544 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4545 global $DB;
4547 if ($rolenamedisplay == ROLENAME_SHORT) {
4548 return $role->shortname;
4551 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4552 $coursecontext = null;
4555 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4556 $role = clone($role); // Do not modify parameters.
4557 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4558 $role->coursealias = $r->name;
4559 } else {
4560 $role->coursealias = null;
4564 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4565 if ($coursecontext) {
4566 return $role->coursealias;
4567 } else {
4568 return null;
4572 if (trim($role->name) !== '') {
4573 // For filtering always use context where was the thing defined - system for roles here.
4574 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4576 } else {
4577 // Empty role->name means we want to see localised role name based on shortname,
4578 // only default roles are supposed to be localised.
4579 switch ($role->shortname) {
4580 case 'manager': $original = get_string('manager', 'role'); break;
4581 case 'coursecreator': $original = get_string('coursecreators'); break;
4582 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4583 case 'teacher': $original = get_string('noneditingteacher'); break;
4584 case 'student': $original = get_string('defaultcoursestudent'); break;
4585 case 'guest': $original = get_string('guest'); break;
4586 case 'user': $original = get_string('authenticateduser'); break;
4587 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4588 // We should not get here, the role UI should require the name for custom roles!
4589 default: $original = $role->shortname; break;
4593 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4594 return $original;
4597 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4598 return "$original ($role->shortname)";
4601 if ($rolenamedisplay == ROLENAME_ALIAS) {
4602 if ($coursecontext and trim($role->coursealias) !== '') {
4603 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4604 } else {
4605 return $original;
4609 if ($rolenamedisplay == ROLENAME_BOTH) {
4610 if ($coursecontext and trim($role->coursealias) !== '') {
4611 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4612 } else {
4613 return $original;
4617 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4621 * Returns localised role description if available.
4622 * If the name is empty it tries to find the default role name using
4623 * hardcoded list of default role names or other methods in the future.
4625 * @param stdClass $role
4626 * @return string localised role name
4628 function role_get_description(stdClass $role) {
4629 if (!html_is_blank($role->description)) {
4630 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4633 switch ($role->shortname) {
4634 case 'manager': return get_string('managerdescription', 'role');
4635 case 'coursecreator': return get_string('coursecreatorsdescription');
4636 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4637 case 'teacher': return get_string('noneditingteacherdescription');
4638 case 'student': return get_string('defaultcoursestudentdescription');
4639 case 'guest': return get_string('guestdescription');
4640 case 'user': return get_string('authenticateduserdescription');
4641 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4642 default: return '';
4647 * Get all the localised role names for a context.
4649 * In new installs default roles have empty names, this function
4650 * add localised role names using current language pack.
4652 * @param context $context the context, null means system context
4653 * @param array of role objects with a ->localname field containing the context-specific role name.
4654 * @param int $rolenamedisplay
4655 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4656 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4658 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4659 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4663 * Prepare list of roles for display, apply aliases and localise default role names.
4665 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4666 * @param context $context the context, null means system context
4667 * @param int $rolenamedisplay
4668 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4669 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4671 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4672 global $DB;
4674 if (empty($roleoptions)) {
4675 return array();
4678 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4679 $coursecontext = null;
4682 // We usually need all role columns...
4683 $first = reset($roleoptions);
4684 if ($returnmenu === null) {
4685 $returnmenu = !is_object($first);
4688 if (!is_object($first) or !property_exists($first, 'shortname')) {
4689 $allroles = get_all_roles($context);
4690 foreach ($roleoptions as $rid => $unused) {
4691 $roleoptions[$rid] = $allroles[$rid];
4695 // Inject coursealias if necessary.
4696 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4697 $first = reset($roleoptions);
4698 if (!property_exists($first, 'coursealias')) {
4699 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4700 foreach ($aliasnames as $alias) {
4701 if (isset($roleoptions[$alias->roleid])) {
4702 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4708 // Add localname property.
4709 foreach ($roleoptions as $rid => $role) {
4710 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4713 if (!$returnmenu) {
4714 return $roleoptions;
4717 $menu = array();
4718 foreach ($roleoptions as $rid => $role) {
4719 $menu[$rid] = $role->localname;
4722 return $menu;
4726 * Aids in detecting if a new line is required when reading a new capability
4728 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4729 * when we read in a new capability.
4730 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4731 * but when we are in grade, all reports/import/export capabilities should be together
4733 * @param string $cap component string a
4734 * @param string $comp component string b
4735 * @param int $contextlevel
4736 * @return bool whether 2 component are in different "sections"
4738 function component_level_changed($cap, $comp, $contextlevel) {
4740 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4741 $compsa = explode('/', $cap->component);
4742 $compsb = explode('/', $comp);
4744 // list of system reports
4745 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4746 return false;
4749 // we are in gradebook, still
4750 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4751 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4752 return false;
4755 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4756 return false;
4760 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4764 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4765 * and return an array of roleids in order.
4767 * @param array $allroles array of roles, as returned by get_all_roles();
4768 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4770 function fix_role_sortorder($allroles) {
4771 global $DB;
4773 $rolesort = array();
4774 $i = 0;
4775 foreach ($allroles as $role) {
4776 $rolesort[$i] = $role->id;
4777 if ($role->sortorder != $i) {
4778 $r = new stdClass();
4779 $r->id = $role->id;
4780 $r->sortorder = $i;
4781 $DB->update_record('role', $r);
4782 $allroles[$role->id]->sortorder = $i;
4784 $i++;
4786 return $rolesort;
4790 * Switch the sort order of two roles (used in admin/roles/manage.php).
4792 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4793 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4794 * @return boolean success or failure
4796 function switch_roles($first, $second) {
4797 global $DB;
4798 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4799 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4800 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4801 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4802 return $result;
4806 * Duplicates all the base definitions of a role
4808 * @param stdClass $sourcerole role to copy from
4809 * @param int $targetrole id of role to copy to
4811 function role_cap_duplicate($sourcerole, $targetrole) {
4812 global $DB;
4814 $systemcontext = context_system::instance();
4815 $caps = $DB->get_records_sql("SELECT *
4816 FROM {role_capabilities}
4817 WHERE roleid = ? AND contextid = ?",
4818 array($sourcerole->id, $systemcontext->id));
4819 // adding capabilities
4820 foreach ($caps as $cap) {
4821 unset($cap->id);
4822 $cap->roleid = $targetrole;
4823 $DB->insert_record('role_capabilities', $cap);
4828 * Returns two lists, this can be used to find out if user has capability.
4829 * Having any needed role and no forbidden role in this context means
4830 * user has this capability in this context.
4831 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4833 * @param stdClass $context
4834 * @param string $capability
4835 * @return array($neededroles, $forbiddenroles)
4837 function get_roles_with_cap_in_context($context, $capability) {
4838 global $DB;
4840 $ctxids = trim($context->path, '/'); // kill leading slash
4841 $ctxids = str_replace('/', ',', $ctxids);
4843 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4844 FROM {role_capabilities} rc
4845 JOIN {context} ctx ON ctx.id = rc.contextid
4846 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4847 ORDER BY rc.roleid ASC, ctx.depth DESC";
4848 $params = array('cap'=>$capability);
4850 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4851 // no cap definitions --> no capability
4852 return array(array(), array());
4855 $forbidden = array();
4856 $needed = array();
4857 foreach($capdefs as $def) {
4858 if (isset($forbidden[$def->roleid])) {
4859 continue;
4861 if ($def->permission == CAP_PROHIBIT) {
4862 $forbidden[$def->roleid] = $def->roleid;
4863 unset($needed[$def->roleid]);
4864 continue;
4866 if (!isset($needed[$def->roleid])) {
4867 if ($def->permission == CAP_ALLOW) {
4868 $needed[$def->roleid] = true;
4869 } else if ($def->permission == CAP_PREVENT) {
4870 $needed[$def->roleid] = false;
4874 unset($capdefs);
4876 // remove all those roles not allowing
4877 foreach($needed as $key=>$value) {
4878 if (!$value) {
4879 unset($needed[$key]);
4880 } else {
4881 $needed[$key] = $key;
4885 return array($needed, $forbidden);
4889 * Returns an array of role IDs that have ALL of the the supplied capabilities
4890 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4892 * @param stdClass $context
4893 * @param array $capabilities An array of capabilities
4894 * @return array of roles with all of the required capabilities
4896 function get_roles_with_caps_in_context($context, $capabilities) {
4897 $neededarr = array();
4898 $forbiddenarr = array();
4899 foreach($capabilities as $caprequired) {
4900 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4903 $rolesthatcanrate = array();
4904 if (!empty($neededarr)) {
4905 foreach ($neededarr as $needed) {
4906 if (empty($rolesthatcanrate)) {
4907 $rolesthatcanrate = $needed;
4908 } else {
4909 //only want roles that have all caps
4910 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4914 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4915 foreach ($forbiddenarr as $forbidden) {
4916 //remove any roles that are forbidden any of the caps
4917 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4920 return $rolesthatcanrate;
4924 * Returns an array of role names that have ALL of the the supplied capabilities
4925 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4927 * @param stdClass $context
4928 * @param array $capabilities An array of capabilities
4929 * @return array of roles with all of the required capabilities
4931 function get_role_names_with_caps_in_context($context, $capabilities) {
4932 global $DB;
4934 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4935 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4937 $roles = array();
4938 foreach ($rolesthatcanrate as $r) {
4939 $roles[$r] = $allroles[$r];
4942 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4946 * This function verifies the prohibit comes from this context
4947 * and there are no more prohibits in parent contexts.
4949 * @param int $roleid
4950 * @param context $context
4951 * @param string $capability name
4952 * @return bool
4954 function prohibit_is_removable($roleid, context $context, $capability) {
4955 global $DB;
4957 $ctxids = trim($context->path, '/'); // kill leading slash
4958 $ctxids = str_replace('/', ',', $ctxids);
4960 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4962 $sql = "SELECT ctx.id
4963 FROM {role_capabilities} rc
4964 JOIN {context} ctx ON ctx.id = rc.contextid
4965 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4966 ORDER BY ctx.depth DESC";
4968 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4969 // no prohibits == nothing to remove
4970 return true;
4973 if (count($prohibits) > 1) {
4974 // more prohibits can not be removed
4975 return false;
4978 return !empty($prohibits[$context->id]);
4982 * More user friendly role permission changing,
4983 * it should produce as few overrides as possible.
4985 * @param int $roleid
4986 * @param stdClass $context
4987 * @param string $capname capability name
4988 * @param int $permission
4989 * @return void
4991 function role_change_permission($roleid, $context, $capname, $permission) {
4992 global $DB;
4994 if ($permission == CAP_INHERIT) {
4995 unassign_capability($capname, $roleid, $context->id);
4996 $context->mark_dirty();
4997 return;
5000 $ctxids = trim($context->path, '/'); // kill leading slash
5001 $ctxids = str_replace('/', ',', $ctxids);
5003 $params = array('roleid'=>$roleid, 'cap'=>$capname);
5005 $sql = "SELECT ctx.id, rc.permission, ctx.depth
5006 FROM {role_capabilities} rc
5007 JOIN {context} ctx ON ctx.id = rc.contextid
5008 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
5009 ORDER BY ctx.depth DESC";
5011 if ($existing = $DB->get_records_sql($sql, $params)) {
5012 foreach($existing as $e) {
5013 if ($e->permission == CAP_PROHIBIT) {
5014 // prohibit can not be overridden, no point in changing anything
5015 return;
5018 $lowest = array_shift($existing);
5019 if ($lowest->permission == $permission) {
5020 // permission already set in this context or parent - nothing to do
5021 return;
5023 if ($existing) {
5024 $parent = array_shift($existing);
5025 if ($parent->permission == $permission) {
5026 // permission already set in parent context or parent - just unset in this context
5027 // we do this because we want as few overrides as possible for performance reasons
5028 unassign_capability($capname, $roleid, $context->id);
5029 $context->mark_dirty();
5030 return;
5034 } else {
5035 if ($permission == CAP_PREVENT) {
5036 // nothing means role does not have permission
5037 return;
5041 // assign the needed capability
5042 assign_capability($capname, $permission, $roleid, $context->id, true);
5044 // force cap reloading
5045 $context->mark_dirty();
5050 * Basic moodle context abstraction class.
5052 * Google confirms that no other important framework is using "context" class,
5053 * we could use something else like mcontext or moodle_context, but we need to type
5054 * this very often which would be annoying and it would take too much space...
5056 * This class is derived from stdClass for backwards compatibility with
5057 * odl $context record that was returned from DML $DB->get_record()
5059 * @package core_access
5060 * @category access
5061 * @copyright Petr Skoda {@link http://skodak.org}
5062 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5063 * @since Moodle 2.2
5065 * @property-read int $id context id
5066 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
5067 * @property-read int $instanceid id of related instance in each context
5068 * @property-read string $path path to context, starts with system context
5069 * @property-read int $depth
5071 abstract class context extends stdClass implements IteratorAggregate {
5074 * The context id
5075 * Can be accessed publicly through $context->id
5076 * @var int
5078 protected $_id;
5081 * The context level
5082 * Can be accessed publicly through $context->contextlevel
5083 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
5085 protected $_contextlevel;
5088 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
5089 * Can be accessed publicly through $context->instanceid
5090 * @var int
5092 protected $_instanceid;
5095 * The path to the context always starting from the system context
5096 * Can be accessed publicly through $context->path
5097 * @var string
5099 protected $_path;
5102 * The depth of the context in relation to parent contexts
5103 * Can be accessed publicly through $context->depth
5104 * @var int
5106 protected $_depth;
5109 * @var array Context caching info
5111 private static $cache_contextsbyid = array();
5114 * @var array Context caching info
5116 private static $cache_contexts = array();
5119 * Context count
5120 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
5121 * @var int
5123 protected static $cache_count = 0;
5126 * @var array Context caching info
5128 protected static $cache_preloaded = array();
5131 * @var context_system The system context once initialised
5133 protected static $systemcontext = null;
5136 * Resets the cache to remove all data.
5137 * @static
5139 protected static function reset_caches() {
5140 self::$cache_contextsbyid = array();
5141 self::$cache_contexts = array();
5142 self::$cache_count = 0;
5143 self::$cache_preloaded = array();
5145 self::$systemcontext = null;
5149 * Adds a context to the cache. If the cache is full, discards a batch of
5150 * older entries.
5152 * @static
5153 * @param context $context New context to add
5154 * @return void
5156 protected static function cache_add(context $context) {
5157 if (isset(self::$cache_contextsbyid[$context->id])) {
5158 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5159 return;
5162 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
5163 $i = 0;
5164 foreach(self::$cache_contextsbyid as $ctx) {
5165 $i++;
5166 if ($i <= 100) {
5167 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
5168 continue;
5170 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
5171 // we remove oldest third of the contexts to make room for more contexts
5172 break;
5174 unset(self::$cache_contextsbyid[$ctx->id]);
5175 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
5176 self::$cache_count--;
5180 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
5181 self::$cache_contextsbyid[$context->id] = $context;
5182 self::$cache_count++;
5186 * Removes a context from the cache.
5188 * @static
5189 * @param context $context Context object to remove
5190 * @return void
5192 protected static function cache_remove(context $context) {
5193 if (!isset(self::$cache_contextsbyid[$context->id])) {
5194 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5195 return;
5197 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
5198 unset(self::$cache_contextsbyid[$context->id]);
5200 self::$cache_count--;
5202 if (self::$cache_count < 0) {
5203 self::$cache_count = 0;
5208 * Gets a context from the cache.
5210 * @static
5211 * @param int $contextlevel Context level
5212 * @param int $instance Instance ID
5213 * @return context|bool Context or false if not in cache
5215 protected static function cache_get($contextlevel, $instance) {
5216 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
5217 return self::$cache_contexts[$contextlevel][$instance];
5219 return false;
5223 * Gets a context from the cache based on its id.
5225 * @static
5226 * @param int $id Context ID
5227 * @return context|bool Context or false if not in cache
5229 protected static function cache_get_by_id($id) {
5230 if (isset(self::$cache_contextsbyid[$id])) {
5231 return self::$cache_contextsbyid[$id];
5233 return false;
5237 * Preloads context information from db record and strips the cached info.
5239 * @static
5240 * @param stdClass $rec
5241 * @return void (modifies $rec)
5243 protected static function preload_from_record(stdClass $rec) {
5244 if (empty($rec->ctxid) or empty($rec->ctxlevel) or !isset($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
5245 // $rec does not have enough data, passed here repeatedly or context does not exist yet
5246 return;
5249 // note: in PHP5 the objects are passed by reference, no need to return $rec
5250 $record = new stdClass();
5251 $record->id = $rec->ctxid; unset($rec->ctxid);
5252 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
5253 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
5254 $record->path = $rec->ctxpath; unset($rec->ctxpath);
5255 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
5257 return context::create_instance_from_record($record);
5261 // ====== magic methods =======
5264 * Magic setter method, we do not want anybody to modify properties from the outside
5265 * @param string $name
5266 * @param mixed $value
5268 public function __set($name, $value) {
5269 debugging('Can not change context instance properties!');
5273 * Magic method getter, redirects to read only values.
5274 * @param string $name
5275 * @return mixed
5277 public function __get($name) {
5278 switch ($name) {
5279 case 'id': return $this->_id;
5280 case 'contextlevel': return $this->_contextlevel;
5281 case 'instanceid': return $this->_instanceid;
5282 case 'path': return $this->_path;
5283 case 'depth': return $this->_depth;
5285 default:
5286 debugging('Invalid context property accessed! '.$name);
5287 return null;
5292 * Full support for isset on our magic read only properties.
5293 * @param string $name
5294 * @return bool
5296 public function __isset($name) {
5297 switch ($name) {
5298 case 'id': return isset($this->_id);
5299 case 'contextlevel': return isset($this->_contextlevel);
5300 case 'instanceid': return isset($this->_instanceid);
5301 case 'path': return isset($this->_path);
5302 case 'depth': return isset($this->_depth);
5304 default: return false;
5310 * ALl properties are read only, sorry.
5311 * @param string $name
5313 public function __unset($name) {
5314 debugging('Can not unset context instance properties!');
5317 // ====== implementing method from interface IteratorAggregate ======
5320 * Create an iterator because magic vars can't be seen by 'foreach'.
5322 * Now we can convert context object to array using convert_to_array(),
5323 * and feed it properly to json_encode().
5325 public function getIterator() {
5326 $ret = array(
5327 'id' => $this->id,
5328 'contextlevel' => $this->contextlevel,
5329 'instanceid' => $this->instanceid,
5330 'path' => $this->path,
5331 'depth' => $this->depth
5333 return new ArrayIterator($ret);
5336 // ====== general context methods ======
5339 * Constructor is protected so that devs are forced to
5340 * use context_xxx::instance() or context::instance_by_id().
5342 * @param stdClass $record
5344 protected function __construct(stdClass $record) {
5345 $this->_id = (int)$record->id;
5346 $this->_contextlevel = (int)$record->contextlevel;
5347 $this->_instanceid = $record->instanceid;
5348 $this->_path = $record->path;
5349 $this->_depth = $record->depth;
5353 * This function is also used to work around 'protected' keyword problems in context_helper.
5354 * @static
5355 * @param stdClass $record
5356 * @return context instance
5358 protected static function create_instance_from_record(stdClass $record) {
5359 $classname = context_helper::get_class_for_level($record->contextlevel);
5361 if ($context = context::cache_get_by_id($record->id)) {
5362 return $context;
5365 $context = new $classname($record);
5366 context::cache_add($context);
5368 return $context;
5372 * Copy prepared new contexts from temp table to context table,
5373 * we do this in db specific way for perf reasons only.
5374 * @static
5376 protected static function merge_context_temp_table() {
5377 global $DB;
5379 /* MDL-11347:
5380 * - mysql does not allow to use FROM in UPDATE statements
5381 * - using two tables after UPDATE works in mysql, but might give unexpected
5382 * results in pg 8 (depends on configuration)
5383 * - using table alias in UPDATE does not work in pg < 8.2
5385 * Different code for each database - mostly for performance reasons
5388 $dbfamily = $DB->get_dbfamily();
5389 if ($dbfamily == 'mysql') {
5390 $updatesql = "UPDATE {context} ct, {context_temp} temp
5391 SET ct.path = temp.path,
5392 ct.depth = temp.depth
5393 WHERE ct.id = temp.id";
5394 } else if ($dbfamily == 'oracle') {
5395 $updatesql = "UPDATE {context} ct
5396 SET (ct.path, ct.depth) =
5397 (SELECT temp.path, temp.depth
5398 FROM {context_temp} temp
5399 WHERE temp.id=ct.id)
5400 WHERE EXISTS (SELECT 'x'
5401 FROM {context_temp} temp
5402 WHERE temp.id = ct.id)";
5403 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5404 $updatesql = "UPDATE {context}
5405 SET path = temp.path,
5406 depth = temp.depth
5407 FROM {context_temp} temp
5408 WHERE temp.id={context}.id";
5409 } else {
5410 // sqlite and others
5411 $updatesql = "UPDATE {context}
5412 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5413 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5414 WHERE id IN (SELECT id FROM {context_temp})";
5417 $DB->execute($updatesql);
5421 * Get a context instance as an object, from a given context id.
5423 * @static
5424 * @param int $id context id
5425 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5426 * MUST_EXIST means throw exception if no record found
5427 * @return context|bool the context object or false if not found
5429 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5430 global $DB;
5432 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5433 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5434 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5437 if ($id == SYSCONTEXTID) {
5438 return context_system::instance(0, $strictness);
5441 if (is_array($id) or is_object($id) or empty($id)) {
5442 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5445 if ($context = context::cache_get_by_id($id)) {
5446 return $context;
5449 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5450 return context::create_instance_from_record($record);
5453 return false;
5457 * Update context info after moving context in the tree structure.
5459 * @param context $newparent
5460 * @return void
5462 public function update_moved(context $newparent) {
5463 global $DB;
5465 $frompath = $this->_path;
5466 $newpath = $newparent->path . '/' . $this->_id;
5468 $trans = $DB->start_delegated_transaction();
5470 $this->mark_dirty();
5472 $setdepth = '';
5473 if (($newparent->depth +1) != $this->_depth) {
5474 $diff = $newparent->depth - $this->_depth + 1;
5475 $setdepth = ", depth = depth + $diff";
5477 $sql = "UPDATE {context}
5478 SET path = ?
5479 $setdepth
5480 WHERE id = ?";
5481 $params = array($newpath, $this->_id);
5482 $DB->execute($sql, $params);
5484 $this->_path = $newpath;
5485 $this->_depth = $newparent->depth + 1;
5487 $sql = "UPDATE {context}
5488 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5489 $setdepth
5490 WHERE path LIKE ?";
5491 $params = array($newpath, "{$frompath}/%");
5492 $DB->execute($sql, $params);
5494 $this->mark_dirty();
5496 context::reset_caches();
5498 $trans->allow_commit();
5502 * Remove all context path info and optionally rebuild it.
5504 * @param bool $rebuild
5505 * @return void
5507 public function reset_paths($rebuild = true) {
5508 global $DB;
5510 if ($this->_path) {
5511 $this->mark_dirty();
5513 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5514 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5515 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5516 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5517 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5518 $this->_depth = 0;
5519 $this->_path = null;
5522 if ($rebuild) {
5523 context_helper::build_all_paths(false);
5526 context::reset_caches();
5530 * Delete all data linked to content, do not delete the context record itself
5532 public function delete_content() {
5533 global $CFG, $DB;
5535 blocks_delete_all_for_context($this->_id);
5536 filter_delete_all_for_context($this->_id);
5538 require_once($CFG->dirroot . '/comment/lib.php');
5539 comment::delete_comments(array('contextid'=>$this->_id));
5541 require_once($CFG->dirroot.'/rating/lib.php');
5542 $delopt = new stdclass();
5543 $delopt->contextid = $this->_id;
5544 $rm = new rating_manager();
5545 $rm->delete_ratings($delopt);
5547 // delete all files attached to this context
5548 $fs = get_file_storage();
5549 $fs->delete_area_files($this->_id);
5551 // Delete all repository instances attached to this context.
5552 require_once($CFG->dirroot . '/repository/lib.php');
5553 repository::delete_all_for_context($this->_id);
5555 // delete all advanced grading data attached to this context
5556 require_once($CFG->dirroot.'/grade/grading/lib.php');
5557 grading_manager::delete_all_for_context($this->_id);
5559 // now delete stuff from role related tables, role_unassign_all
5560 // and unenrol should be called earlier to do proper cleanup
5561 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5562 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5563 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5567 * Delete the context content and the context record itself
5569 public function delete() {
5570 global $DB;
5572 if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5573 throw new coding_exception('Cannot delete system context');
5576 // double check the context still exists
5577 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5578 context::cache_remove($this);
5579 return;
5582 $this->delete_content();
5583 $DB->delete_records('context', array('id'=>$this->_id));
5584 // purge static context cache if entry present
5585 context::cache_remove($this);
5587 // do not mark dirty contexts if parents unknown
5588 if (!is_null($this->_path) and $this->_depth > 0) {
5589 $this->mark_dirty();
5593 // ====== context level related methods ======
5596 * Utility method for context creation
5598 * @static
5599 * @param int $contextlevel
5600 * @param int $instanceid
5601 * @param string $parentpath
5602 * @return stdClass context record
5604 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5605 global $DB;
5607 $record = new stdClass();
5608 $record->contextlevel = $contextlevel;
5609 $record->instanceid = $instanceid;
5610 $record->depth = 0;
5611 $record->path = null; //not known before insert
5613 $record->id = $DB->insert_record('context', $record);
5615 // now add path if known - it can be added later
5616 if (!is_null($parentpath)) {
5617 $record->path = $parentpath.'/'.$record->id;
5618 $record->depth = substr_count($record->path, '/');
5619 $DB->update_record('context', $record);
5622 return $record;
5626 * Returns human readable context identifier.
5628 * @param boolean $withprefix whether to prefix the name of the context with the
5629 * type of context, e.g. User, Course, Forum, etc.
5630 * @param boolean $short whether to use the short name of the thing. Only applies
5631 * to course contexts
5632 * @return string the human readable context name.
5634 public function get_context_name($withprefix = true, $short = false) {
5635 // must be implemented in all context levels
5636 throw new coding_exception('can not get name of abstract context');
5640 * Returns the most relevant URL for this context.
5642 * @return moodle_url
5644 public abstract function get_url();
5647 * Returns array of relevant context capability records.
5649 * @return array
5651 public abstract function get_capabilities();
5654 * Recursive function which, given a context, find all its children context ids.
5656 * For course category contexts it will return immediate children and all subcategory contexts.
5657 * It will NOT recurse into courses or subcategories categories.
5658 * If you want to do that, call it on the returned courses/categories.
5660 * When called for a course context, it will return the modules and blocks
5661 * displayed in the course page and blocks displayed on the module pages.
5663 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5664 * contexts ;-)
5666 * @return array Array of child records
5668 public function get_child_contexts() {
5669 global $DB;
5671 if (empty($this->_path) or empty($this->_depth)) {
5672 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5673 return array();
5676 $sql = "SELECT ctx.*
5677 FROM {context} ctx
5678 WHERE ctx.path LIKE ?";
5679 $params = array($this->_path.'/%');
5680 $records = $DB->get_records_sql($sql, $params);
5682 $result = array();
5683 foreach ($records as $record) {
5684 $result[$record->id] = context::create_instance_from_record($record);
5687 return $result;
5691 * Returns parent contexts of this context in reversed order, i.e. parent first,
5692 * then grand parent, etc.
5694 * @param bool $includeself tre means include self too
5695 * @return array of context instances
5697 public function get_parent_contexts($includeself = false) {
5698 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5699 return array();
5702 $result = array();
5703 foreach ($contextids as $contextid) {
5704 $parent = context::instance_by_id($contextid, MUST_EXIST);
5705 $result[$parent->id] = $parent;
5708 return $result;
5712 * Returns parent contexts of this context in reversed order, i.e. parent first,
5713 * then grand parent, etc.
5715 * @param bool $includeself tre means include self too
5716 * @return array of context ids
5718 public function get_parent_context_ids($includeself = false) {
5719 if (empty($this->_path)) {
5720 return array();
5723 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5724 $parentcontexts = explode('/', $parentcontexts);
5725 if (!$includeself) {
5726 array_pop($parentcontexts); // and remove its own id
5729 return array_reverse($parentcontexts);
5733 * Returns parent context
5735 * @return context
5737 public function get_parent_context() {
5738 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5739 return false;
5742 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5743 $parentcontexts = explode('/', $parentcontexts);
5744 array_pop($parentcontexts); // self
5745 $contextid = array_pop($parentcontexts); // immediate parent
5747 return context::instance_by_id($contextid, MUST_EXIST);
5751 * Is this context part of any course? If yes return course context.
5753 * @param bool $strict true means throw exception if not found, false means return false if not found
5754 * @return context_course context of the enclosing course, null if not found or exception
5756 public function get_course_context($strict = true) {
5757 if ($strict) {
5758 throw new coding_exception('Context does not belong to any course.');
5759 } else {
5760 return false;
5765 * Returns sql necessary for purging of stale context instances.
5767 * @static
5768 * @return string cleanup SQL
5770 protected static function get_cleanup_sql() {
5771 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5775 * Rebuild context paths and depths at context level.
5777 * @static
5778 * @param bool $force
5779 * @return void
5781 protected static function build_paths($force) {
5782 throw new coding_exception('build_paths() method must be implemented in all context levels');
5786 * Create missing context instances at given level
5788 * @static
5789 * @return void
5791 protected static function create_level_instances() {
5792 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5796 * Reset all cached permissions and definitions if the necessary.
5797 * @return void
5799 public function reload_if_dirty() {
5800 global $ACCESSLIB_PRIVATE, $USER;
5802 // Load dirty contexts list if needed
5803 if (CLI_SCRIPT) {
5804 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5805 // we do not load dirty flags in CLI and cron
5806 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5808 } else {
5809 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5810 if (!isset($USER->access['time'])) {
5811 // nothing was loaded yet, we do not need to check dirty contexts now
5812 return;
5814 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5815 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5819 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5820 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5821 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5822 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5823 reload_all_capabilities();
5824 break;
5830 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5832 public function mark_dirty() {
5833 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5835 if (during_initial_install()) {
5836 return;
5839 // only if it is a non-empty string
5840 if (is_string($this->_path) && $this->_path !== '') {
5841 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5842 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5843 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5844 } else {
5845 if (CLI_SCRIPT) {
5846 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5847 } else {
5848 if (isset($USER->access['time'])) {
5849 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5850 } else {
5851 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5853 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5862 * Context maintenance and helper methods.
5864 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5865 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5866 * level implementation from the rest of code, the code completion returns what developers need.
5868 * Thank you Tim Hunt for helping me with this nasty trick.
5870 * @package core_access
5871 * @category access
5872 * @copyright Petr Skoda {@link http://skodak.org}
5873 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5874 * @since Moodle 2.2
5876 class context_helper extends context {
5879 * @var array An array mapping context levels to classes
5881 private static $alllevels;
5884 * Instance does not make sense here, only static use
5886 protected function __construct() {
5890 * Reset internal context levels array.
5892 public static function reset_levels() {
5893 self::$alllevels = null;
5897 * Initialise context levels, call before using self::$alllevels.
5899 private static function init_levels() {
5900 global $CFG;
5902 if (isset(self::$alllevels)) {
5903 return;
5905 self::$alllevels = array(
5906 CONTEXT_SYSTEM => 'context_system',
5907 CONTEXT_USER => 'context_user',
5908 CONTEXT_COURSECAT => 'context_coursecat',
5909 CONTEXT_COURSE => 'context_course',
5910 CONTEXT_MODULE => 'context_module',
5911 CONTEXT_BLOCK => 'context_block',
5914 if (empty($CFG->custom_context_classes)) {
5915 return;
5918 $levels = $CFG->custom_context_classes;
5919 if (!is_array($levels)) {
5920 $levels = @unserialize($levels);
5922 if (!is_array($levels)) {
5923 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
5924 return;
5927 // Unsupported custom levels, use with care!!!
5928 foreach ($levels as $level => $classname) {
5929 self::$alllevels[$level] = $classname;
5931 ksort(self::$alllevels);
5935 * Returns a class name of the context level class
5937 * @static
5938 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5939 * @return string class name of the context class
5941 public static function get_class_for_level($contextlevel) {
5942 self::init_levels();
5943 if (isset(self::$alllevels[$contextlevel])) {
5944 return self::$alllevels[$contextlevel];
5945 } else {
5946 throw new coding_exception('Invalid context level specified');
5951 * Returns a list of all context levels
5953 * @static
5954 * @return array int=>string (level=>level class name)
5956 public static function get_all_levels() {
5957 self::init_levels();
5958 return self::$alllevels;
5962 * Remove stale contexts that belonged to deleted instances.
5963 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5965 * @static
5966 * @return void
5968 public static function cleanup_instances() {
5969 global $DB;
5970 self::init_levels();
5972 $sqls = array();
5973 foreach (self::$alllevels as $level=>$classname) {
5974 $sqls[] = $classname::get_cleanup_sql();
5977 $sql = implode(" UNION ", $sqls);
5979 // it is probably better to use transactions, it might be faster too
5980 $transaction = $DB->start_delegated_transaction();
5982 $rs = $DB->get_recordset_sql($sql);
5983 foreach ($rs as $record) {
5984 $context = context::create_instance_from_record($record);
5985 $context->delete();
5987 $rs->close();
5989 $transaction->allow_commit();
5993 * Create all context instances at the given level and above.
5995 * @static
5996 * @param int $contextlevel null means all levels
5997 * @param bool $buildpaths
5998 * @return void
6000 public static function create_instances($contextlevel = null, $buildpaths = true) {
6001 self::init_levels();
6002 foreach (self::$alllevels as $level=>$classname) {
6003 if ($contextlevel and $level > $contextlevel) {
6004 // skip potential sub-contexts
6005 continue;
6007 $classname::create_level_instances();
6008 if ($buildpaths) {
6009 $classname::build_paths(false);
6015 * Rebuild paths and depths in all context levels.
6017 * @static
6018 * @param bool $force false means add missing only
6019 * @return void
6021 public static function build_all_paths($force = false) {
6022 self::init_levels();
6023 foreach (self::$alllevels as $classname) {
6024 $classname::build_paths($force);
6027 // reset static course cache - it might have incorrect cached data
6028 accesslib_clear_all_caches(true);
6032 * Resets the cache to remove all data.
6033 * @static
6035 public static function reset_caches() {
6036 context::reset_caches();
6040 * Returns all fields necessary for context preloading from user $rec.
6042 * This helps with performance when dealing with hundreds of contexts.
6044 * @static
6045 * @param string $tablealias context table alias in the query
6046 * @return array (table.column=>alias, ...)
6048 public static function get_preload_record_columns($tablealias) {
6049 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
6053 * Returns all fields necessary for context preloading from user $rec.
6055 * This helps with performance when dealing with hundreds of contexts.
6057 * @static
6058 * @param string $tablealias context table alias in the query
6059 * @return string
6061 public static function get_preload_record_columns_sql($tablealias) {
6062 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
6066 * Preloads context information from db record and strips the cached info.
6068 * The db request has to contain all columns from context_helper::get_preload_record_columns().
6070 * @static
6071 * @param stdClass $rec
6072 * @return void (modifies $rec)
6074 public static function preload_from_record(stdClass $rec) {
6075 context::preload_from_record($rec);
6079 * Preload all contexts instances from course.
6081 * To be used if you expect multiple queries for course activities...
6083 * @static
6084 * @param int $courseid
6086 public static function preload_course($courseid) {
6087 // Users can call this multiple times without doing any harm
6088 if (isset(context::$cache_preloaded[$courseid])) {
6089 return;
6091 $coursecontext = context_course::instance($courseid);
6092 $coursecontext->get_child_contexts();
6094 context::$cache_preloaded[$courseid] = true;
6098 * Delete context instance
6100 * @static
6101 * @param int $contextlevel
6102 * @param int $instanceid
6103 * @return void
6105 public static function delete_instance($contextlevel, $instanceid) {
6106 global $DB;
6108 // double check the context still exists
6109 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
6110 $context = context::create_instance_from_record($record);
6111 $context->delete();
6112 } else {
6113 // we should try to purge the cache anyway
6118 * Returns the name of specified context level
6120 * @static
6121 * @param int $contextlevel
6122 * @return string name of the context level
6124 public static function get_level_name($contextlevel) {
6125 $classname = context_helper::get_class_for_level($contextlevel);
6126 return $classname::get_level_name();
6130 * not used
6132 public function get_url() {
6136 * not used
6138 public function get_capabilities() {
6144 * System context class
6146 * @package core_access
6147 * @category access
6148 * @copyright Petr Skoda {@link http://skodak.org}
6149 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6150 * @since Moodle 2.2
6152 class context_system extends context {
6154 * Please use context_system::instance() if you need the instance of context.
6156 * @param stdClass $record
6158 protected function __construct(stdClass $record) {
6159 parent::__construct($record);
6160 if ($record->contextlevel != CONTEXT_SYSTEM) {
6161 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
6166 * Returns human readable context level name.
6168 * @static
6169 * @return string the human readable context level name.
6171 public static function get_level_name() {
6172 return get_string('coresystem');
6176 * Returns human readable context identifier.
6178 * @param boolean $withprefix does not apply to system context
6179 * @param boolean $short does not apply to system context
6180 * @return string the human readable context name.
6182 public function get_context_name($withprefix = true, $short = false) {
6183 return self::get_level_name();
6187 * Returns the most relevant URL for this context.
6189 * @return moodle_url
6191 public function get_url() {
6192 return new moodle_url('/');
6196 * Returns array of relevant context capability records.
6198 * @return array
6200 public function get_capabilities() {
6201 global $DB;
6203 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6205 $params = array();
6206 $sql = "SELECT *
6207 FROM {capabilities}";
6209 return $DB->get_records_sql($sql.' '.$sort, $params);
6213 * Create missing context instances at system context
6214 * @static
6216 protected static function create_level_instances() {
6217 // nothing to do here, the system context is created automatically in installer
6218 self::instance(0);
6222 * Returns system context instance.
6224 * @static
6225 * @param int $instanceid
6226 * @param int $strictness
6227 * @param bool $cache
6228 * @return context_system context instance
6230 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
6231 global $DB;
6233 if ($instanceid != 0) {
6234 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
6237 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
6238 if (!isset(context::$systemcontext)) {
6239 $record = new stdClass();
6240 $record->id = SYSCONTEXTID;
6241 $record->contextlevel = CONTEXT_SYSTEM;
6242 $record->instanceid = 0;
6243 $record->path = '/'.SYSCONTEXTID;
6244 $record->depth = 1;
6245 context::$systemcontext = new context_system($record);
6247 return context::$systemcontext;
6251 try {
6252 // We ignore the strictness completely because system context must exist except during install.
6253 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6254 } catch (dml_exception $e) {
6255 //table or record does not exist
6256 if (!during_initial_install()) {
6257 // do not mess with system context after install, it simply must exist
6258 throw $e;
6260 $record = null;
6263 if (!$record) {
6264 $record = new stdClass();
6265 $record->contextlevel = CONTEXT_SYSTEM;
6266 $record->instanceid = 0;
6267 $record->depth = 1;
6268 $record->path = null; //not known before insert
6270 try {
6271 if ($DB->count_records('context')) {
6272 // contexts already exist, this is very weird, system must be first!!!
6273 return null;
6275 if (defined('SYSCONTEXTID')) {
6276 // this would happen only in unittest on sites that went through weird 1.7 upgrade
6277 $record->id = SYSCONTEXTID;
6278 $DB->import_record('context', $record);
6279 $DB->get_manager()->reset_sequence('context');
6280 } else {
6281 $record->id = $DB->insert_record('context', $record);
6283 } catch (dml_exception $e) {
6284 // can not create context - table does not exist yet, sorry
6285 return null;
6289 if ($record->instanceid != 0) {
6290 // this is very weird, somebody must be messing with context table
6291 debugging('Invalid system context detected');
6294 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6295 // fix path if necessary, initial install or path reset
6296 $record->depth = 1;
6297 $record->path = '/'.$record->id;
6298 $DB->update_record('context', $record);
6301 if (!defined('SYSCONTEXTID')) {
6302 define('SYSCONTEXTID', $record->id);
6305 context::$systemcontext = new context_system($record);
6306 return context::$systemcontext;
6310 * Returns all site contexts except the system context, DO NOT call on production servers!!
6312 * Contexts are not cached.
6314 * @return array
6316 public function get_child_contexts() {
6317 global $DB;
6319 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6321 // Just get all the contexts except for CONTEXT_SYSTEM level
6322 // and hope we don't OOM in the process - don't cache
6323 $sql = "SELECT c.*
6324 FROM {context} c
6325 WHERE contextlevel > ".CONTEXT_SYSTEM;
6326 $records = $DB->get_records_sql($sql);
6328 $result = array();
6329 foreach ($records as $record) {
6330 $result[$record->id] = context::create_instance_from_record($record);
6333 return $result;
6337 * Returns sql necessary for purging of stale context instances.
6339 * @static
6340 * @return string cleanup SQL
6342 protected static function get_cleanup_sql() {
6343 $sql = "
6344 SELECT c.*
6345 FROM {context} c
6346 WHERE 1=2
6349 return $sql;
6353 * Rebuild context paths and depths at system context level.
6355 * @static
6356 * @param bool $force
6358 protected static function build_paths($force) {
6359 global $DB;
6361 /* note: ignore $force here, we always do full test of system context */
6363 // exactly one record must exist
6364 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6366 if ($record->instanceid != 0) {
6367 debugging('Invalid system context detected');
6370 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6371 debugging('Invalid SYSCONTEXTID detected');
6374 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6375 // fix path if necessary, initial install or path reset
6376 $record->depth = 1;
6377 $record->path = '/'.$record->id;
6378 $DB->update_record('context', $record);
6385 * User context class
6387 * @package core_access
6388 * @category access
6389 * @copyright Petr Skoda {@link http://skodak.org}
6390 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6391 * @since Moodle 2.2
6393 class context_user extends context {
6395 * Please use context_user::instance($userid) if you need the instance of context.
6396 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6398 * @param stdClass $record
6400 protected function __construct(stdClass $record) {
6401 parent::__construct($record);
6402 if ($record->contextlevel != CONTEXT_USER) {
6403 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6408 * Returns human readable context level name.
6410 * @static
6411 * @return string the human readable context level name.
6413 public static function get_level_name() {
6414 return get_string('user');
6418 * Returns human readable context identifier.
6420 * @param boolean $withprefix whether to prefix the name of the context with User
6421 * @param boolean $short does not apply to user context
6422 * @return string the human readable context name.
6424 public function get_context_name($withprefix = true, $short = false) {
6425 global $DB;
6427 $name = '';
6428 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6429 if ($withprefix){
6430 $name = get_string('user').': ';
6432 $name .= fullname($user);
6434 return $name;
6438 * Returns the most relevant URL for this context.
6440 * @return moodle_url
6442 public function get_url() {
6443 global $COURSE;
6445 if ($COURSE->id == SITEID) {
6446 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6447 } else {
6448 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6450 return $url;
6454 * Returns array of relevant context capability records.
6456 * @return array
6458 public function get_capabilities() {
6459 global $DB;
6461 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6463 $extracaps = array('moodle/grade:viewall');
6464 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6465 $sql = "SELECT *
6466 FROM {capabilities}
6467 WHERE contextlevel = ".CONTEXT_USER."
6468 OR name $extra";
6470 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6474 * Returns user context instance.
6476 * @static
6477 * @param int $instanceid
6478 * @param int $strictness
6479 * @return context_user context instance
6481 public static function instance($instanceid, $strictness = MUST_EXIST) {
6482 global $DB;
6484 if ($context = context::cache_get(CONTEXT_USER, $instanceid)) {
6485 return $context;
6488 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_USER, 'instanceid'=>$instanceid))) {
6489 if ($user = $DB->get_record('user', array('id'=>$instanceid, 'deleted'=>0), 'id', $strictness)) {
6490 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6494 if ($record) {
6495 $context = new context_user($record);
6496 context::cache_add($context);
6497 return $context;
6500 return false;
6504 * Create missing context instances at user context level
6505 * @static
6507 protected static function create_level_instances() {
6508 global $DB;
6510 $sql = "SELECT ".CONTEXT_USER.", u.id
6511 FROM {user} u
6512 WHERE u.deleted = 0
6513 AND NOT EXISTS (SELECT 'x'
6514 FROM {context} cx
6515 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6516 $contextdata = $DB->get_recordset_sql($sql);
6517 foreach ($contextdata as $context) {
6518 context::insert_context_record(CONTEXT_USER, $context->id, null);
6520 $contextdata->close();
6524 * Returns sql necessary for purging of stale context instances.
6526 * @static
6527 * @return string cleanup SQL
6529 protected static function get_cleanup_sql() {
6530 $sql = "
6531 SELECT c.*
6532 FROM {context} c
6533 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6534 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6537 return $sql;
6541 * Rebuild context paths and depths at user context level.
6543 * @static
6544 * @param bool $force
6546 protected static function build_paths($force) {
6547 global $DB;
6549 // First update normal users.
6550 $path = $DB->sql_concat('?', 'id');
6551 $pathstart = '/' . SYSCONTEXTID . '/';
6552 $params = array($pathstart);
6554 if ($force) {
6555 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6556 $params[] = $pathstart;
6557 } else {
6558 $where = "depth = 0 OR path IS NULL";
6561 $sql = "UPDATE {context}
6562 SET depth = 2,
6563 path = {$path}
6564 WHERE contextlevel = " . CONTEXT_USER . "
6565 AND ($where)";
6566 $DB->execute($sql, $params);
6572 * Course category context class
6574 * @package core_access
6575 * @category access
6576 * @copyright Petr Skoda {@link http://skodak.org}
6577 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6578 * @since Moodle 2.2
6580 class context_coursecat extends context {
6582 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6583 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6585 * @param stdClass $record
6587 protected function __construct(stdClass $record) {
6588 parent::__construct($record);
6589 if ($record->contextlevel != CONTEXT_COURSECAT) {
6590 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6595 * Returns human readable context level name.
6597 * @static
6598 * @return string the human readable context level name.
6600 public static function get_level_name() {
6601 return get_string('category');
6605 * Returns human readable context identifier.
6607 * @param boolean $withprefix whether to prefix the name of the context with Category
6608 * @param boolean $short does not apply to course categories
6609 * @return string the human readable context name.
6611 public function get_context_name($withprefix = true, $short = false) {
6612 global $DB;
6614 $name = '';
6615 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6616 if ($withprefix){
6617 $name = get_string('category').': ';
6619 $name .= format_string($category->name, true, array('context' => $this));
6621 return $name;
6625 * Returns the most relevant URL for this context.
6627 * @return moodle_url
6629 public function get_url() {
6630 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6634 * Returns array of relevant context capability records.
6636 * @return array
6638 public function get_capabilities() {
6639 global $DB;
6641 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6643 $params = array();
6644 $sql = "SELECT *
6645 FROM {capabilities}
6646 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6648 return $DB->get_records_sql($sql.' '.$sort, $params);
6652 * Returns course category context instance.
6654 * @static
6655 * @param int $instanceid
6656 * @param int $strictness
6657 * @return context_coursecat context instance
6659 public static function instance($instanceid, $strictness = MUST_EXIST) {
6660 global $DB;
6662 if ($context = context::cache_get(CONTEXT_COURSECAT, $instanceid)) {
6663 return $context;
6666 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSECAT, 'instanceid'=>$instanceid))) {
6667 if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), 'id,parent', $strictness)) {
6668 if ($category->parent) {
6669 $parentcontext = context_coursecat::instance($category->parent);
6670 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6671 } else {
6672 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6677 if ($record) {
6678 $context = new context_coursecat($record);
6679 context::cache_add($context);
6680 return $context;
6683 return false;
6687 * Returns immediate child contexts of category and all subcategories,
6688 * children of subcategories and courses are not returned.
6690 * @return array
6692 public function get_child_contexts() {
6693 global $DB;
6695 if (empty($this->_path) or empty($this->_depth)) {
6696 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6697 return array();
6700 $sql = "SELECT ctx.*
6701 FROM {context} ctx
6702 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6703 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6704 $records = $DB->get_records_sql($sql, $params);
6706 $result = array();
6707 foreach ($records as $record) {
6708 $result[$record->id] = context::create_instance_from_record($record);
6711 return $result;
6715 * Create missing context instances at course category context level
6716 * @static
6718 protected static function create_level_instances() {
6719 global $DB;
6721 $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6722 FROM {course_categories} cc
6723 WHERE NOT EXISTS (SELECT 'x'
6724 FROM {context} cx
6725 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6726 $contextdata = $DB->get_recordset_sql($sql);
6727 foreach ($contextdata as $context) {
6728 context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6730 $contextdata->close();
6734 * Returns sql necessary for purging of stale context instances.
6736 * @static
6737 * @return string cleanup SQL
6739 protected static function get_cleanup_sql() {
6740 $sql = "
6741 SELECT c.*
6742 FROM {context} c
6743 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6744 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6747 return $sql;
6751 * Rebuild context paths and depths at course category context level.
6753 * @static
6754 * @param bool $force
6756 protected static function build_paths($force) {
6757 global $DB;
6759 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6760 if ($force) {
6761 $ctxemptyclause = $emptyclause = '';
6762 } else {
6763 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6764 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6767 $base = '/'.SYSCONTEXTID;
6769 // Normal top level categories
6770 $sql = "UPDATE {context}
6771 SET depth=2,
6772 path=".$DB->sql_concat("'$base/'", 'id')."
6773 WHERE contextlevel=".CONTEXT_COURSECAT."
6774 AND EXISTS (SELECT 'x'
6775 FROM {course_categories} cc
6776 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6777 $emptyclause";
6778 $DB->execute($sql);
6780 // Deeper categories - one query per depthlevel
6781 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6782 for ($n=2; $n<=$maxdepth; $n++) {
6783 $sql = "INSERT INTO {context_temp} (id, path, depth)
6784 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6785 FROM {context} ctx
6786 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6787 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6788 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6789 $ctxemptyclause";
6790 $trans = $DB->start_delegated_transaction();
6791 $DB->delete_records('context_temp');
6792 $DB->execute($sql);
6793 context::merge_context_temp_table();
6794 $DB->delete_records('context_temp');
6795 $trans->allow_commit();
6804 * Course context class
6806 * @package core_access
6807 * @category access
6808 * @copyright Petr Skoda {@link http://skodak.org}
6809 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6810 * @since Moodle 2.2
6812 class context_course extends context {
6814 * Please use context_course::instance($courseid) if you need the instance of context.
6815 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6817 * @param stdClass $record
6819 protected function __construct(stdClass $record) {
6820 parent::__construct($record);
6821 if ($record->contextlevel != CONTEXT_COURSE) {
6822 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6827 * Returns human readable context level name.
6829 * @static
6830 * @return string the human readable context level name.
6832 public static function get_level_name() {
6833 return get_string('course');
6837 * Returns human readable context identifier.
6839 * @param boolean $withprefix whether to prefix the name of the context with Course
6840 * @param boolean $short whether to use the short name of the thing.
6841 * @return string the human readable context name.
6843 public function get_context_name($withprefix = true, $short = false) {
6844 global $DB;
6846 $name = '';
6847 if ($this->_instanceid == SITEID) {
6848 $name = get_string('frontpage', 'admin');
6849 } else {
6850 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6851 if ($withprefix){
6852 $name = get_string('course').': ';
6854 if ($short){
6855 $name .= format_string($course->shortname, true, array('context' => $this));
6856 } else {
6857 $name .= format_string(get_course_display_name_for_list($course));
6861 return $name;
6865 * Returns the most relevant URL for this context.
6867 * @return moodle_url
6869 public function get_url() {
6870 if ($this->_instanceid != SITEID) {
6871 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6874 return new moodle_url('/');
6878 * Returns array of relevant context capability records.
6880 * @return array
6882 public function get_capabilities() {
6883 global $DB;
6885 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6887 $params = array();
6888 $sql = "SELECT *
6889 FROM {capabilities}
6890 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6892 return $DB->get_records_sql($sql.' '.$sort, $params);
6896 * Is this context part of any course? If yes return course context.
6898 * @param bool $strict true means throw exception if not found, false means return false if not found
6899 * @return context_course context of the enclosing course, null if not found or exception
6901 public function get_course_context($strict = true) {
6902 return $this;
6906 * Returns course context instance.
6908 * @static
6909 * @param int $instanceid
6910 * @param int $strictness
6911 * @return context_course context instance
6913 public static function instance($instanceid, $strictness = MUST_EXIST) {
6914 global $DB;
6916 if ($context = context::cache_get(CONTEXT_COURSE, $instanceid)) {
6917 return $context;
6920 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$instanceid))) {
6921 if ($course = $DB->get_record('course', array('id'=>$instanceid), 'id,category', $strictness)) {
6922 if ($course->category) {
6923 $parentcontext = context_coursecat::instance($course->category);
6924 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6925 } else {
6926 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6931 if ($record) {
6932 $context = new context_course($record);
6933 context::cache_add($context);
6934 return $context;
6937 return false;
6941 * Create missing context instances at course context level
6942 * @static
6944 protected static function create_level_instances() {
6945 global $DB;
6947 $sql = "SELECT ".CONTEXT_COURSE.", c.id
6948 FROM {course} c
6949 WHERE NOT EXISTS (SELECT 'x'
6950 FROM {context} cx
6951 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6952 $contextdata = $DB->get_recordset_sql($sql);
6953 foreach ($contextdata as $context) {
6954 context::insert_context_record(CONTEXT_COURSE, $context->id, null);
6956 $contextdata->close();
6960 * Returns sql necessary for purging of stale context instances.
6962 * @static
6963 * @return string cleanup SQL
6965 protected static function get_cleanup_sql() {
6966 $sql = "
6967 SELECT c.*
6968 FROM {context} c
6969 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6970 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6973 return $sql;
6977 * Rebuild context paths and depths at course context level.
6979 * @static
6980 * @param bool $force
6982 protected static function build_paths($force) {
6983 global $DB;
6985 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6986 if ($force) {
6987 $ctxemptyclause = $emptyclause = '';
6988 } else {
6989 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6990 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6993 $base = '/'.SYSCONTEXTID;
6995 // Standard frontpage
6996 $sql = "UPDATE {context}
6997 SET depth = 2,
6998 path = ".$DB->sql_concat("'$base/'", 'id')."
6999 WHERE contextlevel = ".CONTEXT_COURSE."
7000 AND EXISTS (SELECT 'x'
7001 FROM {course} c
7002 WHERE c.id = {context}.instanceid AND c.category = 0)
7003 $emptyclause";
7004 $DB->execute($sql);
7006 // standard courses
7007 $sql = "INSERT INTO {context_temp} (id, path, depth)
7008 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7009 FROM {context} ctx
7010 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
7011 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
7012 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7013 $ctxemptyclause";
7014 $trans = $DB->start_delegated_transaction();
7015 $DB->delete_records('context_temp');
7016 $DB->execute($sql);
7017 context::merge_context_temp_table();
7018 $DB->delete_records('context_temp');
7019 $trans->allow_commit();
7026 * Course module context class
7028 * @package core_access
7029 * @category access
7030 * @copyright Petr Skoda {@link http://skodak.org}
7031 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7032 * @since Moodle 2.2
7034 class context_module extends context {
7036 * Please use context_module::instance($cmid) if you need the instance of context.
7037 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7039 * @param stdClass $record
7041 protected function __construct(stdClass $record) {
7042 parent::__construct($record);
7043 if ($record->contextlevel != CONTEXT_MODULE) {
7044 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
7049 * Returns human readable context level name.
7051 * @static
7052 * @return string the human readable context level name.
7054 public static function get_level_name() {
7055 return get_string('activitymodule');
7059 * Returns human readable context identifier.
7061 * @param boolean $withprefix whether to prefix the name of the context with the
7062 * module name, e.g. Forum, Glossary, etc.
7063 * @param boolean $short does not apply to module context
7064 * @return string the human readable context name.
7066 public function get_context_name($withprefix = true, $short = false) {
7067 global $DB;
7069 $name = '';
7070 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
7071 FROM {course_modules} cm
7072 JOIN {modules} md ON md.id = cm.module
7073 WHERE cm.id = ?", array($this->_instanceid))) {
7074 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
7075 if ($withprefix){
7076 $name = get_string('modulename', $cm->modname).': ';
7078 $name .= format_string($mod->name, true, array('context' => $this));
7081 return $name;
7085 * Returns the most relevant URL for this context.
7087 * @return moodle_url
7089 public function get_url() {
7090 global $DB;
7092 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
7093 FROM {course_modules} cm
7094 JOIN {modules} md ON md.id = cm.module
7095 WHERE cm.id = ?", array($this->_instanceid))) {
7096 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
7099 return new moodle_url('/');
7103 * Returns array of relevant context capability records.
7105 * @return array
7107 public function get_capabilities() {
7108 global $DB, $CFG;
7110 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7112 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
7113 $module = $DB->get_record('modules', array('id'=>$cm->module));
7115 $subcaps = array();
7116 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
7117 if (file_exists($subpluginsfile)) {
7118 $subplugins = array(); // should be redefined in the file
7119 include($subpluginsfile);
7120 if (!empty($subplugins)) {
7121 foreach (array_keys($subplugins) as $subplugintype) {
7122 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
7123 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
7129 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
7130 $extracaps = array();
7131 if (file_exists($modfile)) {
7132 include_once($modfile);
7133 $modfunction = $module->name.'_get_extra_capabilities';
7134 if (function_exists($modfunction)) {
7135 $extracaps = $modfunction();
7139 $extracaps = array_merge($subcaps, $extracaps);
7140 $extra = '';
7141 list($extra, $params) = $DB->get_in_or_equal(
7142 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
7143 if (!empty($extra)) {
7144 $extra = "OR name $extra";
7146 $sql = "SELECT *
7147 FROM {capabilities}
7148 WHERE (contextlevel = ".CONTEXT_MODULE."
7149 AND (component = :component OR component = 'moodle'))
7150 $extra";
7151 $params['component'] = "mod_$module->name";
7153 return $DB->get_records_sql($sql.' '.$sort, $params);
7157 * Is this context part of any course? If yes return course context.
7159 * @param bool $strict true means throw exception if not found, false means return false if not found
7160 * @return context_course context of the enclosing course, null if not found or exception
7162 public function get_course_context($strict = true) {
7163 return $this->get_parent_context();
7167 * Returns module context instance.
7169 * @static
7170 * @param int $instanceid
7171 * @param int $strictness
7172 * @return context_module context instance
7174 public static function instance($instanceid, $strictness = MUST_EXIST) {
7175 global $DB;
7177 if ($context = context::cache_get(CONTEXT_MODULE, $instanceid)) {
7178 return $context;
7181 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$instanceid))) {
7182 if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), 'id,course', $strictness)) {
7183 $parentcontext = context_course::instance($cm->course);
7184 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
7188 if ($record) {
7189 $context = new context_module($record);
7190 context::cache_add($context);
7191 return $context;
7194 return false;
7198 * Create missing context instances at module context level
7199 * @static
7201 protected static function create_level_instances() {
7202 global $DB;
7204 $sql = "SELECT ".CONTEXT_MODULE.", cm.id
7205 FROM {course_modules} cm
7206 WHERE NOT EXISTS (SELECT 'x'
7207 FROM {context} cx
7208 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
7209 $contextdata = $DB->get_recordset_sql($sql);
7210 foreach ($contextdata as $context) {
7211 context::insert_context_record(CONTEXT_MODULE, $context->id, null);
7213 $contextdata->close();
7217 * Returns sql necessary for purging of stale context instances.
7219 * @static
7220 * @return string cleanup SQL
7222 protected static function get_cleanup_sql() {
7223 $sql = "
7224 SELECT c.*
7225 FROM {context} c
7226 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
7227 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
7230 return $sql;
7234 * Rebuild context paths and depths at module context level.
7236 * @static
7237 * @param bool $force
7239 protected static function build_paths($force) {
7240 global $DB;
7242 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
7243 if ($force) {
7244 $ctxemptyclause = '';
7245 } else {
7246 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7249 $sql = "INSERT INTO {context_temp} (id, path, depth)
7250 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7251 FROM {context} ctx
7252 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
7253 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
7254 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7255 $ctxemptyclause";
7256 $trans = $DB->start_delegated_transaction();
7257 $DB->delete_records('context_temp');
7258 $DB->execute($sql);
7259 context::merge_context_temp_table();
7260 $DB->delete_records('context_temp');
7261 $trans->allow_commit();
7268 * Block context class
7270 * @package core_access
7271 * @category access
7272 * @copyright Petr Skoda {@link http://skodak.org}
7273 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7274 * @since Moodle 2.2
7276 class context_block extends context {
7278 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
7279 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7281 * @param stdClass $record
7283 protected function __construct(stdClass $record) {
7284 parent::__construct($record);
7285 if ($record->contextlevel != CONTEXT_BLOCK) {
7286 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
7291 * Returns human readable context level name.
7293 * @static
7294 * @return string the human readable context level name.
7296 public static function get_level_name() {
7297 return get_string('block');
7301 * Returns human readable context identifier.
7303 * @param boolean $withprefix whether to prefix the name of the context with Block
7304 * @param boolean $short does not apply to block context
7305 * @return string the human readable context name.
7307 public function get_context_name($withprefix = true, $short = false) {
7308 global $DB, $CFG;
7310 $name = '';
7311 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
7312 global $CFG;
7313 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7314 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7315 $blockname = "block_$blockinstance->blockname";
7316 if ($blockobject = new $blockname()) {
7317 if ($withprefix){
7318 $name = get_string('block').': ';
7320 $name .= $blockobject->title;
7324 return $name;
7328 * Returns the most relevant URL for this context.
7330 * @return moodle_url
7332 public function get_url() {
7333 $parentcontexts = $this->get_parent_context();
7334 return $parentcontexts->get_url();
7338 * Returns array of relevant context capability records.
7340 * @return array
7342 public function get_capabilities() {
7343 global $DB;
7345 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7347 $params = array();
7348 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
7350 $extra = '';
7351 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7352 if ($extracaps) {
7353 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7354 $extra = "OR name $extra";
7357 $sql = "SELECT *
7358 FROM {capabilities}
7359 WHERE (contextlevel = ".CONTEXT_BLOCK."
7360 AND component = :component)
7361 $extra";
7362 $params['component'] = 'block_' . $bi->blockname;
7364 return $DB->get_records_sql($sql.' '.$sort, $params);
7368 * Is this context part of any course? If yes return course context.
7370 * @param bool $strict true means throw exception if not found, false means return false if not found
7371 * @return context_course context of the enclosing course, null if not found or exception
7373 public function get_course_context($strict = true) {
7374 $parentcontext = $this->get_parent_context();
7375 return $parentcontext->get_course_context($strict);
7379 * Returns block context instance.
7381 * @static
7382 * @param int $instanceid
7383 * @param int $strictness
7384 * @return context_block context instance
7386 public static function instance($instanceid, $strictness = MUST_EXIST) {
7387 global $DB;
7389 if ($context = context::cache_get(CONTEXT_BLOCK, $instanceid)) {
7390 return $context;
7393 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$instanceid))) {
7394 if ($bi = $DB->get_record('block_instances', array('id'=>$instanceid), 'id,parentcontextid', $strictness)) {
7395 $parentcontext = context::instance_by_id($bi->parentcontextid);
7396 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7400 if ($record) {
7401 $context = new context_block($record);
7402 context::cache_add($context);
7403 return $context;
7406 return false;
7410 * Block do not have child contexts...
7411 * @return array
7413 public function get_child_contexts() {
7414 return array();
7418 * Create missing context instances at block context level
7419 * @static
7421 protected static function create_level_instances() {
7422 global $DB;
7424 $sql = "SELECT ".CONTEXT_BLOCK.", bi.id
7425 FROM {block_instances} bi
7426 WHERE NOT EXISTS (SELECT 'x'
7427 FROM {context} cx
7428 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7429 $contextdata = $DB->get_recordset_sql($sql);
7430 foreach ($contextdata as $context) {
7431 context::insert_context_record(CONTEXT_BLOCK, $context->id, null);
7433 $contextdata->close();
7437 * Returns sql necessary for purging of stale context instances.
7439 * @static
7440 * @return string cleanup SQL
7442 protected static function get_cleanup_sql() {
7443 $sql = "
7444 SELECT c.*
7445 FROM {context} c
7446 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7447 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7450 return $sql;
7454 * Rebuild context paths and depths at block context level.
7456 * @static
7457 * @param bool $force
7459 protected static function build_paths($force) {
7460 global $DB;
7462 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7463 if ($force) {
7464 $ctxemptyclause = '';
7465 } else {
7466 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7469 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7470 $sql = "INSERT INTO {context_temp} (id, path, depth)
7471 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7472 FROM {context} ctx
7473 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7474 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7475 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7476 $ctxemptyclause";
7477 $trans = $DB->start_delegated_transaction();
7478 $DB->delete_records('context_temp');
7479 $DB->execute($sql);
7480 context::merge_context_temp_table();
7481 $DB->delete_records('context_temp');
7482 $trans->allow_commit();
7488 // ============== DEPRECATED FUNCTIONS ==========================================
7489 // Old context related functions were deprecated in 2.0, it is recommended
7490 // to use context classes in new code. Old function can be used when
7491 // creating patches that are supposed to be backported to older stable branches.
7492 // These deprecated functions will not be removed in near future,
7493 // before removing devs will be warned with a debugging message first,
7494 // then we will add error message and only after that we can remove the functions
7495 // completely.
7498 * Runs get_records select on context table and returns the result
7499 * Does get_records_select on the context table, and returns the results ordered
7500 * by contextlevel, and then the natural sort order within each level.
7501 * for the purpose of $select, you need to know that the context table has been
7502 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7504 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7505 * @param array $params any parameters required by $select.
7506 * @return array the requested context records.
7508 function get_sorted_contexts($select, $params = array()) {
7510 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7512 global $DB;
7513 if ($select) {
7514 $select = 'WHERE ' . $select;
7516 return $DB->get_records_sql("
7517 SELECT ctx.*
7518 FROM {context} ctx
7519 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7520 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7521 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7522 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7523 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7524 $select
7525 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7526 ", $params);
7530 * Given context and array of users, returns array of users whose enrolment status is suspended,
7531 * or enrolment has expired or has not started. Also removes those users from the given array
7533 * @param context $context context in which suspended users should be extracted.
7534 * @param array $users list of users.
7535 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7536 * @return array list of suspended users.
7538 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7539 global $DB;
7541 // Get active enrolled users.
7542 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7543 $activeusers = $DB->get_records_sql($sql, $params);
7545 // Move suspended users to a separate array & remove from the initial one.
7546 $susers = array();
7547 if (sizeof($activeusers)) {
7548 foreach ($users as $userid => $user) {
7549 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7550 $susers[$userid] = $user;
7551 unset($users[$userid]);
7555 return $susers;
7559 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7560 * or enrolment has expired or not started.
7562 * @param context $context context in which user enrolment is checked.
7563 * @param bool $usecache Enable or disable (default) the request cache
7564 * @return array list of suspended user id's.
7566 function get_suspended_userids(context $context, $usecache = false) {
7567 global $DB;
7569 if ($usecache) {
7570 $cache = cache::make('core', 'suspended_userids');
7571 $susers = $cache->get($context->id);
7572 if ($susers !== false) {
7573 return $susers;
7577 $coursecontext = $context->get_course_context();
7578 $susers = array();
7580 // Front page users are always enrolled, so suspended list is empty.
7581 if ($coursecontext->instanceid != SITEID) {
7582 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7583 $susers = $DB->get_fieldset_sql($sql, $params);
7584 $susers = array_combine($susers, $susers);
7587 // Cache results for the remainder of this request.
7588 if ($usecache) {
7589 $cache->set($context->id, $susers);
7592 return $susers;