Merge branch 'MDL-56954-32' of git://github.com/lameze/moodle into MOODLE_32_STABLE
[moodle.git] / lib / accesslib.php
blob64126eba08b1ab337907cb74e93134aede8a0834
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"
370 or $SCRIPT === "/$CFG->admin/cli/install.php"
371 or $SCRIPT === "/$CFG->admin/cli/install_database.php"
372 or (defined('BEHAT_UTIL') and BEHAT_UTIL)
373 or (defined('PHPUNIT_UTIL') and PHPUNIT_UTIL)) {
374 // we are in an installer - roles can not work yet
375 return true;
376 } else {
377 return false;
381 if (strpos($capability, 'moodle/legacy:') === 0) {
382 throw new coding_exception('Legacy capabilities can not be used any more!');
385 if (!is_bool($doanything)) {
386 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
389 // capability must exist
390 if (!$capinfo = get_capability_info($capability)) {
391 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
392 return false;
395 if (!isset($USER->id)) {
396 // should never happen
397 $USER->id = 0;
398 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER);
401 // make sure there is a real user specified
402 if ($user === null) {
403 $userid = $USER->id;
404 } else {
405 $userid = is_object($user) ? $user->id : $user;
408 // make sure forcelogin cuts off not-logged-in users if enabled
409 if (!empty($CFG->forcelogin) and $userid == 0) {
410 return false;
413 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
414 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
415 if (isguestuser($userid) or $userid == 0) {
416 return false;
420 // somehow make sure the user is not deleted and actually exists
421 if ($userid != 0) {
422 if ($userid == $USER->id and isset($USER->deleted)) {
423 // this prevents one query per page, it is a bit of cheating,
424 // but hopefully session is terminated properly once user is deleted
425 if ($USER->deleted) {
426 return false;
428 } else {
429 if (!context_user::instance($userid, IGNORE_MISSING)) {
430 // no user context == invalid userid
431 return false;
436 // context path/depth must be valid
437 if (empty($context->path) or $context->depth == 0) {
438 // this should not happen often, each upgrade tries to rebuild the context paths
439 debugging('Context id '.$context->id.' does not have valid path, please use context_helper::build_all_paths()');
440 if (is_siteadmin($userid)) {
441 return true;
442 } else {
443 return false;
447 // Find out if user is admin - it is not possible to override the doanything in any way
448 // and it is not possible to switch to admin role either.
449 if ($doanything) {
450 if (is_siteadmin($userid)) {
451 if ($userid != $USER->id) {
452 return true;
454 // make sure switchrole is not used in this context
455 if (empty($USER->access['rsw'])) {
456 return true;
458 $parts = explode('/', trim($context->path, '/'));
459 $path = '';
460 $switched = false;
461 foreach ($parts as $part) {
462 $path .= '/' . $part;
463 if (!empty($USER->access['rsw'][$path])) {
464 $switched = true;
465 break;
468 if (!$switched) {
469 return true;
471 //ok, admin switched role in this context, let's use normal access control rules
475 // Careful check for staleness...
476 $context->reload_if_dirty();
478 if ($USER->id == $userid) {
479 if (!isset($USER->access)) {
480 load_all_capabilities();
482 $access =& $USER->access;
484 } else {
485 // make sure user accessdata is really loaded
486 get_user_accessdata($userid, true);
487 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
491 // Load accessdata for below-the-course context if necessary,
492 // all contexts at and above all courses are already loaded
493 if ($context->contextlevel != CONTEXT_COURSE and $coursecontext = $context->get_course_context(false)) {
494 load_course_context($userid, $coursecontext, $access);
497 return has_capability_in_accessdata($capability, $context, $access);
501 * Check if the user has any one of several capabilities from a list.
503 * This is just a utility method that calls has_capability in a loop. Try to put
504 * the capabilities that most users are likely to have first in the list for best
505 * performance.
507 * @category access
508 * @see has_capability()
510 * @param array $capabilities an array of capability names.
511 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
512 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
513 * @param boolean $doanything If false, ignore effect of admin role assignment
514 * @return boolean true if the user has any of these capabilities. Otherwise false.
516 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
517 foreach ($capabilities as $capability) {
518 if (has_capability($capability, $context, $user, $doanything)) {
519 return true;
522 return false;
526 * Check if the user has all the capabilities in a list.
528 * This is just a utility method that calls has_capability in a loop. Try to put
529 * the capabilities that fewest users are likely to have first in the list for best
530 * performance.
532 * @category access
533 * @see has_capability()
535 * @param array $capabilities an array of capability names.
536 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
537 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
538 * @param boolean $doanything If false, ignore effect of admin role assignment
539 * @return boolean true if the user has all of these capabilities. Otherwise false.
541 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
542 foreach ($capabilities as $capability) {
543 if (!has_capability($capability, $context, $user, $doanything)) {
544 return false;
547 return true;
551 * Is course creator going to have capability in a new course?
553 * This is intended to be used in enrolment plugins before or during course creation,
554 * do not use after the course is fully created.
556 * @category access
558 * @param string $capability the name of the capability to check.
559 * @param context $context course or category context where is course going to be created
560 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
561 * @return boolean true if the user will have this capability.
563 * @throws coding_exception if different type of context submitted
565 function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) {
566 global $CFG;
568 if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) {
569 throw new coding_exception('Only course or course category context expected');
572 if (has_capability($capability, $context, $user)) {
573 // User already has the capability, it could be only removed if CAP_PROHIBIT
574 // was involved here, but we ignore that.
575 return true;
578 if (!has_capability('moodle/course:create', $context, $user)) {
579 return false;
582 if (!enrol_is_enabled('manual')) {
583 return false;
586 if (empty($CFG->creatornewroleid)) {
587 return false;
590 if ($context->contextlevel == CONTEXT_COURSE) {
591 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
592 return false;
594 } else {
595 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
596 return false;
600 // Most likely they will be enrolled after the course creation is finished,
601 // does the new role have the required capability?
602 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
603 return isset($neededroles[$CFG->creatornewroleid]);
607 * Check if the user is an admin at the site level.
609 * Please note that use of proper capabilities is always encouraged,
610 * this function is supposed to be used from core or for temporary hacks.
612 * @category access
614 * @param int|stdClass $user_or_id user id or user object
615 * @return bool true if user is one of the administrators, false otherwise
617 function is_siteadmin($user_or_id = null) {
618 global $CFG, $USER;
620 if ($user_or_id === null) {
621 $user_or_id = $USER;
624 if (empty($user_or_id)) {
625 return false;
627 if (!empty($user_or_id->id)) {
628 $userid = $user_or_id->id;
629 } else {
630 $userid = $user_or_id;
633 // Because this script is called many times (150+ for course page) with
634 // the same parameters, it is worth doing minor optimisations. This static
635 // cache stores the value for a single userid, saving about 2ms from course
636 // page load time without using significant memory. As the static cache
637 // also includes the value it depends on, this cannot break unit tests.
638 static $knownid, $knownresult, $knownsiteadmins;
639 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
640 return $knownresult;
642 $knownid = $userid;
643 $knownsiteadmins = $CFG->siteadmins;
645 $siteadmins = explode(',', $CFG->siteadmins);
646 $knownresult = in_array($userid, $siteadmins);
647 return $knownresult;
651 * Returns true if user has at least one role assign
652 * of 'coursecontact' role (is potentially listed in some course descriptions).
654 * @param int $userid
655 * @return bool
657 function has_coursecontact_role($userid) {
658 global $DB, $CFG;
660 if (empty($CFG->coursecontact)) {
661 return false;
663 $sql = "SELECT 1
664 FROM {role_assignments}
665 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
666 return $DB->record_exists_sql($sql, array('userid'=>$userid));
670 * Does the user have a capability to do something?
672 * Walk the accessdata array and return true/false.
673 * Deals with prohibits, role switching, aggregating
674 * capabilities, etc.
676 * The main feature of here is being FAST and with no
677 * side effects.
679 * Notes:
681 * Switch Role merges with default role
682 * ------------------------------------
683 * If you are a teacher in course X, you have at least
684 * teacher-in-X + defaultloggedinuser-sitewide. So in the
685 * course you'll have techer+defaultloggedinuser.
686 * We try to mimic that in switchrole.
688 * Permission evaluation
689 * ---------------------
690 * Originally there was an extremely complicated way
691 * to determine the user access that dealt with
692 * "locality" or role assignments and role overrides.
693 * Now we simply evaluate access for each role separately
694 * and then verify if user has at least one role with allow
695 * and at the same time no role with prohibit.
697 * @access private
698 * @param string $capability
699 * @param context $context
700 * @param array $accessdata
701 * @return bool
703 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
704 global $CFG;
706 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
707 $path = $context->path;
708 $paths = array($path);
709 while($path = rtrim($path, '0123456789')) {
710 $path = rtrim($path, '/');
711 if ($path === '') {
712 break;
714 $paths[] = $path;
717 $roles = array();
718 $switchedrole = false;
720 // Find out if role switched
721 if (!empty($accessdata['rsw'])) {
722 // From the bottom up...
723 foreach ($paths as $path) {
724 if (isset($accessdata['rsw'][$path])) {
725 // Found a switchrole assignment - check for that role _plus_ the default user role
726 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
727 $switchedrole = true;
728 break;
733 if (!$switchedrole) {
734 // get all users roles in this context and above
735 foreach ($paths as $path) {
736 if (isset($accessdata['ra'][$path])) {
737 foreach ($accessdata['ra'][$path] as $roleid) {
738 $roles[$roleid] = null;
744 // Now find out what access is given to each role, going bottom-->up direction
745 $allowed = false;
746 foreach ($roles as $roleid => $ignored) {
747 foreach ($paths as $path) {
748 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
749 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
750 if ($perm === CAP_PROHIBIT) {
751 // any CAP_PROHIBIT found means no permission for the user
752 return false;
754 if (is_null($roles[$roleid])) {
755 $roles[$roleid] = $perm;
759 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
760 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
763 return $allowed;
767 * A convenience function that tests has_capability, and displays an error if
768 * the user does not have that capability.
770 * NOTE before Moodle 2.0, this function attempted to make an appropriate
771 * require_login call before checking the capability. This is no longer the case.
772 * You must call require_login (or one of its variants) if you want to check the
773 * user is logged in, before you call this function.
775 * @see has_capability()
777 * @param string $capability the name of the capability to check. For example mod/forum:view
778 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
779 * @param int $userid A user id. By default (null) checks the permissions of the current user.
780 * @param bool $doanything If false, ignore effect of admin role assignment
781 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
782 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
783 * @return void terminates with an error if the user does not have the given capability.
785 function require_capability($capability, context $context, $userid = null, $doanything = true,
786 $errormessage = 'nopermissions', $stringfile = '') {
787 if (!has_capability($capability, $context, $userid, $doanything)) {
788 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
793 * Return a nested array showing role assignments
794 * all relevant role capabilities for the user at
795 * site/course_category/course levels
797 * We do _not_ delve deeper than courses because the number of
798 * overrides at the module/block levels can be HUGE.
800 * [ra] => [/path][roleid]=roleid
801 * [rdef] => [/path:roleid][capability]=permission
803 * @access private
804 * @param int $userid - the id of the user
805 * @return array access info array
807 function get_user_access_sitewide($userid) {
808 global $CFG, $DB, $ACCESSLIB_PRIVATE;
810 /* Get in a few cheap DB queries...
811 * - role assignments
812 * - relevant role caps
813 * - above and within this user's RAs
814 * - below this user's RAs - limited to course level
817 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
818 $raparents = array();
819 $accessdata = get_empty_accessdata();
821 // start with the default role
822 if (!empty($CFG->defaultuserroleid)) {
823 $syscontext = context_system::instance();
824 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
825 $raparents[$CFG->defaultuserroleid][$syscontext->id] = $syscontext->id;
828 // load the "default frontpage role"
829 if (!empty($CFG->defaultfrontpageroleid)) {
830 $frontpagecontext = context_course::instance(get_site()->id);
831 if ($frontpagecontext->path) {
832 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
833 $raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->id] = $frontpagecontext->id;
837 // preload every assigned role at and above course context
838 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
839 FROM {role_assignments} ra
840 JOIN {context} ctx
841 ON ctx.id = ra.contextid
842 LEFT JOIN {block_instances} bi
843 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
844 LEFT JOIN {context} bpctx
845 ON (bpctx.id = bi.parentcontextid)
846 WHERE ra.userid = :userid
847 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")";
848 $params = array('userid'=>$userid);
849 $rs = $DB->get_recordset_sql($sql, $params);
850 foreach ($rs as $ra) {
851 // RAs leafs are arrays to support multi-role assignments...
852 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
853 $raparents[$ra->roleid][$ra->contextid] = $ra->contextid;
855 $rs->close();
857 if (empty($raparents)) {
858 return $accessdata;
861 // now get overrides of interesting roles in all interesting child contexts
862 // hopefully we will not run out of SQL limits here,
863 // users would have to have very many roles at/above course context...
864 $sqls = array();
865 $params = array();
867 static $cp = 0;
868 foreach ($raparents as $roleid=>$ras) {
869 $cp++;
870 list($sqlcids, $cids) = $DB->get_in_or_equal($ras, SQL_PARAMS_NAMED, 'c'.$cp.'_');
871 $params = array_merge($params, $cids);
872 $params['r'.$cp] = $roleid;
873 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
874 FROM {role_capabilities} rc
875 JOIN {context} ctx
876 ON (ctx.id = rc.contextid)
877 JOIN {context} pctx
878 ON (pctx.id $sqlcids
879 AND (ctx.id = pctx.id
880 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
881 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
882 LEFT JOIN {block_instances} bi
883 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
884 LEFT JOIN {context} bpctx
885 ON (bpctx.id = bi.parentcontextid)
886 WHERE rc.roleid = :r{$cp}
887 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")
891 // fixed capability order is necessary for rdef dedupe
892 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
894 foreach ($rs as $rd) {
895 $k = $rd->path.':'.$rd->roleid;
896 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
898 $rs->close();
900 // share the role definitions
901 foreach ($accessdata['rdef'] as $k=>$unused) {
902 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
903 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
905 $accessdata['rdef_count']++;
906 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
909 return $accessdata;
913 * Add to the access ctrl array the data needed by a user for a given course.
915 * This function injects all course related access info into the accessdata array.
917 * @access private
918 * @param int $userid the id of the user
919 * @param context_course $coursecontext course context
920 * @param array $accessdata accessdata array (modified)
921 * @return void modifies $accessdata parameter
923 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
924 global $DB, $CFG, $ACCESSLIB_PRIVATE;
926 if (empty($coursecontext->path)) {
927 // weird, this should not happen
928 return;
931 if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
932 // already loaded, great!
933 return;
936 $roles = array();
938 if (empty($userid)) {
939 if (!empty($CFG->notloggedinroleid)) {
940 $roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
943 } else if (isguestuser($userid)) {
944 if ($guestrole = get_guest_role()) {
945 $roles[$guestrole->id] = $guestrole->id;
948 } else {
949 // Interesting role assignments at, above and below the course context
950 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
951 $params['userid'] = $userid;
952 $params['children'] = $coursecontext->path."/%";
953 $sql = "SELECT ra.*, ctx.path
954 FROM {role_assignments} ra
955 JOIN {context} ctx ON ra.contextid = ctx.id
956 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
957 $rs = $DB->get_recordset_sql($sql, $params);
959 // add missing role definitions
960 foreach ($rs as $ra) {
961 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
962 $roles[$ra->roleid] = $ra->roleid;
964 $rs->close();
966 // add the "default frontpage role" when on the frontpage
967 if (!empty($CFG->defaultfrontpageroleid)) {
968 $frontpagecontext = context_course::instance(get_site()->id);
969 if ($frontpagecontext->id == $coursecontext->id) {
970 $roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
974 // do not forget the default role
975 if (!empty($CFG->defaultuserroleid)) {
976 $roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
980 if (!$roles) {
981 // weird, default roles must be missing...
982 $accessdata['loaded'][$coursecontext->instanceid] = 1;
983 return;
986 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
987 $params = array('pathprefix' => $coursecontext->path . '/%');
988 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
989 $params = array_merge($params, $rparams);
990 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
991 $params = array_merge($params, $rparams);
993 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
994 FROM {context} ctx
995 JOIN {role_capabilities} rc ON rc.contextid = ctx.id
996 WHERE rc.roleid $roleids
997 AND (ctx.id $parentsaself OR ctx.path LIKE :pathprefix)
998 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
999 $rs = $DB->get_recordset_sql($sql, $params);
1001 $newrdefs = array();
1002 foreach ($rs as $rd) {
1003 $k = $rd->path.':'.$rd->roleid;
1004 if (isset($accessdata['rdef'][$k])) {
1005 continue;
1007 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
1009 $rs->close();
1011 // share new role definitions
1012 foreach ($newrdefs as $k=>$unused) {
1013 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
1014 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
1016 $accessdata['rdef_count']++;
1017 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1020 $accessdata['loaded'][$coursecontext->instanceid] = 1;
1022 // we want to deduplicate the USER->access from time to time, this looks like a good place,
1023 // because we have to do it before the end of session
1024 dedupe_user_access();
1028 * Add to the access ctrl array the data needed by a role for a given context.
1030 * The data is added in the rdef key.
1031 * This role-centric function is useful for role_switching
1032 * and temporary course roles.
1034 * @access private
1035 * @param int $roleid the id of the user
1036 * @param context $context needs path!
1037 * @param array $accessdata accessdata array (is modified)
1038 * @return array
1040 function load_role_access_by_context($roleid, context $context, &$accessdata) {
1041 global $DB, $ACCESSLIB_PRIVATE;
1043 /* Get the relevant rolecaps into rdef
1044 * - relevant role caps
1045 * - at ctx and above
1046 * - below this ctx
1049 if (empty($context->path)) {
1050 // weird, this should not happen
1051 return;
1054 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
1055 $params['roleid'] = $roleid;
1056 $params['childpath'] = $context->path.'/%';
1058 $sql = "SELECT ctx.path, rc.capability, rc.permission
1059 FROM {role_capabilities} rc
1060 JOIN {context} ctx ON (rc.contextid = ctx.id)
1061 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
1062 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
1063 $rs = $DB->get_recordset_sql($sql, $params);
1065 $newrdefs = array();
1066 foreach ($rs as $rd) {
1067 $k = $rd->path.':'.$roleid;
1068 if (isset($accessdata['rdef'][$k])) {
1069 continue;
1071 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
1073 $rs->close();
1075 // share new role definitions
1076 foreach ($newrdefs as $k=>$unused) {
1077 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
1078 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
1080 $accessdata['rdef_count']++;
1081 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1086 * Returns empty accessdata structure.
1088 * @access private
1089 * @return array empt accessdata
1091 function get_empty_accessdata() {
1092 $accessdata = array(); // named list
1093 $accessdata['ra'] = array();
1094 $accessdata['rdef'] = array();
1095 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
1096 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
1097 $accessdata['loaded'] = array(); // loaded course contexts
1098 $accessdata['time'] = time();
1099 $accessdata['rsw'] = array();
1101 return $accessdata;
1105 * Get accessdata for a given user.
1107 * @access private
1108 * @param int $userid
1109 * @param bool $preloadonly true means do not return access array
1110 * @return array accessdata
1112 function get_user_accessdata($userid, $preloadonly=false) {
1113 global $CFG, $ACCESSLIB_PRIVATE, $USER;
1115 if (!empty($USER->access['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1116 // share rdef from USER session with rolepermissions cache in order to conserve memory
1117 foreach ($USER->access['rdef'] as $k=>$v) {
1118 $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->access['rdef'][$k];
1120 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->access;
1123 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
1124 if (empty($userid)) {
1125 if (!empty($CFG->notloggedinroleid)) {
1126 $accessdata = get_role_access($CFG->notloggedinroleid);
1127 } else {
1128 // weird
1129 return get_empty_accessdata();
1132 } else if (isguestuser($userid)) {
1133 if ($guestrole = get_guest_role()) {
1134 $accessdata = get_role_access($guestrole->id);
1135 } else {
1136 //weird
1137 return get_empty_accessdata();
1140 } else {
1141 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1144 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1147 if ($preloadonly) {
1148 return;
1149 } else {
1150 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1155 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1156 * this function looks for contexts with the same overrides and shares them.
1158 * @access private
1159 * @return void
1161 function dedupe_user_access() {
1162 global $USER;
1164 if (CLI_SCRIPT) {
1165 // no session in CLI --> no compression necessary
1166 return;
1169 if (empty($USER->access['rdef_count'])) {
1170 // weird, this should not happen
1171 return;
1174 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1175 if ($USER->access['rdef_count'] - $USER->access['rdef_lcc'] > 10) {
1176 // do not compress after each change, wait till there is more stuff to be done
1177 return;
1180 $hashmap = array();
1181 foreach ($USER->access['rdef'] as $k=>$def) {
1182 $hash = sha1(serialize($def));
1183 if (isset($hashmap[$hash])) {
1184 $USER->access['rdef'][$k] =& $hashmap[$hash];
1185 } else {
1186 $hashmap[$hash] =& $USER->access['rdef'][$k];
1190 $USER->access['rdef_lcc'] = $USER->access['rdef_count'];
1194 * A convenience function to completely load all the capabilities
1195 * for the current user. It is called from has_capability() and functions change permissions.
1197 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1198 * @see check_enrolment_plugins()
1200 * @access private
1201 * @return void
1203 function load_all_capabilities() {
1204 global $USER;
1206 // roles not installed yet - we are in the middle of installation
1207 if (during_initial_install()) {
1208 return;
1211 if (!isset($USER->id)) {
1212 // this should not happen
1213 $USER->id = 0;
1216 unset($USER->access);
1217 $USER->access = get_user_accessdata($USER->id);
1219 // deduplicate the overrides to minimize session size
1220 dedupe_user_access();
1222 // Clear to force a refresh
1223 unset($USER->mycourses);
1225 // init/reset internal enrol caches - active course enrolments and temp access
1226 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1230 * A convenience function to completely reload all the capabilities
1231 * for the current user when roles have been updated in a relevant
1232 * context -- but PRESERVING switchroles and loginas.
1233 * This function resets all accesslib and context caches.
1235 * That is - completely transparent to the user.
1237 * Note: reloads $USER->access completely.
1239 * @access private
1240 * @return void
1242 function reload_all_capabilities() {
1243 global $USER, $DB, $ACCESSLIB_PRIVATE;
1245 // copy switchroles
1246 $sw = array();
1247 if (!empty($USER->access['rsw'])) {
1248 $sw = $USER->access['rsw'];
1251 accesslib_clear_all_caches(true);
1252 unset($USER->access);
1253 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
1255 load_all_capabilities();
1257 foreach ($sw as $path => $roleid) {
1258 if ($record = $DB->get_record('context', array('path'=>$path))) {
1259 $context = context::instance_by_id($record->id);
1260 role_switch($roleid, $context);
1266 * Adds a temp role to current USER->access array.
1268 * Useful for the "temporary guest" access we grant to logged-in users.
1269 * This is useful for enrol plugins only.
1271 * @since Moodle 2.2
1272 * @param context_course $coursecontext
1273 * @param int $roleid
1274 * @return void
1276 function load_temp_course_role(context_course $coursecontext, $roleid) {
1277 global $USER, $SITE;
1279 if (empty($roleid)) {
1280 debugging('invalid role specified in load_temp_course_role()');
1281 return;
1284 if ($coursecontext->instanceid == $SITE->id) {
1285 debugging('Can not use temp roles on the frontpage');
1286 return;
1289 if (!isset($USER->access)) {
1290 load_all_capabilities();
1293 $coursecontext->reload_if_dirty();
1295 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1296 return;
1299 // load course stuff first
1300 load_course_context($USER->id, $coursecontext, $USER->access);
1302 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1304 load_role_access_by_context($roleid, $coursecontext, $USER->access);
1308 * Removes any extra guest roles from current USER->access array.
1309 * This is useful for enrol plugins only.
1311 * @since Moodle 2.2
1312 * @param context_course $coursecontext
1313 * @return void
1315 function remove_temp_course_roles(context_course $coursecontext) {
1316 global $DB, $USER, $SITE;
1318 if ($coursecontext->instanceid == $SITE->id) {
1319 debugging('Can not use temp roles on the frontpage');
1320 return;
1323 if (empty($USER->access['ra'][$coursecontext->path])) {
1324 //no roles here, weird
1325 return;
1328 $sql = "SELECT DISTINCT ra.roleid AS id
1329 FROM {role_assignments} ra
1330 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1331 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1333 $USER->access['ra'][$coursecontext->path] = array();
1334 foreach($ras as $r) {
1335 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1340 * Returns array of all role archetypes.
1342 * @return array
1344 function get_role_archetypes() {
1345 return array(
1346 'manager' => 'manager',
1347 'coursecreator' => 'coursecreator',
1348 'editingteacher' => 'editingteacher',
1349 'teacher' => 'teacher',
1350 'student' => 'student',
1351 'guest' => 'guest',
1352 'user' => 'user',
1353 'frontpage' => 'frontpage'
1358 * Assign the defaults found in this capability definition to roles that have
1359 * the corresponding legacy capabilities assigned to them.
1361 * @param string $capability
1362 * @param array $legacyperms an array in the format (example):
1363 * 'guest' => CAP_PREVENT,
1364 * 'student' => CAP_ALLOW,
1365 * 'teacher' => CAP_ALLOW,
1366 * 'editingteacher' => CAP_ALLOW,
1367 * 'coursecreator' => CAP_ALLOW,
1368 * 'manager' => CAP_ALLOW
1369 * @return boolean success or failure.
1371 function assign_legacy_capabilities($capability, $legacyperms) {
1373 $archetypes = get_role_archetypes();
1375 foreach ($legacyperms as $type => $perm) {
1377 $systemcontext = context_system::instance();
1378 if ($type === 'admin') {
1379 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1380 $type = 'manager';
1383 if (!array_key_exists($type, $archetypes)) {
1384 print_error('invalidlegacy', '', '', $type);
1387 if ($roles = get_archetype_roles($type)) {
1388 foreach ($roles as $role) {
1389 // Assign a site level capability.
1390 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1391 return false;
1396 return true;
1400 * Verify capability risks.
1402 * @param stdClass $capability a capability - a row from the capabilities table.
1403 * @return boolean whether this capability is safe - that is, whether people with the
1404 * safeoverrides capability should be allowed to change it.
1406 function is_safe_capability($capability) {
1407 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1411 * Get the local override (if any) for a given capability in a role in a context
1413 * @param int $roleid
1414 * @param int $contextid
1415 * @param string $capability
1416 * @return stdClass local capability override
1418 function get_local_override($roleid, $contextid, $capability) {
1419 global $DB;
1420 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1424 * Returns context instance plus related course and cm instances
1426 * @param int $contextid
1427 * @return array of ($context, $course, $cm)
1429 function get_context_info_array($contextid) {
1430 global $DB;
1432 $context = context::instance_by_id($contextid, MUST_EXIST);
1433 $course = null;
1434 $cm = null;
1436 if ($context->contextlevel == CONTEXT_COURSE) {
1437 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1439 } else if ($context->contextlevel == CONTEXT_MODULE) {
1440 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1441 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1443 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1444 $parent = $context->get_parent_context();
1446 if ($parent->contextlevel == CONTEXT_COURSE) {
1447 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1448 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1449 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1450 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1454 return array($context, $course, $cm);
1458 * Function that creates a role
1460 * @param string $name role name
1461 * @param string $shortname role short name
1462 * @param string $description role description
1463 * @param string $archetype
1464 * @return int id or dml_exception
1466 function create_role($name, $shortname, $description, $archetype = '') {
1467 global $DB;
1469 if (strpos($archetype, 'moodle/legacy:') !== false) {
1470 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1473 // verify role archetype actually exists
1474 $archetypes = get_role_archetypes();
1475 if (empty($archetypes[$archetype])) {
1476 $archetype = '';
1479 // Insert the role record.
1480 $role = new stdClass();
1481 $role->name = $name;
1482 $role->shortname = $shortname;
1483 $role->description = $description;
1484 $role->archetype = $archetype;
1486 //find free sortorder number
1487 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1488 if (empty($role->sortorder)) {
1489 $role->sortorder = 1;
1491 $id = $DB->insert_record('role', $role);
1493 return $id;
1497 * Function that deletes a role and cleanups up after it
1499 * @param int $roleid id of role to delete
1500 * @return bool always true
1502 function delete_role($roleid) {
1503 global $DB;
1505 // first unssign all users
1506 role_unassign_all(array('roleid'=>$roleid));
1508 // cleanup all references to this role, ignore errors
1509 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1510 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1511 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1512 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1513 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1514 $DB->delete_records('role_names', array('roleid'=>$roleid));
1515 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1517 // Get role record before it's deleted.
1518 $role = $DB->get_record('role', array('id'=>$roleid));
1520 // Finally delete the role itself.
1521 $DB->delete_records('role', array('id'=>$roleid));
1523 // Trigger event.
1524 $event = \core\event\role_deleted::create(
1525 array(
1526 'context' => context_system::instance(),
1527 'objectid' => $roleid,
1528 'other' =>
1529 array(
1530 'shortname' => $role->shortname,
1531 'description' => $role->description,
1532 'archetype' => $role->archetype
1536 $event->add_record_snapshot('role', $role);
1537 $event->trigger();
1539 return true;
1543 * Function to write context specific overrides, or default capabilities.
1545 * NOTE: use $context->mark_dirty() after this
1547 * @param string $capability string name
1548 * @param int $permission CAP_ constants
1549 * @param int $roleid role id
1550 * @param int|context $contextid context id
1551 * @param bool $overwrite
1552 * @return bool always true or exception
1554 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1555 global $USER, $DB;
1557 if ($contextid instanceof context) {
1558 $context = $contextid;
1559 } else {
1560 $context = context::instance_by_id($contextid);
1563 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1564 unassign_capability($capability, $roleid, $context->id);
1565 return true;
1568 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1570 if ($existing and !$overwrite) { // We want to keep whatever is there already
1571 return true;
1574 $cap = new stdClass();
1575 $cap->contextid = $context->id;
1576 $cap->roleid = $roleid;
1577 $cap->capability = $capability;
1578 $cap->permission = $permission;
1579 $cap->timemodified = time();
1580 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1582 if ($existing) {
1583 $cap->id = $existing->id;
1584 $DB->update_record('role_capabilities', $cap);
1585 } else {
1586 if ($DB->record_exists('context', array('id'=>$context->id))) {
1587 $DB->insert_record('role_capabilities', $cap);
1590 return true;
1594 * Unassign a capability from a role.
1596 * NOTE: use $context->mark_dirty() after this
1598 * @param string $capability the name of the capability
1599 * @param int $roleid the role id
1600 * @param int|context $contextid null means all contexts
1601 * @return boolean true or exception
1603 function unassign_capability($capability, $roleid, $contextid = null) {
1604 global $DB;
1606 if (!empty($contextid)) {
1607 if ($contextid instanceof context) {
1608 $context = $contextid;
1609 } else {
1610 $context = context::instance_by_id($contextid);
1612 // delete from context rel, if this is the last override in this context
1613 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1614 } else {
1615 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1617 return true;
1621 * Get the roles that have a given capability assigned to it
1623 * This function does not resolve the actual permission of the capability.
1624 * It just checks for permissions and overrides.
1625 * Use get_roles_with_cap_in_context() if resolution is required.
1627 * @param string $capability capability name (string)
1628 * @param string $permission optional, the permission defined for this capability
1629 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1630 * @param stdClass $context null means any
1631 * @return array of role records
1633 function get_roles_with_capability($capability, $permission = null, $context = null) {
1634 global $DB;
1636 if ($context) {
1637 $contexts = $context->get_parent_context_ids(true);
1638 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1639 $contextsql = "AND rc.contextid $insql";
1640 } else {
1641 $params = array();
1642 $contextsql = '';
1645 if ($permission) {
1646 $permissionsql = " AND rc.permission = :permission";
1647 $params['permission'] = $permission;
1648 } else {
1649 $permissionsql = '';
1652 $sql = "SELECT r.*
1653 FROM {role} r
1654 WHERE r.id IN (SELECT rc.roleid
1655 FROM {role_capabilities} rc
1656 WHERE rc.capability = :capname
1657 $contextsql
1658 $permissionsql)";
1659 $params['capname'] = $capability;
1662 return $DB->get_records_sql($sql, $params);
1666 * This function makes a role-assignment (a role for a user in a particular context)
1668 * @param int $roleid the role of the id
1669 * @param int $userid userid
1670 * @param int|context $contextid id of the context
1671 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1672 * @param int $itemid id of enrolment/auth plugin
1673 * @param string $timemodified defaults to current time
1674 * @return int new/existing id of the assignment
1676 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1677 global $USER, $DB, $CFG;
1679 // first of all detect if somebody is using old style parameters
1680 if ($contextid === 0 or is_numeric($component)) {
1681 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1684 // now validate all parameters
1685 if (empty($roleid)) {
1686 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1689 if (empty($userid)) {
1690 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1693 if ($itemid) {
1694 if (strpos($component, '_') === false) {
1695 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1697 } else {
1698 $itemid = 0;
1699 if ($component !== '' and strpos($component, '_') === false) {
1700 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1704 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1705 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1708 if ($contextid instanceof context) {
1709 $context = $contextid;
1710 } else {
1711 $context = context::instance_by_id($contextid, MUST_EXIST);
1714 if (!$timemodified) {
1715 $timemodified = time();
1718 // Check for existing entry
1719 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1721 if ($ras) {
1722 // role already assigned - this should not happen
1723 if (count($ras) > 1) {
1724 // very weird - remove all duplicates!
1725 $ra = array_shift($ras);
1726 foreach ($ras as $r) {
1727 $DB->delete_records('role_assignments', array('id'=>$r->id));
1729 } else {
1730 $ra = reset($ras);
1733 // actually there is no need to update, reset anything or trigger any event, so just return
1734 return $ra->id;
1737 // Create a new entry
1738 $ra = new stdClass();
1739 $ra->roleid = $roleid;
1740 $ra->contextid = $context->id;
1741 $ra->userid = $userid;
1742 $ra->component = $component;
1743 $ra->itemid = $itemid;
1744 $ra->timemodified = $timemodified;
1745 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1746 $ra->sortorder = 0;
1748 $ra->id = $DB->insert_record('role_assignments', $ra);
1750 // mark context as dirty - again expensive, but needed
1751 $context->mark_dirty();
1753 if (!empty($USER->id) && $USER->id == $userid) {
1754 // If the user is the current user, then do full reload of capabilities too.
1755 reload_all_capabilities();
1758 require_once($CFG->libdir . '/coursecatlib.php');
1759 coursecat::role_assignment_changed($roleid, $context);
1761 $event = \core\event\role_assigned::create(array(
1762 'context' => $context,
1763 'objectid' => $ra->roleid,
1764 'relateduserid' => $ra->userid,
1765 'other' => array(
1766 'id' => $ra->id,
1767 'component' => $ra->component,
1768 'itemid' => $ra->itemid
1771 $event->add_record_snapshot('role_assignments', $ra);
1772 $event->trigger();
1774 return $ra->id;
1778 * Removes one role assignment
1780 * @param int $roleid
1781 * @param int $userid
1782 * @param int $contextid
1783 * @param string $component
1784 * @param int $itemid
1785 * @return void
1787 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1788 // first make sure the params make sense
1789 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1790 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1793 if ($itemid) {
1794 if (strpos($component, '_') === false) {
1795 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1797 } else {
1798 $itemid = 0;
1799 if ($component !== '' and strpos($component, '_') === false) {
1800 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1804 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1808 * Removes multiple role assignments, parameters may contain:
1809 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1811 * @param array $params role assignment parameters
1812 * @param bool $subcontexts unassign in subcontexts too
1813 * @param bool $includemanual include manual role assignments too
1814 * @return void
1816 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1817 global $USER, $CFG, $DB;
1818 require_once($CFG->libdir . '/coursecatlib.php');
1820 if (!$params) {
1821 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1824 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1825 foreach ($params as $key=>$value) {
1826 if (!in_array($key, $allowed)) {
1827 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1831 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1832 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1835 if ($includemanual) {
1836 if (!isset($params['component']) or $params['component'] === '') {
1837 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1841 if ($subcontexts) {
1842 if (empty($params['contextid'])) {
1843 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1847 $ras = $DB->get_records('role_assignments', $params);
1848 foreach($ras as $ra) {
1849 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1850 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1851 // this is a bit expensive but necessary
1852 $context->mark_dirty();
1853 // If the user is the current user, then do full reload of capabilities too.
1854 if (!empty($USER->id) && $USER->id == $ra->userid) {
1855 reload_all_capabilities();
1857 $event = \core\event\role_unassigned::create(array(
1858 'context' => $context,
1859 'objectid' => $ra->roleid,
1860 'relateduserid' => $ra->userid,
1861 'other' => array(
1862 'id' => $ra->id,
1863 'component' => $ra->component,
1864 'itemid' => $ra->itemid
1867 $event->add_record_snapshot('role_assignments', $ra);
1868 $event->trigger();
1869 coursecat::role_assignment_changed($ra->roleid, $context);
1872 unset($ras);
1874 // process subcontexts
1875 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1876 if ($params['contextid'] instanceof context) {
1877 $context = $params['contextid'];
1878 } else {
1879 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1882 if ($context) {
1883 $contexts = $context->get_child_contexts();
1884 $mparams = $params;
1885 foreach($contexts as $context) {
1886 $mparams['contextid'] = $context->id;
1887 $ras = $DB->get_records('role_assignments', $mparams);
1888 foreach($ras as $ra) {
1889 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1890 // this is a bit expensive but necessary
1891 $context->mark_dirty();
1892 // If the user is the current user, then do full reload of capabilities too.
1893 if (!empty($USER->id) && $USER->id == $ra->userid) {
1894 reload_all_capabilities();
1896 $event = \core\event\role_unassigned::create(
1897 array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1898 'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1899 $event->add_record_snapshot('role_assignments', $ra);
1900 $event->trigger();
1901 coursecat::role_assignment_changed($ra->roleid, $context);
1907 // do this once more for all manual role assignments
1908 if ($includemanual) {
1909 $params['component'] = '';
1910 role_unassign_all($params, $subcontexts, false);
1915 * Determines if a user is currently logged in
1917 * @category access
1919 * @return bool
1921 function isloggedin() {
1922 global $USER;
1924 return (!empty($USER->id));
1928 * Determines if a user is logged in as real guest user with username 'guest'.
1930 * @category access
1932 * @param int|object $user mixed user object or id, $USER if not specified
1933 * @return bool true if user is the real guest user, false if not logged in or other user
1935 function isguestuser($user = null) {
1936 global $USER, $DB, $CFG;
1938 // make sure we have the user id cached in config table, because we are going to use it a lot
1939 if (empty($CFG->siteguest)) {
1940 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1941 // guest does not exist yet, weird
1942 return false;
1944 set_config('siteguest', $guestid);
1946 if ($user === null) {
1947 $user = $USER;
1950 if ($user === null) {
1951 // happens when setting the $USER
1952 return false;
1954 } else if (is_numeric($user)) {
1955 return ($CFG->siteguest == $user);
1957 } else if (is_object($user)) {
1958 if (empty($user->id)) {
1959 return false; // not logged in means is not be guest
1960 } else {
1961 return ($CFG->siteguest == $user->id);
1964 } else {
1965 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1970 * Does user have a (temporary or real) guest access to course?
1972 * @category access
1974 * @param context $context
1975 * @param stdClass|int $user
1976 * @return bool
1978 function is_guest(context $context, $user = null) {
1979 global $USER;
1981 // first find the course context
1982 $coursecontext = $context->get_course_context();
1984 // make sure there is a real user specified
1985 if ($user === null) {
1986 $userid = isset($USER->id) ? $USER->id : 0;
1987 } else {
1988 $userid = is_object($user) ? $user->id : $user;
1991 if (isguestuser($userid)) {
1992 // can not inspect or be enrolled
1993 return true;
1996 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1997 // viewing users appear out of nowhere, they are neither guests nor participants
1998 return false;
2001 // consider only real active enrolments here
2002 if (is_enrolled($coursecontext, $user, '', true)) {
2003 return false;
2006 return true;
2010 * Returns true if the user has moodle/course:view capability in the course,
2011 * this is intended for admins, managers (aka small admins), inspectors, etc.
2013 * @category access
2015 * @param context $context
2016 * @param int|stdClass $user if null $USER is used
2017 * @param string $withcapability extra capability name
2018 * @return bool
2020 function is_viewing(context $context, $user = null, $withcapability = '') {
2021 // first find the course context
2022 $coursecontext = $context->get_course_context();
2024 if (isguestuser($user)) {
2025 // can not inspect
2026 return false;
2029 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
2030 // admins are allowed to inspect courses
2031 return false;
2034 if ($withcapability and !has_capability($withcapability, $context, $user)) {
2035 // site admins always have the capability, but the enrolment above blocks
2036 return false;
2039 return true;
2043 * Returns true if the user is able to access the course.
2045 * This function is in no way, shape, or form a substitute for require_login.
2046 * It should only be used in circumstances where it is not possible to call require_login
2047 * such as the navigation.
2049 * This function checks many of the methods of access to a course such as the view
2050 * capability, enrollments, and guest access. It also makes use of the cache
2051 * generated by require_login for guest access.
2053 * The flags within the $USER object that are used here should NEVER be used outside
2054 * of this function can_access_course and require_login. Doing so WILL break future
2055 * versions.
2057 * @param stdClass $course record
2058 * @param stdClass|int|null $user user record or id, current user if null
2059 * @param string $withcapability Check for this capability as well.
2060 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2061 * @return boolean Returns true if the user is able to access the course
2063 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
2064 global $DB, $USER;
2066 // this function originally accepted $coursecontext parameter
2067 if ($course instanceof context) {
2068 if ($course instanceof context_course) {
2069 debugging('deprecated context parameter, please use $course record');
2070 $coursecontext = $course;
2071 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2072 } else {
2073 debugging('Invalid context parameter, please use $course record');
2074 return false;
2076 } else {
2077 $coursecontext = context_course::instance($course->id);
2080 if (!isset($USER->id)) {
2081 // should never happen
2082 $USER->id = 0;
2083 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
2086 // make sure there is a user specified
2087 if ($user === null) {
2088 $userid = $USER->id;
2089 } else {
2090 $userid = is_object($user) ? $user->id : $user;
2092 unset($user);
2094 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2095 return false;
2098 if ($userid == $USER->id) {
2099 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2100 // the fact that somebody switched role means they can access the course no matter to what role they switched
2101 return true;
2105 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2106 return false;
2109 if (is_viewing($coursecontext, $userid)) {
2110 return true;
2113 if ($userid != $USER->id) {
2114 // for performance reasons we do not verify temporary guest access for other users, sorry...
2115 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2118 // === from here we deal only with $USER ===
2120 $coursecontext->reload_if_dirty();
2122 if (isset($USER->enrol['enrolled'][$course->id])) {
2123 if ($USER->enrol['enrolled'][$course->id] > time()) {
2124 return true;
2127 if (isset($USER->enrol['tempguest'][$course->id])) {
2128 if ($USER->enrol['tempguest'][$course->id] > time()) {
2129 return true;
2133 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2134 return true;
2137 // if not enrolled try to gain temporary guest access
2138 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2139 $enrols = enrol_get_plugins(true);
2140 foreach($instances as $instance) {
2141 if (!isset($enrols[$instance->enrol])) {
2142 continue;
2144 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2145 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2146 if ($until !== false and $until > time()) {
2147 $USER->enrol['tempguest'][$course->id] = $until;
2148 return true;
2151 if (isset($USER->enrol['tempguest'][$course->id])) {
2152 unset($USER->enrol['tempguest'][$course->id]);
2153 remove_temp_course_roles($coursecontext);
2156 return false;
2160 * Loads the capability definitions for the component (from file).
2162 * Loads the capability definitions for the component (from file). If no
2163 * capabilities are defined for the component, we simply return an empty array.
2165 * @access private
2166 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2167 * @return array array of capabilities
2169 function load_capability_def($component) {
2170 $defpath = core_component::get_component_directory($component).'/db/access.php';
2172 $capabilities = array();
2173 if (file_exists($defpath)) {
2174 require($defpath);
2175 if (!empty(${$component.'_capabilities'})) {
2176 // BC capability array name
2177 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2178 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2179 $capabilities = ${$component.'_capabilities'};
2183 return $capabilities;
2187 * Gets the capabilities that have been cached in the database for this component.
2189 * @access private
2190 * @param string $component - examples: 'moodle', 'mod_forum'
2191 * @return array array of capabilities
2193 function get_cached_capabilities($component = 'moodle') {
2194 global $DB;
2195 $caps = get_all_capabilities();
2196 $componentcaps = array();
2197 foreach ($caps as $cap) {
2198 if ($cap['component'] == $component) {
2199 $componentcaps[] = (object) $cap;
2202 return $componentcaps;
2206 * Returns default capabilities for given role archetype.
2208 * @param string $archetype role archetype
2209 * @return array
2211 function get_default_capabilities($archetype) {
2212 global $DB;
2214 if (!$archetype) {
2215 return array();
2218 $alldefs = array();
2219 $defaults = array();
2220 $components = array();
2221 $allcaps = get_all_capabilities();
2223 foreach ($allcaps as $cap) {
2224 if (!in_array($cap['component'], $components)) {
2225 $components[] = $cap['component'];
2226 $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
2229 foreach($alldefs as $name=>$def) {
2230 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2231 if (isset($def['archetypes'])) {
2232 if (isset($def['archetypes'][$archetype])) {
2233 $defaults[$name] = $def['archetypes'][$archetype];
2235 // 'legacy' is for backward compatibility with 1.9 access.php
2236 } else {
2237 if (isset($def['legacy'][$archetype])) {
2238 $defaults[$name] = $def['legacy'][$archetype];
2243 return $defaults;
2247 * Return default roles that can be assigned, overridden or switched
2248 * by give role archetype.
2250 * @param string $type assign|override|switch
2251 * @param string $archetype
2252 * @return array of role ids
2254 function get_default_role_archetype_allows($type, $archetype) {
2255 global $DB;
2257 if (empty($archetype)) {
2258 return array();
2261 $roles = $DB->get_records('role');
2262 $archetypemap = array();
2263 foreach ($roles as $role) {
2264 if ($role->archetype) {
2265 $archetypemap[$role->archetype][$role->id] = $role->id;
2269 $defaults = array(
2270 'assign' => array(
2271 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2272 'coursecreator' => array(),
2273 'editingteacher' => array('teacher', 'student'),
2274 'teacher' => array(),
2275 'student' => array(),
2276 'guest' => array(),
2277 'user' => array(),
2278 'frontpage' => array(),
2280 'override' => array(
2281 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2282 'coursecreator' => array(),
2283 'editingteacher' => array('teacher', 'student', 'guest'),
2284 'teacher' => array(),
2285 'student' => array(),
2286 'guest' => array(),
2287 'user' => array(),
2288 'frontpage' => array(),
2290 'switch' => array(
2291 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2292 'coursecreator' => array(),
2293 'editingteacher' => array('teacher', 'student', 'guest'),
2294 'teacher' => array('student', 'guest'),
2295 'student' => array(),
2296 'guest' => array(),
2297 'user' => array(),
2298 'frontpage' => array(),
2302 if (!isset($defaults[$type][$archetype])) {
2303 debugging("Unknown type '$type'' or archetype '$archetype''");
2304 return array();
2307 $return = array();
2308 foreach ($defaults[$type][$archetype] as $at) {
2309 if (isset($archetypemap[$at])) {
2310 foreach ($archetypemap[$at] as $roleid) {
2311 $return[$roleid] = $roleid;
2316 return $return;
2320 * Reset role capabilities to default according to selected role archetype.
2321 * If no archetype selected, removes all capabilities.
2323 * This applies to capabilities that are assigned to the role (that you could
2324 * edit in the 'define roles' interface), and not to any capability overrides
2325 * in different locations.
2327 * @param int $roleid ID of role to reset capabilities for
2329 function reset_role_capabilities($roleid) {
2330 global $DB;
2332 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2333 $defaultcaps = get_default_capabilities($role->archetype);
2335 $systemcontext = context_system::instance();
2337 $DB->delete_records('role_capabilities',
2338 array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2340 foreach($defaultcaps as $cap=>$permission) {
2341 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2344 // Mark the system context dirty.
2345 context_system::instance()->mark_dirty();
2349 * Updates the capabilities table with the component capability definitions.
2350 * If no parameters are given, the function updates the core moodle
2351 * capabilities.
2353 * Note that the absence of the db/access.php capabilities definition file
2354 * will cause any stored capabilities for the component to be removed from
2355 * the database.
2357 * @access private
2358 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2359 * @return boolean true if success, exception in case of any problems
2361 function update_capabilities($component = 'moodle') {
2362 global $DB, $OUTPUT;
2364 $storedcaps = array();
2366 $filecaps = load_capability_def($component);
2367 foreach($filecaps as $capname=>$unused) {
2368 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2369 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2373 // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2374 // So ensure our updating is based on fresh data.
2375 cache::make('core', 'capabilities')->delete('core_capabilities');
2377 $cachedcaps = get_cached_capabilities($component);
2378 if ($cachedcaps) {
2379 foreach ($cachedcaps as $cachedcap) {
2380 array_push($storedcaps, $cachedcap->name);
2381 // update risk bitmasks and context levels in existing capabilities if needed
2382 if (array_key_exists($cachedcap->name, $filecaps)) {
2383 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2384 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2386 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2387 $updatecap = new stdClass();
2388 $updatecap->id = $cachedcap->id;
2389 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2390 $DB->update_record('capabilities', $updatecap);
2392 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2393 $updatecap = new stdClass();
2394 $updatecap->id = $cachedcap->id;
2395 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2396 $DB->update_record('capabilities', $updatecap);
2399 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2400 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2402 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2403 $updatecap = new stdClass();
2404 $updatecap->id = $cachedcap->id;
2405 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2406 $DB->update_record('capabilities', $updatecap);
2412 // Flush the cached again, as we have changed DB.
2413 cache::make('core', 'capabilities')->delete('core_capabilities');
2415 // Are there new capabilities in the file definition?
2416 $newcaps = array();
2418 foreach ($filecaps as $filecap => $def) {
2419 if (!$storedcaps ||
2420 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2421 if (!array_key_exists('riskbitmask', $def)) {
2422 $def['riskbitmask'] = 0; // no risk if not specified
2424 $newcaps[$filecap] = $def;
2427 // Add new capabilities to the stored definition.
2428 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2429 foreach ($newcaps as $capname => $capdef) {
2430 $capability = new stdClass();
2431 $capability->name = $capname;
2432 $capability->captype = $capdef['captype'];
2433 $capability->contextlevel = $capdef['contextlevel'];
2434 $capability->component = $component;
2435 $capability->riskbitmask = $capdef['riskbitmask'];
2437 $DB->insert_record('capabilities', $capability, false);
2439 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2440 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2441 foreach ($rolecapabilities as $rolecapability){
2442 //assign_capability will update rather than insert if capability exists
2443 if (!assign_capability($capname, $rolecapability->permission,
2444 $rolecapability->roleid, $rolecapability->contextid, true)){
2445 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2449 // we ignore archetype key if we have cloned permissions
2450 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2451 assign_legacy_capabilities($capname, $capdef['archetypes']);
2452 // 'legacy' is for backward compatibility with 1.9 access.php
2453 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2454 assign_legacy_capabilities($capname, $capdef['legacy']);
2457 // Are there any capabilities that have been removed from the file
2458 // definition that we need to delete from the stored capabilities and
2459 // role assignments?
2460 capabilities_cleanup($component, $filecaps);
2462 // reset static caches
2463 accesslib_clear_all_caches(false);
2465 // Flush the cached again, as we have changed DB.
2466 cache::make('core', 'capabilities')->delete('core_capabilities');
2468 return true;
2472 * Deletes cached capabilities that are no longer needed by the component.
2473 * Also unassigns these capabilities from any roles that have them.
2474 * NOTE: this function is called from lib/db/upgrade.php
2476 * @access private
2477 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2478 * @param array $newcapdef array of the new capability definitions that will be
2479 * compared with the cached capabilities
2480 * @return int number of deprecated capabilities that have been removed
2482 function capabilities_cleanup($component, $newcapdef = null) {
2483 global $DB;
2485 $removedcount = 0;
2487 if ($cachedcaps = get_cached_capabilities($component)) {
2488 foreach ($cachedcaps as $cachedcap) {
2489 if (empty($newcapdef) ||
2490 array_key_exists($cachedcap->name, $newcapdef) === false) {
2492 // Remove from capabilities cache.
2493 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2494 $removedcount++;
2495 // Delete from roles.
2496 if ($roles = get_roles_with_capability($cachedcap->name)) {
2497 foreach($roles as $role) {
2498 if (!unassign_capability($cachedcap->name, $role->id)) {
2499 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2503 } // End if.
2506 if ($removedcount) {
2507 cache::make('core', 'capabilities')->delete('core_capabilities');
2509 return $removedcount;
2513 * Returns an array of all the known types of risk
2514 * The array keys can be used, for example as CSS class names, or in calls to
2515 * print_risk_icon. The values are the corresponding RISK_ constants.
2517 * @return array all the known types of risk.
2519 function get_all_risks() {
2520 return array(
2521 'riskmanagetrust' => RISK_MANAGETRUST,
2522 'riskconfig' => RISK_CONFIG,
2523 'riskxss' => RISK_XSS,
2524 'riskpersonal' => RISK_PERSONAL,
2525 'riskspam' => RISK_SPAM,
2526 'riskdataloss' => RISK_DATALOSS,
2531 * Return a link to moodle docs for a given capability name
2533 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2534 * @return string the human-readable capability name as a link to Moodle Docs.
2536 function get_capability_docs_link($capability) {
2537 $url = get_docs_url('Capabilities/' . $capability->name);
2538 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2542 * This function pulls out all the resolved capabilities (overrides and
2543 * defaults) of a role used in capability overrides in contexts at a given
2544 * context.
2546 * @param int $roleid
2547 * @param context $context
2548 * @param string $cap capability, optional, defaults to ''
2549 * @return array Array of capabilities
2551 function role_context_capabilities($roleid, context $context, $cap = '') {
2552 global $DB;
2554 $contexts = $context->get_parent_context_ids(true);
2555 $contexts = '('.implode(',', $contexts).')';
2557 $params = array($roleid);
2559 if ($cap) {
2560 $search = " AND rc.capability = ? ";
2561 $params[] = $cap;
2562 } else {
2563 $search = '';
2566 $sql = "SELECT rc.*
2567 FROM {role_capabilities} rc, {context} c
2568 WHERE rc.contextid in $contexts
2569 AND rc.roleid = ?
2570 AND rc.contextid = c.id $search
2571 ORDER BY c.contextlevel DESC, rc.capability DESC";
2573 $capabilities = array();
2575 if ($records = $DB->get_records_sql($sql, $params)) {
2576 // We are traversing via reverse order.
2577 foreach ($records as $record) {
2578 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2579 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2580 $capabilities[$record->capability] = $record->permission;
2584 return $capabilities;
2588 * Constructs array with contextids as first parameter and context paths,
2589 * in both cases bottom top including self.
2591 * @access private
2592 * @param context $context
2593 * @return array
2595 function get_context_info_list(context $context) {
2596 $contextids = explode('/', ltrim($context->path, '/'));
2597 $contextpaths = array();
2598 $contextids2 = $contextids;
2599 while ($contextids2) {
2600 $contextpaths[] = '/' . implode('/', $contextids2);
2601 array_pop($contextids2);
2603 return array($contextids, $contextpaths);
2607 * Check if context is the front page context or a context inside it
2609 * Returns true if this context is the front page context, or a context inside it,
2610 * otherwise false.
2612 * @param context $context a context object.
2613 * @return bool
2615 function is_inside_frontpage(context $context) {
2616 $frontpagecontext = context_course::instance(SITEID);
2617 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2621 * Returns capability information (cached)
2623 * @param string $capabilityname
2624 * @return stdClass or null if capability not found
2626 function get_capability_info($capabilityname) {
2627 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2629 $caps = get_all_capabilities();
2631 if (!isset($caps[$capabilityname])) {
2632 return null;
2635 return (object) $caps[$capabilityname];
2639 * Returns all capabilitiy records, preferably from MUC and not database.
2641 * @return array All capability records indexed by capability name
2643 function get_all_capabilities() {
2644 global $DB;
2645 $cache = cache::make('core', 'capabilities');
2646 if (!$allcaps = $cache->get('core_capabilities')) {
2647 $rs = $DB->get_recordset('capabilities');
2648 $allcaps = array();
2649 foreach ($rs as $capability) {
2650 $capability->riskbitmask = (int) $capability->riskbitmask;
2651 $allcaps[$capability->name] = (array) $capability;
2653 $rs->close();
2654 $cache->set('core_capabilities', $allcaps);
2656 return $allcaps;
2660 * Returns the human-readable, translated version of the capability.
2661 * Basically a big switch statement.
2663 * @param string $capabilityname e.g. mod/choice:readresponses
2664 * @return string
2666 function get_capability_string($capabilityname) {
2668 // Typical capability name is 'plugintype/pluginname:capabilityname'
2669 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2671 if ($type === 'moodle') {
2672 $component = 'core_role';
2673 } else if ($type === 'quizreport') {
2674 //ugly hack!!
2675 $component = 'quiz_'.$name;
2676 } else {
2677 $component = $type.'_'.$name;
2680 $stringname = $name.':'.$capname;
2682 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2683 return get_string($stringname, $component);
2686 $dir = core_component::get_component_directory($component);
2687 if (!file_exists($dir)) {
2688 // plugin broken or does not exist, do not bother with printing of debug message
2689 return $capabilityname.' ???';
2692 // something is wrong in plugin, better print debug
2693 return get_string($stringname, $component);
2697 * This gets the mod/block/course/core etc strings.
2699 * @param string $component
2700 * @param int $contextlevel
2701 * @return string|bool String is success, false if failed
2703 function get_component_string($component, $contextlevel) {
2705 if ($component === 'moodle' or $component === 'core') {
2706 switch ($contextlevel) {
2707 // TODO MDL-46123: this should probably use context level names instead
2708 case CONTEXT_SYSTEM: return get_string('coresystem');
2709 case CONTEXT_USER: return get_string('users');
2710 case CONTEXT_COURSECAT: return get_string('categories');
2711 case CONTEXT_COURSE: return get_string('course');
2712 case CONTEXT_MODULE: return get_string('activities');
2713 case CONTEXT_BLOCK: return get_string('block');
2714 default: print_error('unknowncontext');
2718 list($type, $name) = core_component::normalize_component($component);
2719 $dir = core_component::get_plugin_directory($type, $name);
2720 if (!file_exists($dir)) {
2721 // plugin not installed, bad luck, there is no way to find the name
2722 return $component.' ???';
2725 switch ($type) {
2726 // TODO MDL-46123: this is really hacky and should be improved.
2727 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2728 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2729 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2730 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2731 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2732 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2733 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2734 case 'mod':
2735 if (get_string_manager()->string_exists('pluginname', $component)) {
2736 return get_string('activity').': '.get_string('pluginname', $component);
2737 } else {
2738 return get_string('activity').': '.get_string('modulename', $component);
2740 default: return get_string('pluginname', $component);
2745 * Gets the list of roles assigned to this context and up (parents)
2746 * from the list of roles that are visible on user profile page
2747 * and participants page.
2749 * @param context $context
2750 * @return array
2752 function get_profile_roles(context $context) {
2753 global $CFG, $DB;
2755 if (empty($CFG->profileroles)) {
2756 return array();
2759 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2760 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2761 $params = array_merge($params, $cparams);
2763 if ($coursecontext = $context->get_course_context(false)) {
2764 $params['coursecontext'] = $coursecontext->id;
2765 } else {
2766 $params['coursecontext'] = 0;
2769 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2770 FROM {role_assignments} ra, {role} r
2771 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2772 WHERE r.id = ra.roleid
2773 AND ra.contextid $contextlist
2774 AND r.id $rallowed
2775 ORDER BY r.sortorder ASC";
2777 return $DB->get_records_sql($sql, $params);
2781 * Gets the list of roles assigned to this context and up (parents)
2783 * @param context $context
2784 * @return array
2786 function get_roles_used_in_context(context $context) {
2787 global $DB;
2789 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2791 if ($coursecontext = $context->get_course_context(false)) {
2792 $params['coursecontext'] = $coursecontext->id;
2793 } else {
2794 $params['coursecontext'] = 0;
2797 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2798 FROM {role_assignments} ra, {role} r
2799 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2800 WHERE r.id = ra.roleid
2801 AND ra.contextid $contextlist
2802 ORDER BY r.sortorder ASC";
2804 return $DB->get_records_sql($sql, $params);
2808 * This function is used to print roles column in user profile page.
2809 * It is using the CFG->profileroles to limit the list to only interesting roles.
2810 * (The permission tab has full details of user role assignments.)
2812 * @param int $userid
2813 * @param int $courseid
2814 * @return string
2816 function get_user_roles_in_course($userid, $courseid) {
2817 global $CFG, $DB;
2819 if (empty($CFG->profileroles)) {
2820 return '';
2823 if ($courseid == SITEID) {
2824 $context = context_system::instance();
2825 } else {
2826 $context = context_course::instance($courseid);
2829 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2830 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2831 $params = array_merge($params, $cparams);
2833 if ($coursecontext = $context->get_course_context(false)) {
2834 $params['coursecontext'] = $coursecontext->id;
2835 } else {
2836 $params['coursecontext'] = 0;
2839 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2840 FROM {role_assignments} ra, {role} r
2841 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2842 WHERE r.id = ra.roleid
2843 AND ra.contextid $contextlist
2844 AND r.id $rallowed
2845 AND ra.userid = :userid
2846 ORDER BY r.sortorder ASC";
2847 $params['userid'] = $userid;
2849 $rolestring = '';
2851 if ($roles = $DB->get_records_sql($sql, $params)) {
2852 $rolenames = role_fix_names($roles, $context, ROLENAME_ALIAS, true); // Substitute aliases
2854 foreach ($rolenames as $roleid => $rolename) {
2855 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
2857 $rolestring = implode(',', $rolenames);
2860 return $rolestring;
2864 * Checks if a user can assign users to a particular role in this context
2866 * @param context $context
2867 * @param int $targetroleid - the id of the role you want to assign users to
2868 * @return boolean
2870 function user_can_assign(context $context, $targetroleid) {
2871 global $DB;
2873 // First check to see if the user is a site administrator.
2874 if (is_siteadmin()) {
2875 return true;
2878 // Check if user has override capability.
2879 // If not return false.
2880 if (!has_capability('moodle/role:assign', $context)) {
2881 return false;
2883 // pull out all active roles of this user from this context(or above)
2884 if ($userroles = get_user_roles($context)) {
2885 foreach ($userroles as $userrole) {
2886 // if any in the role_allow_override table, then it's ok
2887 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2888 return true;
2893 return false;
2897 * Returns all site roles in correct sort order.
2899 * Note: this method does not localise role names or descriptions,
2900 * use role_get_names() if you need role names.
2902 * @param context $context optional context for course role name aliases
2903 * @return array of role records with optional coursealias property
2905 function get_all_roles(context $context = null) {
2906 global $DB;
2908 if (!$context or !$coursecontext = $context->get_course_context(false)) {
2909 $coursecontext = null;
2912 if ($coursecontext) {
2913 $sql = "SELECT r.*, rn.name AS coursealias
2914 FROM {role} r
2915 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2916 ORDER BY r.sortorder ASC";
2917 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
2919 } else {
2920 return $DB->get_records('role', array(), 'sortorder ASC');
2925 * Returns roles of a specified archetype
2927 * @param string $archetype
2928 * @return array of full role records
2930 function get_archetype_roles($archetype) {
2931 global $DB;
2932 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2936 * Gets all the user roles assigned in this context, or higher contexts
2937 * this is mainly used when checking if a user can assign a role, or overriding a role
2938 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2939 * allow_override tables
2941 * @param context $context
2942 * @param int $userid
2943 * @param bool $checkparentcontexts defaults to true
2944 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2945 * @return array
2947 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2948 global $USER, $DB;
2950 if (empty($userid)) {
2951 if (empty($USER->id)) {
2952 return array();
2954 $userid = $USER->id;
2957 if ($checkparentcontexts) {
2958 $contextids = $context->get_parent_context_ids();
2959 } else {
2960 $contextids = array();
2962 $contextids[] = $context->id;
2964 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2966 array_unshift($params, $userid);
2968 $sql = "SELECT ra.*, r.name, r.shortname
2969 FROM {role_assignments} ra, {role} r, {context} c
2970 WHERE ra.userid = ?
2971 AND ra.roleid = r.id
2972 AND ra.contextid = c.id
2973 AND ra.contextid $contextids
2974 ORDER BY $order";
2976 return $DB->get_records_sql($sql ,$params);
2980 * Like get_user_roles, but adds in the authenticated user role, and the front
2981 * page roles, if applicable.
2983 * @param context $context the context.
2984 * @param int $userid optional. Defaults to $USER->id
2985 * @return array of objects with fields ->userid, ->contextid and ->roleid.
2987 function get_user_roles_with_special(context $context, $userid = 0) {
2988 global $CFG, $USER;
2990 if (empty($userid)) {
2991 if (empty($USER->id)) {
2992 return array();
2994 $userid = $USER->id;
2997 $ras = get_user_roles($context, $userid);
2999 // Add front-page role if relevant.
3000 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3001 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3002 is_inside_frontpage($context);
3003 if ($defaultfrontpageroleid && $isfrontpage) {
3004 $frontpagecontext = context_course::instance(SITEID);
3005 $ra = new stdClass();
3006 $ra->userid = $userid;
3007 $ra->contextid = $frontpagecontext->id;
3008 $ra->roleid = $defaultfrontpageroleid;
3009 $ras[] = $ra;
3012 // Add authenticated user role if relevant.
3013 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3014 if ($defaultuserroleid && !isguestuser($userid)) {
3015 $systemcontext = context_system::instance();
3016 $ra = new stdClass();
3017 $ra->userid = $userid;
3018 $ra->contextid = $systemcontext->id;
3019 $ra->roleid = $defaultuserroleid;
3020 $ras[] = $ra;
3023 return $ras;
3027 * Creates a record in the role_allow_override table
3029 * @param int $sroleid source roleid
3030 * @param int $troleid target roleid
3031 * @return void
3033 function allow_override($sroleid, $troleid) {
3034 global $DB;
3036 $record = new stdClass();
3037 $record->roleid = $sroleid;
3038 $record->allowoverride = $troleid;
3039 $DB->insert_record('role_allow_override', $record);
3043 * Creates a record in the role_allow_assign table
3045 * @param int $fromroleid source roleid
3046 * @param int $targetroleid target roleid
3047 * @return void
3049 function allow_assign($fromroleid, $targetroleid) {
3050 global $DB;
3052 $record = new stdClass();
3053 $record->roleid = $fromroleid;
3054 $record->allowassign = $targetroleid;
3055 $DB->insert_record('role_allow_assign', $record);
3059 * Creates a record in the role_allow_switch table
3061 * @param int $fromroleid source roleid
3062 * @param int $targetroleid target roleid
3063 * @return void
3065 function allow_switch($fromroleid, $targetroleid) {
3066 global $DB;
3068 $record = new stdClass();
3069 $record->roleid = $fromroleid;
3070 $record->allowswitch = $targetroleid;
3071 $DB->insert_record('role_allow_switch', $record);
3075 * Gets a list of roles that this user can assign in this context
3077 * @param context $context the context.
3078 * @param int $rolenamedisplay the type of role name to display. One of the
3079 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3080 * @param bool $withusercounts if true, count the number of users with each role.
3081 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3082 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3083 * if $withusercounts is true, returns a list of three arrays,
3084 * $rolenames, $rolecounts, and $nameswithcounts.
3086 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3087 global $USER, $DB;
3089 // make sure there is a real user specified
3090 if ($user === null) {
3091 $userid = isset($USER->id) ? $USER->id : 0;
3092 } else {
3093 $userid = is_object($user) ? $user->id : $user;
3096 if (!has_capability('moodle/role:assign', $context, $userid)) {
3097 if ($withusercounts) {
3098 return array(array(), array(), array());
3099 } else {
3100 return array();
3104 $params = array();
3105 $extrafields = '';
3107 if ($withusercounts) {
3108 $extrafields = ', (SELECT count(u.id)
3109 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3110 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3111 ) AS usercount';
3112 $params['conid'] = $context->id;
3115 if (is_siteadmin($userid)) {
3116 // show all roles allowed in this context to admins
3117 $assignrestriction = "";
3118 } else {
3119 $parents = $context->get_parent_context_ids(true);
3120 $contexts = implode(',' , $parents);
3121 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3122 FROM {role_allow_assign} raa
3123 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3124 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3125 ) ar ON ar.id = r.id";
3126 $params['userid'] = $userid;
3128 $params['contextlevel'] = $context->contextlevel;
3130 if ($coursecontext = $context->get_course_context(false)) {
3131 $params['coursecontext'] = $coursecontext->id;
3132 } else {
3133 $params['coursecontext'] = 0; // no course aliases
3134 $coursecontext = null;
3136 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3137 FROM {role} r
3138 $assignrestriction
3139 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3140 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3141 ORDER BY r.sortorder ASC";
3142 $roles = $DB->get_records_sql($sql, $params);
3144 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3146 if (!$withusercounts) {
3147 return $rolenames;
3150 $rolecounts = array();
3151 $nameswithcounts = array();
3152 foreach ($roles as $role) {
3153 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3154 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3156 return array($rolenames, $rolecounts, $nameswithcounts);
3160 * Gets a list of roles that this user can switch to in a context
3162 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3163 * This function just process the contents of the role_allow_switch table. You also need to
3164 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3166 * @param context $context a context.
3167 * @return array an array $roleid => $rolename.
3169 function get_switchable_roles(context $context) {
3170 global $USER, $DB;
3172 // You can't switch roles without this capability.
3173 if (!has_capability('moodle/role:switchroles', $context)) {
3174 return [];
3177 $params = array();
3178 $extrajoins = '';
3179 $extrawhere = '';
3180 if (!is_siteadmin()) {
3181 // Admins are allowed to switch to any role with.
3182 // Others are subject to the additional constraint that the switch-to role must be allowed by
3183 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3184 $parents = $context->get_parent_context_ids(true);
3185 $contexts = implode(',' , $parents);
3187 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3188 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3189 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3190 $params['userid'] = $USER->id;
3193 if ($coursecontext = $context->get_course_context(false)) {
3194 $params['coursecontext'] = $coursecontext->id;
3195 } else {
3196 $params['coursecontext'] = 0; // no course aliases
3197 $coursecontext = null;
3200 $query = "
3201 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3202 FROM (SELECT DISTINCT rc.roleid
3203 FROM {role_capabilities} rc
3204 $extrajoins
3205 $extrawhere) idlist
3206 JOIN {role} r ON r.id = idlist.roleid
3207 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3208 ORDER BY r.sortorder";
3209 $roles = $DB->get_records_sql($query, $params);
3211 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3215 * Gets a list of roles that this user can override in this context.
3217 * @param context $context the context.
3218 * @param int $rolenamedisplay the type of role name to display. One of the
3219 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3220 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3221 * @return array if $withcounts is false, then an array $roleid => $rolename.
3222 * if $withusercounts is true, returns a list of three arrays,
3223 * $rolenames, $rolecounts, and $nameswithcounts.
3225 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3226 global $USER, $DB;
3228 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3229 if ($withcounts) {
3230 return array(array(), array(), array());
3231 } else {
3232 return array();
3236 $parents = $context->get_parent_context_ids(true);
3237 $contexts = implode(',' , $parents);
3239 $params = array();
3240 $extrafields = '';
3242 $params['userid'] = $USER->id;
3243 if ($withcounts) {
3244 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3245 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3246 $params['conid'] = $context->id;
3249 if ($coursecontext = $context->get_course_context(false)) {
3250 $params['coursecontext'] = $coursecontext->id;
3251 } else {
3252 $params['coursecontext'] = 0; // no course aliases
3253 $coursecontext = null;
3256 if (is_siteadmin()) {
3257 // show all roles to admins
3258 $roles = $DB->get_records_sql("
3259 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3260 FROM {role} ro
3261 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3262 ORDER BY ro.sortorder ASC", $params);
3264 } else {
3265 $roles = $DB->get_records_sql("
3266 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3267 FROM {role} ro
3268 JOIN (SELECT DISTINCT r.id
3269 FROM {role} r
3270 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3271 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3272 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3273 ) inline_view ON ro.id = inline_view.id
3274 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3275 ORDER BY ro.sortorder ASC", $params);
3278 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3280 if (!$withcounts) {
3281 return $rolenames;
3284 $rolecounts = array();
3285 $nameswithcounts = array();
3286 foreach ($roles as $role) {
3287 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3288 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3290 return array($rolenames, $rolecounts, $nameswithcounts);
3294 * Create a role menu suitable for default role selection in enrol plugins.
3296 * @package core_enrol
3298 * @param context $context
3299 * @param int $addroleid current or default role - always added to list
3300 * @return array roleid=>localised role name
3302 function get_default_enrol_roles(context $context, $addroleid = null) {
3303 global $DB;
3305 $params = array('contextlevel'=>CONTEXT_COURSE);
3307 if ($coursecontext = $context->get_course_context(false)) {
3308 $params['coursecontext'] = $coursecontext->id;
3309 } else {
3310 $params['coursecontext'] = 0; // no course names
3311 $coursecontext = null;
3314 if ($addroleid) {
3315 $addrole = "OR r.id = :addroleid";
3316 $params['addroleid'] = $addroleid;
3317 } else {
3318 $addrole = "";
3321 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3322 FROM {role} r
3323 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3324 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3325 WHERE rcl.id IS NOT NULL $addrole
3326 ORDER BY sortorder DESC";
3328 $roles = $DB->get_records_sql($sql, $params);
3330 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3334 * Return context levels where this role is assignable.
3336 * @param integer $roleid the id of a role.
3337 * @return array list of the context levels at which this role may be assigned.
3339 function get_role_contextlevels($roleid) {
3340 global $DB;
3341 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3342 'contextlevel', 'id,contextlevel');
3346 * Return roles suitable for assignment at the specified context level.
3348 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3350 * @param integer $contextlevel a contextlevel.
3351 * @return array list of role ids that are assignable at this context level.
3353 function get_roles_for_contextlevels($contextlevel) {
3354 global $DB;
3355 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3356 '', 'id,roleid');
3360 * Returns default context levels where roles can be assigned.
3362 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3363 * from the array returned by get_role_archetypes();
3364 * @return array list of the context levels at which this type of role may be assigned by default.
3366 function get_default_contextlevels($rolearchetype) {
3367 static $defaults = array(
3368 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3369 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3370 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3371 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3372 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3373 'guest' => array(),
3374 'user' => array(),
3375 'frontpage' => array());
3377 if (isset($defaults[$rolearchetype])) {
3378 return $defaults[$rolearchetype];
3379 } else {
3380 return array();
3385 * Set the context levels at which a particular role can be assigned.
3386 * Throws exceptions in case of error.
3388 * @param integer $roleid the id of a role.
3389 * @param array $contextlevels the context levels at which this role should be assignable,
3390 * duplicate levels are removed.
3391 * @return void
3393 function set_role_contextlevels($roleid, array $contextlevels) {
3394 global $DB;
3395 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3396 $rcl = new stdClass();
3397 $rcl->roleid = $roleid;
3398 $contextlevels = array_unique($contextlevels);
3399 foreach ($contextlevels as $level) {
3400 $rcl->contextlevel = $level;
3401 $DB->insert_record('role_context_levels', $rcl, false, true);
3406 * Who has this capability in this context?
3408 * This can be a very expensive call - use sparingly and keep
3409 * the results if you are going to need them again soon.
3411 * Note if $fields is empty this function attempts to get u.*
3412 * which can get rather large - and has a serious perf impact
3413 * on some DBs.
3415 * @param context $context
3416 * @param string|array $capability - capability name(s)
3417 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3418 * @param string $sort - the sort order. Default is lastaccess time.
3419 * @param mixed $limitfrom - number of records to skip (offset)
3420 * @param mixed $limitnum - number of records to fetch
3421 * @param string|array $groups - single group or array of groups - only return
3422 * users who are in one of these group(s).
3423 * @param string|array $exceptions - list of users to exclude, comma separated or array
3424 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3425 * @param bool $view_ignored - use get_enrolled_sql() instead
3426 * @param bool $useviewallgroups if $groups is set the return users who
3427 * have capability both $capability and moodle/site:accessallgroups
3428 * in this context, as well as users who have $capability and who are
3429 * in $groups.
3430 * @return array of user records
3432 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3433 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3434 global $CFG, $DB;
3436 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3437 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3439 $ctxids = trim($context->path, '/');
3440 $ctxids = str_replace('/', ',', $ctxids);
3442 // Context is the frontpage
3443 $iscoursepage = false; // coursepage other than fp
3444 $isfrontpage = false;
3445 if ($context->contextlevel == CONTEXT_COURSE) {
3446 if ($context->instanceid == SITEID) {
3447 $isfrontpage = true;
3448 } else {
3449 $iscoursepage = true;
3452 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3454 $caps = (array)$capability;
3456 // construct list of context paths bottom-->top
3457 list($contextids, $paths) = get_context_info_list($context);
3459 // we need to find out all roles that have these capabilities either in definition or in overrides
3460 $defs = array();
3461 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3462 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3463 $params = array_merge($params, $params2);
3464 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3465 FROM {role_capabilities} rc
3466 JOIN {context} ctx on rc.contextid = ctx.id
3467 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3469 $rcs = $DB->get_records_sql($sql, $params);
3470 foreach ($rcs as $rc) {
3471 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3474 // go through the permissions bottom-->top direction to evaluate the current permission,
3475 // first one wins (prohibit is an exception that always wins)
3476 $access = array();
3477 foreach ($caps as $cap) {
3478 foreach ($paths as $path) {
3479 if (empty($defs[$cap][$path])) {
3480 continue;
3482 foreach($defs[$cap][$path] as $roleid => $perm) {
3483 if ($perm == CAP_PROHIBIT) {
3484 $access[$cap][$roleid] = CAP_PROHIBIT;
3485 continue;
3487 if (!isset($access[$cap][$roleid])) {
3488 $access[$cap][$roleid] = (int)$perm;
3494 // make lists of roles that are needed and prohibited in this context
3495 $needed = array(); // one of these is enough
3496 $prohibited = array(); // must not have any of these
3497 foreach ($caps as $cap) {
3498 if (empty($access[$cap])) {
3499 continue;
3501 foreach ($access[$cap] as $roleid => $perm) {
3502 if ($perm == CAP_PROHIBIT) {
3503 unset($needed[$cap][$roleid]);
3504 $prohibited[$cap][$roleid] = true;
3505 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3506 $needed[$cap][$roleid] = true;
3509 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3510 // easy, nobody has the permission
3511 unset($needed[$cap]);
3512 unset($prohibited[$cap]);
3513 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3514 // everybody is disqualified on the frontpage
3515 unset($needed[$cap]);
3516 unset($prohibited[$cap]);
3518 if (empty($prohibited[$cap])) {
3519 unset($prohibited[$cap]);
3523 if (empty($needed)) {
3524 // there can not be anybody if no roles match this request
3525 return array();
3528 if (empty($prohibited)) {
3529 // we can compact the needed roles
3530 $n = array();
3531 foreach ($needed as $cap) {
3532 foreach ($cap as $roleid=>$unused) {
3533 $n[$roleid] = true;
3536 $needed = array('any'=>$n);
3537 unset($n);
3540 // ***** Set up default fields ******
3541 if (empty($fields)) {
3542 if ($iscoursepage) {
3543 $fields = 'u.*, ul.timeaccess AS lastaccess';
3544 } else {
3545 $fields = 'u.*';
3547 } else {
3548 if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3549 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3553 // Set up default sort
3554 if (empty($sort)) { // default to course lastaccess or just lastaccess
3555 if ($iscoursepage) {
3556 $sort = 'ul.timeaccess';
3557 } else {
3558 $sort = 'u.lastaccess';
3562 // Prepare query clauses
3563 $wherecond = array();
3564 $params = array();
3565 $joins = array();
3567 // User lastaccess JOIN
3568 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3569 // user_lastaccess is not required MDL-13810
3570 } else {
3571 if ($iscoursepage) {
3572 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3573 } else {
3574 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3578 // We never return deleted users or guest account.
3579 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3580 $params['guestid'] = $CFG->siteguest;
3582 // Groups
3583 if ($groups) {
3584 $groups = (array)$groups;
3585 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3586 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3587 $params = array_merge($params, $grpparams);
3589 if ($useviewallgroups) {
3590 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3591 if (!empty($viewallgroupsusers)) {
3592 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3593 } else {
3594 $wherecond[] = "($grouptest)";
3596 } else {
3597 $wherecond[] = "($grouptest)";
3601 // User exceptions
3602 if (!empty($exceptions)) {
3603 $exceptions = (array)$exceptions;
3604 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3605 $params = array_merge($params, $exparams);
3606 $wherecond[] = "u.id $exsql";
3609 // now add the needed and prohibited roles conditions as joins
3610 if (!empty($needed['any'])) {
3611 // simple case - there are no prohibits involved
3612 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3613 // everybody
3614 } else {
3615 $joins[] = "JOIN (SELECT DISTINCT userid
3616 FROM {role_assignments}
3617 WHERE contextid IN ($ctxids)
3618 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3619 ) ra ON ra.userid = u.id";
3621 } else {
3622 $unions = array();
3623 $everybody = false;
3624 foreach ($needed as $cap=>$unused) {
3625 if (empty($prohibited[$cap])) {
3626 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3627 $everybody = true;
3628 break;
3629 } else {
3630 $unions[] = "SELECT userid
3631 FROM {role_assignments}
3632 WHERE contextid IN ($ctxids)
3633 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3635 } else {
3636 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3637 // nobody can have this cap because it is prevented in default roles
3638 continue;
3640 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3641 // everybody except the prohibitted - hiding does not matter
3642 $unions[] = "SELECT id AS userid
3643 FROM {user}
3644 WHERE id NOT IN (SELECT userid
3645 FROM {role_assignments}
3646 WHERE contextid IN ($ctxids)
3647 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3649 } else {
3650 $unions[] = "SELECT userid
3651 FROM {role_assignments}
3652 WHERE contextid IN ($ctxids) AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3653 AND userid NOT IN (
3654 SELECT userid
3655 FROM {role_assignments}
3656 WHERE contextid IN ($ctxids)
3657 AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . ")
3662 if (!$everybody) {
3663 if ($unions) {
3664 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3665 } else {
3666 // only prohibits found - nobody can be matched
3667 $wherecond[] = "1 = 2";
3672 // Collect WHERE conditions and needed joins
3673 $where = implode(' AND ', $wherecond);
3674 if ($where !== '') {
3675 $where = 'WHERE ' . $where;
3677 $joins = implode("\n", $joins);
3679 // Ok, let's get the users!
3680 $sql = "SELECT $fields
3681 FROM {user} u
3682 $joins
3683 $where
3684 ORDER BY $sort";
3686 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3690 * Re-sort a users array based on a sorting policy
3692 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3693 * based on a sorting policy. This is to support the odd practice of
3694 * sorting teachers by 'authority', where authority was "lowest id of the role
3695 * assignment".
3697 * Will execute 1 database query. Only suitable for small numbers of users, as it
3698 * uses an u.id IN() clause.
3700 * Notes about the sorting criteria.
3702 * As a default, we cannot rely on role.sortorder because then
3703 * admins/coursecreators will always win. That is why the sane
3704 * rule "is locality matters most", with sortorder as 2nd
3705 * consideration.
3707 * If you want role.sortorder, use the 'sortorder' policy, and
3708 * name explicitly what roles you want to cover. It's probably
3709 * a good idea to see what roles have the capabilities you want
3710 * (array_diff() them against roiles that have 'can-do-anything'
3711 * to weed out admin-ish roles. Or fetch a list of roles from
3712 * variables like $CFG->coursecontact .
3714 * @param array $users Users array, keyed on userid
3715 * @param context $context
3716 * @param array $roles ids of the roles to include, optional
3717 * @param string $sortpolicy defaults to locality, more about
3718 * @return array sorted copy of the array
3720 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3721 global $DB;
3723 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3724 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3725 if (empty($roles)) {
3726 $roleswhere = '';
3727 } else {
3728 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3731 $sql = "SELECT ra.userid
3732 FROM {role_assignments} ra
3733 JOIN {role} r
3734 ON ra.roleid=r.id
3735 JOIN {context} ctx
3736 ON ra.contextid=ctx.id
3737 WHERE $userswhere
3738 $contextwhere
3739 $roleswhere";
3741 // Default 'locality' policy -- read PHPDoc notes
3742 // about sort policies...
3743 $orderby = 'ORDER BY '
3744 .'ctx.depth DESC, ' /* locality wins */
3745 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3746 .'ra.id'; /* role assignment order tie-breaker */
3747 if ($sortpolicy === 'sortorder') {
3748 $orderby = 'ORDER BY '
3749 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3750 .'ra.id'; /* role assignment order tie-breaker */
3753 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3754 $sortedusers = array();
3755 $seen = array();
3757 foreach ($sortedids as $id) {
3758 // Avoid duplicates
3759 if (isset($seen[$id])) {
3760 continue;
3762 $seen[$id] = true;
3764 // assign
3765 $sortedusers[$id] = $users[$id];
3767 return $sortedusers;
3771 * Gets all the users assigned this role in this context or higher
3773 * Note that moodle is based on capabilities and it is usually better
3774 * to check permissions than to check role ids as the capabilities
3775 * system is more flexible. If you really need, you can to use this
3776 * function but consider has_capability() as a possible substitute.
3778 * All $sort fields are added into $fields if not present there yet.
3780 * If $roleid is an array or is empty (all roles) you need to set $fields
3781 * (and $sort by extension) params according to it, as the first field
3782 * returned by the database should be unique (ra.id is the best candidate).
3784 * @param int $roleid (can also be an array of ints!)
3785 * @param context $context
3786 * @param bool $parent if true, get list of users assigned in higher context too
3787 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3788 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3789 * null => use default sort from users_order_by_sql.
3790 * @param bool $all true means all, false means limit to enrolled users
3791 * @param string $group defaults to ''
3792 * @param mixed $limitfrom defaults to ''
3793 * @param mixed $limitnum defaults to ''
3794 * @param string $extrawheretest defaults to ''
3795 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3796 * @return array
3798 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3799 $sort = null, $all = true, $group = '',
3800 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3801 global $DB;
3803 if (empty($fields)) {
3804 $allnames = get_all_user_name_fields(true, 'u');
3805 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
3806 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3807 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3808 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3809 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3812 // Prevent wrong function uses.
3813 if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
3814 debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
3815 'role assignments id (ra.id) as unique field, you can use $fields param for it.');
3817 if (!empty($roleid)) {
3818 // Solving partially the issue when specifying multiple roles.
3819 $users = array();
3820 foreach ($roleid as $id) {
3821 // Ignoring duplicated keys keeping the first user appearance.
3822 $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
3823 $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
3825 return $users;
3829 $parentcontexts = '';
3830 if ($parent) {
3831 $parentcontexts = substr($context->path, 1); // kill leading slash
3832 $parentcontexts = str_replace('/', ',', $parentcontexts);
3833 if ($parentcontexts !== '') {
3834 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3838 if ($roleid) {
3839 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
3840 $roleselect = "AND ra.roleid $rids";
3841 } else {
3842 $params = array();
3843 $roleselect = '';
3846 if ($coursecontext = $context->get_course_context(false)) {
3847 $params['coursecontext'] = $coursecontext->id;
3848 } else {
3849 $params['coursecontext'] = 0;
3852 if ($group) {
3853 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3854 $groupselect = " AND gm.groupid = :groupid ";
3855 $params['groupid'] = $group;
3856 } else {
3857 $groupjoin = '';
3858 $groupselect = '';
3861 $params['contextid'] = $context->id;
3863 if ($extrawheretest) {
3864 $extrawheretest = ' AND ' . $extrawheretest;
3867 if ($whereorsortparams) {
3868 $params = array_merge($params, $whereorsortparams);
3871 if (!$sort) {
3872 list($sort, $sortparams) = users_order_by_sql('u');
3873 $params = array_merge($params, $sortparams);
3876 // Adding the fields from $sort that are not present in $fields.
3877 $sortarray = preg_split('/,\s*/', $sort);
3878 $fieldsarray = preg_split('/,\s*/', $fields);
3880 // Discarding aliases from the fields.
3881 $fieldnames = array();
3882 foreach ($fieldsarray as $key => $field) {
3883 list($fieldnames[$key]) = explode(' ', $field);
3886 $addedfields = array();
3887 foreach ($sortarray as $sortfield) {
3888 // Throw away any additional arguments to the sort (e.g. ASC/DESC).
3889 list($sortfield) = explode(' ', $sortfield);
3890 list($tableprefix) = explode('.', $sortfield);
3891 $fieldpresent = false;
3892 foreach ($fieldnames as $fieldname) {
3893 if ($fieldname === $sortfield || $fieldname === $tableprefix.'.*') {
3894 $fieldpresent = true;
3895 break;
3899 if (!$fieldpresent) {
3900 $fieldsarray[] = $sortfield;
3901 $addedfields[] = $sortfield;
3905 $fields = implode(', ', $fieldsarray);
3906 if (!empty($addedfields)) {
3907 $addedfields = implode(', ', $addedfields);
3908 debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
3911 if ($all === null) {
3912 // Previously null was used to indicate that parameter was not used.
3913 $all = true;
3915 if (!$all and $coursecontext) {
3916 // Do not use get_enrolled_sql() here for performance reasons.
3917 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
3918 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
3919 $params['ecourseid'] = $coursecontext->instanceid;
3920 } else {
3921 $ejoin = "";
3924 $sql = "SELECT DISTINCT $fields, ra.roleid
3925 FROM {role_assignments} ra
3926 JOIN {user} u ON u.id = ra.userid
3927 JOIN {role} r ON ra.roleid = r.id
3928 $ejoin
3929 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3930 $groupjoin
3931 WHERE (ra.contextid = :contextid $parentcontexts)
3932 $roleselect
3933 $groupselect
3934 $extrawheretest
3935 ORDER BY $sort"; // join now so that we can just use fullname() later
3937 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3941 * Counts all the users assigned this role in this context or higher
3943 * @param int|array $roleid either int or an array of ints
3944 * @param context $context
3945 * @param bool $parent if true, get list of users assigned in higher context too
3946 * @return int Returns the result count
3948 function count_role_users($roleid, context $context, $parent = false) {
3949 global $DB;
3951 if ($parent) {
3952 if ($contexts = $context->get_parent_context_ids()) {
3953 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3954 } else {
3955 $parentcontexts = '';
3957 } else {
3958 $parentcontexts = '';
3961 if ($roleid) {
3962 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3963 $roleselect = "AND r.roleid $rids";
3964 } else {
3965 $params = array();
3966 $roleselect = '';
3969 array_unshift($params, $context->id);
3971 $sql = "SELECT COUNT(DISTINCT u.id)
3972 FROM {role_assignments} r
3973 JOIN {user} u ON u.id = r.userid
3974 WHERE (r.contextid = ? $parentcontexts)
3975 $roleselect
3976 AND u.deleted = 0";
3978 return $DB->count_records_sql($sql, $params);
3982 * This function gets the list of courses that this user has a particular capability in.
3983 * It is still not very efficient.
3985 * @param string $capability Capability in question
3986 * @param int $userid User ID or null for current user
3987 * @param bool $doanything True if 'doanything' is permitted (default)
3988 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3989 * otherwise use a comma-separated list of the fields you require, not including id
3990 * @param string $orderby If set, use a comma-separated list of fields from course
3991 * table with sql modifiers (DESC) if needed
3992 * @return array|bool Array of courses, if none found false is returned.
3994 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
3995 global $DB;
3997 // Convert fields list and ordering
3998 $fieldlist = '';
3999 if ($fieldsexceptid) {
4000 $fields = explode(',', $fieldsexceptid);
4001 foreach($fields as $field) {
4002 $fieldlist .= ',c.'.$field;
4005 if ($orderby) {
4006 $fields = explode(',', $orderby);
4007 $orderby = '';
4008 foreach($fields as $field) {
4009 if ($orderby) {
4010 $orderby .= ',';
4012 $orderby .= 'c.'.$field;
4014 $orderby = 'ORDER BY '.$orderby;
4017 // Obtain a list of everything relevant about all courses including context.
4018 // Note the result can be used directly as a context (we are going to), the course
4019 // fields are just appended.
4021 $contextpreload = context_helper::get_preload_record_columns_sql('x');
4023 $courses = array();
4024 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
4025 FROM {course} c
4026 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
4027 $orderby");
4028 // Check capability for each course in turn
4029 foreach ($rs as $course) {
4030 context_helper::preload_from_record($course);
4031 $context = context_course::instance($course->id);
4032 if (has_capability($capability, $context, $userid, $doanything)) {
4033 // We've got the capability. Make the record look like a course record
4034 // and store it
4035 $courses[] = $course;
4038 $rs->close();
4039 return empty($courses) ? false : $courses;
4043 * This function finds the roles assigned directly to this context only
4044 * i.e. no roles in parent contexts
4046 * @param context $context
4047 * @return array
4049 function get_roles_on_exact_context(context $context) {
4050 global $DB;
4052 return $DB->get_records_sql("SELECT r.*
4053 FROM {role_assignments} ra, {role} r
4054 WHERE ra.roleid = r.id AND ra.contextid = ?",
4055 array($context->id));
4059 * Switches the current user to another role for the current session and only
4060 * in the given context.
4062 * The caller *must* check
4063 * - that this op is allowed
4064 * - that the requested role can be switched to in this context (use get_switchable_roles)
4065 * - that the requested role is NOT $CFG->defaultuserroleid
4067 * To "unswitch" pass 0 as the roleid.
4069 * This function *will* modify $USER->access - beware
4071 * @param integer $roleid the role to switch to.
4072 * @param context $context the context in which to perform the switch.
4073 * @return bool success or failure.
4075 function role_switch($roleid, context $context) {
4076 global $USER;
4079 // Plan of action
4081 // - Add the ghost RA to $USER->access
4082 // as $USER->access['rsw'][$path] = $roleid
4084 // - Make sure $USER->access['rdef'] has the roledefs
4085 // it needs to honour the switcherole
4087 // Roledefs will get loaded "deep" here - down to the last child
4088 // context. Note that
4090 // - When visiting subcontexts, our selective accessdata loading
4091 // will still work fine - though those ra/rdefs will be ignored
4092 // appropriately while the switch is in place
4094 // - If a switcherole happens at a category with tons of courses
4095 // (that have many overrides for switched-to role), the session
4096 // will get... quite large. Sometimes you just can't win.
4098 // To un-switch just unset($USER->access['rsw'][$path])
4100 // Note: it is not possible to switch to roles that do not have course:view
4102 if (!isset($USER->access)) {
4103 load_all_capabilities();
4107 // Add the switch RA
4108 if ($roleid == 0) {
4109 unset($USER->access['rsw'][$context->path]);
4110 return true;
4113 $USER->access['rsw'][$context->path] = $roleid;
4115 // Load roledefs
4116 load_role_access_by_context($roleid, $context, $USER->access);
4118 return true;
4122 * Checks if the user has switched roles within the given course.
4124 * Note: You can only switch roles within the course, hence it takes a course id
4125 * rather than a context. On that note Petr volunteered to implement this across
4126 * all other contexts, all requests for this should be forwarded to him ;)
4128 * @param int $courseid The id of the course to check
4129 * @return bool True if the user has switched roles within the course.
4131 function is_role_switched($courseid) {
4132 global $USER;
4133 $context = context_course::instance($courseid, MUST_EXIST);
4134 return (!empty($USER->access['rsw'][$context->path]));
4138 * Get any role that has an override on exact context
4140 * @param context $context The context to check
4141 * @return array An array of roles
4143 function get_roles_with_override_on_context(context $context) {
4144 global $DB;
4146 return $DB->get_records_sql("SELECT r.*
4147 FROM {role_capabilities} rc, {role} r
4148 WHERE rc.roleid = r.id AND rc.contextid = ?",
4149 array($context->id));
4153 * Get all capabilities for this role on this context (overrides)
4155 * @param stdClass $role
4156 * @param context $context
4157 * @return array
4159 function get_capabilities_from_role_on_context($role, context $context) {
4160 global $DB;
4162 return $DB->get_records_sql("SELECT *
4163 FROM {role_capabilities}
4164 WHERE contextid = ? AND roleid = ?",
4165 array($context->id, $role->id));
4169 * Find out which roles has assignment on this context
4171 * @param context $context
4172 * @return array
4175 function get_roles_with_assignment_on_context(context $context) {
4176 global $DB;
4178 return $DB->get_records_sql("SELECT r.*
4179 FROM {role_assignments} ra, {role} r
4180 WHERE ra.roleid = r.id AND ra.contextid = ?",
4181 array($context->id));
4185 * Find all user assignment of users for this role, on this context
4187 * @param stdClass $role
4188 * @param context $context
4189 * @return array
4191 function get_users_from_role_on_context($role, context $context) {
4192 global $DB;
4194 return $DB->get_records_sql("SELECT *
4195 FROM {role_assignments}
4196 WHERE contextid = ? AND roleid = ?",
4197 array($context->id, $role->id));
4201 * Simple function returning a boolean true if user has roles
4202 * in context or parent contexts, otherwise false.
4204 * @param int $userid
4205 * @param int $roleid
4206 * @param int $contextid empty means any context
4207 * @return bool
4209 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4210 global $DB;
4212 if ($contextid) {
4213 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4214 return false;
4216 $parents = $context->get_parent_context_ids(true);
4217 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4218 $params['userid'] = $userid;
4219 $params['roleid'] = $roleid;
4221 $sql = "SELECT COUNT(ra.id)
4222 FROM {role_assignments} ra
4223 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4225 $count = $DB->get_field_sql($sql, $params);
4226 return ($count > 0);
4228 } else {
4229 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4234 * Get localised role name or alias if exists and format the text.
4236 * @param stdClass $role role object
4237 * - optional 'coursealias' property should be included for performance reasons if course context used
4238 * - description property is not required here
4239 * @param context|bool $context empty means system context
4240 * @param int $rolenamedisplay type of role name
4241 * @return string localised role name or course role name alias
4243 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4244 global $DB;
4246 if ($rolenamedisplay == ROLENAME_SHORT) {
4247 return $role->shortname;
4250 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4251 $coursecontext = null;
4254 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4255 $role = clone($role); // Do not modify parameters.
4256 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4257 $role->coursealias = $r->name;
4258 } else {
4259 $role->coursealias = null;
4263 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4264 if ($coursecontext) {
4265 return $role->coursealias;
4266 } else {
4267 return null;
4271 if (trim($role->name) !== '') {
4272 // For filtering always use context where was the thing defined - system for roles here.
4273 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4275 } else {
4276 // Empty role->name means we want to see localised role name based on shortname,
4277 // only default roles are supposed to be localised.
4278 switch ($role->shortname) {
4279 case 'manager': $original = get_string('manager', 'role'); break;
4280 case 'coursecreator': $original = get_string('coursecreators'); break;
4281 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4282 case 'teacher': $original = get_string('noneditingteacher'); break;
4283 case 'student': $original = get_string('defaultcoursestudent'); break;
4284 case 'guest': $original = get_string('guest'); break;
4285 case 'user': $original = get_string('authenticateduser'); break;
4286 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4287 // We should not get here, the role UI should require the name for custom roles!
4288 default: $original = $role->shortname; break;
4292 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4293 return $original;
4296 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4297 return "$original ($role->shortname)";
4300 if ($rolenamedisplay == ROLENAME_ALIAS) {
4301 if ($coursecontext and trim($role->coursealias) !== '') {
4302 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4303 } else {
4304 return $original;
4308 if ($rolenamedisplay == ROLENAME_BOTH) {
4309 if ($coursecontext and trim($role->coursealias) !== '') {
4310 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4311 } else {
4312 return $original;
4316 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4320 * Returns localised role description if available.
4321 * If the name is empty it tries to find the default role name using
4322 * hardcoded list of default role names or other methods in the future.
4324 * @param stdClass $role
4325 * @return string localised role name
4327 function role_get_description(stdClass $role) {
4328 if (!html_is_blank($role->description)) {
4329 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4332 switch ($role->shortname) {
4333 case 'manager': return get_string('managerdescription', 'role');
4334 case 'coursecreator': return get_string('coursecreatorsdescription');
4335 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4336 case 'teacher': return get_string('noneditingteacherdescription');
4337 case 'student': return get_string('defaultcoursestudentdescription');
4338 case 'guest': return get_string('guestdescription');
4339 case 'user': return get_string('authenticateduserdescription');
4340 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4341 default: return '';
4346 * Get all the localised role names for a context.
4348 * In new installs default roles have empty names, this function
4349 * add localised role names using current language pack.
4351 * @param context $context the context, null means system context
4352 * @param array of role objects with a ->localname field containing the context-specific role name.
4353 * @param int $rolenamedisplay
4354 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4355 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4357 function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4358 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4362 * Prepare list of roles for display, apply aliases and localise default role names.
4364 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4365 * @param context $context the context, null means system context
4366 * @param int $rolenamedisplay
4367 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4368 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4370 function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4371 global $DB;
4373 if (empty($roleoptions)) {
4374 return array();
4377 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4378 $coursecontext = null;
4381 // We usually need all role columns...
4382 $first = reset($roleoptions);
4383 if ($returnmenu === null) {
4384 $returnmenu = !is_object($first);
4387 if (!is_object($first) or !property_exists($first, 'shortname')) {
4388 $allroles = get_all_roles($context);
4389 foreach ($roleoptions as $rid => $unused) {
4390 $roleoptions[$rid] = $allroles[$rid];
4394 // Inject coursealias if necessary.
4395 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4396 $first = reset($roleoptions);
4397 if (!property_exists($first, 'coursealias')) {
4398 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4399 foreach ($aliasnames as $alias) {
4400 if (isset($roleoptions[$alias->roleid])) {
4401 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4407 // Add localname property.
4408 foreach ($roleoptions as $rid => $role) {
4409 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4412 if (!$returnmenu) {
4413 return $roleoptions;
4416 $menu = array();
4417 foreach ($roleoptions as $rid => $role) {
4418 $menu[$rid] = $role->localname;
4421 return $menu;
4425 * Aids in detecting if a new line is required when reading a new capability
4427 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4428 * when we read in a new capability.
4429 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4430 * but when we are in grade, all reports/import/export capabilities should be together
4432 * @param string $cap component string a
4433 * @param string $comp component string b
4434 * @param int $contextlevel
4435 * @return bool whether 2 component are in different "sections"
4437 function component_level_changed($cap, $comp, $contextlevel) {
4439 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4440 $compsa = explode('/', $cap->component);
4441 $compsb = explode('/', $comp);
4443 // list of system reports
4444 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4445 return false;
4448 // we are in gradebook, still
4449 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4450 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4451 return false;
4454 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4455 return false;
4459 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4463 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4464 * and return an array of roleids in order.
4466 * @param array $allroles array of roles, as returned by get_all_roles();
4467 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4469 function fix_role_sortorder($allroles) {
4470 global $DB;
4472 $rolesort = array();
4473 $i = 0;
4474 foreach ($allroles as $role) {
4475 $rolesort[$i] = $role->id;
4476 if ($role->sortorder != $i) {
4477 $r = new stdClass();
4478 $r->id = $role->id;
4479 $r->sortorder = $i;
4480 $DB->update_record('role', $r);
4481 $allroles[$role->id]->sortorder = $i;
4483 $i++;
4485 return $rolesort;
4489 * Switch the sort order of two roles (used in admin/roles/manage.php).
4491 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4492 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4493 * @return boolean success or failure
4495 function switch_roles($first, $second) {
4496 global $DB;
4497 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4498 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4499 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4500 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4501 return $result;
4505 * Duplicates all the base definitions of a role
4507 * @param stdClass $sourcerole role to copy from
4508 * @param int $targetrole id of role to copy to
4510 function role_cap_duplicate($sourcerole, $targetrole) {
4511 global $DB;
4513 $systemcontext = context_system::instance();
4514 $caps = $DB->get_records_sql("SELECT *
4515 FROM {role_capabilities}
4516 WHERE roleid = ? AND contextid = ?",
4517 array($sourcerole->id, $systemcontext->id));
4518 // adding capabilities
4519 foreach ($caps as $cap) {
4520 unset($cap->id);
4521 $cap->roleid = $targetrole;
4522 $DB->insert_record('role_capabilities', $cap);
4527 * Returns two lists, this can be used to find out if user has capability.
4528 * Having any needed role and no forbidden role in this context means
4529 * user has this capability in this context.
4530 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4532 * @param stdClass $context
4533 * @param string $capability
4534 * @return array($neededroles, $forbiddenroles)
4536 function get_roles_with_cap_in_context($context, $capability) {
4537 global $DB;
4539 $ctxids = trim($context->path, '/'); // kill leading slash
4540 $ctxids = str_replace('/', ',', $ctxids);
4542 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4543 FROM {role_capabilities} rc
4544 JOIN {context} ctx ON ctx.id = rc.contextid
4545 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4546 ORDER BY rc.roleid ASC, ctx.depth DESC";
4547 $params = array('cap'=>$capability);
4549 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4550 // no cap definitions --> no capability
4551 return array(array(), array());
4554 $forbidden = array();
4555 $needed = array();
4556 foreach($capdefs as $def) {
4557 if (isset($forbidden[$def->roleid])) {
4558 continue;
4560 if ($def->permission == CAP_PROHIBIT) {
4561 $forbidden[$def->roleid] = $def->roleid;
4562 unset($needed[$def->roleid]);
4563 continue;
4565 if (!isset($needed[$def->roleid])) {
4566 if ($def->permission == CAP_ALLOW) {
4567 $needed[$def->roleid] = true;
4568 } else if ($def->permission == CAP_PREVENT) {
4569 $needed[$def->roleid] = false;
4573 unset($capdefs);
4575 // remove all those roles not allowing
4576 foreach($needed as $key=>$value) {
4577 if (!$value) {
4578 unset($needed[$key]);
4579 } else {
4580 $needed[$key] = $key;
4584 return array($needed, $forbidden);
4588 * Returns an array of role IDs that have ALL of the the supplied capabilities
4589 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4591 * @param stdClass $context
4592 * @param array $capabilities An array of capabilities
4593 * @return array of roles with all of the required capabilities
4595 function get_roles_with_caps_in_context($context, $capabilities) {
4596 $neededarr = array();
4597 $forbiddenarr = array();
4598 foreach($capabilities as $caprequired) {
4599 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4602 $rolesthatcanrate = array();
4603 if (!empty($neededarr)) {
4604 foreach ($neededarr as $needed) {
4605 if (empty($rolesthatcanrate)) {
4606 $rolesthatcanrate = $needed;
4607 } else {
4608 //only want roles that have all caps
4609 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4613 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4614 foreach ($forbiddenarr as $forbidden) {
4615 //remove any roles that are forbidden any of the caps
4616 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4619 return $rolesthatcanrate;
4623 * Returns an array of role names that have ALL of the the supplied capabilities
4624 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4626 * @param stdClass $context
4627 * @param array $capabilities An array of capabilities
4628 * @return array of roles with all of the required capabilities
4630 function get_role_names_with_caps_in_context($context, $capabilities) {
4631 global $DB;
4633 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4634 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4636 $roles = array();
4637 foreach ($rolesthatcanrate as $r) {
4638 $roles[$r] = $allroles[$r];
4641 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4645 * This function verifies the prohibit comes from this context
4646 * and there are no more prohibits in parent contexts.
4648 * @param int $roleid
4649 * @param context $context
4650 * @param string $capability name
4651 * @return bool
4653 function prohibit_is_removable($roleid, context $context, $capability) {
4654 global $DB;
4656 $ctxids = trim($context->path, '/'); // kill leading slash
4657 $ctxids = str_replace('/', ',', $ctxids);
4659 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4661 $sql = "SELECT ctx.id
4662 FROM {role_capabilities} rc
4663 JOIN {context} ctx ON ctx.id = rc.contextid
4664 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4665 ORDER BY ctx.depth DESC";
4667 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4668 // no prohibits == nothing to remove
4669 return true;
4672 if (count($prohibits) > 1) {
4673 // more prohibits can not be removed
4674 return false;
4677 return !empty($prohibits[$context->id]);
4681 * More user friendly role permission changing,
4682 * it should produce as few overrides as possible.
4684 * @param int $roleid
4685 * @param stdClass $context
4686 * @param string $capname capability name
4687 * @param int $permission
4688 * @return void
4690 function role_change_permission($roleid, $context, $capname, $permission) {
4691 global $DB;
4693 if ($permission == CAP_INHERIT) {
4694 unassign_capability($capname, $roleid, $context->id);
4695 $context->mark_dirty();
4696 return;
4699 $ctxids = trim($context->path, '/'); // kill leading slash
4700 $ctxids = str_replace('/', ',', $ctxids);
4702 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4704 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4705 FROM {role_capabilities} rc
4706 JOIN {context} ctx ON ctx.id = rc.contextid
4707 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4708 ORDER BY ctx.depth DESC";
4710 if ($existing = $DB->get_records_sql($sql, $params)) {
4711 foreach($existing as $e) {
4712 if ($e->permission == CAP_PROHIBIT) {
4713 // prohibit can not be overridden, no point in changing anything
4714 return;
4717 $lowest = array_shift($existing);
4718 if ($lowest->permission == $permission) {
4719 // permission already set in this context or parent - nothing to do
4720 return;
4722 if ($existing) {
4723 $parent = array_shift($existing);
4724 if ($parent->permission == $permission) {
4725 // permission already set in parent context or parent - just unset in this context
4726 // we do this because we want as few overrides as possible for performance reasons
4727 unassign_capability($capname, $roleid, $context->id);
4728 $context->mark_dirty();
4729 return;
4733 } else {
4734 if ($permission == CAP_PREVENT) {
4735 // nothing means role does not have permission
4736 return;
4740 // assign the needed capability
4741 assign_capability($capname, $permission, $roleid, $context->id, true);
4743 // force cap reloading
4744 $context->mark_dirty();
4749 * Basic moodle context abstraction class.
4751 * Google confirms that no other important framework is using "context" class,
4752 * we could use something else like mcontext or moodle_context, but we need to type
4753 * this very often which would be annoying and it would take too much space...
4755 * This class is derived from stdClass for backwards compatibility with
4756 * odl $context record that was returned from DML $DB->get_record()
4758 * @package core_access
4759 * @category access
4760 * @copyright Petr Skoda {@link http://skodak.org}
4761 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4762 * @since Moodle 2.2
4764 * @property-read int $id context id
4765 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4766 * @property-read int $instanceid id of related instance in each context
4767 * @property-read string $path path to context, starts with system context
4768 * @property-read int $depth
4770 abstract class context extends stdClass implements IteratorAggregate {
4773 * The context id
4774 * Can be accessed publicly through $context->id
4775 * @var int
4777 protected $_id;
4780 * The context level
4781 * Can be accessed publicly through $context->contextlevel
4782 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4784 protected $_contextlevel;
4787 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4788 * Can be accessed publicly through $context->instanceid
4789 * @var int
4791 protected $_instanceid;
4794 * The path to the context always starting from the system context
4795 * Can be accessed publicly through $context->path
4796 * @var string
4798 protected $_path;
4801 * The depth of the context in relation to parent contexts
4802 * Can be accessed publicly through $context->depth
4803 * @var int
4805 protected $_depth;
4808 * @var array Context caching info
4810 private static $cache_contextsbyid = array();
4813 * @var array Context caching info
4815 private static $cache_contexts = array();
4818 * Context count
4819 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4820 * @var int
4822 protected static $cache_count = 0;
4825 * @var array Context caching info
4827 protected static $cache_preloaded = array();
4830 * @var context_system The system context once initialised
4832 protected static $systemcontext = null;
4835 * Resets the cache to remove all data.
4836 * @static
4838 protected static function reset_caches() {
4839 self::$cache_contextsbyid = array();
4840 self::$cache_contexts = array();
4841 self::$cache_count = 0;
4842 self::$cache_preloaded = array();
4844 self::$systemcontext = null;
4848 * Adds a context to the cache. If the cache is full, discards a batch of
4849 * older entries.
4851 * @static
4852 * @param context $context New context to add
4853 * @return void
4855 protected static function cache_add(context $context) {
4856 if (isset(self::$cache_contextsbyid[$context->id])) {
4857 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4858 return;
4861 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4862 $i = 0;
4863 foreach(self::$cache_contextsbyid as $ctx) {
4864 $i++;
4865 if ($i <= 100) {
4866 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4867 continue;
4869 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4870 // we remove oldest third of the contexts to make room for more contexts
4871 break;
4873 unset(self::$cache_contextsbyid[$ctx->id]);
4874 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4875 self::$cache_count--;
4879 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4880 self::$cache_contextsbyid[$context->id] = $context;
4881 self::$cache_count++;
4885 * Removes a context from the cache.
4887 * @static
4888 * @param context $context Context object to remove
4889 * @return void
4891 protected static function cache_remove(context $context) {
4892 if (!isset(self::$cache_contextsbyid[$context->id])) {
4893 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4894 return;
4896 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4897 unset(self::$cache_contextsbyid[$context->id]);
4899 self::$cache_count--;
4901 if (self::$cache_count < 0) {
4902 self::$cache_count = 0;
4907 * Gets a context from the cache.
4909 * @static
4910 * @param int $contextlevel Context level
4911 * @param int $instance Instance ID
4912 * @return context|bool Context or false if not in cache
4914 protected static function cache_get($contextlevel, $instance) {
4915 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4916 return self::$cache_contexts[$contextlevel][$instance];
4918 return false;
4922 * Gets a context from the cache based on its id.
4924 * @static
4925 * @param int $id Context ID
4926 * @return context|bool Context or false if not in cache
4928 protected static function cache_get_by_id($id) {
4929 if (isset(self::$cache_contextsbyid[$id])) {
4930 return self::$cache_contextsbyid[$id];
4932 return false;
4936 * Preloads context information from db record and strips the cached info.
4938 * @static
4939 * @param stdClass $rec
4940 * @return void (modifies $rec)
4942 protected static function preload_from_record(stdClass $rec) {
4943 if (empty($rec->ctxid) or empty($rec->ctxlevel) or !isset($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
4944 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4945 return;
4948 // note: in PHP5 the objects are passed by reference, no need to return $rec
4949 $record = new stdClass();
4950 $record->id = $rec->ctxid; unset($rec->ctxid);
4951 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
4952 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
4953 $record->path = $rec->ctxpath; unset($rec->ctxpath);
4954 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
4956 return context::create_instance_from_record($record);
4960 // ====== magic methods =======
4963 * Magic setter method, we do not want anybody to modify properties from the outside
4964 * @param string $name
4965 * @param mixed $value
4967 public function __set($name, $value) {
4968 debugging('Can not change context instance properties!');
4972 * Magic method getter, redirects to read only values.
4973 * @param string $name
4974 * @return mixed
4976 public function __get($name) {
4977 switch ($name) {
4978 case 'id': return $this->_id;
4979 case 'contextlevel': return $this->_contextlevel;
4980 case 'instanceid': return $this->_instanceid;
4981 case 'path': return $this->_path;
4982 case 'depth': return $this->_depth;
4984 default:
4985 debugging('Invalid context property accessed! '.$name);
4986 return null;
4991 * Full support for isset on our magic read only properties.
4992 * @param string $name
4993 * @return bool
4995 public function __isset($name) {
4996 switch ($name) {
4997 case 'id': return isset($this->_id);
4998 case 'contextlevel': return isset($this->_contextlevel);
4999 case 'instanceid': return isset($this->_instanceid);
5000 case 'path': return isset($this->_path);
5001 case 'depth': return isset($this->_depth);
5003 default: return false;
5009 * ALl properties are read only, sorry.
5010 * @param string $name
5012 public function __unset($name) {
5013 debugging('Can not unset context instance properties!');
5016 // ====== implementing method from interface IteratorAggregate ======
5019 * Create an iterator because magic vars can't be seen by 'foreach'.
5021 * Now we can convert context object to array using convert_to_array(),
5022 * and feed it properly to json_encode().
5024 public function getIterator() {
5025 $ret = array(
5026 'id' => $this->id,
5027 'contextlevel' => $this->contextlevel,
5028 'instanceid' => $this->instanceid,
5029 'path' => $this->path,
5030 'depth' => $this->depth
5032 return new ArrayIterator($ret);
5035 // ====== general context methods ======
5038 * Constructor is protected so that devs are forced to
5039 * use context_xxx::instance() or context::instance_by_id().
5041 * @param stdClass $record
5043 protected function __construct(stdClass $record) {
5044 $this->_id = (int)$record->id;
5045 $this->_contextlevel = (int)$record->contextlevel;
5046 $this->_instanceid = $record->instanceid;
5047 $this->_path = $record->path;
5048 $this->_depth = $record->depth;
5052 * This function is also used to work around 'protected' keyword problems in context_helper.
5053 * @static
5054 * @param stdClass $record
5055 * @return context instance
5057 protected static function create_instance_from_record(stdClass $record) {
5058 $classname = context_helper::get_class_for_level($record->contextlevel);
5060 if ($context = context::cache_get_by_id($record->id)) {
5061 return $context;
5064 $context = new $classname($record);
5065 context::cache_add($context);
5067 return $context;
5071 * Copy prepared new contexts from temp table to context table,
5072 * we do this in db specific way for perf reasons only.
5073 * @static
5075 protected static function merge_context_temp_table() {
5076 global $DB;
5078 /* MDL-11347:
5079 * - mysql does not allow to use FROM in UPDATE statements
5080 * - using two tables after UPDATE works in mysql, but might give unexpected
5081 * results in pg 8 (depends on configuration)
5082 * - using table alias in UPDATE does not work in pg < 8.2
5084 * Different code for each database - mostly for performance reasons
5087 $dbfamily = $DB->get_dbfamily();
5088 if ($dbfamily == 'mysql') {
5089 $updatesql = "UPDATE {context} ct, {context_temp} temp
5090 SET ct.path = temp.path,
5091 ct.depth = temp.depth
5092 WHERE ct.id = temp.id";
5093 } else if ($dbfamily == 'oracle') {
5094 $updatesql = "UPDATE {context} ct
5095 SET (ct.path, ct.depth) =
5096 (SELECT temp.path, temp.depth
5097 FROM {context_temp} temp
5098 WHERE temp.id=ct.id)
5099 WHERE EXISTS (SELECT 'x'
5100 FROM {context_temp} temp
5101 WHERE temp.id = ct.id)";
5102 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5103 $updatesql = "UPDATE {context}
5104 SET path = temp.path,
5105 depth = temp.depth
5106 FROM {context_temp} temp
5107 WHERE temp.id={context}.id";
5108 } else {
5109 // sqlite and others
5110 $updatesql = "UPDATE {context}
5111 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5112 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5113 WHERE id IN (SELECT id FROM {context_temp})";
5116 $DB->execute($updatesql);
5120 * Get a context instance as an object, from a given context id.
5122 * @static
5123 * @param int $id context id
5124 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5125 * MUST_EXIST means throw exception if no record found
5126 * @return context|bool the context object or false if not found
5128 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5129 global $DB;
5131 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5132 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5133 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5136 if ($id == SYSCONTEXTID) {
5137 return context_system::instance(0, $strictness);
5140 if (is_array($id) or is_object($id) or empty($id)) {
5141 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5144 if ($context = context::cache_get_by_id($id)) {
5145 return $context;
5148 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5149 return context::create_instance_from_record($record);
5152 return false;
5156 * Update context info after moving context in the tree structure.
5158 * @param context $newparent
5159 * @return void
5161 public function update_moved(context $newparent) {
5162 global $DB;
5164 $frompath = $this->_path;
5165 $newpath = $newparent->path . '/' . $this->_id;
5167 $trans = $DB->start_delegated_transaction();
5169 $this->mark_dirty();
5171 $setdepth = '';
5172 if (($newparent->depth +1) != $this->_depth) {
5173 $diff = $newparent->depth - $this->_depth + 1;
5174 $setdepth = ", depth = depth + $diff";
5176 $sql = "UPDATE {context}
5177 SET path = ?
5178 $setdepth
5179 WHERE id = ?";
5180 $params = array($newpath, $this->_id);
5181 $DB->execute($sql, $params);
5183 $this->_path = $newpath;
5184 $this->_depth = $newparent->depth + 1;
5186 $sql = "UPDATE {context}
5187 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5188 $setdepth
5189 WHERE path LIKE ?";
5190 $params = array($newpath, "{$frompath}/%");
5191 $DB->execute($sql, $params);
5193 $this->mark_dirty();
5195 context::reset_caches();
5197 $trans->allow_commit();
5201 * Remove all context path info and optionally rebuild it.
5203 * @param bool $rebuild
5204 * @return void
5206 public function reset_paths($rebuild = true) {
5207 global $DB;
5209 if ($this->_path) {
5210 $this->mark_dirty();
5212 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5213 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5214 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5215 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5216 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5217 $this->_depth = 0;
5218 $this->_path = null;
5221 if ($rebuild) {
5222 context_helper::build_all_paths(false);
5225 context::reset_caches();
5229 * Delete all data linked to content, do not delete the context record itself
5231 public function delete_content() {
5232 global $CFG, $DB;
5234 blocks_delete_all_for_context($this->_id);
5235 filter_delete_all_for_context($this->_id);
5237 require_once($CFG->dirroot . '/comment/lib.php');
5238 comment::delete_comments(array('contextid'=>$this->_id));
5240 require_once($CFG->dirroot.'/rating/lib.php');
5241 $delopt = new stdclass();
5242 $delopt->contextid = $this->_id;
5243 $rm = new rating_manager();
5244 $rm->delete_ratings($delopt);
5246 // delete all files attached to this context
5247 $fs = get_file_storage();
5248 $fs->delete_area_files($this->_id);
5250 // Delete all repository instances attached to this context.
5251 require_once($CFG->dirroot . '/repository/lib.php');
5252 repository::delete_all_for_context($this->_id);
5254 // delete all advanced grading data attached to this context
5255 require_once($CFG->dirroot.'/grade/grading/lib.php');
5256 grading_manager::delete_all_for_context($this->_id);
5258 // now delete stuff from role related tables, role_unassign_all
5259 // and unenrol should be called earlier to do proper cleanup
5260 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5261 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5262 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5266 * Delete the context content and the context record itself
5268 public function delete() {
5269 global $DB;
5271 if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5272 throw new coding_exception('Cannot delete system context');
5275 // double check the context still exists
5276 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5277 context::cache_remove($this);
5278 return;
5281 $this->delete_content();
5282 $DB->delete_records('context', array('id'=>$this->_id));
5283 // purge static context cache if entry present
5284 context::cache_remove($this);
5286 // do not mark dirty contexts if parents unknown
5287 if (!is_null($this->_path) and $this->_depth > 0) {
5288 $this->mark_dirty();
5292 // ====== context level related methods ======
5295 * Utility method for context creation
5297 * @static
5298 * @param int $contextlevel
5299 * @param int $instanceid
5300 * @param string $parentpath
5301 * @return stdClass context record
5303 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5304 global $DB;
5306 $record = new stdClass();
5307 $record->contextlevel = $contextlevel;
5308 $record->instanceid = $instanceid;
5309 $record->depth = 0;
5310 $record->path = null; //not known before insert
5312 $record->id = $DB->insert_record('context', $record);
5314 // now add path if known - it can be added later
5315 if (!is_null($parentpath)) {
5316 $record->path = $parentpath.'/'.$record->id;
5317 $record->depth = substr_count($record->path, '/');
5318 $DB->update_record('context', $record);
5321 return $record;
5325 * Returns human readable context identifier.
5327 * @param boolean $withprefix whether to prefix the name of the context with the
5328 * type of context, e.g. User, Course, Forum, etc.
5329 * @param boolean $short whether to use the short name of the thing. Only applies
5330 * to course contexts
5331 * @return string the human readable context name.
5333 public function get_context_name($withprefix = true, $short = false) {
5334 // must be implemented in all context levels
5335 throw new coding_exception('can not get name of abstract context');
5339 * Returns the most relevant URL for this context.
5341 * @return moodle_url
5343 public abstract function get_url();
5346 * Returns array of relevant context capability records.
5348 * @return array
5350 public abstract function get_capabilities();
5353 * Recursive function which, given a context, find all its children context ids.
5355 * For course category contexts it will return immediate children and all subcategory contexts.
5356 * It will NOT recurse into courses or subcategories categories.
5357 * If you want to do that, call it on the returned courses/categories.
5359 * When called for a course context, it will return the modules and blocks
5360 * displayed in the course page and blocks displayed on the module pages.
5362 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5363 * contexts ;-)
5365 * @return array Array of child records
5367 public function get_child_contexts() {
5368 global $DB;
5370 if (empty($this->_path) or empty($this->_depth)) {
5371 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5372 return array();
5375 $sql = "SELECT ctx.*
5376 FROM {context} ctx
5377 WHERE ctx.path LIKE ?";
5378 $params = array($this->_path.'/%');
5379 $records = $DB->get_records_sql($sql, $params);
5381 $result = array();
5382 foreach ($records as $record) {
5383 $result[$record->id] = context::create_instance_from_record($record);
5386 return $result;
5390 * Returns parent contexts of this context in reversed order, i.e. parent first,
5391 * then grand parent, etc.
5393 * @param bool $includeself tre means include self too
5394 * @return array of context instances
5396 public function get_parent_contexts($includeself = false) {
5397 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5398 return array();
5401 $result = array();
5402 foreach ($contextids as $contextid) {
5403 $parent = context::instance_by_id($contextid, MUST_EXIST);
5404 $result[$parent->id] = $parent;
5407 return $result;
5411 * Returns parent contexts of this context in reversed order, i.e. parent first,
5412 * then grand parent, etc.
5414 * @param bool $includeself tre means include self too
5415 * @return array of context ids
5417 public function get_parent_context_ids($includeself = false) {
5418 if (empty($this->_path)) {
5419 return array();
5422 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5423 $parentcontexts = explode('/', $parentcontexts);
5424 if (!$includeself) {
5425 array_pop($parentcontexts); // and remove its own id
5428 return array_reverse($parentcontexts);
5432 * Returns parent context
5434 * @return context
5436 public function get_parent_context() {
5437 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5438 return false;
5441 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5442 $parentcontexts = explode('/', $parentcontexts);
5443 array_pop($parentcontexts); // self
5444 $contextid = array_pop($parentcontexts); // immediate parent
5446 return context::instance_by_id($contextid, MUST_EXIST);
5450 * Is this context part of any course? If yes return course context.
5452 * @param bool $strict true means throw exception if not found, false means return false if not found
5453 * @return context_course context of the enclosing course, null if not found or exception
5455 public function get_course_context($strict = true) {
5456 if ($strict) {
5457 throw new coding_exception('Context does not belong to any course.');
5458 } else {
5459 return false;
5464 * Returns sql necessary for purging of stale context instances.
5466 * @static
5467 * @return string cleanup SQL
5469 protected static function get_cleanup_sql() {
5470 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5474 * Rebuild context paths and depths at context level.
5476 * @static
5477 * @param bool $force
5478 * @return void
5480 protected static function build_paths($force) {
5481 throw new coding_exception('build_paths() method must be implemented in all context levels');
5485 * Create missing context instances at given level
5487 * @static
5488 * @return void
5490 protected static function create_level_instances() {
5491 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5495 * Reset all cached permissions and definitions if the necessary.
5496 * @return void
5498 public function reload_if_dirty() {
5499 global $ACCESSLIB_PRIVATE, $USER;
5501 // Load dirty contexts list if needed
5502 if (CLI_SCRIPT) {
5503 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5504 // we do not load dirty flags in CLI and cron
5505 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5507 } else {
5508 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5509 if (!isset($USER->access['time'])) {
5510 // nothing was loaded yet, we do not need to check dirty contexts now
5511 return;
5513 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5514 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5518 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5519 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5520 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5521 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5522 reload_all_capabilities();
5523 break;
5529 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5531 public function mark_dirty() {
5532 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5534 if (during_initial_install()) {
5535 return;
5538 // only if it is a non-empty string
5539 if (is_string($this->_path) && $this->_path !== '') {
5540 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5541 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5542 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5543 } else {
5544 if (CLI_SCRIPT) {
5545 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5546 } else {
5547 if (isset($USER->access['time'])) {
5548 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5549 } else {
5550 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5552 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5561 * Context maintenance and helper methods.
5563 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5564 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5565 * level implementation from the rest of code, the code completion returns what developers need.
5567 * Thank you Tim Hunt for helping me with this nasty trick.
5569 * @package core_access
5570 * @category access
5571 * @copyright Petr Skoda {@link http://skodak.org}
5572 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5573 * @since Moodle 2.2
5575 class context_helper extends context {
5578 * @var array An array mapping context levels to classes
5580 private static $alllevels;
5583 * Instance does not make sense here, only static use
5585 protected function __construct() {
5589 * Reset internal context levels array.
5591 public static function reset_levels() {
5592 self::$alllevels = null;
5596 * Initialise context levels, call before using self::$alllevels.
5598 private static function init_levels() {
5599 global $CFG;
5601 if (isset(self::$alllevels)) {
5602 return;
5604 self::$alllevels = array(
5605 CONTEXT_SYSTEM => 'context_system',
5606 CONTEXT_USER => 'context_user',
5607 CONTEXT_COURSECAT => 'context_coursecat',
5608 CONTEXT_COURSE => 'context_course',
5609 CONTEXT_MODULE => 'context_module',
5610 CONTEXT_BLOCK => 'context_block',
5613 if (empty($CFG->custom_context_classes)) {
5614 return;
5617 $levels = $CFG->custom_context_classes;
5618 if (!is_array($levels)) {
5619 $levels = @unserialize($levels);
5621 if (!is_array($levels)) {
5622 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
5623 return;
5626 // Unsupported custom levels, use with care!!!
5627 foreach ($levels as $level => $classname) {
5628 self::$alllevels[$level] = $classname;
5630 ksort(self::$alllevels);
5634 * Returns a class name of the context level class
5636 * @static
5637 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5638 * @return string class name of the context class
5640 public static function get_class_for_level($contextlevel) {
5641 self::init_levels();
5642 if (isset(self::$alllevels[$contextlevel])) {
5643 return self::$alllevels[$contextlevel];
5644 } else {
5645 throw new coding_exception('Invalid context level specified');
5650 * Returns a list of all context levels
5652 * @static
5653 * @return array int=>string (level=>level class name)
5655 public static function get_all_levels() {
5656 self::init_levels();
5657 return self::$alllevels;
5661 * Remove stale contexts that belonged to deleted instances.
5662 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5664 * @static
5665 * @return void
5667 public static function cleanup_instances() {
5668 global $DB;
5669 self::init_levels();
5671 $sqls = array();
5672 foreach (self::$alllevels as $level=>$classname) {
5673 $sqls[] = $classname::get_cleanup_sql();
5676 $sql = implode(" UNION ", $sqls);
5678 // it is probably better to use transactions, it might be faster too
5679 $transaction = $DB->start_delegated_transaction();
5681 $rs = $DB->get_recordset_sql($sql);
5682 foreach ($rs as $record) {
5683 $context = context::create_instance_from_record($record);
5684 $context->delete();
5686 $rs->close();
5688 $transaction->allow_commit();
5692 * Create all context instances at the given level and above.
5694 * @static
5695 * @param int $contextlevel null means all levels
5696 * @param bool $buildpaths
5697 * @return void
5699 public static function create_instances($contextlevel = null, $buildpaths = true) {
5700 self::init_levels();
5701 foreach (self::$alllevels as $level=>$classname) {
5702 if ($contextlevel and $level > $contextlevel) {
5703 // skip potential sub-contexts
5704 continue;
5706 $classname::create_level_instances();
5707 if ($buildpaths) {
5708 $classname::build_paths(false);
5714 * Rebuild paths and depths in all context levels.
5716 * @static
5717 * @param bool $force false means add missing only
5718 * @return void
5720 public static function build_all_paths($force = false) {
5721 self::init_levels();
5722 foreach (self::$alllevels as $classname) {
5723 $classname::build_paths($force);
5726 // reset static course cache - it might have incorrect cached data
5727 accesslib_clear_all_caches(true);
5731 * Resets the cache to remove all data.
5732 * @static
5734 public static function reset_caches() {
5735 context::reset_caches();
5739 * Returns all fields necessary for context preloading from user $rec.
5741 * This helps with performance when dealing with hundreds of contexts.
5743 * @static
5744 * @param string $tablealias context table alias in the query
5745 * @return array (table.column=>alias, ...)
5747 public static function get_preload_record_columns($tablealias) {
5748 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5752 * Returns all fields necessary for context preloading from user $rec.
5754 * This helps with performance when dealing with hundreds of contexts.
5756 * @static
5757 * @param string $tablealias context table alias in the query
5758 * @return string
5760 public static function get_preload_record_columns_sql($tablealias) {
5761 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5765 * Preloads context information from db record and strips the cached info.
5767 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5769 * @static
5770 * @param stdClass $rec
5771 * @return void (modifies $rec)
5773 public static function preload_from_record(stdClass $rec) {
5774 context::preload_from_record($rec);
5778 * Preload all contexts instances from course.
5780 * To be used if you expect multiple queries for course activities...
5782 * @static
5783 * @param int $courseid
5785 public static function preload_course($courseid) {
5786 // Users can call this multiple times without doing any harm
5787 if (isset(context::$cache_preloaded[$courseid])) {
5788 return;
5790 $coursecontext = context_course::instance($courseid);
5791 $coursecontext->get_child_contexts();
5793 context::$cache_preloaded[$courseid] = true;
5797 * Delete context instance
5799 * @static
5800 * @param int $contextlevel
5801 * @param int $instanceid
5802 * @return void
5804 public static function delete_instance($contextlevel, $instanceid) {
5805 global $DB;
5807 // double check the context still exists
5808 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5809 $context = context::create_instance_from_record($record);
5810 $context->delete();
5811 } else {
5812 // we should try to purge the cache anyway
5817 * Returns the name of specified context level
5819 * @static
5820 * @param int $contextlevel
5821 * @return string name of the context level
5823 public static function get_level_name($contextlevel) {
5824 $classname = context_helper::get_class_for_level($contextlevel);
5825 return $classname::get_level_name();
5829 * not used
5831 public function get_url() {
5835 * not used
5837 public function get_capabilities() {
5843 * System context class
5845 * @package core_access
5846 * @category access
5847 * @copyright Petr Skoda {@link http://skodak.org}
5848 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5849 * @since Moodle 2.2
5851 class context_system extends context {
5853 * Please use context_system::instance() if you need the instance of context.
5855 * @param stdClass $record
5857 protected function __construct(stdClass $record) {
5858 parent::__construct($record);
5859 if ($record->contextlevel != CONTEXT_SYSTEM) {
5860 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5865 * Returns human readable context level name.
5867 * @static
5868 * @return string the human readable context level name.
5870 public static function get_level_name() {
5871 return get_string('coresystem');
5875 * Returns human readable context identifier.
5877 * @param boolean $withprefix does not apply to system context
5878 * @param boolean $short does not apply to system context
5879 * @return string the human readable context name.
5881 public function get_context_name($withprefix = true, $short = false) {
5882 return self::get_level_name();
5886 * Returns the most relevant URL for this context.
5888 * @return moodle_url
5890 public function get_url() {
5891 return new moodle_url('/');
5895 * Returns array of relevant context capability records.
5897 * @return array
5899 public function get_capabilities() {
5900 global $DB;
5902 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5904 $params = array();
5905 $sql = "SELECT *
5906 FROM {capabilities}";
5908 return $DB->get_records_sql($sql.' '.$sort, $params);
5912 * Create missing context instances at system context
5913 * @static
5915 protected static function create_level_instances() {
5916 // nothing to do here, the system context is created automatically in installer
5917 self::instance(0);
5921 * Returns system context instance.
5923 * @static
5924 * @param int $instanceid should be 0
5925 * @param int $strictness
5926 * @param bool $cache
5927 * @return context_system context instance
5929 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
5930 global $DB;
5932 if ($instanceid != 0) {
5933 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5936 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5937 if (!isset(context::$systemcontext)) {
5938 $record = new stdClass();
5939 $record->id = SYSCONTEXTID;
5940 $record->contextlevel = CONTEXT_SYSTEM;
5941 $record->instanceid = 0;
5942 $record->path = '/'.SYSCONTEXTID;
5943 $record->depth = 1;
5944 context::$systemcontext = new context_system($record);
5946 return context::$systemcontext;
5950 try {
5951 // We ignore the strictness completely because system context must exist except during install.
5952 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5953 } catch (dml_exception $e) {
5954 //table or record does not exist
5955 if (!during_initial_install()) {
5956 // do not mess with system context after install, it simply must exist
5957 throw $e;
5959 $record = null;
5962 if (!$record) {
5963 $record = new stdClass();
5964 $record->contextlevel = CONTEXT_SYSTEM;
5965 $record->instanceid = 0;
5966 $record->depth = 1;
5967 $record->path = null; //not known before insert
5969 try {
5970 if ($DB->count_records('context')) {
5971 // contexts already exist, this is very weird, system must be first!!!
5972 return null;
5974 if (defined('SYSCONTEXTID')) {
5975 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5976 $record->id = SYSCONTEXTID;
5977 $DB->import_record('context', $record);
5978 $DB->get_manager()->reset_sequence('context');
5979 } else {
5980 $record->id = $DB->insert_record('context', $record);
5982 } catch (dml_exception $e) {
5983 // can not create context - table does not exist yet, sorry
5984 return null;
5988 if ($record->instanceid != 0) {
5989 // this is very weird, somebody must be messing with context table
5990 debugging('Invalid system context detected');
5993 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5994 // fix path if necessary, initial install or path reset
5995 $record->depth = 1;
5996 $record->path = '/'.$record->id;
5997 $DB->update_record('context', $record);
6000 if (!defined('SYSCONTEXTID')) {
6001 define('SYSCONTEXTID', $record->id);
6004 context::$systemcontext = new context_system($record);
6005 return context::$systemcontext;
6009 * Returns all site contexts except the system context, DO NOT call on production servers!!
6011 * Contexts are not cached.
6013 * @return array
6015 public function get_child_contexts() {
6016 global $DB;
6018 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6020 // Just get all the contexts except for CONTEXT_SYSTEM level
6021 // and hope we don't OOM in the process - don't cache
6022 $sql = "SELECT c.*
6023 FROM {context} c
6024 WHERE contextlevel > ".CONTEXT_SYSTEM;
6025 $records = $DB->get_records_sql($sql);
6027 $result = array();
6028 foreach ($records as $record) {
6029 $result[$record->id] = context::create_instance_from_record($record);
6032 return $result;
6036 * Returns sql necessary for purging of stale context instances.
6038 * @static
6039 * @return string cleanup SQL
6041 protected static function get_cleanup_sql() {
6042 $sql = "
6043 SELECT c.*
6044 FROM {context} c
6045 WHERE 1=2
6048 return $sql;
6052 * Rebuild context paths and depths at system context level.
6054 * @static
6055 * @param bool $force
6057 protected static function build_paths($force) {
6058 global $DB;
6060 /* note: ignore $force here, we always do full test of system context */
6062 // exactly one record must exist
6063 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6065 if ($record->instanceid != 0) {
6066 debugging('Invalid system context detected');
6069 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6070 debugging('Invalid SYSCONTEXTID detected');
6073 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6074 // fix path if necessary, initial install or path reset
6075 $record->depth = 1;
6076 $record->path = '/'.$record->id;
6077 $DB->update_record('context', $record);
6084 * User context class
6086 * @package core_access
6087 * @category access
6088 * @copyright Petr Skoda {@link http://skodak.org}
6089 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6090 * @since Moodle 2.2
6092 class context_user extends context {
6094 * Please use context_user::instance($userid) if you need the instance of context.
6095 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6097 * @param stdClass $record
6099 protected function __construct(stdClass $record) {
6100 parent::__construct($record);
6101 if ($record->contextlevel != CONTEXT_USER) {
6102 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6107 * Returns human readable context level name.
6109 * @static
6110 * @return string the human readable context level name.
6112 public static function get_level_name() {
6113 return get_string('user');
6117 * Returns human readable context identifier.
6119 * @param boolean $withprefix whether to prefix the name of the context with User
6120 * @param boolean $short does not apply to user context
6121 * @return string the human readable context name.
6123 public function get_context_name($withprefix = true, $short = false) {
6124 global $DB;
6126 $name = '';
6127 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6128 if ($withprefix){
6129 $name = get_string('user').': ';
6131 $name .= fullname($user);
6133 return $name;
6137 * Returns the most relevant URL for this context.
6139 * @return moodle_url
6141 public function get_url() {
6142 global $COURSE;
6144 if ($COURSE->id == SITEID) {
6145 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6146 } else {
6147 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6149 return $url;
6153 * Returns array of relevant context capability records.
6155 * @return array
6157 public function get_capabilities() {
6158 global $DB;
6160 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6162 $extracaps = array('moodle/grade:viewall');
6163 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6164 $sql = "SELECT *
6165 FROM {capabilities}
6166 WHERE contextlevel = ".CONTEXT_USER."
6167 OR name $extra";
6169 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6173 * Returns user context instance.
6175 * @static
6176 * @param int $userid id from {user} table
6177 * @param int $strictness
6178 * @return context_user context instance
6180 public static function instance($userid, $strictness = MUST_EXIST) {
6181 global $DB;
6183 if ($context = context::cache_get(CONTEXT_USER, $userid)) {
6184 return $context;
6187 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER, 'instanceid' => $userid))) {
6188 if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6189 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6193 if ($record) {
6194 $context = new context_user($record);
6195 context::cache_add($context);
6196 return $context;
6199 return false;
6203 * Create missing context instances at user context level
6204 * @static
6206 protected static function create_level_instances() {
6207 global $DB;
6209 $sql = "SELECT ".CONTEXT_USER.", u.id
6210 FROM {user} u
6211 WHERE u.deleted = 0
6212 AND NOT EXISTS (SELECT 'x'
6213 FROM {context} cx
6214 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6215 $contextdata = $DB->get_recordset_sql($sql);
6216 foreach ($contextdata as $context) {
6217 context::insert_context_record(CONTEXT_USER, $context->id, null);
6219 $contextdata->close();
6223 * Returns sql necessary for purging of stale context instances.
6225 * @static
6226 * @return string cleanup SQL
6228 protected static function get_cleanup_sql() {
6229 $sql = "
6230 SELECT c.*
6231 FROM {context} c
6232 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6233 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6236 return $sql;
6240 * Rebuild context paths and depths at user context level.
6242 * @static
6243 * @param bool $force
6245 protected static function build_paths($force) {
6246 global $DB;
6248 // First update normal users.
6249 $path = $DB->sql_concat('?', 'id');
6250 $pathstart = '/' . SYSCONTEXTID . '/';
6251 $params = array($pathstart);
6253 if ($force) {
6254 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6255 $params[] = $pathstart;
6256 } else {
6257 $where = "depth = 0 OR path IS NULL";
6260 $sql = "UPDATE {context}
6261 SET depth = 2,
6262 path = {$path}
6263 WHERE contextlevel = " . CONTEXT_USER . "
6264 AND ($where)";
6265 $DB->execute($sql, $params);
6271 * Course category context class
6273 * @package core_access
6274 * @category access
6275 * @copyright Petr Skoda {@link http://skodak.org}
6276 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6277 * @since Moodle 2.2
6279 class context_coursecat extends context {
6281 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6282 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6284 * @param stdClass $record
6286 protected function __construct(stdClass $record) {
6287 parent::__construct($record);
6288 if ($record->contextlevel != CONTEXT_COURSECAT) {
6289 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6294 * Returns human readable context level name.
6296 * @static
6297 * @return string the human readable context level name.
6299 public static function get_level_name() {
6300 return get_string('category');
6304 * Returns human readable context identifier.
6306 * @param boolean $withprefix whether to prefix the name of the context with Category
6307 * @param boolean $short does not apply to course categories
6308 * @return string the human readable context name.
6310 public function get_context_name($withprefix = true, $short = false) {
6311 global $DB;
6313 $name = '';
6314 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6315 if ($withprefix){
6316 $name = get_string('category').': ';
6318 $name .= format_string($category->name, true, array('context' => $this));
6320 return $name;
6324 * Returns the most relevant URL for this context.
6326 * @return moodle_url
6328 public function get_url() {
6329 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6333 * Returns array of relevant context capability records.
6335 * @return array
6337 public function get_capabilities() {
6338 global $DB;
6340 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6342 $params = array();
6343 $sql = "SELECT *
6344 FROM {capabilities}
6345 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6347 return $DB->get_records_sql($sql.' '.$sort, $params);
6351 * Returns course category context instance.
6353 * @static
6354 * @param int $categoryid id from {course_categories} table
6355 * @param int $strictness
6356 * @return context_coursecat context instance
6358 public static function instance($categoryid, $strictness = MUST_EXIST) {
6359 global $DB;
6361 if ($context = context::cache_get(CONTEXT_COURSECAT, $categoryid)) {
6362 return $context;
6365 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT, 'instanceid' => $categoryid))) {
6366 if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6367 if ($category->parent) {
6368 $parentcontext = context_coursecat::instance($category->parent);
6369 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6370 } else {
6371 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6376 if ($record) {
6377 $context = new context_coursecat($record);
6378 context::cache_add($context);
6379 return $context;
6382 return false;
6386 * Returns immediate child contexts of category and all subcategories,
6387 * children of subcategories and courses are not returned.
6389 * @return array
6391 public function get_child_contexts() {
6392 global $DB;
6394 if (empty($this->_path) or empty($this->_depth)) {
6395 debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6396 return array();
6399 $sql = "SELECT ctx.*
6400 FROM {context} ctx
6401 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6402 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6403 $records = $DB->get_records_sql($sql, $params);
6405 $result = array();
6406 foreach ($records as $record) {
6407 $result[$record->id] = context::create_instance_from_record($record);
6410 return $result;
6414 * Create missing context instances at course category context level
6415 * @static
6417 protected static function create_level_instances() {
6418 global $DB;
6420 $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6421 FROM {course_categories} cc
6422 WHERE NOT EXISTS (SELECT 'x'
6423 FROM {context} cx
6424 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6425 $contextdata = $DB->get_recordset_sql($sql);
6426 foreach ($contextdata as $context) {
6427 context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6429 $contextdata->close();
6433 * Returns sql necessary for purging of stale context instances.
6435 * @static
6436 * @return string cleanup SQL
6438 protected static function get_cleanup_sql() {
6439 $sql = "
6440 SELECT c.*
6441 FROM {context} c
6442 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6443 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6446 return $sql;
6450 * Rebuild context paths and depths at course category context level.
6452 * @static
6453 * @param bool $force
6455 protected static function build_paths($force) {
6456 global $DB;
6458 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6459 if ($force) {
6460 $ctxemptyclause = $emptyclause = '';
6461 } else {
6462 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6463 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6466 $base = '/'.SYSCONTEXTID;
6468 // Normal top level categories
6469 $sql = "UPDATE {context}
6470 SET depth=2,
6471 path=".$DB->sql_concat("'$base/'", 'id')."
6472 WHERE contextlevel=".CONTEXT_COURSECAT."
6473 AND EXISTS (SELECT 'x'
6474 FROM {course_categories} cc
6475 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6476 $emptyclause";
6477 $DB->execute($sql);
6479 // Deeper categories - one query per depthlevel
6480 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6481 for ($n=2; $n<=$maxdepth; $n++) {
6482 $sql = "INSERT INTO {context_temp} (id, path, depth)
6483 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6484 FROM {context} ctx
6485 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6486 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6487 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6488 $ctxemptyclause";
6489 $trans = $DB->start_delegated_transaction();
6490 $DB->delete_records('context_temp');
6491 $DB->execute($sql);
6492 context::merge_context_temp_table();
6493 $DB->delete_records('context_temp');
6494 $trans->allow_commit();
6503 * Course context class
6505 * @package core_access
6506 * @category access
6507 * @copyright Petr Skoda {@link http://skodak.org}
6508 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6509 * @since Moodle 2.2
6511 class context_course extends context {
6513 * Please use context_course::instance($courseid) if you need the instance of context.
6514 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6516 * @param stdClass $record
6518 protected function __construct(stdClass $record) {
6519 parent::__construct($record);
6520 if ($record->contextlevel != CONTEXT_COURSE) {
6521 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6526 * Returns human readable context level name.
6528 * @static
6529 * @return string the human readable context level name.
6531 public static function get_level_name() {
6532 return get_string('course');
6536 * Returns human readable context identifier.
6538 * @param boolean $withprefix whether to prefix the name of the context with Course
6539 * @param boolean $short whether to use the short name of the thing.
6540 * @return string the human readable context name.
6542 public function get_context_name($withprefix = true, $short = false) {
6543 global $DB;
6545 $name = '';
6546 if ($this->_instanceid == SITEID) {
6547 $name = get_string('frontpage', 'admin');
6548 } else {
6549 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6550 if ($withprefix){
6551 $name = get_string('course').': ';
6553 if ($short){
6554 $name .= format_string($course->shortname, true, array('context' => $this));
6555 } else {
6556 $name .= format_string(get_course_display_name_for_list($course));
6560 return $name;
6564 * Returns the most relevant URL for this context.
6566 * @return moodle_url
6568 public function get_url() {
6569 if ($this->_instanceid != SITEID) {
6570 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6573 return new moodle_url('/');
6577 * Returns array of relevant context capability records.
6579 * @return array
6581 public function get_capabilities() {
6582 global $DB;
6584 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6586 $params = array();
6587 $sql = "SELECT *
6588 FROM {capabilities}
6589 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6591 return $DB->get_records_sql($sql.' '.$sort, $params);
6595 * Is this context part of any course? If yes return course context.
6597 * @param bool $strict true means throw exception if not found, false means return false if not found
6598 * @return context_course context of the enclosing course, null if not found or exception
6600 public function get_course_context($strict = true) {
6601 return $this;
6605 * Returns course context instance.
6607 * @static
6608 * @param int $courseid id from {course} table
6609 * @param int $strictness
6610 * @return context_course context instance
6612 public static function instance($courseid, $strictness = MUST_EXIST) {
6613 global $DB;
6615 if ($context = context::cache_get(CONTEXT_COURSE, $courseid)) {
6616 return $context;
6619 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $courseid))) {
6620 if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
6621 if ($course->category) {
6622 $parentcontext = context_coursecat::instance($course->category);
6623 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6624 } else {
6625 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6630 if ($record) {
6631 $context = new context_course($record);
6632 context::cache_add($context);
6633 return $context;
6636 return false;
6640 * Create missing context instances at course context level
6641 * @static
6643 protected static function create_level_instances() {
6644 global $DB;
6646 $sql = "SELECT ".CONTEXT_COURSE.", c.id
6647 FROM {course} c
6648 WHERE NOT EXISTS (SELECT 'x'
6649 FROM {context} cx
6650 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6651 $contextdata = $DB->get_recordset_sql($sql);
6652 foreach ($contextdata as $context) {
6653 context::insert_context_record(CONTEXT_COURSE, $context->id, null);
6655 $contextdata->close();
6659 * Returns sql necessary for purging of stale context instances.
6661 * @static
6662 * @return string cleanup SQL
6664 protected static function get_cleanup_sql() {
6665 $sql = "
6666 SELECT c.*
6667 FROM {context} c
6668 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6669 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6672 return $sql;
6676 * Rebuild context paths and depths at course context level.
6678 * @static
6679 * @param bool $force
6681 protected static function build_paths($force) {
6682 global $DB;
6684 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6685 if ($force) {
6686 $ctxemptyclause = $emptyclause = '';
6687 } else {
6688 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6689 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6692 $base = '/'.SYSCONTEXTID;
6694 // Standard frontpage
6695 $sql = "UPDATE {context}
6696 SET depth = 2,
6697 path = ".$DB->sql_concat("'$base/'", 'id')."
6698 WHERE contextlevel = ".CONTEXT_COURSE."
6699 AND EXISTS (SELECT 'x'
6700 FROM {course} c
6701 WHERE c.id = {context}.instanceid AND c.category = 0)
6702 $emptyclause";
6703 $DB->execute($sql);
6705 // standard courses
6706 $sql = "INSERT INTO {context_temp} (id, path, depth)
6707 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6708 FROM {context} ctx
6709 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6710 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6711 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6712 $ctxemptyclause";
6713 $trans = $DB->start_delegated_transaction();
6714 $DB->delete_records('context_temp');
6715 $DB->execute($sql);
6716 context::merge_context_temp_table();
6717 $DB->delete_records('context_temp');
6718 $trans->allow_commit();
6725 * Course module context class
6727 * @package core_access
6728 * @category access
6729 * @copyright Petr Skoda {@link http://skodak.org}
6730 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6731 * @since Moodle 2.2
6733 class context_module extends context {
6735 * Please use context_module::instance($cmid) if you need the instance of context.
6736 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6738 * @param stdClass $record
6740 protected function __construct(stdClass $record) {
6741 parent::__construct($record);
6742 if ($record->contextlevel != CONTEXT_MODULE) {
6743 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6748 * Returns human readable context level name.
6750 * @static
6751 * @return string the human readable context level name.
6753 public static function get_level_name() {
6754 return get_string('activitymodule');
6758 * Returns human readable context identifier.
6760 * @param boolean $withprefix whether to prefix the name of the context with the
6761 * module name, e.g. Forum, Glossary, etc.
6762 * @param boolean $short does not apply to module context
6763 * @return string the human readable context name.
6765 public function get_context_name($withprefix = true, $short = false) {
6766 global $DB;
6768 $name = '';
6769 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6770 FROM {course_modules} cm
6771 JOIN {modules} md ON md.id = cm.module
6772 WHERE cm.id = ?", array($this->_instanceid))) {
6773 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6774 if ($withprefix){
6775 $name = get_string('modulename', $cm->modname).': ';
6777 $name .= format_string($mod->name, true, array('context' => $this));
6780 return $name;
6784 * Returns the most relevant URL for this context.
6786 * @return moodle_url
6788 public function get_url() {
6789 global $DB;
6791 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6792 FROM {course_modules} cm
6793 JOIN {modules} md ON md.id = cm.module
6794 WHERE cm.id = ?", array($this->_instanceid))) {
6795 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6798 return new moodle_url('/');
6802 * Returns array of relevant context capability records.
6804 * @return array
6806 public function get_capabilities() {
6807 global $DB, $CFG;
6809 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6811 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6812 $module = $DB->get_record('modules', array('id'=>$cm->module));
6814 $subcaps = array();
6815 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6816 if (file_exists($subpluginsfile)) {
6817 $subplugins = array(); // should be redefined in the file
6818 include($subpluginsfile);
6819 if (!empty($subplugins)) {
6820 foreach (array_keys($subplugins) as $subplugintype) {
6821 foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
6822 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6828 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6829 $extracaps = array();
6830 if (file_exists($modfile)) {
6831 include_once($modfile);
6832 $modfunction = $module->name.'_get_extra_capabilities';
6833 if (function_exists($modfunction)) {
6834 $extracaps = $modfunction();
6838 $extracaps = array_merge($subcaps, $extracaps);
6839 $extra = '';
6840 list($extra, $params) = $DB->get_in_or_equal(
6841 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
6842 if (!empty($extra)) {
6843 $extra = "OR name $extra";
6845 $sql = "SELECT *
6846 FROM {capabilities}
6847 WHERE (contextlevel = ".CONTEXT_MODULE."
6848 AND (component = :component OR component = 'moodle'))
6849 $extra";
6850 $params['component'] = "mod_$module->name";
6852 return $DB->get_records_sql($sql.' '.$sort, $params);
6856 * Is this context part of any course? If yes return course context.
6858 * @param bool $strict true means throw exception if not found, false means return false if not found
6859 * @return context_course context of the enclosing course, null if not found or exception
6861 public function get_course_context($strict = true) {
6862 return $this->get_parent_context();
6866 * Returns module context instance.
6868 * @static
6869 * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
6870 * @param int $strictness
6871 * @return context_module context instance
6873 public static function instance($cmid, $strictness = MUST_EXIST) {
6874 global $DB;
6876 if ($context = context::cache_get(CONTEXT_MODULE, $cmid)) {
6877 return $context;
6880 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE, 'instanceid' => $cmid))) {
6881 if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
6882 $parentcontext = context_course::instance($cm->course);
6883 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
6887 if ($record) {
6888 $context = new context_module($record);
6889 context::cache_add($context);
6890 return $context;
6893 return false;
6897 * Create missing context instances at module context level
6898 * @static
6900 protected static function create_level_instances() {
6901 global $DB;
6903 $sql = "SELECT ".CONTEXT_MODULE.", cm.id
6904 FROM {course_modules} cm
6905 WHERE NOT EXISTS (SELECT 'x'
6906 FROM {context} cx
6907 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
6908 $contextdata = $DB->get_recordset_sql($sql);
6909 foreach ($contextdata as $context) {
6910 context::insert_context_record(CONTEXT_MODULE, $context->id, null);
6912 $contextdata->close();
6916 * Returns sql necessary for purging of stale context instances.
6918 * @static
6919 * @return string cleanup SQL
6921 protected static function get_cleanup_sql() {
6922 $sql = "
6923 SELECT c.*
6924 FROM {context} c
6925 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6926 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
6929 return $sql;
6933 * Rebuild context paths and depths at module context level.
6935 * @static
6936 * @param bool $force
6938 protected static function build_paths($force) {
6939 global $DB;
6941 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
6942 if ($force) {
6943 $ctxemptyclause = '';
6944 } else {
6945 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6948 $sql = "INSERT INTO {context_temp} (id, path, depth)
6949 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6950 FROM {context} ctx
6951 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
6952 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
6953 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6954 $ctxemptyclause";
6955 $trans = $DB->start_delegated_transaction();
6956 $DB->delete_records('context_temp');
6957 $DB->execute($sql);
6958 context::merge_context_temp_table();
6959 $DB->delete_records('context_temp');
6960 $trans->allow_commit();
6967 * Block context class
6969 * @package core_access
6970 * @category access
6971 * @copyright Petr Skoda {@link http://skodak.org}
6972 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6973 * @since Moodle 2.2
6975 class context_block extends context {
6977 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6978 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6980 * @param stdClass $record
6982 protected function __construct(stdClass $record) {
6983 parent::__construct($record);
6984 if ($record->contextlevel != CONTEXT_BLOCK) {
6985 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6990 * Returns human readable context level name.
6992 * @static
6993 * @return string the human readable context level name.
6995 public static function get_level_name() {
6996 return get_string('block');
7000 * Returns human readable context identifier.
7002 * @param boolean $withprefix whether to prefix the name of the context with Block
7003 * @param boolean $short does not apply to block context
7004 * @return string the human readable context name.
7006 public function get_context_name($withprefix = true, $short = false) {
7007 global $DB, $CFG;
7009 $name = '';
7010 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
7011 global $CFG;
7012 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7013 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7014 $blockname = "block_$blockinstance->blockname";
7015 if ($blockobject = new $blockname()) {
7016 if ($withprefix){
7017 $name = get_string('block').': ';
7019 $name .= $blockobject->title;
7023 return $name;
7027 * Returns the most relevant URL for this context.
7029 * @return moodle_url
7031 public function get_url() {
7032 $parentcontexts = $this->get_parent_context();
7033 return $parentcontexts->get_url();
7037 * Returns array of relevant context capability records.
7039 * @return array
7041 public function get_capabilities() {
7042 global $DB;
7044 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7046 $params = array();
7047 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
7049 $extra = '';
7050 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7051 if ($extracaps) {
7052 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7053 $extra = "OR name $extra";
7056 $sql = "SELECT *
7057 FROM {capabilities}
7058 WHERE (contextlevel = ".CONTEXT_BLOCK."
7059 AND component = :component)
7060 $extra";
7061 $params['component'] = 'block_' . $bi->blockname;
7063 return $DB->get_records_sql($sql.' '.$sort, $params);
7067 * Is this context part of any course? If yes return course context.
7069 * @param bool $strict true means throw exception if not found, false means return false if not found
7070 * @return context_course context of the enclosing course, null if not found or exception
7072 public function get_course_context($strict = true) {
7073 $parentcontext = $this->get_parent_context();
7074 return $parentcontext->get_course_context($strict);
7078 * Returns block context instance.
7080 * @static
7081 * @param int $blockinstanceid id from {block_instances} table.
7082 * @param int $strictness
7083 * @return context_block context instance
7085 public static function instance($blockinstanceid, $strictness = MUST_EXIST) {
7086 global $DB;
7088 if ($context = context::cache_get(CONTEXT_BLOCK, $blockinstanceid)) {
7089 return $context;
7092 if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $blockinstanceid))) {
7093 if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
7094 $parentcontext = context::instance_by_id($bi->parentcontextid);
7095 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7099 if ($record) {
7100 $context = new context_block($record);
7101 context::cache_add($context);
7102 return $context;
7105 return false;
7109 * Block do not have child contexts...
7110 * @return array
7112 public function get_child_contexts() {
7113 return array();
7117 * Create missing context instances at block context level
7118 * @static
7120 protected static function create_level_instances() {
7121 global $DB;
7123 $sql = "SELECT ".CONTEXT_BLOCK.", bi.id
7124 FROM {block_instances} bi
7125 WHERE NOT EXISTS (SELECT 'x'
7126 FROM {context} cx
7127 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7128 $contextdata = $DB->get_recordset_sql($sql);
7129 foreach ($contextdata as $context) {
7130 context::insert_context_record(CONTEXT_BLOCK, $context->id, null);
7132 $contextdata->close();
7136 * Returns sql necessary for purging of stale context instances.
7138 * @static
7139 * @return string cleanup SQL
7141 protected static function get_cleanup_sql() {
7142 $sql = "
7143 SELECT c.*
7144 FROM {context} c
7145 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7146 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7149 return $sql;
7153 * Rebuild context paths and depths at block context level.
7155 * @static
7156 * @param bool $force
7158 protected static function build_paths($force) {
7159 global $DB;
7161 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7162 if ($force) {
7163 $ctxemptyclause = '';
7164 } else {
7165 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7168 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7169 $sql = "INSERT INTO {context_temp} (id, path, depth)
7170 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7171 FROM {context} ctx
7172 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7173 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7174 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7175 $ctxemptyclause";
7176 $trans = $DB->start_delegated_transaction();
7177 $DB->delete_records('context_temp');
7178 $DB->execute($sql);
7179 context::merge_context_temp_table();
7180 $DB->delete_records('context_temp');
7181 $trans->allow_commit();
7187 // ============== DEPRECATED FUNCTIONS ==========================================
7188 // Old context related functions were deprecated in 2.0, it is recommended
7189 // to use context classes in new code. Old function can be used when
7190 // creating patches that are supposed to be backported to older stable branches.
7191 // These deprecated functions will not be removed in near future,
7192 // before removing devs will be warned with a debugging message first,
7193 // then we will add error message and only after that we can remove the functions
7194 // completely.
7197 * Runs get_records select on context table and returns the result
7198 * Does get_records_select on the context table, and returns the results ordered
7199 * by contextlevel, and then the natural sort order within each level.
7200 * for the purpose of $select, you need to know that the context table has been
7201 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7203 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7204 * @param array $params any parameters required by $select.
7205 * @return array the requested context records.
7207 function get_sorted_contexts($select, $params = array()) {
7209 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7211 global $DB;
7212 if ($select) {
7213 $select = 'WHERE ' . $select;
7215 return $DB->get_records_sql("
7216 SELECT ctx.*
7217 FROM {context} ctx
7218 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7219 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7220 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7221 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7222 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7223 $select
7224 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7225 ", $params);
7229 * Given context and array of users, returns array of users whose enrolment status is suspended,
7230 * or enrolment has expired or has not started. Also removes those users from the given array
7232 * @param context $context context in which suspended users should be extracted.
7233 * @param array $users list of users.
7234 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7235 * @return array list of suspended users.
7237 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7238 global $DB;
7240 // Get active enrolled users.
7241 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7242 $activeusers = $DB->get_records_sql($sql, $params);
7244 // Move suspended users to a separate array & remove from the initial one.
7245 $susers = array();
7246 if (sizeof($activeusers)) {
7247 foreach ($users as $userid => $user) {
7248 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7249 $susers[$userid] = $user;
7250 unset($users[$userid]);
7254 return $susers;
7258 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7259 * or enrolment has expired or not started.
7261 * @param context $context context in which user enrolment is checked.
7262 * @param bool $usecache Enable or disable (default) the request cache
7263 * @return array list of suspended user id's.
7265 function get_suspended_userids(context $context, $usecache = false) {
7266 global $DB;
7268 if ($usecache) {
7269 $cache = cache::make('core', 'suspended_userids');
7270 $susers = $cache->get($context->id);
7271 if ($susers !== false) {
7272 return $susers;
7276 $coursecontext = $context->get_course_context();
7277 $susers = array();
7279 // Front page users are always enrolled, so suspended list is empty.
7280 if ($coursecontext->instanceid != SITEID) {
7281 list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7282 $susers = $DB->get_fieldset_sql($sql, $params);
7283 $susers = array_combine($susers, $susers);
7286 // Cache results for the remainder of this request.
7287 if ($usecache) {
7288 $cache->set($context->id, $susers);
7291 return $susers;
7295 * Gets sql for finding users with capability in the given context
7297 * @param context $context
7298 * @param string|array $capability Capability name or array of names.
7299 * If an array is provided then this is the equivalent of a logical 'OR',
7300 * i.e. the user needs to have one of these capabilities.
7301 * @return array($sql, $params)
7303 function get_with_capability_sql(context $context, $capability) {
7304 static $i = 0;
7305 $i++;
7306 $prefix = 'cu' . $i . '_';
7308 $capjoin = get_with_capability_join($context, $capability, $prefix . 'u.id');
7310 $sql = "SELECT DISTINCT {$prefix}u.id
7311 FROM {user} {$prefix}u
7312 $capjoin->joins
7313 WHERE {$prefix}u.deleted = 0 AND $capjoin->wheres";
7315 return array($sql, $capjoin->params);
7319 * Gets sql joins for finding users with capability in the given context
7321 * @param context $context Context for the join
7322 * @param string|array $capability Capability name or array of names.
7323 * If an array is provided then this is the equivalent of a logical 'OR',
7324 * i.e. the user needs to have one of these capabilities.
7325 * @param string $useridcolumn e.g. 'u.id'
7326 * @return \core\dml\sql_join Contains joins, wheres, params
7328 function get_with_capability_join(context $context, $capability, $useridcolumn) {
7329 global $DB, $CFG;
7331 // Use unique prefix just in case somebody makes some SQL magic with the result.
7332 static $i = 0;
7333 $i++;
7334 $prefix = 'eu' . $i . '_';
7336 // First find the course context.
7337 $coursecontext = $context->get_course_context();
7339 $isfrontpage = ($coursecontext->instanceid == SITEID);
7341 $joins = array();
7342 $wheres = array();
7343 $params = array();
7345 list($contextids, $contextpaths) = get_context_info_list($context);
7347 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
7349 list($incaps, $capsparams) = $DB->get_in_or_equal($capability, SQL_PARAMS_NAMED, 'cap');
7351 $defs = array();
7352 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
7353 FROM {role_capabilities} rc
7354 JOIN {context} ctx on rc.contextid = ctx.id
7355 WHERE rc.contextid $incontexts AND rc.capability $incaps";
7356 $rcs = $DB->get_records_sql($sql, array_merge($cparams, $capsparams));
7357 foreach ($rcs as $rc) {
7358 $defs[$rc->path][$rc->roleid] = $rc->permission;
7361 $access = array();
7362 if (!empty($defs)) {
7363 foreach ($contextpaths as $path) {
7364 if (empty($defs[$path])) {
7365 continue;
7367 foreach ($defs[$path] as $roleid => $perm) {
7368 if ($perm == CAP_PROHIBIT) {
7369 $access[$roleid] = CAP_PROHIBIT;
7370 continue;
7372 if (!isset($access[$roleid])) {
7373 $access[$roleid] = (int) $perm;
7379 unset($defs);
7381 // Make lists of roles that are needed and prohibited.
7382 $needed = array(); // One of these is enough.
7383 $prohibited = array(); // Must not have any of these.
7384 foreach ($access as $roleid => $perm) {
7385 if ($perm == CAP_PROHIBIT) {
7386 unset($needed[$roleid]);
7387 $prohibited[$roleid] = true;
7388 } else {
7389 if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
7390 $needed[$roleid] = true;
7395 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
7396 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
7398 $nobody = false;
7400 if ($isfrontpage) {
7401 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
7402 $nobody = true;
7403 } else {
7404 if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
7405 // Everybody not having prohibit has the capability.
7406 $needed = array();
7407 } else {
7408 if (empty($needed)) {
7409 $nobody = true;
7413 } else {
7414 if (!empty($prohibited[$defaultuserroleid])) {
7415 $nobody = true;
7416 } else {
7417 if (!empty($needed[$defaultuserroleid])) {
7418 // Everybody not having prohibit has the capability.
7419 $needed = array();
7420 } else {
7421 if (empty($needed)) {
7422 $nobody = true;
7428 if ($nobody) {
7429 // Nobody can match so return some SQL that does not return any results.
7430 $wheres[] = "1 = 2";
7432 } else {
7434 if ($needed) {
7435 $ctxids = implode(',', $contextids);
7436 $roleids = implode(',', array_keys($needed));
7437 $joins[] = "JOIN {role_assignments} {$prefix}ra3
7438 ON ({$prefix}ra3.userid = $useridcolumn
7439 AND {$prefix}ra3.roleid IN ($roleids)
7440 AND {$prefix}ra3.contextid IN ($ctxids))";
7443 if ($prohibited) {
7444 $ctxids = implode(',', $contextids);
7445 $roleids = implode(',', array_keys($prohibited));
7446 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4
7447 ON ({$prefix}ra4.userid = $useridcolumn
7448 AND {$prefix}ra4.roleid IN ($roleids)
7449 AND {$prefix}ra4.contextid IN ($ctxids))";
7450 $wheres[] = "{$prefix}ra4.id IS NULL";
7455 $wheres[] = "$useridcolumn <> :{$prefix}guestid";
7456 $params["{$prefix}guestid"] = $CFG->siteguest;
7458 $joins = implode("\n", $joins);
7459 $wheres = "(" . implode(" AND ", $wheres) . ")";
7461 return new \core\dml\sql_join($joins, $wheres, $params);