MDL-53451 competency: Improve performance by bypassing api::is_enabled()
[moodle.git] / lib / accesslib.php
blob32362d1e6b7b5c95f52d4e46de22025c7f2fc28a
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 * All $sort fields are added into $fields if not present there yet.
4115 * If $roleid is an array or is empty (all roles) you need to set $fields
4116 * (and $sort by extension) params according to it, as the first field
4117 * returned by the database should be unique (ra.id is the best candidate).
4119 * @param int $roleid (can also be an array of ints!)
4120 * @param context $context
4121 * @param bool $parent if true, get list of users assigned in higher context too
4122 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
4123 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
4124 * null => use default sort from users_order_by_sql.
4125 * @param bool $all true means all, false means limit to enrolled users
4126 * @param string $group defaults to ''
4127 * @param mixed $limitfrom defaults to ''
4128 * @param mixed $limitnum defaults to ''
4129 * @param string $extrawheretest defaults to ''
4130 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
4131 * @return array
4133 function get_role_users($roleid, context $context, $parent = false, $fields = '',
4134 $sort = null, $all = true, $group = '',
4135 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
4136 global $DB;
4138 if (empty($fields)) {
4139 $allnames = get_all_user_name_fields(true, 'u');
4140 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
4141 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
4142 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
4143 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
4144 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
4147 // Prevent wrong function uses.
4148 if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
4149 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
4150 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
4152 if (!empty($roleid)) {
4153 // Solving partially the issue when specifying multiple roles.
4154 $users = array();
4155 foreach ($roleid as $id) {
4156 // Ignoring duplicated keys keeping the first user appearance.
4157 $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
4158 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
4160 return $users;
4164 $parentcontexts = '';
4165 if ($parent) {
4166 $parentcontexts = substr($context->path, 1); // kill leading slash
4167 $parentcontexts = str_replace('/', ',', $parentcontexts);
4168 if ($parentcontexts !== '') {
4169 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4173 if ($roleid) {
4174 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
4175 $roleselect = "AND ra.roleid $rids";
4176 } else {
4177 $params = array();
4178 $roleselect = '';
4181 if ($coursecontext = $context->get_course_context(false)) {
4182 $params['coursecontext'] = $coursecontext->id;
4183 } else {
4184 $params['coursecontext'] = 0;
4187 if ($group) {
4188 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
4189 $groupselect = " AND gm.groupid = :groupid ";
4190 $params['groupid'] = $group;
4191 } else {
4192 $groupjoin = '';
4193 $groupselect = '';
4196 $params['contextid'] = $context->id;
4198 if ($extrawheretest) {
4199 $extrawheretest = ' AND ' . $extrawheretest;
4202 if ($whereorsortparams) {
4203 $params = array_merge($params, $whereorsortparams);
4206 if (!$sort) {
4207 list($sort, $sortparams) = users_order_by_sql('u');
4208 $params = array_merge($params, $sortparams);
4211 // Adding the fields from $sort that are not present in $fields.
4212 $sortarray = preg_split('/,\s*/', $sort);
4213 $fieldsarray = preg_split('/,\s*/', $fields);
4214 $addedfields = array();
4215 foreach ($sortarray as $sortfield) {
4216 // Throw away any additional arguments to the sort (e.g. ASC/DESC).
4217 list ($sortfield) = explode(' ', $sortfield);
4218 if (!in_array($sortfield, $fieldsarray)) {
4219 $fieldsarray[] = $sortfield;
4220 $addedfields[] = $sortfield;
4223 $fields = implode(', ', $fieldsarray);
4224 if (!empty($addedfields)) {
4225 $addedfields = implode(', ', $addedfields);
4226 debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
4229 if ($all === null) {
4230 // Previously null was used to indicate that parameter was not used.
4231 $all = true;
4233 if (!$all and $coursecontext) {
4234 // Do not use get_enrolled_sql() here for performance reasons.
4235 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
4236 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
4237 $params['ecourseid'] = $coursecontext->instanceid;
4238 } else {
4239 $ejoin = "";
4242 $sql = "SELECT DISTINCT $fields, ra.roleid
4243 FROM {role_assignments} ra
4244 JOIN {user} u ON u.id = ra.userid
4245 JOIN {role} r ON ra.roleid = r.id
4246 $ejoin
4247 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
4248 $groupjoin
4249 WHERE (ra.contextid = :contextid $parentcontexts)
4250 $roleselect
4251 $groupselect
4252 $extrawheretest
4253 ORDER BY $sort"; // join now so that we can just use fullname() later
4255 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
4259 * Counts all the users assigned this role in this context or higher
4261 * @param int|array $roleid either int or an array of ints
4262 * @param context $context
4263 * @param bool $parent if true, get list of users assigned in higher context too
4264 * @return int Returns the result count
4266 function count_role_users($roleid, context $context, $parent = false) {
4267 global $DB;
4269 if ($parent) {
4270 if ($contexts = $context->get_parent_context_ids()) {
4271 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4272 } else {
4273 $parentcontexts = '';
4275 } else {
4276 $parentcontexts = '';
4279 if ($roleid) {
4280 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
4281 $roleselect = "AND r.roleid $rids";
4282 } else {
4283 $params = array();
4284 $roleselect = '';
4287 array_unshift($params, $context->id);
4289 $sql = "SELECT COUNT(DISTINCT u.id)
4290 FROM {role_assignments} r
4291 JOIN {user} u ON u.id = r.userid
4292 WHERE (r.contextid = ? $parentcontexts)
4293 $roleselect
4294 AND u.deleted = 0";
4296 return $DB->count_records_sql($sql, $params);
4300 * This function gets the list of courses that this user has a particular capability in.
4301 * It is still not very efficient.
4303 * @param string $capability Capability in question
4304 * @param int $userid User ID or null for current user
4305 * @param bool $doanything True if 'doanything' is permitted (default)
4306 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4307 * otherwise use a comma-separated list of the fields you require, not including id
4308 * @param string $orderby If set, use a comma-separated list of fields from course
4309 * table with sql modifiers (DESC) if needed
4310 * @return array|bool Array of courses, if none found false is returned.
4312 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
4313 global $DB;
4315 // Convert fields list and ordering
4316 $fieldlist = '';
4317 if ($fieldsexceptid) {
4318 $fields = explode(',', $fieldsexceptid);
4319 foreach($fields as $field) {
4320 $fieldlist .= ',c.'.$field;
4323 if ($orderby) {
4324 $fields = explode(',', $orderby);
4325 $orderby = '';
4326 foreach($fields as $field) {
4327 if ($orderby) {
4328 $orderby .= ',';
4330 $orderby .= 'c.'.$field;
4332 $orderby = 'ORDER BY '.$orderby;
4335 // Obtain a list of everything relevant about all courses including context.
4336 // Note the result can be used directly as a context (we are going to), the course
4337 // fields are just appended.
4339 $contextpreload = context_helper::get_preload_record_columns_sql('x');
4341 $courses = array();
4342 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
4343 FROM {course} c
4344 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
4345 $orderby");
4346 // Check capability for each course in turn
4347 foreach ($rs as $course) {
4348 context_helper::preload_from_record($course);
4349 $context = context_course::instance($course->id);
4350 if (has_capability($capability, $context, $userid, $doanything)) {
4351 // We've got the capability. Make the record look like a course record
4352 // and store it
4353 $courses[] = $course;
4356 $rs->close();
4357 return empty($courses) ? false : $courses;
4361 * This function finds the roles assigned directly to this context only
4362 * i.e. no roles in parent contexts
4364 * @param context $context
4365 * @return array
4367 function get_roles_on_exact_context(context $context) {
4368 global $DB;
4370 return $DB->get_records_sql("SELECT r.*
4371 FROM {role_assignments} ra, {role} r
4372 WHERE ra.roleid = r.id AND ra.contextid = ?",
4373 array($context->id));
4377 * Switches the current user to another role for the current session and only
4378 * in the given context.
4380 * The caller *must* check
4381 * - that this op is allowed
4382 * - that the requested role can be switched to in this context (use get_switchable_roles)
4383 * - that the requested role is NOT $CFG->defaultuserroleid
4385 * To "unswitch" pass 0 as the roleid.
4387 * This function *will* modify $USER->access - beware
4389 * @param integer $roleid the role to switch to.
4390 * @param context $context the context in which to perform the switch.
4391 * @return bool success or failure.
4393 function role_switch($roleid, context $context) {
4394 global $USER;
4397 // Plan of action
4399 // - Add the ghost RA to $USER->access
4400 // as $USER->access['rsw'][$path] = $roleid
4402 // - Make sure $USER->access['rdef'] has the roledefs
4403 // it needs to honour the switcherole
4405 // Roledefs will get loaded "deep" here - down to the last child
4406 // context. Note that
4408 // - When visiting subcontexts, our selective accessdata loading
4409 // will still work fine - though those ra/rdefs will be ignored
4410 // appropriately while the switch is in place
4412 // - If a switcherole happens at a category with tons of courses
4413 // (that have many overrides for switched-to role), the session
4414 // will get... quite large. Sometimes you just can't win.
4416 // To un-switch just unset($USER->access['rsw'][$path])
4418 // Note: it is not possible to switch to roles that do not have course:view
4420 if (!isset($USER->access)) {
4421 load_all_capabilities();
4425 // Add the switch RA
4426 if ($roleid == 0) {
4427 unset($USER->access['rsw'][$context->path]);
4428 return true;
4431 $USER->access['rsw'][$context->path] = $roleid;
4433 // Load roledefs
4434 load_role_access_by_context($roleid, $context, $USER->access);
4436 return true;
4440 * Checks if the user has switched roles within the given course.
4442 * Note: You can only switch roles within the course, hence it takes a course id
4443 * rather than a context. On that note Petr volunteered to implement this across
4444 * all other contexts, all requests for this should be forwarded to him ;)
4446 * @param int $courseid The id of the course to check
4447 * @return bool True if the user has switched roles within the course.
4449 function is_role_switched($courseid) {
4450 global $USER;
4451 $context = context_course::instance($courseid, MUST_EXIST);
4452 return (!empty($USER->access['rsw'][$context->path]));
4456 * Get any role that has an override on exact context
4458 * @param context $context The context to check
4459 * @return array An array of roles
4461 function get_roles_with_override_on_context(context $context) {
4462 global $DB;
4464 return $DB->get_records_sql("SELECT r.*
4465 FROM {role_capabilities} rc, {role} r
4466 WHERE rc.roleid = r.id AND rc.contextid = ?",
4467 array($context->id));
4471 * Get all capabilities for this role on this context (overrides)
4473 * @param stdClass $role
4474 * @param context $context
4475 * @return array
4477 function get_capabilities_from_role_on_context($role, context $context) {
4478 global $DB;
4480 return $DB->get_records_sql("SELECT *
4481 FROM {role_capabilities}
4482 WHERE contextid = ? AND roleid = ?",
4483 array($context->id, $role->id));
4487 * Find out which roles has assignment on this context
4489 * @param context $context
4490 * @return array
4493 function get_roles_with_assignment_on_context(context $context) {
4494 global $DB;
4496 return $DB->get_records_sql("SELECT r.*
4497 FROM {role_assignments} ra, {role} r
4498 WHERE ra.roleid = r.id AND ra.contextid = ?",
4499 array($context->id));
4503 * Find all user assignment of users for this role, on this context
4505 * @param stdClass $role
4506 * @param context $context
4507 * @return array
4509 function get_users_from_role_on_context($role, context $context) {
4510 global $DB;
4512 return $DB->get_records_sql("SELECT *
4513 FROM {role_assignments}
4514 WHERE contextid = ? AND roleid = ?",
4515 array($context->id, $role->id));
4519 * Simple function returning a boolean true if user has roles
4520 * in context or parent contexts, otherwise false.
4522 * @param int $userid
4523 * @param int $roleid
4524 * @param int $contextid empty means any context
4525 * @return bool
4527 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4528 global $DB;
4530 if ($contextid) {
4531 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4532 return false;
4534 $parents = $context->get_parent_context_ids(true);
4535 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4536 $params['userid'] = $userid;
4537 $params['roleid'] = $roleid;
4539 $sql = "SELECT COUNT(ra.id)
4540 FROM {role_assignments} ra
4541 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4543 $count = $DB->get_field_sql($sql, $params);
4544 return ($count > 0);
4546 } else {
4547 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4552 * Get localised role name or alias if exists and format the text.
4554 * @param stdClass $role role object
4555 * - optional 'coursealias' property should be included for performance reasons if course context used
4556 * - description property is not required here
4557 * @param context|bool $context empty means system context
4558 * @param int $rolenamedisplay type of role name
4559 * @return string localised role name or course role name alias
4561 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4562 global $DB;
4564 if ($rolenamedisplay == ROLENAME_SHORT) {
4565 return $role->shortname;
4568 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4569 $coursecontext = null;
4572 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4573 $role = clone($role); // Do not modify parameters.
4574 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4575 $role->coursealias = $r->name;
4576 } else {
4577 $role->coursealias = null;
4581 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4582 if ($coursecontext) {
4583 return $role->coursealias;
4584 } else {
4585 return null;
4589 if (trim($role->name) !== '') {
4590 // For filtering always use context where was the thing defined - system for roles here.
4591 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4593 } else {
4594 // Empty role->name means we want to see localised role name based on shortname,
4595 // only default roles are supposed to be localised.
4596 switch ($role->shortname) {
4597 case 'manager': $original = get_string('manager', 'role'); break;
4598 case 'coursecreator': $original = get_string('coursecreators'); break;
4599 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4600 case 'teacher': $original = get_string('noneditingteacher'); break;
4601 case 'student': $original = get_string('defaultcoursestudent'); break;
4602 case 'guest': $original = get_string('guest'); break;
4603 case 'user': $original = get_string('authenticateduser'); break;
4604 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4605 // We should not get here, the role UI should require the name for custom roles!
4606 default: $original = $role->shortname; break;
4610 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4611 return $original;
4614 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4615 return "$original ($role->shortname)";
4618 if ($rolenamedisplay == ROLENAME_ALIAS) {
4619 if ($coursecontext and trim($role->coursealias) !== '') {
4620 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4621 } else {
4622 return $original;
4626 if ($rolenamedisplay == ROLENAME_BOTH) {
4627 if ($coursecontext and trim($role->coursealias) !== '') {
4628 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4629 } else {
4630 return $original;
4634 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4638 * Returns localised role description if available.
4639 * If the name is empty it tries to find the default role name using
4640 * hardcoded list of default role names or other methods in the future.
4642 * @param stdClass $role
4643 * @return string localised role name
4645 function role_get_description(stdClass $role) {
4646 if (!html_is_blank($role->description)) {
4647 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4650 switch ($role->shortname) {
4651 case 'manager': return get_string('managerdescription', 'role');
4652 case 'coursecreator': return get_string('coursecreatorsdescription');
4653 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4654 case 'teacher': return get_string('noneditingteacherdescription');
4655 case 'student': return get_string('defaultcoursestudentdescription');
4656 case 'guest': return get_string('guestdescription');
4657 case 'user': return get_string('authenticateduserdescription');
4658 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4659 default: return '';
4664 * Get all the localised role names for a context.
4666 * In new installs default roles have empty names, this function
4667 * add localised role names using current language pack.
4669 * @param context $context the context, null means system context
4670 * @param array of role objects with a ->localname field containing the context-specific role name.
4671 * @param int $rolenamedisplay
4672 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4673 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4675 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4676 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4680 * Prepare list of roles for display, apply aliases and localise default role names.
4682 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4683 * @param context $context the context, null means system context
4684 * @param int $rolenamedisplay
4685 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4686 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4688 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4689 global $DB;
4691 if (empty($roleoptions)) {
4692 return array();
4695 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4696 $coursecontext = null;
4699 // We usually need all role columns...
4700 $first = reset($roleoptions);
4701 if ($returnmenu === null) {
4702 $returnmenu = !is_object($first);
4705 if (!is_object($first) or !property_exists($first, 'shortname')) {
4706 $allroles = get_all_roles($context);
4707 foreach ($roleoptions as $rid => $unused) {
4708 $roleoptions[$rid] = $allroles[$rid];
4712 // Inject coursealias if necessary.
4713 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4714 $first = reset($roleoptions);
4715 if (!property_exists($first, 'coursealias')) {
4716 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4717 foreach ($aliasnames as $alias) {
4718 if (isset($roleoptions[$alias->roleid])) {
4719 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4725 // Add localname property.
4726 foreach ($roleoptions as $rid => $role) {
4727 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4730 if (!$returnmenu) {
4731 return $roleoptions;
4734 $menu = array();
4735 foreach ($roleoptions as $rid => $role) {
4736 $menu[$rid] = $role->localname;
4739 return $menu;
4743 * Aids in detecting if a new line is required when reading a new capability
4745 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4746 * when we read in a new capability.
4747 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4748 * but when we are in grade, all reports/import/export capabilities should be together
4750 * @param string $cap component string a
4751 * @param string $comp component string b
4752 * @param int $contextlevel
4753 * @return bool whether 2 component are in different "sections"
4755 function component_level_changed($cap, $comp, $contextlevel) {
4757 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4758 $compsa = explode('/', $cap->component);
4759 $compsb = explode('/', $comp);
4761 // list of system reports
4762 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4763 return false;
4766 // we are in gradebook, still
4767 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4768 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4769 return false;
4772 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4773 return false;
4777 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4781 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4782 * and return an array of roleids in order.
4784 * @param array $allroles array of roles, as returned by get_all_roles();
4785 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4787 function fix_role_sortorder($allroles) {
4788 global $DB;
4790 $rolesort = array();
4791 $i = 0;
4792 foreach ($allroles as $role) {
4793 $rolesort[$i] = $role->id;
4794 if ($role->sortorder != $i) {
4795 $r = new stdClass();
4796 $r->id = $role->id;
4797 $r->sortorder = $i;
4798 $DB->update_record('role', $r);
4799 $allroles[$role->id]->sortorder = $i;
4801 $i++;
4803 return $rolesort;
4807 * Switch the sort order of two roles (used in admin/roles/manage.php).
4809 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4810 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4811 * @return boolean success or failure
4813 function switch_roles($first, $second) {
4814 global $DB;
4815 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4816 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4817 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4818 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4819 return $result;
4823 * Duplicates all the base definitions of a role
4825 * @param stdClass $sourcerole role to copy from
4826 * @param int $targetrole id of role to copy to
4828 function role_cap_duplicate($sourcerole, $targetrole) {
4829 global $DB;
4831 $systemcontext = context_system::instance();
4832 $caps = $DB->get_records_sql("SELECT *
4833 FROM {role_capabilities}
4834 WHERE roleid = ? AND contextid = ?",
4835 array($sourcerole->id, $systemcontext->id));
4836 // adding capabilities
4837 foreach ($caps as $cap) {
4838 unset($cap->id);
4839 $cap->roleid = $targetrole;
4840 $DB->insert_record('role_capabilities', $cap);
4845 * Returns two lists, this can be used to find out if user has capability.
4846 * Having any needed role and no forbidden role in this context means
4847 * user has this capability in this context.
4848 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4850 * @param stdClass $context
4851 * @param string $capability
4852 * @return array($neededroles, $forbiddenroles)
4854 function get_roles_with_cap_in_context($context, $capability) {
4855 global $DB;
4857 $ctxids = trim($context->path, '/'); // kill leading slash
4858 $ctxids = str_replace('/', ',', $ctxids);
4860 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4861 FROM {role_capabilities} rc
4862 JOIN {context} ctx ON ctx.id = rc.contextid
4863 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4864 ORDER BY rc.roleid ASC, ctx.depth DESC";
4865 $params = array('cap'=>$capability);
4867 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4868 // no cap definitions --> no capability
4869 return array(array(), array());
4872 $forbidden = array();
4873 $needed = array();
4874 foreach($capdefs as $def) {
4875 if (isset($forbidden[$def->roleid])) {
4876 continue;
4878 if ($def->permission == CAP_PROHIBIT) {
4879 $forbidden[$def->roleid] = $def->roleid;
4880 unset($needed[$def->roleid]);
4881 continue;
4883 if (!isset($needed[$def->roleid])) {
4884 if ($def->permission == CAP_ALLOW) {
4885 $needed[$def->roleid] = true;
4886 } else if ($def->permission == CAP_PREVENT) {
4887 $needed[$def->roleid] = false;
4891 unset($capdefs);
4893 // remove all those roles not allowing
4894 foreach($needed as $key=>$value) {
4895 if (!$value) {
4896 unset($needed[$key]);
4897 } else {
4898 $needed[$key] = $key;
4902 return array($needed, $forbidden);
4906 * Returns an array of role IDs that have ALL of the the supplied capabilities
4907 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4909 * @param stdClass $context
4910 * @param array $capabilities An array of capabilities
4911 * @return array of roles with all of the required capabilities
4913 function get_roles_with_caps_in_context($context, $capabilities) {
4914 $neededarr = array();
4915 $forbiddenarr = array();
4916 foreach($capabilities as $caprequired) {
4917 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4920 $rolesthatcanrate = array();
4921 if (!empty($neededarr)) {
4922 foreach ($neededarr as $needed) {
4923 if (empty($rolesthatcanrate)) {
4924 $rolesthatcanrate = $needed;
4925 } else {
4926 //only want roles that have all caps
4927 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4931 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4932 foreach ($forbiddenarr as $forbidden) {
4933 //remove any roles that are forbidden any of the caps
4934 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4937 return $rolesthatcanrate;
4941 * Returns an array of role names that have ALL of the the supplied capabilities
4942 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4944 * @param stdClass $context
4945 * @param array $capabilities An array of capabilities
4946 * @return array of roles with all of the required capabilities
4948 function get_role_names_with_caps_in_context($context, $capabilities) {
4949 global $DB;
4951 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4952 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4954 $roles = array();
4955 foreach ($rolesthatcanrate as $r) {
4956 $roles[$r] = $allroles[$r];
4959 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4963 * This function verifies the prohibit comes from this context
4964 * and there are no more prohibits in parent contexts.
4966 * @param int $roleid
4967 * @param context $context
4968 * @param string $capability name
4969 * @return bool
4971 function prohibit_is_removable($roleid, context $context, $capability) {
4972 global $DB;
4974 $ctxids = trim($context->path, '/'); // kill leading slash
4975 $ctxids = str_replace('/', ',', $ctxids);
4977 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4979 $sql = "SELECT ctx.id
4980 FROM {role_capabilities} rc
4981 JOIN {context} ctx ON ctx.id = rc.contextid
4982 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4983 ORDER BY ctx.depth DESC";
4985 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4986 // no prohibits == nothing to remove
4987 return true;
4990 if (count($prohibits) > 1) {
4991 // more prohibits can not be removed
4992 return false;
4995 return !empty($prohibits[$context->id]);
4999 * More user friendly role permission changing,
5000 * it should produce as few overrides as possible.
5002 * @param int $roleid
5003 * @param stdClass $context
5004 * @param string $capname capability name
5005 * @param int $permission
5006 * @return void
5008 function role_change_permission($roleid, $context, $capname, $permission) {
5009 global $DB;
5011 if ($permission == CAP_INHERIT) {
5012 unassign_capability($capname, $roleid, $context->id);
5013 $context->mark_dirty();
5014 return;
5017 $ctxids = trim($context->path, '/'); // kill leading slash
5018 $ctxids = str_replace('/', ',', $ctxids);
5020 $params = array('roleid'=>$roleid, 'cap'=>$capname);
5022 $sql = "SELECT ctx.id, rc.permission, ctx.depth
5023 FROM {role_capabilities} rc
5024 JOIN {context} ctx ON ctx.id = rc.contextid
5025 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
5026 ORDER BY ctx.depth DESC";
5028 if ($existing = $DB->get_records_sql($sql, $params)) {
5029 foreach($existing as $e) {
5030 if ($e->permission == CAP_PROHIBIT) {
5031 // prohibit can not be overridden, no point in changing anything
5032 return;
5035 $lowest = array_shift($existing);
5036 if ($lowest->permission == $permission) {
5037 // permission already set in this context or parent - nothing to do
5038 return;
5040 if ($existing) {
5041 $parent = array_shift($existing);
5042 if ($parent->permission == $permission) {
5043 // permission already set in parent context or parent - just unset in this context
5044 // we do this because we want as few overrides as possible for performance reasons
5045 unassign_capability($capname, $roleid, $context->id);
5046 $context->mark_dirty();
5047 return;
5051 } else {
5052 if ($permission == CAP_PREVENT) {
5053 // nothing means role does not have permission
5054 return;
5058 // assign the needed capability
5059 assign_capability($capname, $permission, $roleid, $context->id, true);
5061 // force cap reloading
5062 $context->mark_dirty();
5067 * Basic moodle context abstraction class.
5069 * Google confirms that no other important framework is using "context" class,
5070 * we could use something else like mcontext or moodle_context, but we need to type
5071 * this very often which would be annoying and it would take too much space...
5073 * This class is derived from stdClass for backwards compatibility with
5074 * odl $context record that was returned from DML $DB->get_record()
5076 * @package core_access
5077 * @category access
5078 * @copyright Petr Skoda {@link http://skodak.org}
5079 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5080 * @since Moodle 2.2
5082 * @property-read int $id context id
5083 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
5084 * @property-read int $instanceid id of related instance in each context
5085 * @property-read string $path path to context, starts with system context
5086 * @property-read int $depth
5088 abstract class context extends stdClass implements IteratorAggregate {
5091 * The context id
5092 * Can be accessed publicly through $context->id
5093 * @var int
5095 protected $_id;
5098 * The context level
5099 * Can be accessed publicly through $context->contextlevel
5100 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
5102 protected $_contextlevel;
5105 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
5106 * Can be accessed publicly through $context->instanceid
5107 * @var int
5109 protected $_instanceid;
5112 * The path to the context always starting from the system context
5113 * Can be accessed publicly through $context->path
5114 * @var string
5116 protected $_path;
5119 * The depth of the context in relation to parent contexts
5120 * Can be accessed publicly through $context->depth
5121 * @var int
5123 protected $_depth;
5126 * @var array Context caching info
5128 private static $cache_contextsbyid = array();
5131 * @var array Context caching info
5133 private static $cache_contexts = array();
5136 * Context count
5137 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
5138 * @var int
5140 protected static $cache_count = 0;
5143 * @var array Context caching info
5145 protected static $cache_preloaded = array();
5148 * @var context_system The system context once initialised
5150 protected static $systemcontext = null;
5153 * Resets the cache to remove all data.
5154 * @static
5156 protected static function reset_caches() {
5157 self::$cache_contextsbyid = array();
5158 self::$cache_contexts = array();
5159 self::$cache_count = 0;
5160 self::$cache_preloaded = array();
5162 self::$systemcontext = null;
5166 * Adds a context to the cache. If the cache is full, discards a batch of
5167 * older entries.
5169 * @static
5170 * @param context $context New context to add
5171 * @return void
5173 protected static function cache_add(context $context) {
5174 if (isset(self::$cache_contextsbyid[$context->id])) {
5175 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5176 return;
5179 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
5180 $i = 0;
5181 foreach(self::$cache_contextsbyid as $ctx) {
5182 $i++;
5183 if ($i <= 100) {
5184 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
5185 continue;
5187 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
5188 // we remove oldest third of the contexts to make room for more contexts
5189 break;
5191 unset(self::$cache_contextsbyid[$ctx->id]);
5192 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
5193 self::$cache_count--;
5197 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
5198 self::$cache_contextsbyid[$context->id] = $context;
5199 self::$cache_count++;
5203 * Removes a context from the cache.
5205 * @static
5206 * @param context $context Context object to remove
5207 * @return void
5209 protected static function cache_remove(context $context) {
5210 if (!isset(self::$cache_contextsbyid[$context->id])) {
5211 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5212 return;
5214 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
5215 unset(self::$cache_contextsbyid[$context->id]);
5217 self::$cache_count--;
5219 if (self::$cache_count < 0) {
5220 self::$cache_count = 0;
5225 * Gets a context from the cache.
5227 * @static
5228 * @param int $contextlevel Context level
5229 * @param int $instance Instance ID
5230 * @return context|bool Context or false if not in cache
5232 protected static function cache_get($contextlevel, $instance) {
5233 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
5234 return self::$cache_contexts[$contextlevel][$instance];
5236 return false;
5240 * Gets a context from the cache based on its id.
5242 * @static
5243 * @param int $id Context ID
5244 * @return context|bool Context or false if not in cache
5246 protected static function cache_get_by_id($id) {
5247 if (isset(self::$cache_contextsbyid[$id])) {
5248 return self::$cache_contextsbyid[$id];
5250 return false;
5254 * Preloads context information from db record and strips the cached info.
5256 * @static
5257 * @param stdClass $rec
5258 * @return void (modifies $rec)
5260 protected static function preload_from_record(stdClass $rec) {
5261 if (empty($rec->ctxid) or empty($rec->ctxlevel) or !isset($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
5262 // $rec does not have enough data, passed here repeatedly or context does not exist yet
5263 return;
5266 // note: in PHP5 the objects are passed by reference, no need to return $rec
5267 $record = new stdClass();
5268 $record->id = $rec->ctxid; unset($rec->ctxid);
5269 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
5270 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
5271 $record->path = $rec->ctxpath; unset($rec->ctxpath);
5272 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
5274 return context::create_instance_from_record($record);
5278 // ====== magic methods =======
5281 * Magic setter method, we do not want anybody to modify properties from the outside
5282 * @param string $name
5283 * @param mixed $value
5285 public function __set($name, $value) {
5286 debugging('Can not change context instance properties!');
5290 * Magic method getter, redirects to read only values.
5291 * @param string $name
5292 * @return mixed
5294 public function __get($name) {
5295 switch ($name) {
5296 case 'id': return $this->_id;
5297 case 'contextlevel': return $this->_contextlevel;
5298 case 'instanceid': return $this->_instanceid;
5299 case 'path': return $this->_path;
5300 case 'depth': return $this->_depth;
5302 default:
5303 debugging('Invalid context property accessed! '.$name);
5304 return null;
5309 * Full support for isset on our magic read only properties.
5310 * @param string $name
5311 * @return bool
5313 public function __isset($name) {
5314 switch ($name) {
5315 case 'id': return isset($this->_id);
5316 case 'contextlevel': return isset($this->_contextlevel);
5317 case 'instanceid': return isset($this->_instanceid);
5318 case 'path': return isset($this->_path);
5319 case 'depth': return isset($this->_depth);
5321 default: return false;
5327 * ALl properties are read only, sorry.
5328 * @param string $name
5330 public function __unset($name) {
5331 debugging('Can not unset context instance properties!');
5334 // ====== implementing method from interface IteratorAggregate ======
5337 * Create an iterator because magic vars can't be seen by 'foreach'.
5339 * Now we can convert context object to array using convert_to_array(),
5340 * and feed it properly to json_encode().
5342 public function getIterator() {
5343 $ret = array(
5344 'id' => $this->id,
5345 'contextlevel' => $this->contextlevel,
5346 'instanceid' => $this->instanceid,
5347 'path' => $this->path,
5348 'depth' => $this->depth
5350 return new ArrayIterator($ret);
5353 // ====== general context methods ======
5356 * Constructor is protected so that devs are forced to
5357 * use context_xxx::instance() or context::instance_by_id().
5359 * @param stdClass $record
5361 protected function __construct(stdClass $record) {
5362 $this->_id = (int)$record->id;
5363 $this->_contextlevel = (int)$record->contextlevel;
5364 $this->_instanceid = $record->instanceid;
5365 $this->_path = $record->path;
5366 $this->_depth = $record->depth;
5370 * This function is also used to work around 'protected' keyword problems in context_helper.
5371 * @static
5372 * @param stdClass $record
5373 * @return context instance
5375 protected static function create_instance_from_record(stdClass $record) {
5376 $classname = context_helper::get_class_for_level($record->contextlevel);
5378 if ($context = context::cache_get_by_id($record->id)) {
5379 return $context;
5382 $context = new $classname($record);
5383 context::cache_add($context);
5385 return $context;
5389 * Copy prepared new contexts from temp table to context table,
5390 * we do this in db specific way for perf reasons only.
5391 * @static
5393 protected static function merge_context_temp_table() {
5394 global $DB;
5396 /* MDL-11347:
5397 * - mysql does not allow to use FROM in UPDATE statements
5398 * - using two tables after UPDATE works in mysql, but might give unexpected
5399 * results in pg 8 (depends on configuration)
5400 * - using table alias in UPDATE does not work in pg < 8.2
5402 * Different code for each database - mostly for performance reasons
5405 $dbfamily = $DB->get_dbfamily();
5406 if ($dbfamily == 'mysql') {
5407 $updatesql = "UPDATE {context} ct, {context_temp} temp
5408 SET ct.path = temp.path,
5409 ct.depth = temp.depth
5410 WHERE ct.id = temp.id";
5411 } else if ($dbfamily == 'oracle') {
5412 $updatesql = "UPDATE {context} ct
5413 SET (ct.path, ct.depth) =
5414 (SELECT temp.path, temp.depth
5415 FROM {context_temp} temp
5416 WHERE temp.id=ct.id)
5417 WHERE EXISTS (SELECT 'x'
5418 FROM {context_temp} temp
5419 WHERE temp.id = ct.id)";
5420 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5421 $updatesql = "UPDATE {context}
5422 SET path = temp.path,
5423 depth = temp.depth
5424 FROM {context_temp} temp
5425 WHERE temp.id={context}.id";
5426 } else {
5427 // sqlite and others
5428 $updatesql = "UPDATE {context}
5429 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5430 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5431 WHERE id IN (SELECT id FROM {context_temp})";
5434 $DB->execute($updatesql);
5438 * Get a context instance as an object, from a given context id.
5440 * @static
5441 * @param int $id context id
5442 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5443 * MUST_EXIST means throw exception if no record found
5444 * @return context|bool the context object or false if not found
5446 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5447 global $DB;
5449 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5450 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5451 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5454 if ($id == SYSCONTEXTID) {
5455 return context_system::instance(0, $strictness);
5458 if (is_array($id) or is_object($id) or empty($id)) {
5459 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5462 if ($context = context::cache_get_by_id($id)) {
5463 return $context;
5466 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5467 return context::create_instance_from_record($record);
5470 return false;
5474 * Update context info after moving context in the tree structure.
5476 * @param context $newparent
5477 * @return void
5479 public function update_moved(context $newparent) {
5480 global $DB;
5482 $frompath = $this->_path;
5483 $newpath = $newparent->path . '/' . $this->_id;
5485 $trans = $DB->start_delegated_transaction();
5487 $this->mark_dirty();
5489 $setdepth = '';
5490 if (($newparent->depth +1) != $this->_depth) {
5491 $diff = $newparent->depth - $this->_depth + 1;
5492 $setdepth = ", depth = depth + $diff";
5494 $sql = "UPDATE {context}
5495 SET path = ?
5496 $setdepth
5497 WHERE id = ?";
5498 $params = array($newpath, $this->_id);
5499 $DB->execute($sql, $params);
5501 $this->_path = $newpath;
5502 $this->_depth = $newparent->depth + 1;
5504 $sql = "UPDATE {context}
5505 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5506 $setdepth
5507 WHERE path LIKE ?";
5508 $params = array($newpath, "{$frompath}/%");
5509 $DB->execute($sql, $params);
5511 $this->mark_dirty();
5513 context::reset_caches();
5515 $trans->allow_commit();
5519 * Remove all context path info and optionally rebuild it.
5521 * @param bool $rebuild
5522 * @return void
5524 public function reset_paths($rebuild = true) {
5525 global $DB;
5527 if ($this->_path) {
5528 $this->mark_dirty();
5530 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5531 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5532 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5533 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5534 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5535 $this->_depth = 0;
5536 $this->_path = null;
5539 if ($rebuild) {
5540 context_helper::build_all_paths(false);
5543 context::reset_caches();
5547 * Delete all data linked to content, do not delete the context record itself
5549 public function delete_content() {
5550 global $CFG, $DB;
5552 blocks_delete_all_for_context($this->_id);
5553 filter_delete_all_for_context($this->_id);
5555 require_once($CFG->dirroot . '/comment/lib.php');
5556 comment::delete_comments(array('contextid'=>$this->_id));
5558 require_once($CFG->dirroot.'/rating/lib.php');
5559 $delopt = new stdclass();
5560 $delopt->contextid = $this->_id;
5561 $rm = new rating_manager();
5562 $rm->delete_ratings($delopt);
5564 // delete all files attached to this context
5565 $fs = get_file_storage();
5566 $fs->delete_area_files($this->_id);
5568 // Delete all repository instances attached to this context.
5569 require_once($CFG->dirroot . '/repository/lib.php');
5570 repository::delete_all_for_context($this->_id);
5572 // delete all advanced grading data attached to this context
5573 require_once($CFG->dirroot.'/grade/grading/lib.php');
5574 grading_manager::delete_all_for_context($this->_id);
5576 // now delete stuff from role related tables, role_unassign_all
5577 // and unenrol should be called earlier to do proper cleanup
5578 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5579 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5580 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5584 * Delete the context content and the context record itself
5586 public function delete() {
5587 global $DB;
5589 if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5590 throw new coding_exception('Cannot delete system context');
5593 // double check the context still exists
5594 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5595 context::cache_remove($this);
5596 return;
5599 $this->delete_content();
5600 $DB->delete_records('context', array('id'=>$this->_id));
5601 // purge static context cache if entry present
5602 context::cache_remove($this);
5604 // do not mark dirty contexts if parents unknown
5605 if (!is_null($this->_path) and $this->_depth > 0) {
5606 $this->mark_dirty();
5610 // ====== context level related methods ======
5613 * Utility method for context creation
5615 * @static
5616 * @param int $contextlevel
5617 * @param int $instanceid
5618 * @param string $parentpath
5619 * @return stdClass context record
5621 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5622 global $DB;
5624 $record = new stdClass();
5625 $record->contextlevel = $contextlevel;
5626 $record->instanceid = $instanceid;
5627 $record->depth = 0;
5628 $record->path = null; //not known before insert
5630 $record->id = $DB->insert_record('context', $record);
5632 // now add path if known - it can be added later
5633 if (!is_null($parentpath)) {
5634 $record->path = $parentpath.'/'.$record->id;
5635 $record->depth = substr_count($record->path, '/');
5636 $DB->update_record('context', $record);
5639 return $record;
5643 * Returns human readable context identifier.
5645 * @param boolean $withprefix whether to prefix the name of the context with the
5646 * type of context, e.g. User, Course, Forum, etc.
5647 * @param boolean $short whether to use the short name of the thing. Only applies
5648 * to course contexts
5649 * @return string the human readable context name.
5651 public function get_context_name($withprefix = true, $short = false) {
5652 // must be implemented in all context levels
5653 throw new coding_exception('can not get name of abstract context');
5657 * Returns the most relevant URL for this context.
5659 * @return moodle_url
5661 public abstract function get_url();
5664 * Returns array of relevant context capability records.
5666 * @return array
5668 public abstract function get_capabilities();
5671 * Recursive function which, given a context, find all its children context ids.
5673 * For course category contexts it will return immediate children and all subcategory contexts.
5674 * It will NOT recurse into courses or subcategories categories.
5675 * If you want to do that, call it on the returned courses/categories.
5677 * When called for a course context, it will return the modules and blocks
5678 * displayed in the course page and blocks displayed on the module pages.
5680 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5681 * contexts ;-)
5683 * @return array Array of child records
5685 public function get_child_contexts() {
5686 global $DB;
5688 if (empty($this->_path) or empty($this->_depth)) {
5689 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5690 return array();
5693 $sql = "SELECT ctx.*
5694 FROM {context} ctx
5695 WHERE ctx.path LIKE ?";
5696 $params = array($this->_path.'/%');
5697 $records = $DB->get_records_sql($sql, $params);
5699 $result = array();
5700 foreach ($records as $record) {
5701 $result[$record->id] = context::create_instance_from_record($record);
5704 return $result;
5708 * Returns parent contexts of this context in reversed order, i.e. parent first,
5709 * then grand parent, etc.
5711 * @param bool $includeself tre means include self too
5712 * @return array of context instances
5714 public function get_parent_contexts($includeself = false) {
5715 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5716 return array();
5719 $result = array();
5720 foreach ($contextids as $contextid) {
5721 $parent = context::instance_by_id($contextid, MUST_EXIST);
5722 $result[$parent->id] = $parent;
5725 return $result;
5729 * Returns parent contexts of this context in reversed order, i.e. parent first,
5730 * then grand parent, etc.
5732 * @param bool $includeself tre means include self too
5733 * @return array of context ids
5735 public function get_parent_context_ids($includeself = false) {
5736 if (empty($this->_path)) {
5737 return array();
5740 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5741 $parentcontexts = explode('/', $parentcontexts);
5742 if (!$includeself) {
5743 array_pop($parentcontexts); // and remove its own id
5746 return array_reverse($parentcontexts);
5750 * Returns parent context
5752 * @return context
5754 public function get_parent_context() {
5755 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5756 return false;
5759 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5760 $parentcontexts = explode('/', $parentcontexts);
5761 array_pop($parentcontexts); // self
5762 $contextid = array_pop($parentcontexts); // immediate parent
5764 return context::instance_by_id($contextid, MUST_EXIST);
5768 * Is this context part of any course? If yes return course context.
5770 * @param bool $strict true means throw exception if not found, false means return false if not found
5771 * @return context_course context of the enclosing course, null if not found or exception
5773 public function get_course_context($strict = true) {
5774 if ($strict) {
5775 throw new coding_exception('Context does not belong to any course.');
5776 } else {
5777 return false;
5782 * Returns sql necessary for purging of stale context instances.
5784 * @static
5785 * @return string cleanup SQL
5787 protected static function get_cleanup_sql() {
5788 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5792 * Rebuild context paths and depths at context level.
5794 * @static
5795 * @param bool $force
5796 * @return void
5798 protected static function build_paths($force) {
5799 throw new coding_exception('build_paths() method must be implemented in all context levels');
5803 * Create missing context instances at given level
5805 * @static
5806 * @return void
5808 protected static function create_level_instances() {
5809 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5813 * Reset all cached permissions and definitions if the necessary.
5814 * @return void
5816 public function reload_if_dirty() {
5817 global $ACCESSLIB_PRIVATE, $USER;
5819 // Load dirty contexts list if needed
5820 if (CLI_SCRIPT) {
5821 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5822 // we do not load dirty flags in CLI and cron
5823 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5825 } else {
5826 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5827 if (!isset($USER->access['time'])) {
5828 // nothing was loaded yet, we do not need to check dirty contexts now
5829 return;
5831 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5832 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5836 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5837 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5838 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5839 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5840 reload_all_capabilities();
5841 break;
5847 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5849 public function mark_dirty() {
5850 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5852 if (during_initial_install()) {
5853 return;
5856 // only if it is a non-empty string
5857 if (is_string($this->_path) && $this->_path !== '') {
5858 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5859 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5860 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5861 } else {
5862 if (CLI_SCRIPT) {
5863 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5864 } else {
5865 if (isset($USER->access['time'])) {
5866 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5867 } else {
5868 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5870 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5879 * Context maintenance and helper methods.
5881 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5882 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5883 * level implementation from the rest of code, the code completion returns what developers need.
5885 * Thank you Tim Hunt for helping me with this nasty trick.
5887 * @package core_access
5888 * @category access
5889 * @copyright Petr Skoda {@link http://skodak.org}
5890 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5891 * @since Moodle 2.2
5893 class context_helper extends context {
5896 * @var array An array mapping context levels to classes
5898 private static $alllevels;
5901 * Instance does not make sense here, only static use
5903 protected function __construct() {
5907 * Reset internal context levels array.
5909 public static function reset_levels() {
5910 self::$alllevels = null;
5914 * Initialise context levels, call before using self::$alllevels.
5916 private static function init_levels() {
5917 global $CFG;
5919 if (isset(self::$alllevels)) {
5920 return;
5922 self::$alllevels = array(
5923 CONTEXT_SYSTEM => 'context_system',
5924 CONTEXT_USER => 'context_user',
5925 CONTEXT_COURSECAT => 'context_coursecat',
5926 CONTEXT_COURSE => 'context_course',
5927 CONTEXT_MODULE => 'context_module',
5928 CONTEXT_BLOCK => 'context_block',
5931 if (empty($CFG->custom_context_classes)) {
5932 return;
5935 $levels = $CFG->custom_context_classes;
5936 if (!is_array($levels)) {
5937 $levels = @unserialize($levels);
5939 if (!is_array($levels)) {
5940 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
5941 return;
5944 // Unsupported custom levels, use with care!!!
5945 foreach ($levels as $level => $classname) {
5946 self::$alllevels[$level] = $classname;
5948 ksort(self::$alllevels);
5952 * Returns a class name of the context level class
5954 * @static
5955 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5956 * @return string class name of the context class
5958 public static function get_class_for_level($contextlevel) {
5959 self::init_levels();
5960 if (isset(self::$alllevels[$contextlevel])) {
5961 return self::$alllevels[$contextlevel];
5962 } else {
5963 throw new coding_exception('Invalid context level specified');
5968 * Returns a list of all context levels
5970 * @static
5971 * @return array int=>string (level=>level class name)
5973 public static function get_all_levels() {
5974 self::init_levels();
5975 return self::$alllevels;
5979 * Remove stale contexts that belonged to deleted instances.
5980 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5982 * @static
5983 * @return void
5985 public static function cleanup_instances() {
5986 global $DB;
5987 self::init_levels();
5989 $sqls = array();
5990 foreach (self::$alllevels as $level=>$classname) {
5991 $sqls[] = $classname::get_cleanup_sql();
5994 $sql = implode(" UNION ", $sqls);
5996 // it is probably better to use transactions, it might be faster too
5997 $transaction = $DB->start_delegated_transaction();
5999 $rs = $DB->get_recordset_sql($sql);
6000 foreach ($rs as $record) {
6001 $context = context::create_instance_from_record($record);
6002 $context->delete();
6004 $rs->close();
6006 $transaction->allow_commit();
6010 * Create all context instances at the given level and above.
6012 * @static
6013 * @param int $contextlevel null means all levels
6014 * @param bool $buildpaths
6015 * @return void
6017 public static function create_instances($contextlevel = null, $buildpaths = true) {
6018 self::init_levels();
6019 foreach (self::$alllevels as $level=>$classname) {
6020 if ($contextlevel and $level > $contextlevel) {
6021 // skip potential sub-contexts
6022 continue;
6024 $classname::create_level_instances();
6025 if ($buildpaths) {
6026 $classname::build_paths(false);
6032 * Rebuild paths and depths in all context levels.
6034 * @static
6035 * @param bool $force false means add missing only
6036 * @return void
6038 public static function build_all_paths($force = false) {
6039 self::init_levels();
6040 foreach (self::$alllevels as $classname) {
6041 $classname::build_paths($force);
6044 // reset static course cache - it might have incorrect cached data
6045 accesslib_clear_all_caches(true);
6049 * Resets the cache to remove all data.
6050 * @static
6052 public static function reset_caches() {
6053 context::reset_caches();
6057 * Returns all fields necessary for context preloading from user $rec.
6059 * This helps with performance when dealing with hundreds of contexts.
6061 * @static
6062 * @param string $tablealias context table alias in the query
6063 * @return array (table.column=>alias, ...)
6065 public static function get_preload_record_columns($tablealias) {
6066 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
6070 * Returns all fields necessary for context preloading from user $rec.
6072 * This helps with performance when dealing with hundreds of contexts.
6074 * @static
6075 * @param string $tablealias context table alias in the query
6076 * @return string
6078 public static function get_preload_record_columns_sql($tablealias) {
6079 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
6083 * Preloads context information from db record and strips the cached info.
6085 * The db request has to contain all columns from context_helper::get_preload_record_columns().
6087 * @static
6088 * @param stdClass $rec
6089 * @return void (modifies $rec)
6091 public static function preload_from_record(stdClass $rec) {
6092 context::preload_from_record($rec);
6096 * Preload all contexts instances from course.
6098 * To be used if you expect multiple queries for course activities...
6100 * @static
6101 * @param int $courseid
6103 public static function preload_course($courseid) {
6104 // Users can call this multiple times without doing any harm
6105 if (isset(context::$cache_preloaded[$courseid])) {
6106 return;
6108 $coursecontext = context_course::instance($courseid);
6109 $coursecontext->get_child_contexts();
6111 context::$cache_preloaded[$courseid] = true;
6115 * Delete context instance
6117 * @static
6118 * @param int $contextlevel
6119 * @param int $instanceid
6120 * @return void
6122 public static function delete_instance($contextlevel, $instanceid) {
6123 global $DB;
6125 // double check the context still exists
6126 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
6127 $context = context::create_instance_from_record($record);
6128 $context->delete();
6129 } else {
6130 // we should try to purge the cache anyway
6135 * Returns the name of specified context level
6137 * @static
6138 * @param int $contextlevel
6139 * @return string name of the context level
6141 public static function get_level_name($contextlevel) {
6142 $classname = context_helper::get_class_for_level($contextlevel);
6143 return $classname::get_level_name();
6147 * not used
6149 public function get_url() {
6153 * not used
6155 public function get_capabilities() {
6161 * System context class
6163 * @package core_access
6164 * @category access
6165 * @copyright Petr Skoda {@link http://skodak.org}
6166 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6167 * @since Moodle 2.2
6169 class context_system extends context {
6171 * Please use context_system::instance() if you need the instance of context.
6173 * @param stdClass $record
6175 protected function __construct(stdClass $record) {
6176 parent::__construct($record);
6177 if ($record->contextlevel != CONTEXT_SYSTEM) {
6178 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
6183 * Returns human readable context level name.
6185 * @static
6186 * @return string the human readable context level name.
6188 public static function get_level_name() {
6189 return get_string('coresystem');
6193 * Returns human readable context identifier.
6195 * @param boolean $withprefix does not apply to system context
6196 * @param boolean $short does not apply to system context
6197 * @return string the human readable context name.
6199 public function get_context_name($withprefix = true, $short = false) {
6200 return self::get_level_name();
6204 * Returns the most relevant URL for this context.
6206 * @return moodle_url
6208 public function get_url() {
6209 return new moodle_url('/');
6213 * Returns array of relevant context capability records.
6215 * @return array
6217 public function get_capabilities() {
6218 global $DB;
6220 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6222 $params = array();
6223 $sql = "SELECT *
6224 FROM {capabilities}";
6226 return $DB->get_records_sql($sql.' '.$sort, $params);
6230 * Create missing context instances at system context
6231 * @static
6233 protected static function create_level_instances() {
6234 // nothing to do here, the system context is created automatically in installer
6235 self::instance(0);
6239 * Returns system context instance.
6241 * @static
6242 * @param int $instanceid should be 0
6243 * @param int $strictness
6244 * @param bool $cache
6245 * @return context_system context instance
6247 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
6248 global $DB;
6250 if ($instanceid != 0) {
6251 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
6254 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
6255 if (!isset(context::$systemcontext)) {
6256 $record = new stdClass();
6257 $record->id = SYSCONTEXTID;
6258 $record->contextlevel = CONTEXT_SYSTEM;
6259 $record->instanceid = 0;
6260 $record->path = '/'.SYSCONTEXTID;
6261 $record->depth = 1;
6262 context::$systemcontext = new context_system($record);
6264 return context::$systemcontext;
6268 try {
6269 // We ignore the strictness completely because system context must exist except during install.
6270 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6271 } catch (dml_exception $e) {
6272 //table or record does not exist
6273 if (!during_initial_install()) {
6274 // do not mess with system context after install, it simply must exist
6275 throw $e;
6277 $record = null;
6280 if (!$record) {
6281 $record = new stdClass();
6282 $record->contextlevel = CONTEXT_SYSTEM;
6283 $record->instanceid = 0;
6284 $record->depth = 1;
6285 $record->path = null; //not known before insert
6287 try {
6288 if ($DB->count_records('context')) {
6289 // contexts already exist, this is very weird, system must be first!!!
6290 return null;
6292 if (defined('SYSCONTEXTID')) {
6293 // this would happen only in unittest on sites that went through weird 1.7 upgrade
6294 $record->id = SYSCONTEXTID;
6295 $DB->import_record('context', $record);
6296 $DB->get_manager()->reset_sequence('context');
6297 } else {
6298 $record->id = $DB->insert_record('context', $record);
6300 } catch (dml_exception $e) {
6301 // can not create context - table does not exist yet, sorry
6302 return null;
6306 if ($record->instanceid != 0) {
6307 // this is very weird, somebody must be messing with context table
6308 debugging('Invalid system context detected');
6311 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6312 // fix path if necessary, initial install or path reset
6313 $record->depth = 1;
6314 $record->path = '/'.$record->id;
6315 $DB->update_record('context', $record);
6318 if (!defined('SYSCONTEXTID')) {
6319 define('SYSCONTEXTID', $record->id);
6322 context::$systemcontext = new context_system($record);
6323 return context::$systemcontext;
6327 * Returns all site contexts except the system context, DO NOT call on production servers!!
6329 * Contexts are not cached.
6331 * @return array
6333 public function get_child_contexts() {
6334 global $DB;
6336 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6338 // Just get all the contexts except for CONTEXT_SYSTEM level
6339 // and hope we don't OOM in the process - don't cache
6340 $sql = "SELECT c.*
6341 FROM {context} c
6342 WHERE contextlevel > ".CONTEXT_SYSTEM;
6343 $records = $DB->get_records_sql($sql);
6345 $result = array();
6346 foreach ($records as $record) {
6347 $result[$record->id] = context::create_instance_from_record($record);
6350 return $result;
6354 * Returns sql necessary for purging of stale context instances.
6356 * @static
6357 * @return string cleanup SQL
6359 protected static function get_cleanup_sql() {
6360 $sql = "
6361 SELECT c.*
6362 FROM {context} c
6363 WHERE 1=2
6366 return $sql;
6370 * Rebuild context paths and depths at system context level.
6372 * @static
6373 * @param bool $force
6375 protected static function build_paths($force) {
6376 global $DB;
6378 /* note: ignore $force here, we always do full test of system context */
6380 // exactly one record must exist
6381 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6383 if ($record->instanceid != 0) {
6384 debugging('Invalid system context detected');
6387 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6388 debugging('Invalid SYSCONTEXTID detected');
6391 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6392 // fix path if necessary, initial install or path reset
6393 $record->depth = 1;
6394 $record->path = '/'.$record->id;
6395 $DB->update_record('context', $record);
6402 * User context class
6404 * @package core_access
6405 * @category access
6406 * @copyright Petr Skoda {@link http://skodak.org}
6407 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6408 * @since Moodle 2.2
6410 class context_user extends context {
6412 * Please use context_user::instance($userid) if you need the instance of context.
6413 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6415 * @param stdClass $record
6417 protected function __construct(stdClass $record) {
6418 parent::__construct($record);
6419 if ($record->contextlevel != CONTEXT_USER) {
6420 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6425 * Returns human readable context level name.
6427 * @static
6428 * @return string the human readable context level name.
6430 public static function get_level_name() {
6431 return get_string('user');
6435 * Returns human readable context identifier.
6437 * @param boolean $withprefix whether to prefix the name of the context with User
6438 * @param boolean $short does not apply to user context
6439 * @return string the human readable context name.
6441 public function get_context_name($withprefix = true, $short = false) {
6442 global $DB;
6444 $name = '';
6445 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6446 if ($withprefix){
6447 $name = get_string('user').': ';
6449 $name .= fullname($user);
6451 return $name;
6455 * Returns the most relevant URL for this context.
6457 * @return moodle_url
6459 public function get_url() {
6460 global $COURSE;
6462 if ($COURSE->id == SITEID) {
6463 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6464 } else {
6465 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6467 return $url;
6471 * Returns array of relevant context capability records.
6473 * @return array
6475 public function get_capabilities() {
6476 global $DB;
6478 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6480 $extracaps = array('moodle/grade:viewall');
6481 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6482 $sql = "SELECT *
6483 FROM {capabilities}
6484 WHERE contextlevel = ".CONTEXT_USER."
6485 OR name $extra";
6487 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6491 * Returns user context instance.
6493 * @static
6494 * @param int $userid id from {user} table
6495 * @param int $strictness
6496 * @return context_user context instance
6498 public static function instance($userid, $strictness = MUST_EXIST) {
6499 global $DB;
6501 if ($context = context::cache_get(CONTEXT_USER, $userid)) {
6502 return $context;
6505 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER, 'instanceid' => $userid))) {
6506 if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6507 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6511 if ($record) {
6512 $context = new context_user($record);
6513 context::cache_add($context);
6514 return $context;
6517 return false;
6521 * Create missing context instances at user context level
6522 * @static
6524 protected static function create_level_instances() {
6525 global $DB;
6527 $sql = "SELECT ".CONTEXT_USER.", u.id
6528 FROM {user} u
6529 WHERE u.deleted = 0
6530 AND NOT EXISTS (SELECT 'x'
6531 FROM {context} cx
6532 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6533 $contextdata = $DB->get_recordset_sql($sql);
6534 foreach ($contextdata as $context) {
6535 context::insert_context_record(CONTEXT_USER, $context->id, null);
6537 $contextdata->close();
6541 * Returns sql necessary for purging of stale context instances.
6543 * @static
6544 * @return string cleanup SQL
6546 protected static function get_cleanup_sql() {
6547 $sql = "
6548 SELECT c.*
6549 FROM {context} c
6550 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6551 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6554 return $sql;
6558 * Rebuild context paths and depths at user context level.
6560 * @static
6561 * @param bool $force
6563 protected static function build_paths($force) {
6564 global $DB;
6566 // First update normal users.
6567 $path = $DB->sql_concat('?', 'id');
6568 $pathstart = '/' . SYSCONTEXTID . '/';
6569 $params = array($pathstart);
6571 if ($force) {
6572 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6573 $params[] = $pathstart;
6574 } else {
6575 $where = "depth = 0 OR path IS NULL";
6578 $sql = "UPDATE {context}
6579 SET depth = 2,
6580 path = {$path}
6581 WHERE contextlevel = " . CONTEXT_USER . "
6582 AND ($where)";
6583 $DB->execute($sql, $params);
6589 * Course category context class
6591 * @package core_access
6592 * @category access
6593 * @copyright Petr Skoda {@link http://skodak.org}
6594 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6595 * @since Moodle 2.2
6597 class context_coursecat extends context {
6599 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6600 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6602 * @param stdClass $record
6604 protected function __construct(stdClass $record) {
6605 parent::__construct($record);
6606 if ($record->contextlevel != CONTEXT_COURSECAT) {
6607 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6612 * Returns human readable context level name.
6614 * @static
6615 * @return string the human readable context level name.
6617 public static function get_level_name() {
6618 return get_string('category');
6622 * Returns human readable context identifier.
6624 * @param boolean $withprefix whether to prefix the name of the context with Category
6625 * @param boolean $short does not apply to course categories
6626 * @return string the human readable context name.
6628 public function get_context_name($withprefix = true, $short = false) {
6629 global $DB;
6631 $name = '';
6632 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6633 if ($withprefix){
6634 $name = get_string('category').': ';
6636 $name .= format_string($category->name, true, array('context' => $this));
6638 return $name;
6642 * Returns the most relevant URL for this context.
6644 * @return moodle_url
6646 public function get_url() {
6647 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6651 * Returns array of relevant context capability records.
6653 * @return array
6655 public function get_capabilities() {
6656 global $DB;
6658 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6660 $params = array();
6661 $sql = "SELECT *
6662 FROM {capabilities}
6663 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6665 return $DB->get_records_sql($sql.' '.$sort, $params);
6669 * Returns course category context instance.
6671 * @static
6672 * @param int $categoryid id from {course_categories} table
6673 * @param int $strictness
6674 * @return context_coursecat context instance
6676 public static function instance($categoryid, $strictness = MUST_EXIST) {
6677 global $DB;
6679 if ($context = context::cache_get(CONTEXT_COURSECAT, $categoryid)) {
6680 return $context;
6683 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT, 'instanceid' => $categoryid))) {
6684 if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6685 if ($category->parent) {
6686 $parentcontext = context_coursecat::instance($category->parent);
6687 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6688 } else {
6689 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6694 if ($record) {
6695 $context = new context_coursecat($record);
6696 context::cache_add($context);
6697 return $context;
6700 return false;
6704 * Returns immediate child contexts of category and all subcategories,
6705 * children of subcategories and courses are not returned.
6707 * @return array
6709 public function get_child_contexts() {
6710 global $DB;
6712 if (empty($this->_path) or empty($this->_depth)) {
6713 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6714 return array();
6717 $sql = "SELECT ctx.*
6718 FROM {context} ctx
6719 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6720 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6721 $records = $DB->get_records_sql($sql, $params);
6723 $result = array();
6724 foreach ($records as $record) {
6725 $result[$record->id] = context::create_instance_from_record($record);
6728 return $result;
6732 * Create missing context instances at course category context level
6733 * @static
6735 protected static function create_level_instances() {
6736 global $DB;
6738 $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6739 FROM {course_categories} cc
6740 WHERE NOT EXISTS (SELECT 'x'
6741 FROM {context} cx
6742 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6743 $contextdata = $DB->get_recordset_sql($sql);
6744 foreach ($contextdata as $context) {
6745 context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6747 $contextdata->close();
6751 * Returns sql necessary for purging of stale context instances.
6753 * @static
6754 * @return string cleanup SQL
6756 protected static function get_cleanup_sql() {
6757 $sql = "
6758 SELECT c.*
6759 FROM {context} c
6760 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6761 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6764 return $sql;
6768 * Rebuild context paths and depths at course category context level.
6770 * @static
6771 * @param bool $force
6773 protected static function build_paths($force) {
6774 global $DB;
6776 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6777 if ($force) {
6778 $ctxemptyclause = $emptyclause = '';
6779 } else {
6780 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6781 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6784 $base = '/'.SYSCONTEXTID;
6786 // Normal top level categories
6787 $sql = "UPDATE {context}
6788 SET depth=2,
6789 path=".$DB->sql_concat("'$base/'", 'id')."
6790 WHERE contextlevel=".CONTEXT_COURSECAT."
6791 AND EXISTS (SELECT 'x'
6792 FROM {course_categories} cc
6793 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6794 $emptyclause";
6795 $DB->execute($sql);
6797 // Deeper categories - one query per depthlevel
6798 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6799 for ($n=2; $n<=$maxdepth; $n++) {
6800 $sql = "INSERT INTO {context_temp} (id, path, depth)
6801 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6802 FROM {context} ctx
6803 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6804 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6805 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6806 $ctxemptyclause";
6807 $trans = $DB->start_delegated_transaction();
6808 $DB->delete_records('context_temp');
6809 $DB->execute($sql);
6810 context::merge_context_temp_table();
6811 $DB->delete_records('context_temp');
6812 $trans->allow_commit();
6821 * Course context class
6823 * @package core_access
6824 * @category access
6825 * @copyright Petr Skoda {@link http://skodak.org}
6826 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6827 * @since Moodle 2.2
6829 class context_course extends context {
6831 * Please use context_course::instance($courseid) if you need the instance of context.
6832 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6834 * @param stdClass $record
6836 protected function __construct(stdClass $record) {
6837 parent::__construct($record);
6838 if ($record->contextlevel != CONTEXT_COURSE) {
6839 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6844 * Returns human readable context level name.
6846 * @static
6847 * @return string the human readable context level name.
6849 public static function get_level_name() {
6850 return get_string('course');
6854 * Returns human readable context identifier.
6856 * @param boolean $withprefix whether to prefix the name of the context with Course
6857 * @param boolean $short whether to use the short name of the thing.
6858 * @return string the human readable context name.
6860 public function get_context_name($withprefix = true, $short = false) {
6861 global $DB;
6863 $name = '';
6864 if ($this->_instanceid == SITEID) {
6865 $name = get_string('frontpage', 'admin');
6866 } else {
6867 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6868 if ($withprefix){
6869 $name = get_string('course').': ';
6871 if ($short){
6872 $name .= format_string($course->shortname, true, array('context' => $this));
6873 } else {
6874 $name .= format_string(get_course_display_name_for_list($course));
6878 return $name;
6882 * Returns the most relevant URL for this context.
6884 * @return moodle_url
6886 public function get_url() {
6887 if ($this->_instanceid != SITEID) {
6888 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6891 return new moodle_url('/');
6895 * Returns array of relevant context capability records.
6897 * @return array
6899 public function get_capabilities() {
6900 global $DB;
6902 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6904 $params = array();
6905 $sql = "SELECT *
6906 FROM {capabilities}
6907 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6909 return $DB->get_records_sql($sql.' '.$sort, $params);
6913 * Is this context part of any course? If yes return course context.
6915 * @param bool $strict true means throw exception if not found, false means return false if not found
6916 * @return context_course context of the enclosing course, null if not found or exception
6918 public function get_course_context($strict = true) {
6919 return $this;
6923 * Returns course context instance.
6925 * @static
6926 * @param int $courseid id from {course} table
6927 * @param int $strictness
6928 * @return context_course context instance
6930 public static function instance($courseid, $strictness = MUST_EXIST) {
6931 global $DB;
6933 if ($context = context::cache_get(CONTEXT_COURSE, $courseid)) {
6934 return $context;
6937 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $courseid))) {
6938 if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
6939 if ($course->category) {
6940 $parentcontext = context_coursecat::instance($course->category);
6941 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6942 } else {
6943 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6948 if ($record) {
6949 $context = new context_course($record);
6950 context::cache_add($context);
6951 return $context;
6954 return false;
6958 * Create missing context instances at course context level
6959 * @static
6961 protected static function create_level_instances() {
6962 global $DB;
6964 $sql = "SELECT ".CONTEXT_COURSE.", c.id
6965 FROM {course} c
6966 WHERE NOT EXISTS (SELECT 'x'
6967 FROM {context} cx
6968 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6969 $contextdata = $DB->get_recordset_sql($sql);
6970 foreach ($contextdata as $context) {
6971 context::insert_context_record(CONTEXT_COURSE, $context->id, null);
6973 $contextdata->close();
6977 * Returns sql necessary for purging of stale context instances.
6979 * @static
6980 * @return string cleanup SQL
6982 protected static function get_cleanup_sql() {
6983 $sql = "
6984 SELECT c.*
6985 FROM {context} c
6986 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6987 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6990 return $sql;
6994 * Rebuild context paths and depths at course context level.
6996 * @static
6997 * @param bool $force
6999 protected static function build_paths($force) {
7000 global $DB;
7002 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
7003 if ($force) {
7004 $ctxemptyclause = $emptyclause = '';
7005 } else {
7006 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7007 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
7010 $base = '/'.SYSCONTEXTID;
7012 // Standard frontpage
7013 $sql = "UPDATE {context}
7014 SET depth = 2,
7015 path = ".$DB->sql_concat("'$base/'", 'id')."
7016 WHERE contextlevel = ".CONTEXT_COURSE."
7017 AND EXISTS (SELECT 'x'
7018 FROM {course} c
7019 WHERE c.id = {context}.instanceid AND c.category = 0)
7020 $emptyclause";
7021 $DB->execute($sql);
7023 // standard courses
7024 $sql = "INSERT INTO {context_temp} (id, path, depth)
7025 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7026 FROM {context} ctx
7027 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
7028 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
7029 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7030 $ctxemptyclause";
7031 $trans = $DB->start_delegated_transaction();
7032 $DB->delete_records('context_temp');
7033 $DB->execute($sql);
7034 context::merge_context_temp_table();
7035 $DB->delete_records('context_temp');
7036 $trans->allow_commit();
7043 * Course module context class
7045 * @package core_access
7046 * @category access
7047 * @copyright Petr Skoda {@link http://skodak.org}
7048 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7049 * @since Moodle 2.2
7051 class context_module extends context {
7053 * Please use context_module::instance($cmid) if you need the instance of context.
7054 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7056 * @param stdClass $record
7058 protected function __construct(stdClass $record) {
7059 parent::__construct($record);
7060 if ($record->contextlevel != CONTEXT_MODULE) {
7061 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
7066 * Returns human readable context level name.
7068 * @static
7069 * @return string the human readable context level name.
7071 public static function get_level_name() {
7072 return get_string('activitymodule');
7076 * Returns human readable context identifier.
7078 * @param boolean $withprefix whether to prefix the name of the context with the
7079 * module name, e.g. Forum, Glossary, etc.
7080 * @param boolean $short does not apply to module context
7081 * @return string the human readable context name.
7083 public function get_context_name($withprefix = true, $short = false) {
7084 global $DB;
7086 $name = '';
7087 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
7088 FROM {course_modules} cm
7089 JOIN {modules} md ON md.id = cm.module
7090 WHERE cm.id = ?", array($this->_instanceid))) {
7091 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
7092 if ($withprefix){
7093 $name = get_string('modulename', $cm->modname).': ';
7095 $name .= format_string($mod->name, true, array('context' => $this));
7098 return $name;
7102 * Returns the most relevant URL for this context.
7104 * @return moodle_url
7106 public function get_url() {
7107 global $DB;
7109 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
7110 FROM {course_modules} cm
7111 JOIN {modules} md ON md.id = cm.module
7112 WHERE cm.id = ?", array($this->_instanceid))) {
7113 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
7116 return new moodle_url('/');
7120 * Returns array of relevant context capability records.
7122 * @return array
7124 public function get_capabilities() {
7125 global $DB, $CFG;
7127 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7129 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
7130 $module = $DB->get_record('modules', array('id'=>$cm->module));
7132 $subcaps = array();
7133 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
7134 if (file_exists($subpluginsfile)) {
7135 $subplugins = array(); // should be redefined in the file
7136 include($subpluginsfile);
7137 if (!empty($subplugins)) {
7138 foreach (array_keys($subplugins) as $subplugintype) {
7139 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
7140 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
7146 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
7147 $extracaps = array();
7148 if (file_exists($modfile)) {
7149 include_once($modfile);
7150 $modfunction = $module->name.'_get_extra_capabilities';
7151 if (function_exists($modfunction)) {
7152 $extracaps = $modfunction();
7156 $extracaps = array_merge($subcaps, $extracaps);
7157 $extra = '';
7158 list($extra, $params) = $DB->get_in_or_equal(
7159 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
7160 if (!empty($extra)) {
7161 $extra = "OR name $extra";
7163 $sql = "SELECT *
7164 FROM {capabilities}
7165 WHERE (contextlevel = ".CONTEXT_MODULE."
7166 AND (component = :component OR component = 'moodle'))
7167 $extra";
7168 $params['component'] = "mod_$module->name";
7170 return $DB->get_records_sql($sql.' '.$sort, $params);
7174 * Is this context part of any course? If yes return course context.
7176 * @param bool $strict true means throw exception if not found, false means return false if not found
7177 * @return context_course context of the enclosing course, null if not found or exception
7179 public function get_course_context($strict = true) {
7180 return $this->get_parent_context();
7184 * Returns module context instance.
7186 * @static
7187 * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
7188 * @param int $strictness
7189 * @return context_module context instance
7191 public static function instance($cmid, $strictness = MUST_EXIST) {
7192 global $DB;
7194 if ($context = context::cache_get(CONTEXT_MODULE, $cmid)) {
7195 return $context;
7198 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE, 'instanceid' => $cmid))) {
7199 if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
7200 $parentcontext = context_course::instance($cm->course);
7201 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
7205 if ($record) {
7206 $context = new context_module($record);
7207 context::cache_add($context);
7208 return $context;
7211 return false;
7215 * Create missing context instances at module context level
7216 * @static
7218 protected static function create_level_instances() {
7219 global $DB;
7221 $sql = "SELECT ".CONTEXT_MODULE.", cm.id
7222 FROM {course_modules} cm
7223 WHERE NOT EXISTS (SELECT 'x'
7224 FROM {context} cx
7225 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
7226 $contextdata = $DB->get_recordset_sql($sql);
7227 foreach ($contextdata as $context) {
7228 context::insert_context_record(CONTEXT_MODULE, $context->id, null);
7230 $contextdata->close();
7234 * Returns sql necessary for purging of stale context instances.
7236 * @static
7237 * @return string cleanup SQL
7239 protected static function get_cleanup_sql() {
7240 $sql = "
7241 SELECT c.*
7242 FROM {context} c
7243 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
7244 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
7247 return $sql;
7251 * Rebuild context paths and depths at module context level.
7253 * @static
7254 * @param bool $force
7256 protected static function build_paths($force) {
7257 global $DB;
7259 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
7260 if ($force) {
7261 $ctxemptyclause = '';
7262 } else {
7263 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7266 $sql = "INSERT INTO {context_temp} (id, path, depth)
7267 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7268 FROM {context} ctx
7269 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
7270 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
7271 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7272 $ctxemptyclause";
7273 $trans = $DB->start_delegated_transaction();
7274 $DB->delete_records('context_temp');
7275 $DB->execute($sql);
7276 context::merge_context_temp_table();
7277 $DB->delete_records('context_temp');
7278 $trans->allow_commit();
7285 * Block context class
7287 * @package core_access
7288 * @category access
7289 * @copyright Petr Skoda {@link http://skodak.org}
7290 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7291 * @since Moodle 2.2
7293 class context_block extends context {
7295 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
7296 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7298 * @param stdClass $record
7300 protected function __construct(stdClass $record) {
7301 parent::__construct($record);
7302 if ($record->contextlevel != CONTEXT_BLOCK) {
7303 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
7308 * Returns human readable context level name.
7310 * @static
7311 * @return string the human readable context level name.
7313 public static function get_level_name() {
7314 return get_string('block');
7318 * Returns human readable context identifier.
7320 * @param boolean $withprefix whether to prefix the name of the context with Block
7321 * @param boolean $short does not apply to block context
7322 * @return string the human readable context name.
7324 public function get_context_name($withprefix = true, $short = false) {
7325 global $DB, $CFG;
7327 $name = '';
7328 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
7329 global $CFG;
7330 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7331 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7332 $blockname = "block_$blockinstance->blockname";
7333 if ($blockobject = new $blockname()) {
7334 if ($withprefix){
7335 $name = get_string('block').': ';
7337 $name .= $blockobject->title;
7341 return $name;
7345 * Returns the most relevant URL for this context.
7347 * @return moodle_url
7349 public function get_url() {
7350 $parentcontexts = $this->get_parent_context();
7351 return $parentcontexts->get_url();
7355 * Returns array of relevant context capability records.
7357 * @return array
7359 public function get_capabilities() {
7360 global $DB;
7362 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7364 $params = array();
7365 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
7367 $extra = '';
7368 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7369 if ($extracaps) {
7370 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7371 $extra = "OR name $extra";
7374 $sql = "SELECT *
7375 FROM {capabilities}
7376 WHERE (contextlevel = ".CONTEXT_BLOCK."
7377 AND component = :component)
7378 $extra";
7379 $params['component'] = 'block_' . $bi->blockname;
7381 return $DB->get_records_sql($sql.' '.$sort, $params);
7385 * Is this context part of any course? If yes return course context.
7387 * @param bool $strict true means throw exception if not found, false means return false if not found
7388 * @return context_course context of the enclosing course, null if not found or exception
7390 public function get_course_context($strict = true) {
7391 $parentcontext = $this->get_parent_context();
7392 return $parentcontext->get_course_context($strict);
7396 * Returns block context instance.
7398 * @static
7399 * @param int $blockinstanceid id from {block_instances} table.
7400 * @param int $strictness
7401 * @return context_block context instance
7403 public static function instance($blockinstanceid, $strictness = MUST_EXIST) {
7404 global $DB;
7406 if ($context = context::cache_get(CONTEXT_BLOCK, $blockinstanceid)) {
7407 return $context;
7410 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $blockinstanceid))) {
7411 if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
7412 $parentcontext = context::instance_by_id($bi->parentcontextid);
7413 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7417 if ($record) {
7418 $context = new context_block($record);
7419 context::cache_add($context);
7420 return $context;
7423 return false;
7427 * Block do not have child contexts...
7428 * @return array
7430 public function get_child_contexts() {
7431 return array();
7435 * Create missing context instances at block context level
7436 * @static
7438 protected static function create_level_instances() {
7439 global $DB;
7441 $sql = "SELECT ".CONTEXT_BLOCK.", bi.id
7442 FROM {block_instances} bi
7443 WHERE NOT EXISTS (SELECT 'x'
7444 FROM {context} cx
7445 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7446 $contextdata = $DB->get_recordset_sql($sql);
7447 foreach ($contextdata as $context) {
7448 context::insert_context_record(CONTEXT_BLOCK, $context->id, null);
7450 $contextdata->close();
7454 * Returns sql necessary for purging of stale context instances.
7456 * @static
7457 * @return string cleanup SQL
7459 protected static function get_cleanup_sql() {
7460 $sql = "
7461 SELECT c.*
7462 FROM {context} c
7463 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7464 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7467 return $sql;
7471 * Rebuild context paths and depths at block context level.
7473 * @static
7474 * @param bool $force
7476 protected static function build_paths($force) {
7477 global $DB;
7479 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7480 if ($force) {
7481 $ctxemptyclause = '';
7482 } else {
7483 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7486 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7487 $sql = "INSERT INTO {context_temp} (id, path, depth)
7488 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7489 FROM {context} ctx
7490 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7491 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7492 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7493 $ctxemptyclause";
7494 $trans = $DB->start_delegated_transaction();
7495 $DB->delete_records('context_temp');
7496 $DB->execute($sql);
7497 context::merge_context_temp_table();
7498 $DB->delete_records('context_temp');
7499 $trans->allow_commit();
7505 // ============== DEPRECATED FUNCTIONS ==========================================
7506 // Old context related functions were deprecated in 2.0, it is recommended
7507 // to use context classes in new code. Old function can be used when
7508 // creating patches that are supposed to be backported to older stable branches.
7509 // These deprecated functions will not be removed in near future,
7510 // before removing devs will be warned with a debugging message first,
7511 // then we will add error message and only after that we can remove the functions
7512 // completely.
7515 * Runs get_records select on context table and returns the result
7516 * Does get_records_select on the context table, and returns the results ordered
7517 * by contextlevel, and then the natural sort order within each level.
7518 * for the purpose of $select, you need to know that the context table has been
7519 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7521 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7522 * @param array $params any parameters required by $select.
7523 * @return array the requested context records.
7525 function get_sorted_contexts($select, $params = array()) {
7527 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7529 global $DB;
7530 if ($select) {
7531 $select = 'WHERE ' . $select;
7533 return $DB->get_records_sql("
7534 SELECT ctx.*
7535 FROM {context} ctx
7536 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7537 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7538 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7539 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7540 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7541 $select
7542 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7543 ", $params);
7547 * Given context and array of users, returns array of users whose enrolment status is suspended,
7548 * or enrolment has expired or has not started. Also removes those users from the given array
7550 * @param context $context context in which suspended users should be extracted.
7551 * @param array $users list of users.
7552 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7553 * @return array list of suspended users.
7555 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7556 global $DB;
7558 // Get active enrolled users.
7559 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7560 $activeusers = $DB->get_records_sql($sql, $params);
7562 // Move suspended users to a separate array & remove from the initial one.
7563 $susers = array();
7564 if (sizeof($activeusers)) {
7565 foreach ($users as $userid => $user) {
7566 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7567 $susers[$userid] = $user;
7568 unset($users[$userid]);
7572 return $susers;
7576 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7577 * or enrolment has expired or not started.
7579 * @param context $context context in which user enrolment is checked.
7580 * @param bool $usecache Enable or disable (default) the request cache
7581 * @return array list of suspended user id's.
7583 function get_suspended_userids(context $context, $usecache = false) {
7584 global $DB;
7586 if ($usecache) {
7587 $cache = cache::make('core', 'suspended_userids');
7588 $susers = $cache->get($context->id);
7589 if ($susers !== false) {
7590 return $susers;
7594 $coursecontext = $context->get_course_context();
7595 $susers = array();
7597 // Front page users are always enrolled, so suspended list is empty.
7598 if ($coursecontext->instanceid != SITEID) {
7599 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7600 $susers = $DB->get_fieldset_sql($sql, $params);
7601 $susers = array_combine($susers, $susers);
7604 // Cache results for the remainder of this request.
7605 if ($usecache) {
7606 $cache->set($context->id, $susers);
7609 return $susers;