Merge branch 'MDL-32903' of git://github.com/netspotau/moodle-mod_assign
[moodle.git] / lib / accesslib.php
blobfcd91b8b41d4ade1582d5958d5638458a416c945
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 */
172 define('ROLENAME_ORIGINAL', 0);
173 /** rolename displays - the name as defined by a role alias */
174 define('ROLENAME_ALIAS', 1);
175 /** rolename displays - Both, like this: Role alias (Original) */
176 define('ROLENAME_BOTH', 2);
177 /** rolename displays - the name as defined in the role definition and the shortname in brackets */
178 define('ROLENAME_ORIGINALANDSHORT', 3);
179 /** rolename displays - the name as defined by a role alias, in raw form suitable for editing */
180 define('ROLENAME_ALIAS_RAW', 4);
181 /** rolename displays - the name is simply short role name */
182 define('ROLENAME_SHORT', 5);
184 if (!defined('CONTEXT_CACHE_MAX_SIZE')) {
185 /** maximum size of context cache - it is possible to tweak this config.php or in any script before inclusion of context.php */
186 define('CONTEXT_CACHE_MAX_SIZE', 2500);
190 * Although this looks like a global variable, it isn't really.
192 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
193 * It is used to cache various bits of data between function calls for performance reasons.
194 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
195 * as methods of a class, instead of functions.
197 * @access private
198 * @global stdClass $ACCESSLIB_PRIVATE
199 * @name $ACCESSLIB_PRIVATE
201 global $ACCESSLIB_PRIVATE;
202 $ACCESSLIB_PRIVATE = new stdClass();
203 $ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache, loaded from DB once per page
204 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
205 $ACCESSLIB_PRIVATE->rolepermissions = array(); // role permissions cache - helps a lot with mem usage
206 $ACCESSLIB_PRIVATE->capabilities = null; // detailed information about the capabilities
209 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
211 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
212 * accesslib's private caches. You need to do this before setting up test data,
213 * and also at the end of the tests.
215 * @access private
216 * @return void
218 function accesslib_clear_all_caches_for_unit_testing() {
219 global $UNITTEST, $USER;
220 if (empty($UNITTEST->running) and !PHPUNIT_TEST) {
221 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
224 accesslib_clear_all_caches(true);
226 unset($USER->access);
230 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
232 * This reset does not touch global $USER.
234 * @access private
235 * @param bool $resetcontexts
236 * @return void
238 function accesslib_clear_all_caches($resetcontexts) {
239 global $ACCESSLIB_PRIVATE;
241 $ACCESSLIB_PRIVATE->dirtycontexts = null;
242 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
243 $ACCESSLIB_PRIVATE->rolepermissions = array();
244 $ACCESSLIB_PRIVATE->capabilities = null;
246 if ($resetcontexts) {
247 context_helper::reset_caches();
252 * Gets the accessdata for role "sitewide" (system down to course)
254 * @access private
255 * @param int $roleid
256 * @return array
258 function get_role_access($roleid) {
259 global $DB, $ACCESSLIB_PRIVATE;
261 /* Get it in 1 DB query...
262 * - relevant role caps at the root and down
263 * to the course level - but not below
266 //TODO: MUC - this could be cached in shared memory to speed up first page loading, web crawlers, etc.
268 $accessdata = get_empty_accessdata();
270 $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
273 // Overrides for the role IN ANY CONTEXTS
274 // down to COURSE - not below -
276 $sql = "SELECT ctx.path,
277 rc.capability, rc.permission
278 FROM {context} ctx
279 JOIN {role_capabilities} rc ON rc.contextid = ctx.id
280 LEFT JOIN {context} cctx
281 ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
282 WHERE rc.roleid = ? AND cctx.id IS NULL";
283 $params = array($roleid);
285 // we need extra caching in CLI scripts and cron
286 $rs = $DB->get_recordset_sql($sql, $params);
287 foreach ($rs as $rd) {
288 $k = "{$rd->path}:{$roleid}";
289 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
291 $rs->close();
293 // share the role definitions
294 foreach ($accessdata['rdef'] as $k=>$unused) {
295 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
296 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
298 $accessdata['rdef_count']++;
299 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
302 return $accessdata;
306 * Get the default guest role, this is used for guest account,
307 * search engine spiders, etc.
309 * @return stdClass role record
311 function get_guest_role() {
312 global $CFG, $DB;
314 if (empty($CFG->guestroleid)) {
315 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
316 $guestrole = array_shift($roles); // Pick the first one
317 set_config('guestroleid', $guestrole->id);
318 return $guestrole;
319 } else {
320 debugging('Can not find any guest role!');
321 return false;
323 } else {
324 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
325 return $guestrole;
326 } else {
327 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
328 set_config('guestroleid', '');
329 return get_guest_role();
335 * Check whether a user has a particular capability in a given context.
337 * For example:
338 * $context = context_module::instance($cm->id);
339 * has_capability('mod/forum:replypost', $context)
341 * By default checks the capabilities of the current user, but you can pass a
342 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
344 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
345 * or capabilities with XSS, config or data loss risks.
347 * @category access
349 * @param string $capability the name of the capability to check. For example mod/forum:view
350 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
351 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
352 * @param boolean $doanything If false, ignores effect of admin role assignment
353 * @return boolean true if the user has this capability. Otherwise false.
355 function has_capability($capability, context $context, $user = null, $doanything = true) {
356 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
358 if (during_initial_install()) {
359 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cli/install.php" or $SCRIPT === "/$CFG->admin/cli/install_database.php") {
360 // we are in an installer - roles can not work yet
361 return true;
362 } else {
363 return false;
367 if (strpos($capability, 'moodle/legacy:') === 0) {
368 throw new coding_exception('Legacy capabilities can not be used any more!');
371 if (!is_bool($doanything)) {
372 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
375 // capability must exist
376 if (!$capinfo = get_capability_info($capability)) {
377 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
378 return false;
381 if (!isset($USER->id)) {
382 // should never happen
383 $USER->id = 0;
386 // make sure there is a real user specified
387 if ($user === null) {
388 $userid = $USER->id;
389 } else {
390 $userid = is_object($user) ? $user->id : $user;
393 // make sure forcelogin cuts off not-logged-in users if enabled
394 if (!empty($CFG->forcelogin) and $userid == 0) {
395 return false;
398 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
399 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
400 if (isguestuser($userid) or $userid == 0) {
401 return false;
405 // somehow make sure the user is not deleted and actually exists
406 if ($userid != 0) {
407 if ($userid == $USER->id and isset($USER->deleted)) {
408 // this prevents one query per page, it is a bit of cheating,
409 // but hopefully session is terminated properly once user is deleted
410 if ($USER->deleted) {
411 return false;
413 } else {
414 if (!context_user::instance($userid, IGNORE_MISSING)) {
415 // no user context == invalid userid
416 return false;
421 // context path/depth must be valid
422 if (empty($context->path) or $context->depth == 0) {
423 // this should not happen often, each upgrade tries to rebuild the context paths
424 debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()');
425 if (is_siteadmin($userid)) {
426 return true;
427 } else {
428 return false;
432 // Find out if user is admin - it is not possible to override the doanything in any way
433 // and it is not possible to switch to admin role either.
434 if ($doanything) {
435 if (is_siteadmin($userid)) {
436 if ($userid != $USER->id) {
437 return true;
439 // make sure switchrole is not used in this context
440 if (empty($USER->access['rsw'])) {
441 return true;
443 $parts = explode('/', trim($context->path, '/'));
444 $path = '';
445 $switched = false;
446 foreach ($parts as $part) {
447 $path .= '/' . $part;
448 if (!empty($USER->access['rsw'][$path])) {
449 $switched = true;
450 break;
453 if (!$switched) {
454 return true;
456 //ok, admin switched role in this context, let's use normal access control rules
460 // Careful check for staleness...
461 $context->reload_if_dirty();
463 if ($USER->id == $userid) {
464 if (!isset($USER->access)) {
465 load_all_capabilities();
467 $access =& $USER->access;
469 } else {
470 // make sure user accessdata is really loaded
471 get_user_accessdata($userid, true);
472 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
476 // Load accessdata for below-the-course context if necessary,
477 // all contexts at and above all courses are already loaded
478 if ($context->contextlevel != CONTEXT_COURSE and $coursecontext = $context->get_course_context(false)) {
479 load_course_context($userid, $coursecontext, $access);
482 return has_capability_in_accessdata($capability, $context, $access);
486 * Check if the user has any one of several capabilities from a list.
488 * This is just a utility method that calls has_capability in a loop. Try to put
489 * the capabilities that most users are likely to have first in the list for best
490 * performance.
492 * @category access
493 * @see has_capability()
495 * @param array $capabilities an array of capability names.
496 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
497 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
498 * @param boolean $doanything If false, ignore effect of admin role assignment
499 * @return boolean true if the user has any of these capabilities. Otherwise false.
501 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
502 foreach ($capabilities as $capability) {
503 if (has_capability($capability, $context, $user, $doanything)) {
504 return true;
507 return false;
511 * Check if the user has all the capabilities in a list.
513 * This is just a utility method that calls has_capability in a loop. Try to put
514 * the capabilities that fewest users are likely to have first in the list for best
515 * performance.
517 * @category access
518 * @see has_capability()
520 * @param array $capabilities an array of capability names.
521 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
522 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
523 * @param boolean $doanything If false, ignore effect of admin role assignment
524 * @return boolean true if the user has all of these capabilities. Otherwise false.
526 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
527 foreach ($capabilities as $capability) {
528 if (!has_capability($capability, $context, $user, $doanything)) {
529 return false;
532 return true;
536 * Check if the user is an admin at the site level.
538 * Please note that use of proper capabilities is always encouraged,
539 * this function is supposed to be used from core or for temporary hacks.
541 * @category access
543 * @param int|stdClass $user_or_id user id or user object
544 * @return bool true if user is one of the administrators, false otherwise
546 function is_siteadmin($user_or_id = null) {
547 global $CFG, $USER;
549 if ($user_or_id === null) {
550 $user_or_id = $USER;
553 if (empty($user_or_id)) {
554 return false;
556 if (!empty($user_or_id->id)) {
557 $userid = $user_or_id->id;
558 } else {
559 $userid = $user_or_id;
562 $siteadmins = explode(',', $CFG->siteadmins);
563 return in_array($userid, $siteadmins);
567 * Returns true if user has at least one role assign
568 * of 'coursecontact' role (is potentially listed in some course descriptions).
570 * @param int $userid
571 * @return bool
573 function has_coursecontact_role($userid) {
574 global $DB, $CFG;
576 if (empty($CFG->coursecontact)) {
577 return false;
579 $sql = "SELECT 1
580 FROM {role_assignments}
581 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
582 return $DB->record_exists_sql($sql, array('userid'=>$userid));
586 * Does the user have a capability to do something?
588 * Walk the accessdata array and return true/false.
589 * Deals with prohibits, role switching, aggregating
590 * capabilities, etc.
592 * The main feature of here is being FAST and with no
593 * side effects.
595 * Notes:
597 * Switch Role merges with default role
598 * ------------------------------------
599 * If you are a teacher in course X, you have at least
600 * teacher-in-X + defaultloggedinuser-sitewide. So in the
601 * course you'll have techer+defaultloggedinuser.
602 * We try to mimic that in switchrole.
604 * Permission evaluation
605 * ---------------------
606 * Originally there was an extremely complicated way
607 * to determine the user access that dealt with
608 * "locality" or role assignments and role overrides.
609 * Now we simply evaluate access for each role separately
610 * and then verify if user has at least one role with allow
611 * and at the same time no role with prohibit.
613 * @access private
614 * @param string $capability
615 * @param context $context
616 * @param array $accessdata
617 * @return bool
619 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
620 global $CFG;
622 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
623 $path = $context->path;
624 $paths = array($path);
625 while($path = rtrim($path, '0123456789')) {
626 $path = rtrim($path, '/');
627 if ($path === '') {
628 break;
630 $paths[] = $path;
633 $roles = array();
634 $switchedrole = false;
636 // Find out if role switched
637 if (!empty($accessdata['rsw'])) {
638 // From the bottom up...
639 foreach ($paths as $path) {
640 if (isset($accessdata['rsw'][$path])) {
641 // Found a switchrole assignment - check for that role _plus_ the default user role
642 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
643 $switchedrole = true;
644 break;
649 if (!$switchedrole) {
650 // get all users roles in this context and above
651 foreach ($paths as $path) {
652 if (isset($accessdata['ra'][$path])) {
653 foreach ($accessdata['ra'][$path] as $roleid) {
654 $roles[$roleid] = null;
660 // Now find out what access is given to each role, going bottom-->up direction
661 $allowed = false;
662 foreach ($roles as $roleid => $ignored) {
663 foreach ($paths as $path) {
664 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
665 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
666 if ($perm === CAP_PROHIBIT) {
667 // any CAP_PROHIBIT found means no permission for the user
668 return false;
670 if (is_null($roles[$roleid])) {
671 $roles[$roleid] = $perm;
675 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
676 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
679 return $allowed;
683 * A convenience function that tests has_capability, and displays an error if
684 * the user does not have that capability.
686 * NOTE before Moodle 2.0, this function attempted to make an appropriate
687 * require_login call before checking the capability. This is no longer the case.
688 * You must call require_login (or one of its variants) if you want to check the
689 * user is logged in, before you call this function.
691 * @see has_capability()
693 * @param string $capability the name of the capability to check. For example mod/forum:view
694 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
695 * @param int $userid A user id. By default (null) checks the permissions of the current user.
696 * @param bool $doanything If false, ignore effect of admin role assignment
697 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
698 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
699 * @return void terminates with an error if the user does not have the given capability.
701 function require_capability($capability, context $context, $userid = null, $doanything = true,
702 $errormessage = 'nopermissions', $stringfile = '') {
703 if (!has_capability($capability, $context, $userid, $doanything)) {
704 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
709 * Return a nested array showing role assignments
710 * all relevant role capabilities for the user at
711 * site/course_category/course levels
713 * We do _not_ delve deeper than courses because the number of
714 * overrides at the module/block levels can be HUGE.
716 * [ra] => [/path][roleid]=roleid
717 * [rdef] => [/path:roleid][capability]=permission
719 * @access private
720 * @param int $userid - the id of the user
721 * @return array access info array
723 function get_user_access_sitewide($userid) {
724 global $CFG, $DB, $ACCESSLIB_PRIVATE;
726 /* Get in a few cheap DB queries...
727 * - role assignments
728 * - relevant role caps
729 * - above and within this user's RAs
730 * - below this user's RAs - limited to course level
733 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
734 $raparents = array();
735 $accessdata = get_empty_accessdata();
737 // start with the default role
738 if (!empty($CFG->defaultuserroleid)) {
739 $syscontext = context_system::instance();
740 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
741 $raparents[$CFG->defaultuserroleid][$syscontext->id] = $syscontext->id;
744 // load the "default frontpage role"
745 if (!empty($CFG->defaultfrontpageroleid)) {
746 $frontpagecontext = context_course::instance(get_site()->id);
747 if ($frontpagecontext->path) {
748 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
749 $raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->id] = $frontpagecontext->id;
753 // preload every assigned role at and above course context
754 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
755 FROM {role_assignments} ra
756 JOIN {context} ctx
757 ON ctx.id = ra.contextid
758 LEFT JOIN {block_instances} bi
759 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
760 LEFT JOIN {context} bpctx
761 ON (bpctx.id = bi.parentcontextid)
762 WHERE ra.userid = :userid
763 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")";
764 $params = array('userid'=>$userid);
765 $rs = $DB->get_recordset_sql($sql, $params);
766 foreach ($rs as $ra) {
767 // RAs leafs are arrays to support multi-role assignments...
768 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
769 $raparents[$ra->roleid][$ra->contextid] = $ra->contextid;
771 $rs->close();
773 if (empty($raparents)) {
774 return $accessdata;
777 // now get overrides of interesting roles in all interesting child contexts
778 // hopefully we will not run out of SQL limits here,
779 // users would have to have very many roles at/above course context...
780 $sqls = array();
781 $params = array();
783 static $cp = 0;
784 foreach ($raparents as $roleid=>$ras) {
785 $cp++;
786 list($sqlcids, $cids) = $DB->get_in_or_equal($ras, SQL_PARAMS_NAMED, 'c'.$cp.'_');
787 $params = array_merge($params, $cids);
788 $params['r'.$cp] = $roleid;
789 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
790 FROM {role_capabilities} rc
791 JOIN {context} ctx
792 ON (ctx.id = rc.contextid)
793 JOIN {context} pctx
794 ON (pctx.id $sqlcids
795 AND (ctx.id = pctx.id
796 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
797 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
798 LEFT JOIN {block_instances} bi
799 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
800 LEFT JOIN {context} bpctx
801 ON (bpctx.id = bi.parentcontextid)
802 WHERE rc.roleid = :r{$cp}
803 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")
807 // fixed capability order is necessary for rdef dedupe
808 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
810 foreach ($rs as $rd) {
811 $k = $rd->path.':'.$rd->roleid;
812 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
814 $rs->close();
816 // share the role definitions
817 foreach ($accessdata['rdef'] as $k=>$unused) {
818 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
819 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
821 $accessdata['rdef_count']++;
822 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
825 return $accessdata;
829 * Add to the access ctrl array the data needed by a user for a given course.
831 * This function injects all course related access info into the accessdata array.
833 * @access private
834 * @param int $userid the id of the user
835 * @param context_course $coursecontext course context
836 * @param array $accessdata accessdata array (modified)
837 * @return void modifies $accessdata parameter
839 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
840 global $DB, $CFG, $ACCESSLIB_PRIVATE;
842 if (empty($coursecontext->path)) {
843 // weird, this should not happen
844 return;
847 if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
848 // already loaded, great!
849 return;
852 $roles = array();
854 if (empty($userid)) {
855 if (!empty($CFG->notloggedinroleid)) {
856 $roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
859 } else if (isguestuser($userid)) {
860 if ($guestrole = get_guest_role()) {
861 $roles[$guestrole->id] = $guestrole->id;
864 } else {
865 // Interesting role assignments at, above and below the course context
866 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
867 $params['userid'] = $userid;
868 $params['children'] = $coursecontext->path."/%";
869 $sql = "SELECT ra.*, ctx.path
870 FROM {role_assignments} ra
871 JOIN {context} ctx ON ra.contextid = ctx.id
872 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
873 $rs = $DB->get_recordset_sql($sql, $params);
875 // add missing role definitions
876 foreach ($rs as $ra) {
877 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
878 $roles[$ra->roleid] = $ra->roleid;
880 $rs->close();
882 // add the "default frontpage role" when on the frontpage
883 if (!empty($CFG->defaultfrontpageroleid)) {
884 $frontpagecontext = context_course::instance(get_site()->id);
885 if ($frontpagecontext->id == $coursecontext->id) {
886 $roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
890 // do not forget the default role
891 if (!empty($CFG->defaultuserroleid)) {
892 $roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
896 if (!$roles) {
897 // weird, default roles must be missing...
898 $accessdata['loaded'][$coursecontext->instanceid] = 1;
899 return;
902 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
903 $params = array('c'=>$coursecontext->id);
904 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
905 $params = array_merge($params, $rparams);
906 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
907 $params = array_merge($params, $rparams);
909 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
910 FROM {role_capabilities} rc
911 JOIN {context} ctx
912 ON (ctx.id = rc.contextid)
913 JOIN {context} cctx
914 ON (cctx.id = :c
915 AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
916 WHERE rc.roleid $roleids
917 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
918 $rs = $DB->get_recordset_sql($sql, $params);
920 $newrdefs = array();
921 foreach ($rs as $rd) {
922 $k = $rd->path.':'.$rd->roleid;
923 if (isset($accessdata['rdef'][$k])) {
924 continue;
926 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
928 $rs->close();
930 // share new role definitions
931 foreach ($newrdefs as $k=>$unused) {
932 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
933 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
935 $accessdata['rdef_count']++;
936 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
939 $accessdata['loaded'][$coursecontext->instanceid] = 1;
941 // we want to deduplicate the USER->access from time to time, this looks like a good place,
942 // because we have to do it before the end of session
943 dedupe_user_access();
947 * Add to the access ctrl array the data needed by a role for a given context.
949 * The data is added in the rdef key.
950 * This role-centric function is useful for role_switching
951 * and temporary course roles.
953 * @access private
954 * @param int $roleid the id of the user
955 * @param context $context needs path!
956 * @param array $accessdata accessdata array (is modified)
957 * @return array
959 function load_role_access_by_context($roleid, context $context, &$accessdata) {
960 global $DB, $ACCESSLIB_PRIVATE;
962 /* Get the relevant rolecaps into rdef
963 * - relevant role caps
964 * - at ctx and above
965 * - below this ctx
968 if (empty($context->path)) {
969 // weird, this should not happen
970 return;
973 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
974 $params['roleid'] = $roleid;
975 $params['childpath'] = $context->path.'/%';
977 $sql = "SELECT ctx.path, rc.capability, rc.permission
978 FROM {role_capabilities} rc
979 JOIN {context} ctx ON (rc.contextid = ctx.id)
980 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
981 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
982 $rs = $DB->get_recordset_sql($sql, $params);
984 $newrdefs = array();
985 foreach ($rs as $rd) {
986 $k = $rd->path.':'.$roleid;
987 if (isset($accessdata['rdef'][$k])) {
988 continue;
990 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
992 $rs->close();
994 // share new role definitions
995 foreach ($newrdefs as $k=>$unused) {
996 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
997 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
999 $accessdata['rdef_count']++;
1000 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1005 * Returns empty accessdata structure.
1007 * @access private
1008 * @return array empt accessdata
1010 function get_empty_accessdata() {
1011 $accessdata = array(); // named list
1012 $accessdata['ra'] = array();
1013 $accessdata['rdef'] = array();
1014 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
1015 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
1016 $accessdata['loaded'] = array(); // loaded course contexts
1017 $accessdata['time'] = time();
1018 $accessdata['rsw'] = array();
1020 return $accessdata;
1024 * Get accessdata for a given user.
1026 * @access private
1027 * @param int $userid
1028 * @param bool $preloadonly true means do not return access array
1029 * @return array accessdata
1031 function get_user_accessdata($userid, $preloadonly=false) {
1032 global $CFG, $ACCESSLIB_PRIVATE, $USER;
1034 if (!empty($USER->acces['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1035 // share rdef from USER session with rolepermissions cache in order to conserve memory
1036 foreach($USER->acces['rdef'] as $k=>$v) {
1037 $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->acces['rdef'][$k];
1039 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->acces;
1042 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
1043 if (empty($userid)) {
1044 if (!empty($CFG->notloggedinroleid)) {
1045 $accessdata = get_role_access($CFG->notloggedinroleid);
1046 } else {
1047 // weird
1048 return get_empty_accessdata();
1051 } else if (isguestuser($userid)) {
1052 if ($guestrole = get_guest_role()) {
1053 $accessdata = get_role_access($guestrole->id);
1054 } else {
1055 //weird
1056 return get_empty_accessdata();
1059 } else {
1060 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1063 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1066 if ($preloadonly) {
1067 return;
1068 } else {
1069 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1074 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1075 * this function looks for contexts with the same overrides and shares them.
1077 * @access private
1078 * @return void
1080 function dedupe_user_access() {
1081 global $USER;
1083 if (CLI_SCRIPT) {
1084 // no session in CLI --> no compression necessary
1085 return;
1088 if (empty($USER->access['rdef_count'])) {
1089 // weird, this should not happen
1090 return;
1093 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1094 if ($USER->access['rdef_count'] - $USER->access['rdef_lcc'] > 10) {
1095 // do not compress after each change, wait till there is more stuff to be done
1096 return;
1099 $hashmap = array();
1100 foreach ($USER->access['rdef'] as $k=>$def) {
1101 $hash = sha1(serialize($def));
1102 if (isset($hashmap[$hash])) {
1103 $USER->access['rdef'][$k] =& $hashmap[$hash];
1104 } else {
1105 $hashmap[$hash] =& $USER->access['rdef'][$k];
1109 $USER->access['rdef_lcc'] = $USER->access['rdef_count'];
1113 * A convenience function to completely load all the capabilities
1114 * for the current user. It is called from has_capability() and functions change permissions.
1116 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1117 * @see check_enrolment_plugins()
1119 * @access private
1120 * @return void
1122 function load_all_capabilities() {
1123 global $USER;
1125 // roles not installed yet - we are in the middle of installation
1126 if (during_initial_install()) {
1127 return;
1130 if (!isset($USER->id)) {
1131 // this should not happen
1132 $USER->id = 0;
1135 unset($USER->access);
1136 $USER->access = get_user_accessdata($USER->id);
1138 // deduplicate the overrides to minimize session size
1139 dedupe_user_access();
1141 // Clear to force a refresh
1142 unset($USER->mycourses);
1144 // init/reset internal enrol caches - active course enrolments and temp access
1145 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1149 * A convenience function to completely reload all the capabilities
1150 * for the current user when roles have been updated in a relevant
1151 * context -- but PRESERVING switchroles and loginas.
1152 * This function resets all accesslib and context caches.
1154 * That is - completely transparent to the user.
1156 * Note: reloads $USER->access completely.
1158 * @access private
1159 * @return void
1161 function reload_all_capabilities() {
1162 global $USER, $DB, $ACCESSLIB_PRIVATE;
1164 // copy switchroles
1165 $sw = array();
1166 if (!empty($USER->access['rsw'])) {
1167 $sw = $USER->access['rsw'];
1170 accesslib_clear_all_caches(true);
1171 unset($USER->access);
1172 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
1174 load_all_capabilities();
1176 foreach ($sw as $path => $roleid) {
1177 if ($record = $DB->get_record('context', array('path'=>$path))) {
1178 $context = context::instance_by_id($record->id);
1179 role_switch($roleid, $context);
1185 * Adds a temp role to current USER->access array.
1187 * Useful for the "temporary guest" access we grant to logged-in users.
1188 * This is useful for enrol plugins only.
1190 * @since 2.2
1191 * @param context_course $coursecontext
1192 * @param int $roleid
1193 * @return void
1195 function load_temp_course_role(context_course $coursecontext, $roleid) {
1196 global $USER, $SITE;
1198 if (empty($roleid)) {
1199 debugging('invalid role specified in load_temp_course_role()');
1200 return;
1203 if ($coursecontext->instanceid == $SITE->id) {
1204 debugging('Can not use temp roles on the frontpage');
1205 return;
1208 if (!isset($USER->access)) {
1209 load_all_capabilities();
1212 $coursecontext->reload_if_dirty();
1214 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1215 return;
1218 // load course stuff first
1219 load_course_context($USER->id, $coursecontext, $USER->access);
1221 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1223 load_role_access_by_context($roleid, $coursecontext, $USER->access);
1227 * Removes any extra guest roles from current USER->access array.
1228 * This is useful for enrol plugins only.
1230 * @since 2.2
1231 * @param context_course $coursecontext
1232 * @return void
1234 function remove_temp_course_roles(context_course $coursecontext) {
1235 global $DB, $USER, $SITE;
1237 if ($coursecontext->instanceid == $SITE->id) {
1238 debugging('Can not use temp roles on the frontpage');
1239 return;
1242 if (empty($USER->access['ra'][$coursecontext->path])) {
1243 //no roles here, weird
1244 return;
1247 $sql = "SELECT DISTINCT ra.roleid AS id
1248 FROM {role_assignments} ra
1249 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1250 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1252 $USER->access['ra'][$coursecontext->path] = array();
1253 foreach($ras as $r) {
1254 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1259 * Returns array of all role archetypes.
1261 * @return array
1263 function get_role_archetypes() {
1264 return array(
1265 'manager' => 'manager',
1266 'coursecreator' => 'coursecreator',
1267 'editingteacher' => 'editingteacher',
1268 'teacher' => 'teacher',
1269 'student' => 'student',
1270 'guest' => 'guest',
1271 'user' => 'user',
1272 'frontpage' => 'frontpage'
1277 * Assign the defaults found in this capability definition to roles that have
1278 * the corresponding legacy capabilities assigned to them.
1280 * @param string $capability
1281 * @param array $legacyperms an array in the format (example):
1282 * 'guest' => CAP_PREVENT,
1283 * 'student' => CAP_ALLOW,
1284 * 'teacher' => CAP_ALLOW,
1285 * 'editingteacher' => CAP_ALLOW,
1286 * 'coursecreator' => CAP_ALLOW,
1287 * 'manager' => CAP_ALLOW
1288 * @return boolean success or failure.
1290 function assign_legacy_capabilities($capability, $legacyperms) {
1292 $archetypes = get_role_archetypes();
1294 foreach ($legacyperms as $type => $perm) {
1296 $systemcontext = context_system::instance();
1297 if ($type === 'admin') {
1298 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1299 $type = 'manager';
1302 if (!array_key_exists($type, $archetypes)) {
1303 print_error('invalidlegacy', '', '', $type);
1306 if ($roles = get_archetype_roles($type)) {
1307 foreach ($roles as $role) {
1308 // Assign a site level capability.
1309 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1310 return false;
1315 return true;
1319 * Verify capability risks.
1321 * @param stdClass $capability a capability - a row from the capabilities table.
1322 * @return boolean whether this capability is safe - that is, whether people with the
1323 * safeoverrides capability should be allowed to change it.
1325 function is_safe_capability($capability) {
1326 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1330 * Get the local override (if any) for a given capability in a role in a context
1332 * @param int $roleid
1333 * @param int $contextid
1334 * @param string $capability
1335 * @return stdClass local capability override
1337 function get_local_override($roleid, $contextid, $capability) {
1338 global $DB;
1339 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1343 * Returns context instance plus related course and cm instances
1345 * @param int $contextid
1346 * @return array of ($context, $course, $cm)
1348 function get_context_info_array($contextid) {
1349 global $DB;
1351 $context = context::instance_by_id($contextid, MUST_EXIST);
1352 $course = null;
1353 $cm = null;
1355 if ($context->contextlevel == CONTEXT_COURSE) {
1356 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1358 } else if ($context->contextlevel == CONTEXT_MODULE) {
1359 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1360 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1362 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1363 $parent = $context->get_parent_context();
1365 if ($parent->contextlevel == CONTEXT_COURSE) {
1366 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1367 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1368 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1369 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1373 return array($context, $course, $cm);
1377 * Function that creates a role
1379 * @param string $name role name
1380 * @param string $shortname role short name
1381 * @param string $description role description
1382 * @param string $archetype
1383 * @return int id or dml_exception
1385 function create_role($name, $shortname, $description, $archetype = '') {
1386 global $DB;
1388 if (strpos($archetype, 'moodle/legacy:') !== false) {
1389 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1392 // verify role archetype actually exists
1393 $archetypes = get_role_archetypes();
1394 if (empty($archetypes[$archetype])) {
1395 $archetype = '';
1398 // Insert the role record.
1399 $role = new stdClass();
1400 $role->name = $name;
1401 $role->shortname = $shortname;
1402 $role->description = $description;
1403 $role->archetype = $archetype;
1405 //find free sortorder number
1406 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1407 if (empty($role->sortorder)) {
1408 $role->sortorder = 1;
1410 $id = $DB->insert_record('role', $role);
1412 return $id;
1416 * Function that deletes a role and cleanups up after it
1418 * @param int $roleid id of role to delete
1419 * @return bool always true
1421 function delete_role($roleid) {
1422 global $DB;
1424 // first unssign all users
1425 role_unassign_all(array('roleid'=>$roleid));
1427 // cleanup all references to this role, ignore errors
1428 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1429 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1430 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1431 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1432 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1433 $DB->delete_records('role_names', array('roleid'=>$roleid));
1434 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1436 // finally delete the role itself
1437 // get this before the name is gone for logging
1438 $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
1440 $DB->delete_records('role', array('id'=>$roleid));
1442 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
1444 return true;
1448 * Function to write context specific overrides, or default capabilities.
1450 * NOTE: use $context->mark_dirty() after this
1452 * @param string $capability string name
1453 * @param int $permission CAP_ constants
1454 * @param int $roleid role id
1455 * @param int|context $contextid context id
1456 * @param bool $overwrite
1457 * @return bool always true or exception
1459 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1460 global $USER, $DB;
1462 if ($contextid instanceof context) {
1463 $context = $contextid;
1464 } else {
1465 $context = context::instance_by_id($contextid);
1468 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1469 unassign_capability($capability, $roleid, $context->id);
1470 return true;
1473 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1475 if ($existing and !$overwrite) { // We want to keep whatever is there already
1476 return true;
1479 $cap = new stdClass();
1480 $cap->contextid = $context->id;
1481 $cap->roleid = $roleid;
1482 $cap->capability = $capability;
1483 $cap->permission = $permission;
1484 $cap->timemodified = time();
1485 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1487 if ($existing) {
1488 $cap->id = $existing->id;
1489 $DB->update_record('role_capabilities', $cap);
1490 } else {
1491 if ($DB->record_exists('context', array('id'=>$context->id))) {
1492 $DB->insert_record('role_capabilities', $cap);
1495 return true;
1499 * Unassign a capability from a role.
1501 * NOTE: use $context->mark_dirty() after this
1503 * @param string $capability the name of the capability
1504 * @param int $roleid the role id
1505 * @param int|context $contextid null means all contexts
1506 * @return boolean true or exception
1508 function unassign_capability($capability, $roleid, $contextid = null) {
1509 global $DB;
1511 if (!empty($contextid)) {
1512 if ($contextid instanceof context) {
1513 $context = $contextid;
1514 } else {
1515 $context = context::instance_by_id($contextid);
1517 // delete from context rel, if this is the last override in this context
1518 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1519 } else {
1520 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1522 return true;
1526 * Get the roles that have a given capability assigned to it
1528 * This function does not resolve the actual permission of the capability.
1529 * It just checks for permissions and overrides.
1530 * Use get_roles_with_cap_in_context() if resolution is required.
1532 * @param string $capability capability name (string)
1533 * @param string $permission optional, the permission defined for this capability
1534 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1535 * @param stdClass $context null means any
1536 * @return array of role records
1538 function get_roles_with_capability($capability, $permission = null, $context = null) {
1539 global $DB;
1541 if ($context) {
1542 $contexts = $context->get_parent_context_ids(true);
1543 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1544 $contextsql = "AND rc.contextid $insql";
1545 } else {
1546 $params = array();
1547 $contextsql = '';
1550 if ($permission) {
1551 $permissionsql = " AND rc.permission = :permission";
1552 $params['permission'] = $permission;
1553 } else {
1554 $permissionsql = '';
1557 $sql = "SELECT r.*
1558 FROM {role} r
1559 WHERE r.id IN (SELECT rc.roleid
1560 FROM {role_capabilities} rc
1561 WHERE rc.capability = :capname
1562 $contextsql
1563 $permissionsql)";
1564 $params['capname'] = $capability;
1567 return $DB->get_records_sql($sql, $params);
1571 * This function makes a role-assignment (a role for a user in a particular context)
1573 * @param int $roleid the role of the id
1574 * @param int $userid userid
1575 * @param int|context $contextid id of the context
1576 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1577 * @param int $itemid id of enrolment/auth plugin
1578 * @param string $timemodified defaults to current time
1579 * @return int new/existing id of the assignment
1581 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1582 global $USER, $DB;
1584 // first of all detect if somebody is using old style parameters
1585 if ($contextid === 0 or is_numeric($component)) {
1586 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1589 // now validate all parameters
1590 if (empty($roleid)) {
1591 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1594 if (empty($userid)) {
1595 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1598 if ($itemid) {
1599 if (strpos($component, '_') === false) {
1600 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1602 } else {
1603 $itemid = 0;
1604 if ($component !== '' and strpos($component, '_') === false) {
1605 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1609 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1610 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1613 if ($contextid instanceof context) {
1614 $context = $contextid;
1615 } else {
1616 $context = context::instance_by_id($contextid, MUST_EXIST);
1619 if (!$timemodified) {
1620 $timemodified = time();
1623 // Check for existing entry
1624 // TODO: Revisit this sql_empty() use once Oracle bindings are improved. MDL-29765
1625 $component = ($component === '') ? $DB->sql_empty() : $component;
1626 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1628 if ($ras) {
1629 // role already assigned - this should not happen
1630 if (count($ras) > 1) {
1631 // very weird - remove all duplicates!
1632 $ra = array_shift($ras);
1633 foreach ($ras as $r) {
1634 $DB->delete_records('role_assignments', array('id'=>$r->id));
1636 } else {
1637 $ra = reset($ras);
1640 // actually there is no need to update, reset anything or trigger any event, so just return
1641 return $ra->id;
1644 // Create a new entry
1645 $ra = new stdClass();
1646 $ra->roleid = $roleid;
1647 $ra->contextid = $context->id;
1648 $ra->userid = $userid;
1649 $ra->component = $component;
1650 $ra->itemid = $itemid;
1651 $ra->timemodified = $timemodified;
1652 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1654 $ra->id = $DB->insert_record('role_assignments', $ra);
1656 // mark context as dirty - again expensive, but needed
1657 $context->mark_dirty();
1659 if (!empty($USER->id) && $USER->id == $userid) {
1660 // If the user is the current user, then do full reload of capabilities too.
1661 reload_all_capabilities();
1664 events_trigger('role_assigned', $ra);
1666 return $ra->id;
1670 * Removes one role assignment
1672 * @param int $roleid
1673 * @param int $userid
1674 * @param int|context $contextid
1675 * @param string $component
1676 * @param int $itemid
1677 * @return void
1679 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1680 // first make sure the params make sense
1681 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1682 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1685 if ($itemid) {
1686 if (strpos($component, '_') === false) {
1687 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1689 } else {
1690 $itemid = 0;
1691 if ($component !== '' and strpos($component, '_') === false) {
1692 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1696 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1700 * Removes multiple role assignments, parameters may contain:
1701 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1703 * @param array $params role assignment parameters
1704 * @param bool $subcontexts unassign in subcontexts too
1705 * @param bool $includemanual include manual role assignments too
1706 * @return void
1708 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1709 global $USER, $CFG, $DB;
1711 if (!$params) {
1712 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1715 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1716 foreach ($params as $key=>$value) {
1717 if (!in_array($key, $allowed)) {
1718 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1722 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1723 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1726 if ($includemanual) {
1727 if (!isset($params['component']) or $params['component'] === '') {
1728 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1732 if ($subcontexts) {
1733 if (empty($params['contextid'])) {
1734 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1738 // TODO: Revisit this sql_empty() use once Oracle bindings are improved. MDL-29765
1739 if (isset($params['component'])) {
1740 $params['component'] = ($params['component'] === '') ? $DB->sql_empty() : $params['component'];
1742 $ras = $DB->get_records('role_assignments', $params);
1743 foreach($ras as $ra) {
1744 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1745 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1746 // this is a bit expensive but necessary
1747 $context->mark_dirty();
1748 // If the user is the current user, then do full reload of capabilities too.
1749 if (!empty($USER->id) && $USER->id == $ra->userid) {
1750 reload_all_capabilities();
1753 events_trigger('role_unassigned', $ra);
1755 unset($ras);
1757 // process subcontexts
1758 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1759 if ($params['contextid'] instanceof context) {
1760 $context = $params['contextid'];
1761 } else {
1762 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1765 if ($context) {
1766 $contexts = $context->get_child_contexts();
1767 $mparams = $params;
1768 foreach($contexts as $context) {
1769 $mparams['contextid'] = $context->id;
1770 $ras = $DB->get_records('role_assignments', $mparams);
1771 foreach($ras as $ra) {
1772 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1773 // this is a bit expensive but necessary
1774 $context->mark_dirty();
1775 // If the user is the current user, then do full reload of capabilities too.
1776 if (!empty($USER->id) && $USER->id == $ra->userid) {
1777 reload_all_capabilities();
1779 events_trigger('role_unassigned', $ra);
1785 // do this once more for all manual role assignments
1786 if ($includemanual) {
1787 $params['component'] = '';
1788 role_unassign_all($params, $subcontexts, false);
1793 * Determines if a user is currently logged in
1795 * @category access
1797 * @return bool
1799 function isloggedin() {
1800 global $USER;
1802 return (!empty($USER->id));
1806 * Determines if a user is logged in as real guest user with username 'guest'.
1808 * @category access
1810 * @param int|object $user mixed user object or id, $USER if not specified
1811 * @return bool true if user is the real guest user, false if not logged in or other user
1813 function isguestuser($user = null) {
1814 global $USER, $DB, $CFG;
1816 // make sure we have the user id cached in config table, because we are going to use it a lot
1817 if (empty($CFG->siteguest)) {
1818 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1819 // guest does not exist yet, weird
1820 return false;
1822 set_config('siteguest', $guestid);
1824 if ($user === null) {
1825 $user = $USER;
1828 if ($user === null) {
1829 // happens when setting the $USER
1830 return false;
1832 } else if (is_numeric($user)) {
1833 return ($CFG->siteguest == $user);
1835 } else if (is_object($user)) {
1836 if (empty($user->id)) {
1837 return false; // not logged in means is not be guest
1838 } else {
1839 return ($CFG->siteguest == $user->id);
1842 } else {
1843 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1848 * Does user have a (temporary or real) guest access to course?
1850 * @category access
1852 * @param context $context
1853 * @param stdClass|int $user
1854 * @return bool
1856 function is_guest(context $context, $user = null) {
1857 global $USER;
1859 // first find the course context
1860 $coursecontext = $context->get_course_context();
1862 // make sure there is a real user specified
1863 if ($user === null) {
1864 $userid = isset($USER->id) ? $USER->id : 0;
1865 } else {
1866 $userid = is_object($user) ? $user->id : $user;
1869 if (isguestuser($userid)) {
1870 // can not inspect or be enrolled
1871 return true;
1874 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1875 // viewing users appear out of nowhere, they are neither guests nor participants
1876 return false;
1879 // consider only real active enrolments here
1880 if (is_enrolled($coursecontext, $user, '', true)) {
1881 return false;
1884 return true;
1888 * Returns true if the user has moodle/course:view capability in the course,
1889 * this is intended for admins, managers (aka small admins), inspectors, etc.
1891 * @category access
1893 * @param context $context
1894 * @param int|stdClass $user if null $USER is used
1895 * @param string $withcapability extra capability name
1896 * @return bool
1898 function is_viewing(context $context, $user = null, $withcapability = '') {
1899 // first find the course context
1900 $coursecontext = $context->get_course_context();
1902 if (isguestuser($user)) {
1903 // can not inspect
1904 return false;
1907 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1908 // admins are allowed to inspect courses
1909 return false;
1912 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1913 // site admins always have the capability, but the enrolment above blocks
1914 return false;
1917 return true;
1921 * Returns true if user is enrolled (is participating) in course
1922 * this is intended for students and teachers.
1924 * Since 2.2 the result for active enrolments and current user are cached.
1926 * @package core_enrol
1927 * @category access
1929 * @param context $context
1930 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1931 * @param string $withcapability extra capability name
1932 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1933 * @return bool
1935 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1936 global $USER, $DB;
1938 // first find the course context
1939 $coursecontext = $context->get_course_context();
1941 // make sure there is a real user specified
1942 if ($user === null) {
1943 $userid = isset($USER->id) ? $USER->id : 0;
1944 } else {
1945 $userid = is_object($user) ? $user->id : $user;
1948 if (empty($userid)) {
1949 // not-logged-in!
1950 return false;
1951 } else if (isguestuser($userid)) {
1952 // guest account can not be enrolled anywhere
1953 return false;
1956 if ($coursecontext->instanceid == SITEID) {
1957 // everybody participates on frontpage
1958 } else {
1959 // try cached info first - the enrolled flag is set only when active enrolment present
1960 if ($USER->id == $userid) {
1961 $coursecontext->reload_if_dirty();
1962 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1963 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
1964 return true;
1969 if ($onlyactive) {
1970 // look for active enrolments only
1971 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1973 if ($until === false) {
1974 return false;
1977 if ($USER->id == $userid) {
1978 if ($until == 0) {
1979 $until = ENROL_MAX_TIMESTAMP;
1981 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
1982 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
1983 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
1984 remove_temp_course_roles($coursecontext);
1988 } else {
1989 // any enrolment is good for us here, even outdated, disabled or inactive
1990 $sql = "SELECT 'x'
1991 FROM {user_enrolments} ue
1992 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1993 JOIN {user} u ON u.id = ue.userid
1994 WHERE ue.userid = :userid AND u.deleted = 0";
1995 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
1996 if (!$DB->record_exists_sql($sql, $params)) {
1997 return false;
2002 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2003 return false;
2006 return true;
2010 * Returns true if the user is able to access the course.
2012 * This function is in no way, shape, or form a substitute for require_login.
2013 * It should only be used in circumstances where it is not possible to call require_login
2014 * such as the navigation.
2016 * This function checks many of the methods of access to a course such as the view
2017 * capability, enrollments, and guest access. It also makes use of the cache
2018 * generated by require_login for guest access.
2020 * The flags within the $USER object that are used here should NEVER be used outside
2021 * of this function can_access_course and require_login. Doing so WILL break future
2022 * versions.
2024 * @param stdClass $course record
2025 * @param stdClass|int|null $user user record or id, current user if null
2026 * @param string $withcapability Check for this capability as well.
2027 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2028 * @return boolean Returns true if the user is able to access the course
2030 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
2031 global $DB, $USER;
2033 // this function originally accepted $coursecontext parameter
2034 if ($course instanceof context) {
2035 if ($course instanceof context_course) {
2036 debugging('deprecated context parameter, please use $course record');
2037 $coursecontext = $course;
2038 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2039 } else {
2040 debugging('Invalid context parameter, please use $course record');
2041 return false;
2043 } else {
2044 $coursecontext = context_course::instance($course->id);
2047 if (!isset($USER->id)) {
2048 // should never happen
2049 $USER->id = 0;
2052 // make sure there is a user specified
2053 if ($user === null) {
2054 $userid = $USER->id;
2055 } else {
2056 $userid = is_object($user) ? $user->id : $user;
2058 unset($user);
2060 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2061 return false;
2064 if ($userid == $USER->id) {
2065 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2066 // the fact that somebody switched role means they can access the course no matter to what role they switched
2067 return true;
2071 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2072 return false;
2075 if (is_viewing($coursecontext, $userid)) {
2076 return true;
2079 if ($userid != $USER->id) {
2080 // for performance reasons we do not verify temporary guest access for other users, sorry...
2081 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2084 // === from here we deal only with $USER ===
2086 $coursecontext->reload_if_dirty();
2088 if (isset($USER->enrol['enrolled'][$course->id])) {
2089 if ($USER->enrol['enrolled'][$course->id] > time()) {
2090 return true;
2093 if (isset($USER->enrol['tempguest'][$course->id])) {
2094 if ($USER->enrol['tempguest'][$course->id] > time()) {
2095 return true;
2099 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2100 return true;
2103 // if not enrolled try to gain temporary guest access
2104 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2105 $enrols = enrol_get_plugins(true);
2106 foreach($instances as $instance) {
2107 if (!isset($enrols[$instance->enrol])) {
2108 continue;
2110 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2111 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2112 if ($until !== false and $until > time()) {
2113 $USER->enrol['tempguest'][$course->id] = $until;
2114 return true;
2117 if (isset($USER->enrol['tempguest'][$course->id])) {
2118 unset($USER->enrol['tempguest'][$course->id]);
2119 remove_temp_course_roles($coursecontext);
2122 return false;
2126 * Returns array with sql code and parameters returning all ids
2127 * of users enrolled into course.
2129 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2131 * @package core_enrol
2132 * @category access
2134 * @param context $context
2135 * @param string $withcapability
2136 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2137 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2138 * @return array list($sql, $params)
2140 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2141 global $DB, $CFG;
2143 // use unique prefix just in case somebody makes some SQL magic with the result
2144 static $i = 0;
2145 $i++;
2146 $prefix = 'eu'.$i.'_';
2148 // first find the course context
2149 $coursecontext = $context->get_course_context();
2151 $isfrontpage = ($coursecontext->instanceid == SITEID);
2153 $joins = array();
2154 $wheres = array();
2155 $params = array();
2157 list($contextids, $contextpaths) = get_context_info_list($context);
2159 // get all relevant capability info for all roles
2160 if ($withcapability) {
2161 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2162 $cparams['cap'] = $withcapability;
2164 $defs = array();
2165 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2166 FROM {role_capabilities} rc
2167 JOIN {context} ctx on rc.contextid = ctx.id
2168 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2169 $rcs = $DB->get_records_sql($sql, $cparams);
2170 foreach ($rcs as $rc) {
2171 $defs[$rc->path][$rc->roleid] = $rc->permission;
2174 $access = array();
2175 if (!empty($defs)) {
2176 foreach ($contextpaths as $path) {
2177 if (empty($defs[$path])) {
2178 continue;
2180 foreach($defs[$path] as $roleid => $perm) {
2181 if ($perm == CAP_PROHIBIT) {
2182 $access[$roleid] = CAP_PROHIBIT;
2183 continue;
2185 if (!isset($access[$roleid])) {
2186 $access[$roleid] = (int)$perm;
2192 unset($defs);
2194 // make lists of roles that are needed and prohibited
2195 $needed = array(); // one of these is enough
2196 $prohibited = array(); // must not have any of these
2197 foreach ($access as $roleid => $perm) {
2198 if ($perm == CAP_PROHIBIT) {
2199 unset($needed[$roleid]);
2200 $prohibited[$roleid] = true;
2201 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2202 $needed[$roleid] = true;
2206 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2207 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2209 $nobody = false;
2211 if ($isfrontpage) {
2212 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2213 $nobody = true;
2214 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2215 // everybody not having prohibit has the capability
2216 $needed = array();
2217 } else if (empty($needed)) {
2218 $nobody = true;
2220 } else {
2221 if (!empty($prohibited[$defaultuserroleid])) {
2222 $nobody = true;
2223 } else if (!empty($needed[$defaultuserroleid])) {
2224 // everybody not having prohibit has the capability
2225 $needed = array();
2226 } else if (empty($needed)) {
2227 $nobody = true;
2231 if ($nobody) {
2232 // nobody can match so return some SQL that does not return any results
2233 $wheres[] = "1 = 2";
2235 } else {
2237 if ($needed) {
2238 $ctxids = implode(',', $contextids);
2239 $roleids = implode(',', array_keys($needed));
2240 $joins[] = "JOIN {role_assignments} {$prefix}ra3 ON ({$prefix}ra3.userid = {$prefix}u.id AND {$prefix}ra3.roleid IN ($roleids) AND {$prefix}ra3.contextid IN ($ctxids))";
2243 if ($prohibited) {
2244 $ctxids = implode(',', $contextids);
2245 $roleids = implode(',', array_keys($prohibited));
2246 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4 ON ({$prefix}ra4.userid = {$prefix}u.id AND {$prefix}ra4.roleid IN ($roleids) AND {$prefix}ra4.contextid IN ($ctxids))";
2247 $wheres[] = "{$prefix}ra4.id IS NULL";
2250 if ($groupid) {
2251 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2252 $params["{$prefix}gmid"] = $groupid;
2256 } else {
2257 if ($groupid) {
2258 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2259 $params["{$prefix}gmid"] = $groupid;
2263 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2264 $params["{$prefix}guestid"] = $CFG->siteguest;
2266 if ($isfrontpage) {
2267 // all users are "enrolled" on the frontpage
2268 } else {
2269 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2270 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2271 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2273 if ($onlyactive) {
2274 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2275 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2276 $now = round(time(), -2); // rounding helps caching in DB
2277 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2278 $prefix.'active'=>ENROL_USER_ACTIVE,
2279 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2283 $joins = implode("\n", $joins);
2284 $wheres = "WHERE ".implode(" AND ", $wheres);
2286 $sql = "SELECT DISTINCT {$prefix}u.id
2287 FROM {user} {$prefix}u
2288 $joins
2289 $wheres";
2291 return array($sql, $params);
2295 * Returns list of users enrolled into course.
2297 * @package core_enrol
2298 * @category access
2300 * @param context $context
2301 * @param string $withcapability
2302 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2303 * @param string $userfields requested user record fields
2304 * @param string $orderby
2305 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2306 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2307 * @return array of user records
2309 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = '', $limitfrom = 0, $limitnum = 0) {
2310 global $DB;
2312 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2313 $sql = "SELECT $userfields
2314 FROM {user} u
2315 JOIN ($esql) je ON je.id = u.id
2316 WHERE u.deleted = 0";
2318 if ($orderby) {
2319 $sql = "$sql ORDER BY $orderby";
2320 } else {
2321 $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
2324 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2328 * Counts list of users enrolled into course (as per above function)
2330 * @package core_enrol
2331 * @category access
2333 * @param context $context
2334 * @param string $withcapability
2335 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2336 * @return array of user records
2338 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0) {
2339 global $DB;
2341 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2342 $sql = "SELECT count(u.id)
2343 FROM {user} u
2344 JOIN ($esql) je ON je.id = u.id
2345 WHERE u.deleted = 0";
2347 return $DB->count_records_sql($sql, $params);
2351 * Loads the capability definitions for the component (from file).
2353 * Loads the capability definitions for the component (from file). If no
2354 * capabilities are defined for the component, we simply return an empty array.
2356 * @access private
2357 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2358 * @return array array of capabilities
2360 function load_capability_def($component) {
2361 $defpath = get_component_directory($component).'/db/access.php';
2363 $capabilities = array();
2364 if (file_exists($defpath)) {
2365 require($defpath);
2366 if (!empty(${$component.'_capabilities'})) {
2367 // BC capability array name
2368 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2369 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2370 $capabilities = ${$component.'_capabilities'};
2374 return $capabilities;
2378 * Gets the capabilities that have been cached in the database for this component.
2380 * @access private
2381 * @param string $component - examples: 'moodle', 'mod_forum'
2382 * @return array array of capabilities
2384 function get_cached_capabilities($component = 'moodle') {
2385 global $DB;
2386 return $DB->get_records('capabilities', array('component'=>$component));
2390 * Returns default capabilities for given role archetype.
2392 * @param string $archetype role archetype
2393 * @return array
2395 function get_default_capabilities($archetype) {
2396 global $DB;
2398 if (!$archetype) {
2399 return array();
2402 $alldefs = array();
2403 $defaults = array();
2404 $components = array();
2405 $allcaps = $DB->get_records('capabilities');
2407 foreach ($allcaps as $cap) {
2408 if (!in_array($cap->component, $components)) {
2409 $components[] = $cap->component;
2410 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2413 foreach($alldefs as $name=>$def) {
2414 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2415 if (isset($def['archetypes'])) {
2416 if (isset($def['archetypes'][$archetype])) {
2417 $defaults[$name] = $def['archetypes'][$archetype];
2419 // 'legacy' is for backward compatibility with 1.9 access.php
2420 } else {
2421 if (isset($def['legacy'][$archetype])) {
2422 $defaults[$name] = $def['legacy'][$archetype];
2427 return $defaults;
2431 * Reset role capabilities to default according to selected role archetype.
2432 * If no archetype selected, removes all capabilities.
2434 * @param int $roleid
2435 * @return void
2437 function reset_role_capabilities($roleid) {
2438 global $DB;
2440 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2441 $defaultcaps = get_default_capabilities($role->archetype);
2443 $systemcontext = context_system::instance();
2445 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2447 foreach($defaultcaps as $cap=>$permission) {
2448 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2453 * Updates the capabilities table with the component capability definitions.
2454 * If no parameters are given, the function updates the core moodle
2455 * capabilities.
2457 * Note that the absence of the db/access.php capabilities definition file
2458 * will cause any stored capabilities for the component to be removed from
2459 * the database.
2461 * @access private
2462 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2463 * @return boolean true if success, exception in case of any problems
2465 function update_capabilities($component = 'moodle') {
2466 global $DB, $OUTPUT;
2468 $storedcaps = array();
2470 $filecaps = load_capability_def($component);
2471 foreach($filecaps as $capname=>$unused) {
2472 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2473 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2477 $cachedcaps = get_cached_capabilities($component);
2478 if ($cachedcaps) {
2479 foreach ($cachedcaps as $cachedcap) {
2480 array_push($storedcaps, $cachedcap->name);
2481 // update risk bitmasks and context levels in existing capabilities if needed
2482 if (array_key_exists($cachedcap->name, $filecaps)) {
2483 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2484 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2486 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2487 $updatecap = new stdClass();
2488 $updatecap->id = $cachedcap->id;
2489 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2490 $DB->update_record('capabilities', $updatecap);
2492 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2493 $updatecap = new stdClass();
2494 $updatecap->id = $cachedcap->id;
2495 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2496 $DB->update_record('capabilities', $updatecap);
2499 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2500 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2502 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2503 $updatecap = new stdClass();
2504 $updatecap->id = $cachedcap->id;
2505 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2506 $DB->update_record('capabilities', $updatecap);
2512 // Are there new capabilities in the file definition?
2513 $newcaps = array();
2515 foreach ($filecaps as $filecap => $def) {
2516 if (!$storedcaps ||
2517 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2518 if (!array_key_exists('riskbitmask', $def)) {
2519 $def['riskbitmask'] = 0; // no risk if not specified
2521 $newcaps[$filecap] = $def;
2524 // Add new capabilities to the stored definition.
2525 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2526 foreach ($newcaps as $capname => $capdef) {
2527 $capability = new stdClass();
2528 $capability->name = $capname;
2529 $capability->captype = $capdef['captype'];
2530 $capability->contextlevel = $capdef['contextlevel'];
2531 $capability->component = $component;
2532 $capability->riskbitmask = $capdef['riskbitmask'];
2534 $DB->insert_record('capabilities', $capability, false);
2536 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2537 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2538 foreach ($rolecapabilities as $rolecapability){
2539 //assign_capability will update rather than insert if capability exists
2540 if (!assign_capability($capname, $rolecapability->permission,
2541 $rolecapability->roleid, $rolecapability->contextid, true)){
2542 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2546 // we ignore archetype key if we have cloned permissions
2547 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2548 assign_legacy_capabilities($capname, $capdef['archetypes']);
2549 // 'legacy' is for backward compatibility with 1.9 access.php
2550 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2551 assign_legacy_capabilities($capname, $capdef['legacy']);
2554 // Are there any capabilities that have been removed from the file
2555 // definition that we need to delete from the stored capabilities and
2556 // role assignments?
2557 capabilities_cleanup($component, $filecaps);
2559 // reset static caches
2560 accesslib_clear_all_caches(false);
2562 return true;
2566 * Deletes cached capabilities that are no longer needed by the component.
2567 * Also unassigns these capabilities from any roles that have them.
2569 * @access private
2570 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2571 * @param array $newcapdef array of the new capability definitions that will be
2572 * compared with the cached capabilities
2573 * @return int number of deprecated capabilities that have been removed
2575 function capabilities_cleanup($component, $newcapdef = null) {
2576 global $DB;
2578 $removedcount = 0;
2580 if ($cachedcaps = get_cached_capabilities($component)) {
2581 foreach ($cachedcaps as $cachedcap) {
2582 if (empty($newcapdef) ||
2583 array_key_exists($cachedcap->name, $newcapdef) === false) {
2585 // Remove from capabilities cache.
2586 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2587 $removedcount++;
2588 // Delete from roles.
2589 if ($roles = get_roles_with_capability($cachedcap->name)) {
2590 foreach($roles as $role) {
2591 if (!unassign_capability($cachedcap->name, $role->id)) {
2592 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2596 } // End if.
2599 return $removedcount;
2603 * Returns an array of all the known types of risk
2604 * The array keys can be used, for example as CSS class names, or in calls to
2605 * print_risk_icon. The values are the corresponding RISK_ constants.
2607 * @return array all the known types of risk.
2609 function get_all_risks() {
2610 return array(
2611 'riskmanagetrust' => RISK_MANAGETRUST,
2612 'riskconfig' => RISK_CONFIG,
2613 'riskxss' => RISK_XSS,
2614 'riskpersonal' => RISK_PERSONAL,
2615 'riskspam' => RISK_SPAM,
2616 'riskdataloss' => RISK_DATALOSS,
2621 * Return a link to moodle docs for a given capability name
2623 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2624 * @return string the human-readable capability name as a link to Moodle Docs.
2626 function get_capability_docs_link($capability) {
2627 $url = get_docs_url('Capabilities/' . $capability->name);
2628 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2632 * This function pulls out all the resolved capabilities (overrides and
2633 * defaults) of a role used in capability overrides in contexts at a given
2634 * context.
2636 * @param int $roleid
2637 * @param context $context
2638 * @param string $cap capability, optional, defaults to ''
2639 * @return array Array of capabilities
2641 function role_context_capabilities($roleid, context $context, $cap = '') {
2642 global $DB;
2644 $contexts = $context->get_parent_context_ids(true);
2645 $contexts = '('.implode(',', $contexts).')';
2647 $params = array($roleid);
2649 if ($cap) {
2650 $search = " AND rc.capability = ? ";
2651 $params[] = $cap;
2652 } else {
2653 $search = '';
2656 $sql = "SELECT rc.*
2657 FROM {role_capabilities} rc, {context} c
2658 WHERE rc.contextid in $contexts
2659 AND rc.roleid = ?
2660 AND rc.contextid = c.id $search
2661 ORDER BY c.contextlevel DESC, rc.capability DESC";
2663 $capabilities = array();
2665 if ($records = $DB->get_records_sql($sql, $params)) {
2666 // We are traversing via reverse order.
2667 foreach ($records as $record) {
2668 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2669 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2670 $capabilities[$record->capability] = $record->permission;
2674 return $capabilities;
2678 * Constructs array with contextids as first parameter and context paths,
2679 * in both cases bottom top including self.
2681 * @access private
2682 * @param context $context
2683 * @return array
2685 function get_context_info_list(context $context) {
2686 $contextids = explode('/', ltrim($context->path, '/'));
2687 $contextpaths = array();
2688 $contextids2 = $contextids;
2689 while ($contextids2) {
2690 $contextpaths[] = '/' . implode('/', $contextids2);
2691 array_pop($contextids2);
2693 return array($contextids, $contextpaths);
2697 * Check if context is the front page context or a context inside it
2699 * Returns true if this context is the front page context, or a context inside it,
2700 * otherwise false.
2702 * @param context $context a context object.
2703 * @return bool
2705 function is_inside_frontpage(context $context) {
2706 $frontpagecontext = context_course::instance(SITEID);
2707 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2711 * Returns capability information (cached)
2713 * @param string $capabilityname
2714 * @return stdClass or null if capability not found
2716 function get_capability_info($capabilityname) {
2717 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2719 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2721 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2722 $ACCESSLIB_PRIVATE->capabilities = array();
2723 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2724 foreach ($caps as $cap) {
2725 $capname = $cap->name;
2726 unset($cap->id);
2727 unset($cap->name);
2728 $cap->riskbitmask = (int)$cap->riskbitmask;
2729 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2733 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2737 * Returns the human-readable, translated version of the capability.
2738 * Basically a big switch statement.
2740 * @param string $capabilityname e.g. mod/choice:readresponses
2741 * @return string
2743 function get_capability_string($capabilityname) {
2745 // Typical capability name is 'plugintype/pluginname:capabilityname'
2746 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2748 if ($type === 'moodle') {
2749 $component = 'core_role';
2750 } else if ($type === 'quizreport') {
2751 //ugly hack!!
2752 $component = 'quiz_'.$name;
2753 } else {
2754 $component = $type.'_'.$name;
2757 $stringname = $name.':'.$capname;
2759 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2760 return get_string($stringname, $component);
2763 $dir = get_component_directory($component);
2764 if (!file_exists($dir)) {
2765 // plugin broken or does not exist, do not bother with printing of debug message
2766 return $capabilityname.' ???';
2769 // something is wrong in plugin, better print debug
2770 return get_string($stringname, $component);
2774 * This gets the mod/block/course/core etc strings.
2776 * @param string $component
2777 * @param int $contextlevel
2778 * @return string|bool String is success, false if failed
2780 function get_component_string($component, $contextlevel) {
2782 if ($component === 'moodle' or $component === 'core') {
2783 switch ($contextlevel) {
2784 // TODO: this should probably use context level names instead
2785 case CONTEXT_SYSTEM: return get_string('coresystem');
2786 case CONTEXT_USER: return get_string('users');
2787 case CONTEXT_COURSECAT: return get_string('categories');
2788 case CONTEXT_COURSE: return get_string('course');
2789 case CONTEXT_MODULE: return get_string('activities');
2790 case CONTEXT_BLOCK: return get_string('block');
2791 default: print_error('unknowncontext');
2795 list($type, $name) = normalize_component($component);
2796 $dir = get_plugin_directory($type, $name);
2797 if (!file_exists($dir)) {
2798 // plugin not installed, bad luck, there is no way to find the name
2799 return $component.' ???';
2802 switch ($type) {
2803 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2804 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2805 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2806 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2807 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2808 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2809 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2810 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2811 case 'mod':
2812 if (get_string_manager()->string_exists('pluginname', $component)) {
2813 return get_string('activity').': '.get_string('pluginname', $component);
2814 } else {
2815 return get_string('activity').': '.get_string('modulename', $component);
2817 default: return get_string('pluginname', $component);
2822 * Gets the list of roles assigned to this context and up (parents)
2823 * from the list of roles that are visible on user profile page
2824 * and participants page.
2826 * @param context $context
2827 * @return array
2829 function get_profile_roles(context $context) {
2830 global $CFG, $DB;
2832 if (empty($CFG->profileroles)) {
2833 return array();
2836 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2837 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2838 $params = array_merge($params, $cparams);
2840 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2841 FROM {role_assignments} ra, {role} r
2842 WHERE r.id = ra.roleid
2843 AND ra.contextid $contextlist
2844 AND r.id $rallowed
2845 ORDER BY r.sortorder ASC";
2847 return $DB->get_records_sql($sql, $params);
2851 * Gets the list of roles assigned to this context and up (parents)
2853 * @param context $context
2854 * @return array
2856 function get_roles_used_in_context(context $context) {
2857 global $DB;
2859 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true));
2861 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2862 FROM {role_assignments} ra, {role} r
2863 WHERE r.id = ra.roleid
2864 AND ra.contextid $contextlist
2865 ORDER BY r.sortorder ASC";
2867 return $DB->get_records_sql($sql, $params);
2871 * This function is used to print roles column in user profile page.
2872 * It is using the CFG->profileroles to limit the list to only interesting roles.
2873 * (The permission tab has full details of user role assignments.)
2875 * @param int $userid
2876 * @param int $courseid
2877 * @return string
2879 function get_user_roles_in_course($userid, $courseid) {
2880 global $CFG, $DB;
2882 if (empty($CFG->profileroles)) {
2883 return '';
2886 if ($courseid == SITEID) {
2887 $context = context_system::instance();
2888 } else {
2889 $context = context_course::instance($courseid);
2892 if (empty($CFG->profileroles)) {
2893 return array();
2896 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2897 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2898 $params = array_merge($params, $cparams);
2900 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2901 FROM {role_assignments} ra, {role} r
2902 WHERE r.id = ra.roleid
2903 AND ra.contextid $contextlist
2904 AND r.id $rallowed
2905 AND ra.userid = :userid
2906 ORDER BY r.sortorder ASC";
2907 $params['userid'] = $userid;
2909 $rolestring = '';
2911 if ($roles = $DB->get_records_sql($sql, $params)) {
2912 foreach ($roles as $userrole) {
2913 $rolenames[$userrole->id] = $userrole->name;
2916 $rolenames = role_fix_names($rolenames, $context); // Substitute aliases
2918 foreach ($rolenames as $roleid => $rolename) {
2919 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
2921 $rolestring = implode(',', $rolenames);
2924 return $rolestring;
2928 * Checks if a user can assign users to a particular role in this context
2930 * @param context $context
2931 * @param int $targetroleid - the id of the role you want to assign users to
2932 * @return boolean
2934 function user_can_assign(context $context, $targetroleid) {
2935 global $DB;
2937 // first check if user has override capability
2938 // if not return false;
2939 if (!has_capability('moodle/role:assign', $context)) {
2940 return false;
2942 // pull out all active roles of this user from this context(or above)
2943 if ($userroles = get_user_roles($context)) {
2944 foreach ($userroles as $userrole) {
2945 // if any in the role_allow_override table, then it's ok
2946 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2947 return true;
2952 return false;
2956 * Returns all site roles in correct sort order.
2958 * @return array
2960 function get_all_roles() {
2961 global $DB;
2962 return $DB->get_records('role', null, 'sortorder ASC');
2966 * Returns roles of a specified archetype
2968 * @param string $archetype
2969 * @return array of full role records
2971 function get_archetype_roles($archetype) {
2972 global $DB;
2973 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2977 * Gets all the user roles assigned in this context, or higher contexts
2978 * this is mainly used when checking if a user can assign a role, or overriding a role
2979 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2980 * allow_override tables
2982 * @param context $context
2983 * @param int $userid
2984 * @param bool $checkparentcontexts defaults to true
2985 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2986 * @return array
2988 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2989 global $USER, $DB;
2991 if (empty($userid)) {
2992 if (empty($USER->id)) {
2993 return array();
2995 $userid = $USER->id;
2998 if ($checkparentcontexts) {
2999 $contextids = $context->get_parent_context_ids();
3000 } else {
3001 $contextids = array();
3003 $contextids[] = $context->id;
3005 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3007 array_unshift($params, $userid);
3009 $sql = "SELECT ra.*, r.name, r.shortname
3010 FROM {role_assignments} ra, {role} r, {context} c
3011 WHERE ra.userid = ?
3012 AND ra.roleid = r.id
3013 AND ra.contextid = c.id
3014 AND ra.contextid $contextids
3015 ORDER BY $order";
3017 return $DB->get_records_sql($sql ,$params);
3021 * Creates a record in the role_allow_override table
3023 * @param int $sroleid source roleid
3024 * @param int $troleid target roleid
3025 * @return void
3027 function allow_override($sroleid, $troleid) {
3028 global $DB;
3030 $record = new stdClass();
3031 $record->roleid = $sroleid;
3032 $record->allowoverride = $troleid;
3033 $DB->insert_record('role_allow_override', $record);
3037 * Creates a record in the role_allow_assign table
3039 * @param int $fromroleid source roleid
3040 * @param int $targetroleid target roleid
3041 * @return void
3043 function allow_assign($fromroleid, $targetroleid) {
3044 global $DB;
3046 $record = new stdClass();
3047 $record->roleid = $fromroleid;
3048 $record->allowassign = $targetroleid;
3049 $DB->insert_record('role_allow_assign', $record);
3053 * Creates a record in the role_allow_switch table
3055 * @param int $fromroleid source roleid
3056 * @param int $targetroleid target roleid
3057 * @return void
3059 function allow_switch($fromroleid, $targetroleid) {
3060 global $DB;
3062 $record = new stdClass();
3063 $record->roleid = $fromroleid;
3064 $record->allowswitch = $targetroleid;
3065 $DB->insert_record('role_allow_switch', $record);
3069 * Gets a list of roles that this user can assign in this context
3071 * @param context $context the context.
3072 * @param int $rolenamedisplay the type of role name to display. One of the
3073 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3074 * @param bool $withusercounts if true, count the number of users with each role.
3075 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3076 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3077 * if $withusercounts is true, returns a list of three arrays,
3078 * $rolenames, $rolecounts, and $nameswithcounts.
3080 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3081 global $USER, $DB;
3083 // make sure there is a real user specified
3084 if ($user === null) {
3085 $userid = isset($USER->id) ? $USER->id : 0;
3086 } else {
3087 $userid = is_object($user) ? $user->id : $user;
3090 if (!has_capability('moodle/role:assign', $context, $userid)) {
3091 if ($withusercounts) {
3092 return array(array(), array(), array());
3093 } else {
3094 return array();
3098 $parents = $context->get_parent_context_ids(true);
3099 $contexts = implode(',' , $parents);
3101 $params = array();
3102 $extrafields = '';
3103 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT or $rolenamedisplay == ROLENAME_SHORT) {
3104 $extrafields .= ', r.shortname';
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 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3120 FROM {role_allow_assign} raa
3121 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3122 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3123 ) ar ON ar.id = r.id";
3124 $params['userid'] = $userid;
3126 $params['contextlevel'] = $context->contextlevel;
3127 $sql = "SELECT r.id, r.name $extrafields
3128 FROM {role} r
3129 $assignrestriction
3130 JOIN {role_context_levels} rcl ON r.id = rcl.roleid
3131 WHERE rcl.contextlevel = :contextlevel
3132 ORDER BY r.sortorder ASC";
3133 $roles = $DB->get_records_sql($sql, $params);
3135 $rolenames = array();
3136 foreach ($roles as $role) {
3137 if ($rolenamedisplay == ROLENAME_SHORT) {
3138 $rolenames[$role->id] = $role->shortname;
3139 continue;
3141 $rolenames[$role->id] = $role->name;
3142 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3143 $rolenames[$role->id] .= ' (' . $role->shortname . ')';
3146 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT and $rolenamedisplay != ROLENAME_SHORT) {
3147 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3150 if (!$withusercounts) {
3151 return $rolenames;
3154 $rolecounts = array();
3155 $nameswithcounts = array();
3156 foreach ($roles as $role) {
3157 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3158 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3160 return array($rolenames, $rolecounts, $nameswithcounts);
3164 * Gets a list of roles that this user can switch to in a context
3166 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3167 * This function just process the contents of the role_allow_switch table. You also need to
3168 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3170 * @param context $context a context.
3171 * @return array an array $roleid => $rolename.
3173 function get_switchable_roles(context $context) {
3174 global $USER, $DB;
3176 $params = array();
3177 $extrajoins = '';
3178 $extrawhere = '';
3179 if (!is_siteadmin()) {
3180 // Admins are allowed to switch to any role with.
3181 // Others are subject to the additional constraint that the switch-to role must be allowed by
3182 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3183 $parents = $context->get_parent_context_ids(true);
3184 $contexts = implode(',' , $parents);
3186 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3187 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3188 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3189 $params['userid'] = $USER->id;
3192 $query = "
3193 SELECT r.id, r.name
3194 FROM (SELECT DISTINCT rc.roleid
3195 FROM {role_capabilities} rc
3196 $extrajoins
3197 $extrawhere) idlist
3198 JOIN {role} r ON r.id = idlist.roleid
3199 ORDER BY r.sortorder";
3201 $rolenames = $DB->get_records_sql_menu($query, $params);
3202 return role_fix_names($rolenames, $context, ROLENAME_ALIAS);
3206 * Gets a list of roles that this user can override in this context.
3208 * @param context $context the context.
3209 * @param int $rolenamedisplay the type of role name to display. One of the
3210 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3211 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3212 * @return array if $withcounts is false, then an array $roleid => $rolename.
3213 * if $withusercounts is true, returns a list of three arrays,
3214 * $rolenames, $rolecounts, and $nameswithcounts.
3216 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3217 global $USER, $DB;
3219 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3220 if ($withcounts) {
3221 return array(array(), array(), array());
3222 } else {
3223 return array();
3227 $parents = $context->get_parent_context_ids(true);
3228 $contexts = implode(',' , $parents);
3230 $params = array();
3231 $extrafields = '';
3232 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3233 $extrafields .= ', ro.shortname';
3236 $params['userid'] = $USER->id;
3237 if ($withcounts) {
3238 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3239 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3240 $params['conid'] = $context->id;
3243 if (is_siteadmin()) {
3244 // show all roles to admins
3245 $roles = $DB->get_records_sql("
3246 SELECT ro.id, ro.name$extrafields
3247 FROM {role} ro
3248 ORDER BY ro.sortorder ASC", $params);
3250 } else {
3251 $roles = $DB->get_records_sql("
3252 SELECT ro.id, ro.name$extrafields
3253 FROM {role} ro
3254 JOIN (SELECT DISTINCT r.id
3255 FROM {role} r
3256 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3257 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3258 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3259 ) inline_view ON ro.id = inline_view.id
3260 ORDER BY ro.sortorder ASC", $params);
3263 $rolenames = array();
3264 foreach ($roles as $role) {
3265 $rolenames[$role->id] = $role->name;
3266 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3267 $rolenames[$role->id] .= ' (' . $role->shortname . ')';
3270 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT) {
3271 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3274 if (!$withcounts) {
3275 return $rolenames;
3278 $rolecounts = array();
3279 $nameswithcounts = array();
3280 foreach ($roles as $role) {
3281 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3282 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3284 return array($rolenames, $rolecounts, $nameswithcounts);
3288 * Create a role menu suitable for default role selection in enrol plugins.
3290 * @package core_enrol
3292 * @param context $context
3293 * @param int $addroleid current or default role - always added to list
3294 * @return array roleid=>localised role name
3296 function get_default_enrol_roles(context $context, $addroleid = null) {
3297 global $DB;
3299 $params = array('contextlevel'=>CONTEXT_COURSE);
3300 if ($addroleid) {
3301 $addrole = "OR r.id = :addroleid";
3302 $params['addroleid'] = $addroleid;
3303 } else {
3304 $addrole = "";
3306 $sql = "SELECT r.id, r.name
3307 FROM {role} r
3308 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3309 WHERE rcl.id IS NOT NULL $addrole
3310 ORDER BY sortorder DESC";
3312 $roles = $DB->get_records_sql_menu($sql, $params);
3313 $roles = role_fix_names($roles, $context, ROLENAME_BOTH);
3315 return $roles;
3319 * Return context levels where this role is assignable.
3321 * @param integer $roleid the id of a role.
3322 * @return array list of the context levels at which this role may be assigned.
3324 function get_role_contextlevels($roleid) {
3325 global $DB;
3326 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3327 'contextlevel', 'id,contextlevel');
3331 * Return roles suitable for assignment at the specified context level.
3333 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3335 * @param integer $contextlevel a contextlevel.
3336 * @return array list of role ids that are assignable at this context level.
3338 function get_roles_for_contextlevels($contextlevel) {
3339 global $DB;
3340 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3341 '', 'id,roleid');
3345 * Returns default context levels where roles can be assigned.
3347 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3348 * from the array returned by get_role_archetypes();
3349 * @return array list of the context levels at which this type of role may be assigned by default.
3351 function get_default_contextlevels($rolearchetype) {
3352 static $defaults = array(
3353 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3354 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3355 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3356 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3357 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3358 'guest' => array(),
3359 'user' => array(),
3360 'frontpage' => array());
3362 if (isset($defaults[$rolearchetype])) {
3363 return $defaults[$rolearchetype];
3364 } else {
3365 return array();
3370 * Set the context levels at which a particular role can be assigned.
3371 * Throws exceptions in case of error.
3373 * @param integer $roleid the id of a role.
3374 * @param array $contextlevels the context levels at which this role should be assignable,
3375 * duplicate levels are removed.
3376 * @return void
3378 function set_role_contextlevels($roleid, array $contextlevels) {
3379 global $DB;
3380 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3381 $rcl = new stdClass();
3382 $rcl->roleid = $roleid;
3383 $contextlevels = array_unique($contextlevels);
3384 foreach ($contextlevels as $level) {
3385 $rcl->contextlevel = $level;
3386 $DB->insert_record('role_context_levels', $rcl, false, true);
3391 * Who has this capability in this context?
3393 * This can be a very expensive call - use sparingly and keep
3394 * the results if you are going to need them again soon.
3396 * Note if $fields is empty this function attempts to get u.*
3397 * which can get rather large - and has a serious perf impact
3398 * on some DBs.
3400 * @param context $context
3401 * @param string|array $capability - capability name(s)
3402 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3403 * @param string $sort - the sort order. Default is lastaccess time.
3404 * @param mixed $limitfrom - number of records to skip (offset)
3405 * @param mixed $limitnum - number of records to fetch
3406 * @param string|array $groups - single group or array of groups - only return
3407 * users who are in one of these group(s).
3408 * @param string|array $exceptions - list of users to exclude, comma separated or array
3409 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3410 * @param bool $view_ignored - use get_enrolled_sql() instead
3411 * @param bool $useviewallgroups if $groups is set the return users who
3412 * have capability both $capability and moodle/site:accessallgroups
3413 * in this context, as well as users who have $capability and who are
3414 * in $groups.
3415 * @return array of user records
3417 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3418 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3419 global $CFG, $DB;
3421 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3422 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3424 $ctxids = trim($context->path, '/');
3425 $ctxids = str_replace('/', ',', $ctxids);
3427 // Context is the frontpage
3428 $iscoursepage = false; // coursepage other than fp
3429 $isfrontpage = false;
3430 if ($context->contextlevel == CONTEXT_COURSE) {
3431 if ($context->instanceid == SITEID) {
3432 $isfrontpage = true;
3433 } else {
3434 $iscoursepage = true;
3437 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3439 $caps = (array)$capability;
3441 // construct list of context paths bottom-->top
3442 list($contextids, $paths) = get_context_info_list($context);
3444 // we need to find out all roles that have these capabilities either in definition or in overrides
3445 $defs = array();
3446 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3447 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3448 $params = array_merge($params, $params2);
3449 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3450 FROM {role_capabilities} rc
3451 JOIN {context} ctx on rc.contextid = ctx.id
3452 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3454 $rcs = $DB->get_records_sql($sql, $params);
3455 foreach ($rcs as $rc) {
3456 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3459 // go through the permissions bottom-->top direction to evaluate the current permission,
3460 // first one wins (prohibit is an exception that always wins)
3461 $access = array();
3462 foreach ($caps as $cap) {
3463 foreach ($paths as $path) {
3464 if (empty($defs[$cap][$path])) {
3465 continue;
3467 foreach($defs[$cap][$path] as $roleid => $perm) {
3468 if ($perm == CAP_PROHIBIT) {
3469 $access[$cap][$roleid] = CAP_PROHIBIT;
3470 continue;
3472 if (!isset($access[$cap][$roleid])) {
3473 $access[$cap][$roleid] = (int)$perm;
3479 // make lists of roles that are needed and prohibited in this context
3480 $needed = array(); // one of these is enough
3481 $prohibited = array(); // must not have any of these
3482 foreach ($caps as $cap) {
3483 if (empty($access[$cap])) {
3484 continue;
3486 foreach ($access[$cap] as $roleid => $perm) {
3487 if ($perm == CAP_PROHIBIT) {
3488 unset($needed[$cap][$roleid]);
3489 $prohibited[$cap][$roleid] = true;
3490 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3491 $needed[$cap][$roleid] = true;
3494 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3495 // easy, nobody has the permission
3496 unset($needed[$cap]);
3497 unset($prohibited[$cap]);
3498 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3499 // everybody is disqualified on the frontpage
3500 unset($needed[$cap]);
3501 unset($prohibited[$cap]);
3503 if (empty($prohibited[$cap])) {
3504 unset($prohibited[$cap]);
3508 if (empty($needed)) {
3509 // there can not be anybody if no roles match this request
3510 return array();
3513 if (empty($prohibited)) {
3514 // we can compact the needed roles
3515 $n = array();
3516 foreach ($needed as $cap) {
3517 foreach ($cap as $roleid=>$unused) {
3518 $n[$roleid] = true;
3521 $needed = array('any'=>$n);
3522 unset($n);
3525 // ***** Set up default fields ******
3526 if (empty($fields)) {
3527 if ($iscoursepage) {
3528 $fields = 'u.*, ul.timeaccess AS lastaccess';
3529 } else {
3530 $fields = 'u.*';
3532 } else {
3533 if (debugging('', DEBUG_DEVELOPER) && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3534 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3538 // Set up default sort
3539 if (empty($sort)) { // default to course lastaccess or just lastaccess
3540 if ($iscoursepage) {
3541 $sort = 'ul.timeaccess';
3542 } else {
3543 $sort = 'u.lastaccess';
3547 // Prepare query clauses
3548 $wherecond = array();
3549 $params = array();
3550 $joins = array();
3552 // User lastaccess JOIN
3553 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3554 // user_lastaccess is not required MDL-13810
3555 } else {
3556 if ($iscoursepage) {
3557 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3558 } else {
3559 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3563 // We never return deleted users or guest account.
3564 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3565 $params['guestid'] = $CFG->siteguest;
3567 // Groups
3568 if ($groups) {
3569 $groups = (array)$groups;
3570 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3571 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3572 $params = array_merge($params, $grpparams);
3574 if ($useviewallgroups) {
3575 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3576 if (!empty($viewallgroupsusers)) {
3577 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3578 } else {
3579 $wherecond[] = "($grouptest)";
3581 } else {
3582 $wherecond[] = "($grouptest)";
3586 // User exceptions
3587 if (!empty($exceptions)) {
3588 $exceptions = (array)$exceptions;
3589 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3590 $params = array_merge($params, $exparams);
3591 $wherecond[] = "u.id $exsql";
3594 // now add the needed and prohibited roles conditions as joins
3595 if (!empty($needed['any'])) {
3596 // simple case - there are no prohibits involved
3597 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3598 // everybody
3599 } else {
3600 $joins[] = "JOIN (SELECT DISTINCT userid
3601 FROM {role_assignments}
3602 WHERE contextid IN ($ctxids)
3603 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3604 ) ra ON ra.userid = u.id";
3606 } else {
3607 $unions = array();
3608 $everybody = false;
3609 foreach ($needed as $cap=>$unused) {
3610 if (empty($prohibited[$cap])) {
3611 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3612 $everybody = true;
3613 break;
3614 } else {
3615 $unions[] = "SELECT userid
3616 FROM {role_assignments}
3617 WHERE contextid IN ($ctxids)
3618 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3620 } else {
3621 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3622 // nobody can have this cap because it is prevented in default roles
3623 continue;
3625 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3626 // everybody except the prohibitted - hiding does not matter
3627 $unions[] = "SELECT id AS userid
3628 FROM {user}
3629 WHERE id NOT IN (SELECT userid
3630 FROM {role_assignments}
3631 WHERE contextid IN ($ctxids)
3632 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3634 } else {
3635 $unions[] = "SELECT userid
3636 FROM {role_assignments}
3637 WHERE contextid IN ($ctxids)
3638 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3639 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3643 if (!$everybody) {
3644 if ($unions) {
3645 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3646 } else {
3647 // only prohibits found - nobody can be matched
3648 $wherecond[] = "1 = 2";
3653 // Collect WHERE conditions and needed joins
3654 $where = implode(' AND ', $wherecond);
3655 if ($where !== '') {
3656 $where = 'WHERE ' . $where;
3658 $joins = implode("\n", $joins);
3660 // Ok, let's get the users!
3661 $sql = "SELECT $fields
3662 FROM {user} u
3663 $joins
3664 $where
3665 ORDER BY $sort";
3667 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3671 * Re-sort a users array based on a sorting policy
3673 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3674 * based on a sorting policy. This is to support the odd practice of
3675 * sorting teachers by 'authority', where authority was "lowest id of the role
3676 * assignment".
3678 * Will execute 1 database query. Only suitable for small numbers of users, as it
3679 * uses an u.id IN() clause.
3681 * Notes about the sorting criteria.
3683 * As a default, we cannot rely on role.sortorder because then
3684 * admins/coursecreators will always win. That is why the sane
3685 * rule "is locality matters most", with sortorder as 2nd
3686 * consideration.
3688 * If you want role.sortorder, use the 'sortorder' policy, and
3689 * name explicitly what roles you want to cover. It's probably
3690 * a good idea to see what roles have the capabilities you want
3691 * (array_diff() them against roiles that have 'can-do-anything'
3692 * to weed out admin-ish roles. Or fetch a list of roles from
3693 * variables like $CFG->coursecontact .
3695 * @param array $users Users array, keyed on userid
3696 * @param context $context
3697 * @param array $roles ids of the roles to include, optional
3698 * @param string $sortpolicy defaults to locality, more about
3699 * @return array sorted copy of the array
3701 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3702 global $DB;
3704 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3705 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3706 if (empty($roles)) {
3707 $roleswhere = '';
3708 } else {
3709 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3712 $sql = "SELECT ra.userid
3713 FROM {role_assignments} ra
3714 JOIN {role} r
3715 ON ra.roleid=r.id
3716 JOIN {context} ctx
3717 ON ra.contextid=ctx.id
3718 WHERE $userswhere
3719 $contextwhere
3720 $roleswhere";
3722 // Default 'locality' policy -- read PHPDoc notes
3723 // about sort policies...
3724 $orderby = 'ORDER BY '
3725 .'ctx.depth DESC, ' /* locality wins */
3726 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3727 .'ra.id'; /* role assignment order tie-breaker */
3728 if ($sortpolicy === 'sortorder') {
3729 $orderby = 'ORDER BY '
3730 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3731 .'ra.id'; /* role assignment order tie-breaker */
3734 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3735 $sortedusers = array();
3736 $seen = array();
3738 foreach ($sortedids as $id) {
3739 // Avoid duplicates
3740 if (isset($seen[$id])) {
3741 continue;
3743 $seen[$id] = true;
3745 // assign
3746 $sortedusers[$id] = $users[$id];
3748 return $sortedusers;
3752 * Gets all the users assigned this role in this context or higher
3754 * @param int $roleid (can also be an array of ints!)
3755 * @param context $context
3756 * @param bool $parent if true, get list of users assigned in higher context too
3757 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3758 * @param string $sort sort from user (u.) , role assignment (ra) or role (r.)
3759 * @param bool $gethidden_ignored use enrolments instead
3760 * @param string $group defaults to ''
3761 * @param mixed $limitfrom defaults to ''
3762 * @param mixed $limitnum defaults to ''
3763 * @param string $extrawheretest defaults to ''
3764 * @param string|array $whereparams defaults to ''
3765 * @return array
3767 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3768 $sort = 'u.lastname, u.firstname', $gethidden_ignored = null, $group = '',
3769 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereparams = array()) {
3770 global $DB;
3772 if (empty($fields)) {
3773 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3774 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3775 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3776 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder';
3779 $parentcontexts = '';
3780 if ($parent) {
3781 $parentcontexts = substr($context->path, 1); // kill leading slash
3782 $parentcontexts = str_replace('/', ',', $parentcontexts);
3783 if ($parentcontexts !== '') {
3784 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3788 if ($roleid) {
3789 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3790 $roleselect = "AND ra.roleid $rids";
3791 } else {
3792 $params = array();
3793 $roleselect = '';
3796 if ($group) {
3797 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3798 $groupselect = " AND gm.groupid = ? ";
3799 $params[] = $group;
3800 } else {
3801 $groupjoin = '';
3802 $groupselect = '';
3805 array_unshift($params, $context->id);
3807 if ($extrawheretest) {
3808 $extrawheretest = ' AND ' . $extrawheretest;
3809 $params = array_merge($params, $whereparams);
3812 $sql = "SELECT DISTINCT $fields, ra.roleid
3813 FROM {role_assignments} ra
3814 JOIN {user} u ON u.id = ra.userid
3815 JOIN {role} r ON ra.roleid = r.id
3816 $groupjoin
3817 WHERE (ra.contextid = ? $parentcontexts)
3818 $roleselect
3819 $groupselect
3820 $extrawheretest
3821 ORDER BY $sort"; // join now so that we can just use fullname() later
3823 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3827 * Counts all the users assigned this role in this context or higher
3829 * @param int|array $roleid either int or an array of ints
3830 * @param context $context
3831 * @param bool $parent if true, get list of users assigned in higher context too
3832 * @return int Returns the result count
3834 function count_role_users($roleid, context $context, $parent = false) {
3835 global $DB;
3837 if ($parent) {
3838 if ($contexts = $context->get_parent_context_ids()) {
3839 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3840 } else {
3841 $parentcontexts = '';
3843 } else {
3844 $parentcontexts = '';
3847 if ($roleid) {
3848 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3849 $roleselect = "AND r.roleid $rids";
3850 } else {
3851 $params = array();
3852 $roleselect = '';
3855 array_unshift($params, $context->id);
3857 $sql = "SELECT COUNT(u.id)
3858 FROM {role_assignments} r
3859 JOIN {user} u ON u.id = r.userid
3860 WHERE (r.contextid = ? $parentcontexts)
3861 $roleselect
3862 AND u.deleted = 0";
3864 return $DB->count_records_sql($sql, $params);
3868 * This function gets the list of courses that this user has a particular capability in.
3869 * It is still not very efficient.
3871 * @param string $capability Capability in question
3872 * @param int $userid User ID or null for current user
3873 * @param bool $doanything True if 'doanything' is permitted (default)
3874 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3875 * otherwise use a comma-separated list of the fields you require, not including id
3876 * @param string $orderby If set, use a comma-separated list of fields from course
3877 * table with sql modifiers (DESC) if needed
3878 * @return array Array of courses, may have zero entries. Or false if query failed.
3880 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
3881 global $DB;
3883 // Convert fields list and ordering
3884 $fieldlist = '';
3885 if ($fieldsexceptid) {
3886 $fields = explode(',', $fieldsexceptid);
3887 foreach($fields as $field) {
3888 $fieldlist .= ',c.'.$field;
3891 if ($orderby) {
3892 $fields = explode(',', $orderby);
3893 $orderby = '';
3894 foreach($fields as $field) {
3895 if ($orderby) {
3896 $orderby .= ',';
3898 $orderby .= 'c.'.$field;
3900 $orderby = 'ORDER BY '.$orderby;
3903 // Obtain a list of everything relevant about all courses including context.
3904 // Note the result can be used directly as a context (we are going to), the course
3905 // fields are just appended.
3907 $contextpreload = context_helper::get_preload_record_columns_sql('x');
3909 $courses = array();
3910 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
3911 FROM {course} c
3912 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
3913 $orderby");
3914 // Check capability for each course in turn
3915 foreach ($rs as $course) {
3916 context_helper::preload_from_record($course);
3917 $context = context_course::instance($course->id);
3918 if (has_capability($capability, $context, $userid, $doanything)) {
3919 // We've got the capability. Make the record look like a course record
3920 // and store it
3921 $courses[] = $course;
3924 $rs->close();
3925 return empty($courses) ? false : $courses;
3929 * This function finds the roles assigned directly to this context only
3930 * i.e. no roles in parent contexts
3932 * @param context $context
3933 * @return array
3935 function get_roles_on_exact_context(context $context) {
3936 global $DB;
3938 return $DB->get_records_sql("SELECT r.*
3939 FROM {role_assignments} ra, {role} r
3940 WHERE ra.roleid = r.id AND ra.contextid = ?",
3941 array($context->id));
3945 * Switches the current user to another role for the current session and only
3946 * in the given context.
3948 * The caller *must* check
3949 * - that this op is allowed
3950 * - that the requested role can be switched to in this context (use get_switchable_roles)
3951 * - that the requested role is NOT $CFG->defaultuserroleid
3953 * To "unswitch" pass 0 as the roleid.
3955 * This function *will* modify $USER->access - beware
3957 * @param integer $roleid the role to switch to.
3958 * @param context $context the context in which to perform the switch.
3959 * @return bool success or failure.
3961 function role_switch($roleid, context $context) {
3962 global $USER;
3965 // Plan of action
3967 // - Add the ghost RA to $USER->access
3968 // as $USER->access['rsw'][$path] = $roleid
3970 // - Make sure $USER->access['rdef'] has the roledefs
3971 // it needs to honour the switcherole
3973 // Roledefs will get loaded "deep" here - down to the last child
3974 // context. Note that
3976 // - When visiting subcontexts, our selective accessdata loading
3977 // will still work fine - though those ra/rdefs will be ignored
3978 // appropriately while the switch is in place
3980 // - If a switcherole happens at a category with tons of courses
3981 // (that have many overrides for switched-to role), the session
3982 // will get... quite large. Sometimes you just can't win.
3984 // To un-switch just unset($USER->access['rsw'][$path])
3986 // Note: it is not possible to switch to roles that do not have course:view
3988 if (!isset($USER->access)) {
3989 load_all_capabilities();
3993 // Add the switch RA
3994 if ($roleid == 0) {
3995 unset($USER->access['rsw'][$context->path]);
3996 return true;
3999 $USER->access['rsw'][$context->path] = $roleid;
4001 // Load roledefs
4002 load_role_access_by_context($roleid, $context, $USER->access);
4004 return true;
4008 * Checks if the user has switched roles within the given course.
4010 * Note: You can only switch roles within the course, hence it takes a course id
4011 * rather than a context. On that note Petr volunteered to implement this across
4012 * all other contexts, all requests for this should be forwarded to him ;)
4014 * @param int $courseid The id of the course to check
4015 * @return bool True if the user has switched roles within the course.
4017 function is_role_switched($courseid) {
4018 global $USER;
4019 $context = context_course::instance($courseid, MUST_EXIST);
4020 return (!empty($USER->access['rsw'][$context->path]));
4024 * Get any role that has an override on exact context
4026 * @param context $context The context to check
4027 * @return array An array of roles
4029 function get_roles_with_override_on_context(context $context) {
4030 global $DB;
4032 return $DB->get_records_sql("SELECT r.*
4033 FROM {role_capabilities} rc, {role} r
4034 WHERE rc.roleid = r.id AND rc.contextid = ?",
4035 array($context->id));
4039 * Get all capabilities for this role on this context (overrides)
4041 * @param stdClass $role
4042 * @param context $context
4043 * @return array
4045 function get_capabilities_from_role_on_context($role, context $context) {
4046 global $DB;
4048 return $DB->get_records_sql("SELECT *
4049 FROM {role_capabilities}
4050 WHERE contextid = ? AND roleid = ?",
4051 array($context->id, $role->id));
4055 * Find out which roles has assignment on this context
4057 * @param context $context
4058 * @return array
4061 function get_roles_with_assignment_on_context(context $context) {
4062 global $DB;
4064 return $DB->get_records_sql("SELECT r.*
4065 FROM {role_assignments} ra, {role} r
4066 WHERE ra.roleid = r.id AND ra.contextid = ?",
4067 array($context->id));
4071 * Find all user assignment of users for this role, on this context
4073 * @param stdClass $role
4074 * @param context $context
4075 * @return array
4077 function get_users_from_role_on_context($role, context $context) {
4078 global $DB;
4080 return $DB->get_records_sql("SELECT *
4081 FROM {role_assignments}
4082 WHERE contextid = ? AND roleid = ?",
4083 array($context->id, $role->id));
4087 * Simple function returning a boolean true if user has roles
4088 * in context or parent contexts, otherwise false.
4090 * @param int $userid
4091 * @param int $roleid
4092 * @param int $contextid empty means any context
4093 * @return bool
4095 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4096 global $DB;
4098 if ($contextid) {
4099 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4100 return false;
4102 $parents = $context->get_parent_context_ids(true);
4103 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4104 $params['userid'] = $userid;
4105 $params['roleid'] = $roleid;
4107 $sql = "SELECT COUNT(ra.id)
4108 FROM {role_assignments} ra
4109 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4111 $count = $DB->get_field_sql($sql, $params);
4112 return ($count > 0);
4114 } else {
4115 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4120 * Get role name or alias if exists and format the text.
4122 * @param stdClass $role role object
4123 * @param context_course $coursecontext
4124 * @return string name of role in course context
4126 function role_get_name($role, context_course $coursecontext) {
4127 global $DB;
4129 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4130 return strip_tags(format_string($r->name));
4131 } else {
4132 return strip_tags(format_string($role->name));
4137 * Prepare list of roles for display, apply aliases and format text
4139 * @param array $roleoptions array roleid => rolename or roleid => roleobject
4140 * @param context $context a context
4141 * @param int $rolenamedisplay
4142 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4144 function role_fix_names($roleoptions, context $context, $rolenamedisplay = ROLENAME_ALIAS) {
4145 global $DB;
4147 // Make sure we have a course context.
4148 $coursecontext = $context->get_course_context(false);
4150 // Make sure we are working with an array roleid => name. Normally we
4151 // want to use the unlocalised name if the localised one is not present.
4152 $newnames = array();
4153 foreach ($roleoptions as $rid => $roleorname) {
4154 if ($rolenamedisplay != ROLENAME_ALIAS_RAW) {
4155 if (is_object($roleorname)) {
4156 $newnames[$rid] = $roleorname->name;
4157 } else {
4158 $newnames[$rid] = $roleorname;
4160 } else {
4161 $newnames[$rid] = '';
4165 // If necessary, get the localised names.
4166 if ($rolenamedisplay != ROLENAME_ORIGINAL && !empty($coursecontext->id)) {
4167 // The get the relevant renames, and use them.
4168 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4169 foreach ($aliasnames as $alias) {
4170 if (isset($newnames[$alias->roleid])) {
4171 if ($rolenamedisplay == ROLENAME_ALIAS || $rolenamedisplay == ROLENAME_ALIAS_RAW) {
4172 $newnames[$alias->roleid] = $alias->name;
4173 } else if ($rolenamedisplay == ROLENAME_BOTH) {
4174 $newnames[$alias->roleid] = $alias->name . ' (' . $roleoptions[$alias->roleid] . ')';
4180 // Finally, apply format_string and put the result in the right place.
4181 foreach ($roleoptions as $rid => $roleorname) {
4182 if ($rolenamedisplay != ROLENAME_ALIAS_RAW) {
4183 $newnames[$rid] = strip_tags(format_string($newnames[$rid]));
4185 if (is_object($roleorname)) {
4186 $roleoptions[$rid]->localname = $newnames[$rid];
4187 } else {
4188 $roleoptions[$rid] = $newnames[$rid];
4191 return $roleoptions;
4195 * Aids in detecting if a new line is required when reading a new capability
4197 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4198 * when we read in a new capability.
4199 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4200 * but when we are in grade, all reports/import/export capabilities should be together
4202 * @param string $cap component string a
4203 * @param string $comp component string b
4204 * @param int $contextlevel
4205 * @return bool whether 2 component are in different "sections"
4207 function component_level_changed($cap, $comp, $contextlevel) {
4209 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4210 $compsa = explode('/', $cap->component);
4211 $compsb = explode('/', $comp);
4213 // list of system reports
4214 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4215 return false;
4218 // we are in gradebook, still
4219 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4220 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4221 return false;
4224 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4225 return false;
4229 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4233 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4234 * and return an array of roleids in order.
4236 * @param array $allroles array of roles, as returned by get_all_roles();
4237 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4239 function fix_role_sortorder($allroles) {
4240 global $DB;
4242 $rolesort = array();
4243 $i = 0;
4244 foreach ($allroles as $role) {
4245 $rolesort[$i] = $role->id;
4246 if ($role->sortorder != $i) {
4247 $r = new stdClass();
4248 $r->id = $role->id;
4249 $r->sortorder = $i;
4250 $DB->update_record('role', $r);
4251 $allroles[$role->id]->sortorder = $i;
4253 $i++;
4255 return $rolesort;
4259 * Switch the sort order of two roles (used in admin/roles/manage.php).
4261 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4262 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4263 * @return boolean success or failure
4265 function switch_roles($first, $second) {
4266 global $DB;
4267 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4268 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4269 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4270 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4271 return $result;
4275 * Duplicates all the base definitions of a role
4277 * @param stdClass $sourcerole role to copy from
4278 * @param int $targetrole id of role to copy to
4280 function role_cap_duplicate($sourcerole, $targetrole) {
4281 global $DB;
4283 $systemcontext = context_system::instance();
4284 $caps = $DB->get_records_sql("SELECT *
4285 FROM {role_capabilities}
4286 WHERE roleid = ? AND contextid = ?",
4287 array($sourcerole->id, $systemcontext->id));
4288 // adding capabilities
4289 foreach ($caps as $cap) {
4290 unset($cap->id);
4291 $cap->roleid = $targetrole;
4292 $DB->insert_record('role_capabilities', $cap);
4297 * Returns two lists, this can be used to find out if user has capability.
4298 * Having any needed role and no forbidden role in this context means
4299 * user has this capability in this context.
4300 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4302 * @param stdClass $context
4303 * @param string $capability
4304 * @return array($neededroles, $forbiddenroles)
4306 function get_roles_with_cap_in_context($context, $capability) {
4307 global $DB;
4309 $ctxids = trim($context->path, '/'); // kill leading slash
4310 $ctxids = str_replace('/', ',', $ctxids);
4312 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4313 FROM {role_capabilities} rc
4314 JOIN {context} ctx ON ctx.id = rc.contextid
4315 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4316 ORDER BY rc.roleid ASC, ctx.depth DESC";
4317 $params = array('cap'=>$capability);
4319 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4320 // no cap definitions --> no capability
4321 return array(array(), array());
4324 $forbidden = array();
4325 $needed = array();
4326 foreach($capdefs as $def) {
4327 if (isset($forbidden[$def->roleid])) {
4328 continue;
4330 if ($def->permission == CAP_PROHIBIT) {
4331 $forbidden[$def->roleid] = $def->roleid;
4332 unset($needed[$def->roleid]);
4333 continue;
4335 if (!isset($needed[$def->roleid])) {
4336 if ($def->permission == CAP_ALLOW) {
4337 $needed[$def->roleid] = true;
4338 } else if ($def->permission == CAP_PREVENT) {
4339 $needed[$def->roleid] = false;
4343 unset($capdefs);
4345 // remove all those roles not allowing
4346 foreach($needed as $key=>$value) {
4347 if (!$value) {
4348 unset($needed[$key]);
4349 } else {
4350 $needed[$key] = $key;
4354 return array($needed, $forbidden);
4358 * Returns an array of role IDs that have ALL of the the supplied capabilities
4359 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4361 * @param stdClass $context
4362 * @param array $capabilities An array of capabilities
4363 * @return array of roles with all of the required capabilities
4365 function get_roles_with_caps_in_context($context, $capabilities) {
4366 $neededarr = array();
4367 $forbiddenarr = array();
4368 foreach($capabilities as $caprequired) {
4369 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4372 $rolesthatcanrate = array();
4373 if (!empty($neededarr)) {
4374 foreach ($neededarr as $needed) {
4375 if (empty($rolesthatcanrate)) {
4376 $rolesthatcanrate = $needed;
4377 } else {
4378 //only want roles that have all caps
4379 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4383 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4384 foreach ($forbiddenarr as $forbidden) {
4385 //remove any roles that are forbidden any of the caps
4386 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4389 return $rolesthatcanrate;
4393 * Returns an array of role names that have ALL of the the supplied capabilities
4394 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4396 * @param stdClass $context
4397 * @param array $capabilities An array of capabilities
4398 * @return array of roles with all of the required capabilities
4400 function get_role_names_with_caps_in_context($context, $capabilities) {
4401 global $DB;
4403 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4405 $allroles = array();
4406 $roles = $DB->get_records('role', null, 'sortorder DESC');
4407 foreach ($roles as $roleid=>$role) {
4408 $allroles[$roleid] = $role->name;
4411 $rolenames = array();
4412 foreach ($rolesthatcanrate as $r) {
4413 $rolenames[$r] = $allroles[$r];
4415 $rolenames = role_fix_names($rolenames, $context);
4416 return $rolenames;
4420 * This function verifies the prohibit comes from this context
4421 * and there are no more prohibits in parent contexts.
4423 * @param int $roleid
4424 * @param context $context
4425 * @param string $capability name
4426 * @return bool
4428 function prohibit_is_removable($roleid, context $context, $capability) {
4429 global $DB;
4431 $ctxids = trim($context->path, '/'); // kill leading slash
4432 $ctxids = str_replace('/', ',', $ctxids);
4434 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4436 $sql = "SELECT ctx.id
4437 FROM {role_capabilities} rc
4438 JOIN {context} ctx ON ctx.id = rc.contextid
4439 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4440 ORDER BY ctx.depth DESC";
4442 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4443 // no prohibits == nothing to remove
4444 return true;
4447 if (count($prohibits) > 1) {
4448 // more prohibits can not be removed
4449 return false;
4452 return !empty($prohibits[$context->id]);
4456 * More user friendly role permission changing,
4457 * it should produce as few overrides as possible.
4459 * @param int $roleid
4460 * @param stdClass $context
4461 * @param string $capname capability name
4462 * @param int $permission
4463 * @return void
4465 function role_change_permission($roleid, $context, $capname, $permission) {
4466 global $DB;
4468 if ($permission == CAP_INHERIT) {
4469 unassign_capability($capname, $roleid, $context->id);
4470 $context->mark_dirty();
4471 return;
4474 $ctxids = trim($context->path, '/'); // kill leading slash
4475 $ctxids = str_replace('/', ',', $ctxids);
4477 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4479 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4480 FROM {role_capabilities} rc
4481 JOIN {context} ctx ON ctx.id = rc.contextid
4482 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4483 ORDER BY ctx.depth DESC";
4485 if ($existing = $DB->get_records_sql($sql, $params)) {
4486 foreach($existing as $e) {
4487 if ($e->permission == CAP_PROHIBIT) {
4488 // prohibit can not be overridden, no point in changing anything
4489 return;
4492 $lowest = array_shift($existing);
4493 if ($lowest->permission == $permission) {
4494 // permission already set in this context or parent - nothing to do
4495 return;
4497 if ($existing) {
4498 $parent = array_shift($existing);
4499 if ($parent->permission == $permission) {
4500 // permission already set in parent context or parent - just unset in this context
4501 // we do this because we want as few overrides as possible for performance reasons
4502 unassign_capability($capname, $roleid, $context->id);
4503 $context->mark_dirty();
4504 return;
4508 } else {
4509 if ($permission == CAP_PREVENT) {
4510 // nothing means role does not have permission
4511 return;
4515 // assign the needed capability
4516 assign_capability($capname, $permission, $roleid, $context->id, true);
4518 // force cap reloading
4519 $context->mark_dirty();
4524 * Basic moodle context abstraction class.
4526 * Google confirms that no other important framework is using "context" class,
4527 * we could use something else like mcontext or moodle_context, but we need to type
4528 * this very often which would be annoying and it would take too much space...
4530 * This class is derived from stdClass for backwards compatibility with
4531 * odl $context record that was returned from DML $DB->get_record()
4533 * @package core_access
4534 * @category access
4535 * @copyright Petr Skoda {@link http://skodak.org}
4536 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4537 * @since 2.2
4539 * @property-read int $id context id
4540 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4541 * @property-read int $instanceid id of related instance in each context
4542 * @property-read string $path path to context, starts with system context
4543 * @property-read int $depth
4545 abstract class context extends stdClass implements IteratorAggregate {
4548 * The context id
4549 * Can be accessed publicly through $context->id
4550 * @var int
4552 protected $_id;
4555 * The context level
4556 * Can be accessed publicly through $context->contextlevel
4557 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4559 protected $_contextlevel;
4562 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4563 * Can be accessed publicly through $context->instanceid
4564 * @var int
4566 protected $_instanceid;
4569 * The path to the context always starting from the system context
4570 * Can be accessed publicly through $context->path
4571 * @var string
4573 protected $_path;
4576 * The depth of the context in relation to parent contexts
4577 * Can be accessed publicly through $context->depth
4578 * @var int
4580 protected $_depth;
4583 * @var array Context caching info
4585 private static $cache_contextsbyid = array();
4588 * @var array Context caching info
4590 private static $cache_contexts = array();
4593 * Context count
4594 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4595 * @var int
4597 protected static $cache_count = 0;
4600 * @var array Context caching info
4602 protected static $cache_preloaded = array();
4605 * @var context_system The system context once initialised
4607 protected static $systemcontext = null;
4610 * Resets the cache to remove all data.
4611 * @static
4613 protected static function reset_caches() {
4614 self::$cache_contextsbyid = array();
4615 self::$cache_contexts = array();
4616 self::$cache_count = 0;
4617 self::$cache_preloaded = array();
4619 self::$systemcontext = null;
4623 * Adds a context to the cache. If the cache is full, discards a batch of
4624 * older entries.
4626 * @static
4627 * @param context $context New context to add
4628 * @return void
4630 protected static function cache_add(context $context) {
4631 if (isset(self::$cache_contextsbyid[$context->id])) {
4632 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4633 return;
4636 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4637 $i = 0;
4638 foreach(self::$cache_contextsbyid as $ctx) {
4639 $i++;
4640 if ($i <= 100) {
4641 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4642 continue;
4644 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4645 // we remove oldest third of the contexts to make room for more contexts
4646 break;
4648 unset(self::$cache_contextsbyid[$ctx->id]);
4649 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4650 self::$cache_count--;
4654 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4655 self::$cache_contextsbyid[$context->id] = $context;
4656 self::$cache_count++;
4660 * Removes a context from the cache.
4662 * @static
4663 * @param context $context Context object to remove
4664 * @return void
4666 protected static function cache_remove(context $context) {
4667 if (!isset(self::$cache_contextsbyid[$context->id])) {
4668 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4669 return;
4671 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4672 unset(self::$cache_contextsbyid[$context->id]);
4674 self::$cache_count--;
4676 if (self::$cache_count < 0) {
4677 self::$cache_count = 0;
4682 * Gets a context from the cache.
4684 * @static
4685 * @param int $contextlevel Context level
4686 * @param int $instance Instance ID
4687 * @return context|bool Context or false if not in cache
4689 protected static function cache_get($contextlevel, $instance) {
4690 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4691 return self::$cache_contexts[$contextlevel][$instance];
4693 return false;
4697 * Gets a context from the cache based on its id.
4699 * @static
4700 * @param int $id Context ID
4701 * @return context|bool Context or false if not in cache
4703 protected static function cache_get_by_id($id) {
4704 if (isset(self::$cache_contextsbyid[$id])) {
4705 return self::$cache_contextsbyid[$id];
4707 return false;
4711 * Preloads context information from db record and strips the cached info.
4713 * @static
4714 * @param stdClass $rec
4715 * @return void (modifies $rec)
4717 protected static function preload_from_record(stdClass $rec) {
4718 if (empty($rec->ctxid) or empty($rec->ctxlevel) or empty($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
4719 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4720 return;
4723 // note: in PHP5 the objects are passed by reference, no need to return $rec
4724 $record = new stdClass();
4725 $record->id = $rec->ctxid; unset($rec->ctxid);
4726 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
4727 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
4728 $record->path = $rec->ctxpath; unset($rec->ctxpath);
4729 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
4731 return context::create_instance_from_record($record);
4735 // ====== magic methods =======
4738 * Magic setter method, we do not want anybody to modify properties from the outside
4739 * @param string $name
4740 * @param mixed $value
4742 public function __set($name, $value) {
4743 debugging('Can not change context instance properties!');
4747 * Magic method getter, redirects to read only values.
4748 * @param string $name
4749 * @return mixed
4751 public function __get($name) {
4752 switch ($name) {
4753 case 'id': return $this->_id;
4754 case 'contextlevel': return $this->_contextlevel;
4755 case 'instanceid': return $this->_instanceid;
4756 case 'path': return $this->_path;
4757 case 'depth': return $this->_depth;
4759 default:
4760 debugging('Invalid context property accessed! '.$name);
4761 return null;
4766 * Full support for isset on our magic read only properties.
4767 * @param string $name
4768 * @return bool
4770 public function __isset($name) {
4771 switch ($name) {
4772 case 'id': return isset($this->_id);
4773 case 'contextlevel': return isset($this->_contextlevel);
4774 case 'instanceid': return isset($this->_instanceid);
4775 case 'path': return isset($this->_path);
4776 case 'depth': return isset($this->_depth);
4778 default: return false;
4784 * ALl properties are read only, sorry.
4785 * @param string $name
4787 public function __unset($name) {
4788 debugging('Can not unset context instance properties!');
4791 // ====== implementing method from interface IteratorAggregate ======
4794 * Create an iterator because magic vars can't be seen by 'foreach'.
4796 * Now we can convert context object to array using convert_to_array(),
4797 * and feed it properly to json_encode().
4799 public function getIterator() {
4800 $ret = array(
4801 'id' => $this->id,
4802 'contextlevel' => $this->contextlevel,
4803 'instanceid' => $this->instanceid,
4804 'path' => $this->path,
4805 'depth' => $this->depth
4807 return new ArrayIterator($ret);
4810 // ====== general context methods ======
4813 * Constructor is protected so that devs are forced to
4814 * use context_xxx::instance() or context::instance_by_id().
4816 * @param stdClass $record
4818 protected function __construct(stdClass $record) {
4819 $this->_id = $record->id;
4820 $this->_contextlevel = (int)$record->contextlevel;
4821 $this->_instanceid = $record->instanceid;
4822 $this->_path = $record->path;
4823 $this->_depth = $record->depth;
4827 * This function is also used to work around 'protected' keyword problems in context_helper.
4828 * @static
4829 * @param stdClass $record
4830 * @return context instance
4832 protected static function create_instance_from_record(stdClass $record) {
4833 $classname = context_helper::get_class_for_level($record->contextlevel);
4835 if ($context = context::cache_get_by_id($record->id)) {
4836 return $context;
4839 $context = new $classname($record);
4840 context::cache_add($context);
4842 return $context;
4846 * Copy prepared new contexts from temp table to context table,
4847 * we do this in db specific way for perf reasons only.
4848 * @static
4850 protected static function merge_context_temp_table() {
4851 global $DB;
4853 /* MDL-11347:
4854 * - mysql does not allow to use FROM in UPDATE statements
4855 * - using two tables after UPDATE works in mysql, but might give unexpected
4856 * results in pg 8 (depends on configuration)
4857 * - using table alias in UPDATE does not work in pg < 8.2
4859 * Different code for each database - mostly for performance reasons
4862 $dbfamily = $DB->get_dbfamily();
4863 if ($dbfamily == 'mysql') {
4864 $updatesql = "UPDATE {context} ct, {context_temp} temp
4865 SET ct.path = temp.path,
4866 ct.depth = temp.depth
4867 WHERE ct.id = temp.id";
4868 } else if ($dbfamily == 'oracle') {
4869 $updatesql = "UPDATE {context} ct
4870 SET (ct.path, ct.depth) =
4871 (SELECT temp.path, temp.depth
4872 FROM {context_temp} temp
4873 WHERE temp.id=ct.id)
4874 WHERE EXISTS (SELECT 'x'
4875 FROM {context_temp} temp
4876 WHERE temp.id = ct.id)";
4877 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
4878 $updatesql = "UPDATE {context}
4879 SET path = temp.path,
4880 depth = temp.depth
4881 FROM {context_temp} temp
4882 WHERE temp.id={context}.id";
4883 } else {
4884 // sqlite and others
4885 $updatesql = "UPDATE {context}
4886 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
4887 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
4888 WHERE id IN (SELECT id FROM {context_temp})";
4891 $DB->execute($updatesql);
4895 * Get a context instance as an object, from a given context id.
4897 * @static
4898 * @param int $id context id
4899 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
4900 * MUST_EXIST means throw exception if no record found
4901 * @return context|bool the context object or false if not found
4903 public static function instance_by_id($id, $strictness = MUST_EXIST) {
4904 global $DB;
4906 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
4907 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
4908 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
4911 if ($id == SYSCONTEXTID) {
4912 return context_system::instance(0, $strictness);
4915 if (is_array($id) or is_object($id) or empty($id)) {
4916 throw new coding_exception('Invalid context id specified context::instance_by_id()');
4919 if ($context = context::cache_get_by_id($id)) {
4920 return $context;
4923 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
4924 return context::create_instance_from_record($record);
4927 return false;
4931 * Update context info after moving context in the tree structure.
4933 * @param context $newparent
4934 * @return void
4936 public function update_moved(context $newparent) {
4937 global $DB;
4939 $frompath = $this->_path;
4940 $newpath = $newparent->path . '/' . $this->_id;
4942 $trans = $DB->start_delegated_transaction();
4944 $this->mark_dirty();
4946 $setdepth = '';
4947 if (($newparent->depth +1) != $this->_depth) {
4948 $diff = $newparent->depth - $this->_depth + 1;
4949 $setdepth = ", depth = depth + $diff";
4951 $sql = "UPDATE {context}
4952 SET path = ?
4953 $setdepth
4954 WHERE id = ?";
4955 $params = array($newpath, $this->_id);
4956 $DB->execute($sql, $params);
4958 $this->_path = $newpath;
4959 $this->_depth = $newparent->depth + 1;
4961 $sql = "UPDATE {context}
4962 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
4963 $setdepth
4964 WHERE path LIKE ?";
4965 $params = array($newpath, "{$frompath}/%");
4966 $DB->execute($sql, $params);
4968 $this->mark_dirty();
4970 context::reset_caches();
4972 $trans->allow_commit();
4976 * Remove all context path info and optionally rebuild it.
4978 * @param bool $rebuild
4979 * @return void
4981 public function reset_paths($rebuild = true) {
4982 global $DB;
4984 if ($this->_path) {
4985 $this->mark_dirty();
4987 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
4988 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
4989 if ($this->_contextlevel != CONTEXT_SYSTEM) {
4990 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
4991 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
4992 $this->_depth = 0;
4993 $this->_path = null;
4996 if ($rebuild) {
4997 context_helper::build_all_paths(false);
5000 context::reset_caches();
5004 * Delete all data linked to content, do not delete the context record itself
5006 public function delete_content() {
5007 global $CFG, $DB;
5009 blocks_delete_all_for_context($this->_id);
5010 filter_delete_all_for_context($this->_id);
5012 require_once($CFG->dirroot . '/comment/lib.php');
5013 comment::delete_comments(array('contextid'=>$this->_id));
5015 require_once($CFG->dirroot.'/rating/lib.php');
5016 $delopt = new stdclass();
5017 $delopt->contextid = $this->_id;
5018 $rm = new rating_manager();
5019 $rm->delete_ratings($delopt);
5021 // delete all files attached to this context
5022 $fs = get_file_storage();
5023 $fs->delete_area_files($this->_id);
5025 // delete all advanced grading data attached to this context
5026 require_once($CFG->dirroot.'/grade/grading/lib.php');
5027 grading_manager::delete_all_for_context($this->_id);
5029 // now delete stuff from role related tables, role_unassign_all
5030 // and unenrol should be called earlier to do proper cleanup
5031 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5032 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5033 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5037 * Delete the context content and the context record itself
5039 public function delete() {
5040 global $DB;
5042 // double check the context still exists
5043 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5044 context::cache_remove($this);
5045 return;
5048 $this->delete_content();
5049 $DB->delete_records('context', array('id'=>$this->_id));
5050 // purge static context cache if entry present
5051 context::cache_remove($this);
5053 // do not mark dirty contexts if parents unknown
5054 if (!is_null($this->_path) and $this->_depth > 0) {
5055 $this->mark_dirty();
5059 // ====== context level related methods ======
5062 * Utility method for context creation
5064 * @static
5065 * @param int $contextlevel
5066 * @param int $instanceid
5067 * @param string $parentpath
5068 * @return stdClass context record
5070 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5071 global $DB;
5073 $record = new stdClass();
5074 $record->contextlevel = $contextlevel;
5075 $record->instanceid = $instanceid;
5076 $record->depth = 0;
5077 $record->path = null; //not known before insert
5079 $record->id = $DB->insert_record('context', $record);
5081 // now add path if known - it can be added later
5082 if (!is_null($parentpath)) {
5083 $record->path = $parentpath.'/'.$record->id;
5084 $record->depth = substr_count($record->path, '/');
5085 $DB->update_record('context', $record);
5088 return $record;
5092 * Returns human readable context identifier.
5094 * @param boolean $withprefix whether to prefix the name of the context with the
5095 * type of context, e.g. User, Course, Forum, etc.
5096 * @param boolean $short whether to use the short name of the thing. Only applies
5097 * to course contexts
5098 * @return string the human readable context name.
5100 public function get_context_name($withprefix = true, $short = false) {
5101 // must be implemented in all context levels
5102 throw new coding_exception('can not get name of abstract context');
5106 * Returns the most relevant URL for this context.
5108 * @return moodle_url
5110 public abstract function get_url();
5113 * Returns array of relevant context capability records.
5115 * @return array
5117 public abstract function get_capabilities();
5120 * Recursive function which, given a context, find all its children context ids.
5122 * For course category contexts it will return immediate children and all subcategory contexts.
5123 * It will NOT recurse into courses or subcategories categories.
5124 * If you want to do that, call it on the returned courses/categories.
5126 * When called for a course context, it will return the modules and blocks
5127 * displayed in the course page and blocks displayed on the module pages.
5129 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5130 * contexts ;-)
5132 * @return array Array of child records
5134 public function get_child_contexts() {
5135 global $DB;
5137 $sql = "SELECT ctx.*
5138 FROM {context} ctx
5139 WHERE ctx.path LIKE ?";
5140 $params = array($this->_path.'/%');
5141 $records = $DB->get_records_sql($sql, $params);
5143 $result = array();
5144 foreach ($records as $record) {
5145 $result[$record->id] = context::create_instance_from_record($record);
5148 return $result;
5152 * Returns parent contexts of this context in reversed order, i.e. parent first,
5153 * then grand parent, etc.
5155 * @param bool $includeself tre means include self too
5156 * @return array of context instances
5158 public function get_parent_contexts($includeself = false) {
5159 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5160 return array();
5163 $result = array();
5164 foreach ($contextids as $contextid) {
5165 $parent = context::instance_by_id($contextid, MUST_EXIST);
5166 $result[$parent->id] = $parent;
5169 return $result;
5173 * Returns parent contexts of this context in reversed order, i.e. parent first,
5174 * then grand parent, etc.
5176 * @param bool $includeself tre means include self too
5177 * @return array of context ids
5179 public function get_parent_context_ids($includeself = false) {
5180 if (empty($this->_path)) {
5181 return array();
5184 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5185 $parentcontexts = explode('/', $parentcontexts);
5186 if (!$includeself) {
5187 array_pop($parentcontexts); // and remove its own id
5190 return array_reverse($parentcontexts);
5194 * Returns parent context
5196 * @return context
5198 public function get_parent_context() {
5199 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5200 return false;
5203 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5204 $parentcontexts = explode('/', $parentcontexts);
5205 array_pop($parentcontexts); // self
5206 $contextid = array_pop($parentcontexts); // immediate parent
5208 return context::instance_by_id($contextid, MUST_EXIST);
5212 * Is this context part of any course? If yes return course context.
5214 * @param bool $strict true means throw exception if not found, false means return false if not found
5215 * @return course_context context of the enclosing course, null if not found or exception
5217 public function get_course_context($strict = true) {
5218 if ($strict) {
5219 throw new coding_exception('Context does not belong to any course.');
5220 } else {
5221 return false;
5226 * Returns sql necessary for purging of stale context instances.
5228 * @static
5229 * @return string cleanup SQL
5231 protected static function get_cleanup_sql() {
5232 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5236 * Rebuild context paths and depths at context level.
5238 * @static
5239 * @param bool $force
5240 * @return void
5242 protected static function build_paths($force) {
5243 throw new coding_exception('build_paths() method must be implemented in all context levels');
5247 * Create missing context instances at given level
5249 * @static
5250 * @return void
5252 protected static function create_level_instances() {
5253 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5257 * Reset all cached permissions and definitions if the necessary.
5258 * @return void
5260 public function reload_if_dirty() {
5261 global $ACCESSLIB_PRIVATE, $USER;
5263 // Load dirty contexts list if needed
5264 if (CLI_SCRIPT) {
5265 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5266 // we do not load dirty flags in CLI and cron
5267 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5269 } else {
5270 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5271 if (!isset($USER->access['time'])) {
5272 // nothing was loaded yet, we do not need to check dirty contexts now
5273 return;
5275 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5276 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5280 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5281 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5282 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5283 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5284 reload_all_capabilities();
5285 break;
5291 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5293 public function mark_dirty() {
5294 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5296 if (during_initial_install()) {
5297 return;
5300 // only if it is a non-empty string
5301 if (is_string($this->_path) && $this->_path !== '') {
5302 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5303 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5304 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5305 } else {
5306 if (CLI_SCRIPT) {
5307 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5308 } else {
5309 if (isset($USER->access['time'])) {
5310 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5311 } else {
5312 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5314 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5323 * Context maintenance and helper methods.
5325 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5326 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5327 * level implementation from the rest of code, the code completion returns what developers need.
5329 * Thank you Tim Hunt for helping me with this nasty trick.
5331 * @package core_access
5332 * @category access
5333 * @copyright Petr Skoda {@link http://skodak.org}
5334 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5335 * @since 2.2
5337 class context_helper extends context {
5340 * @var array An array mapping context levels to classes
5342 private static $alllevels = array(
5343 CONTEXT_SYSTEM => 'context_system',
5344 CONTEXT_USER => 'context_user',
5345 CONTEXT_COURSECAT => 'context_coursecat',
5346 CONTEXT_COURSE => 'context_course',
5347 CONTEXT_MODULE => 'context_module',
5348 CONTEXT_BLOCK => 'context_block',
5352 * Instance does not make sense here, only static use
5354 protected function __construct() {
5358 * Returns a class name of the context level class
5360 * @static
5361 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5362 * @return string class name of the context class
5364 public static function get_class_for_level($contextlevel) {
5365 if (isset(self::$alllevels[$contextlevel])) {
5366 return self::$alllevels[$contextlevel];
5367 } else {
5368 throw new coding_exception('Invalid context level specified');
5373 * Returns a list of all context levels
5375 * @static
5376 * @return array int=>string (level=>level class name)
5378 public static function get_all_levels() {
5379 return self::$alllevels;
5383 * Remove stale contexts that belonged to deleted instances.
5384 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5386 * @static
5387 * @return void
5389 public static function cleanup_instances() {
5390 global $DB;
5391 $sqls = array();
5392 foreach (self::$alllevels as $level=>$classname) {
5393 $sqls[] = $classname::get_cleanup_sql();
5396 $sql = implode(" UNION ", $sqls);
5398 // it is probably better to use transactions, it might be faster too
5399 $transaction = $DB->start_delegated_transaction();
5401 $rs = $DB->get_recordset_sql($sql);
5402 foreach ($rs as $record) {
5403 $context = context::create_instance_from_record($record);
5404 $context->delete();
5406 $rs->close();
5408 $transaction->allow_commit();
5412 * Create all context instances at the given level and above.
5414 * @static
5415 * @param int $contextlevel null means all levels
5416 * @param bool $buildpaths
5417 * @return void
5419 public static function create_instances($contextlevel = null, $buildpaths = true) {
5420 foreach (self::$alllevels as $level=>$classname) {
5421 if ($contextlevel and $level > $contextlevel) {
5422 // skip potential sub-contexts
5423 continue;
5425 $classname::create_level_instances();
5426 if ($buildpaths) {
5427 $classname::build_paths(false);
5433 * Rebuild paths and depths in all context levels.
5435 * @static
5436 * @param bool $force false means add missing only
5437 * @return void
5439 public static function build_all_paths($force = false) {
5440 foreach (self::$alllevels as $classname) {
5441 $classname::build_paths($force);
5444 // reset static course cache - it might have incorrect cached data
5445 accesslib_clear_all_caches(true);
5449 * Resets the cache to remove all data.
5450 * @static
5452 public static function reset_caches() {
5453 context::reset_caches();
5457 * Returns all fields necessary for context preloading from user $rec.
5459 * This helps with performance when dealing with hundreds of contexts.
5461 * @static
5462 * @param string $tablealias context table alias in the query
5463 * @return array (table.column=>alias, ...)
5465 public static function get_preload_record_columns($tablealias) {
5466 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5470 * Returns all fields necessary for context preloading from user $rec.
5472 * This helps with performance when dealing with hundreds of contexts.
5474 * @static
5475 * @param string $tablealias context table alias in the query
5476 * @return string
5478 public static function get_preload_record_columns_sql($tablealias) {
5479 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5483 * Preloads context information from db record and strips the cached info.
5485 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5487 * @static
5488 * @param stdClass $rec
5489 * @return void (modifies $rec)
5491 public static function preload_from_record(stdClass $rec) {
5492 context::preload_from_record($rec);
5496 * Preload all contexts instances from course.
5498 * To be used if you expect multiple queries for course activities...
5500 * @static
5501 * @param int $courseid
5503 public static function preload_course($courseid) {
5504 // Users can call this multiple times without doing any harm
5505 if (isset(context::$cache_preloaded[$courseid])) {
5506 return;
5508 $coursecontext = context_course::instance($courseid);
5509 $coursecontext->get_child_contexts();
5511 context::$cache_preloaded[$courseid] = true;
5515 * Delete context instance
5517 * @static
5518 * @param int $contextlevel
5519 * @param int $instanceid
5520 * @return void
5522 public static function delete_instance($contextlevel, $instanceid) {
5523 global $DB;
5525 // double check the context still exists
5526 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5527 $context = context::create_instance_from_record($record);
5528 $context->delete();
5529 } else {
5530 // we should try to purge the cache anyway
5535 * Returns the name of specified context level
5537 * @static
5538 * @param int $contextlevel
5539 * @return string name of the context level
5541 public static function get_level_name($contextlevel) {
5542 $classname = context_helper::get_class_for_level($contextlevel);
5543 return $classname::get_level_name();
5547 * not used
5549 public function get_url() {
5553 * not used
5555 public function get_capabilities() {
5561 * System context class
5563 * @package core_access
5564 * @category access
5565 * @copyright Petr Skoda {@link http://skodak.org}
5566 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5567 * @since 2.2
5569 class context_system extends context {
5571 * Please use context_system::instance() if you need the instance of context.
5573 * @param stdClass $record
5575 protected function __construct(stdClass $record) {
5576 parent::__construct($record);
5577 if ($record->contextlevel != CONTEXT_SYSTEM) {
5578 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5583 * Returns human readable context level name.
5585 * @static
5586 * @return string the human readable context level name.
5588 public static function get_level_name() {
5589 return get_string('coresystem');
5593 * Returns human readable context identifier.
5595 * @param boolean $withprefix does not apply to system context
5596 * @param boolean $short does not apply to system context
5597 * @return string the human readable context name.
5599 public function get_context_name($withprefix = true, $short = false) {
5600 return self::get_level_name();
5604 * Returns the most relevant URL for this context.
5606 * @return moodle_url
5608 public function get_url() {
5609 return new moodle_url('/');
5613 * Returns array of relevant context capability records.
5615 * @return array
5617 public function get_capabilities() {
5618 global $DB;
5620 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5622 $params = array();
5623 $sql = "SELECT *
5624 FROM {capabilities}";
5626 return $DB->get_records_sql($sql.' '.$sort, $params);
5630 * Create missing context instances at system context
5631 * @static
5633 protected static function create_level_instances() {
5634 // nothing to do here, the system context is created automatically in installer
5635 self::instance(0);
5639 * Returns system context instance.
5641 * @static
5642 * @param int $instanceid
5643 * @param int $strictness
5644 * @param bool $cache
5645 * @return context_system context instance
5647 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
5648 global $DB;
5650 if ($instanceid != 0) {
5651 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5654 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5655 if (!isset(context::$systemcontext)) {
5656 $record = new stdClass();
5657 $record->id = SYSCONTEXTID;
5658 $record->contextlevel = CONTEXT_SYSTEM;
5659 $record->instanceid = 0;
5660 $record->path = '/'.SYSCONTEXTID;
5661 $record->depth = 1;
5662 context::$systemcontext = new context_system($record);
5664 return context::$systemcontext;
5668 try {
5669 // we ignore the strictness completely because system context must except except during install
5670 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5671 } catch (dml_exception $e) {
5672 //table or record does not exist
5673 if (!during_initial_install()) {
5674 // do not mess with system context after install, it simply must exist
5675 throw $e;
5677 $record = null;
5680 if (!$record) {
5681 $record = new stdClass();
5682 $record->contextlevel = CONTEXT_SYSTEM;
5683 $record->instanceid = 0;
5684 $record->depth = 1;
5685 $record->path = null; //not known before insert
5687 try {
5688 if ($DB->count_records('context')) {
5689 // contexts already exist, this is very weird, system must be first!!!
5690 return null;
5692 if (defined('SYSCONTEXTID')) {
5693 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5694 $record->id = SYSCONTEXTID;
5695 $DB->import_record('context', $record);
5696 $DB->get_manager()->reset_sequence('context');
5697 } else {
5698 $record->id = $DB->insert_record('context', $record);
5700 } catch (dml_exception $e) {
5701 // can not create context - table does not exist yet, sorry
5702 return null;
5706 if ($record->instanceid != 0) {
5707 // this is very weird, somebody must be messing with context table
5708 debugging('Invalid system context detected');
5711 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5712 // fix path if necessary, initial install or path reset
5713 $record->depth = 1;
5714 $record->path = '/'.$record->id;
5715 $DB->update_record('context', $record);
5718 if (!defined('SYSCONTEXTID')) {
5719 define('SYSCONTEXTID', $record->id);
5722 context::$systemcontext = new context_system($record);
5723 return context::$systemcontext;
5727 * Returns all site contexts except the system context, DO NOT call on production servers!!
5729 * Contexts are not cached.
5731 * @return array
5733 public function get_child_contexts() {
5734 global $DB;
5736 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
5738 // Just get all the contexts except for CONTEXT_SYSTEM level
5739 // and hope we don't OOM in the process - don't cache
5740 $sql = "SELECT c.*
5741 FROM {context} c
5742 WHERE contextlevel > ".CONTEXT_SYSTEM;
5743 $records = $DB->get_records_sql($sql);
5745 $result = array();
5746 foreach ($records as $record) {
5747 $result[$record->id] = context::create_instance_from_record($record);
5750 return $result;
5754 * Returns sql necessary for purging of stale context instances.
5756 * @static
5757 * @return string cleanup SQL
5759 protected static function get_cleanup_sql() {
5760 $sql = "
5761 SELECT c.*
5762 FROM {context} c
5763 WHERE 1=2
5766 return $sql;
5770 * Rebuild context paths and depths at system context level.
5772 * @static
5773 * @param bool $force
5775 protected static function build_paths($force) {
5776 global $DB;
5778 /* note: ignore $force here, we always do full test of system context */
5780 // exactly one record must exist
5781 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5783 if ($record->instanceid != 0) {
5784 debugging('Invalid system context detected');
5787 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
5788 debugging('Invalid SYSCONTEXTID detected');
5791 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5792 // fix path if necessary, initial install or path reset
5793 $record->depth = 1;
5794 $record->path = '/'.$record->id;
5795 $DB->update_record('context', $record);
5802 * User context class
5804 * @package core_access
5805 * @category access
5806 * @copyright Petr Skoda {@link http://skodak.org}
5807 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5808 * @since 2.2
5810 class context_user extends context {
5812 * Please use context_user::instance($userid) if you need the instance of context.
5813 * Alternatively if you know only the context id use context::instance_by_id($contextid)
5815 * @param stdClass $record
5817 protected function __construct(stdClass $record) {
5818 parent::__construct($record);
5819 if ($record->contextlevel != CONTEXT_USER) {
5820 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
5825 * Returns human readable context level name.
5827 * @static
5828 * @return string the human readable context level name.
5830 public static function get_level_name() {
5831 return get_string('user');
5835 * Returns human readable context identifier.
5837 * @param boolean $withprefix whether to prefix the name of the context with User
5838 * @param boolean $short does not apply to user context
5839 * @return string the human readable context name.
5841 public function get_context_name($withprefix = true, $short = false) {
5842 global $DB;
5844 $name = '';
5845 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
5846 if ($withprefix){
5847 $name = get_string('user').': ';
5849 $name .= fullname($user);
5851 return $name;
5855 * Returns the most relevant URL for this context.
5857 * @return moodle_url
5859 public function get_url() {
5860 global $COURSE;
5862 if ($COURSE->id == SITEID) {
5863 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
5864 } else {
5865 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
5867 return $url;
5871 * Returns array of relevant context capability records.
5873 * @return array
5875 public function get_capabilities() {
5876 global $DB;
5878 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5880 $extracaps = array('moodle/grade:viewall');
5881 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
5882 $sql = "SELECT *
5883 FROM {capabilities}
5884 WHERE contextlevel = ".CONTEXT_USER."
5885 OR name $extra";
5887 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
5891 * Returns user context instance.
5893 * @static
5894 * @param int $instanceid
5895 * @param int $strictness
5896 * @return context_user context instance
5898 public static function instance($instanceid, $strictness = MUST_EXIST) {
5899 global $DB;
5901 if ($context = context::cache_get(CONTEXT_USER, $instanceid)) {
5902 return $context;
5905 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_USER, 'instanceid'=>$instanceid))) {
5906 if ($user = $DB->get_record('user', array('id'=>$instanceid, 'deleted'=>0), 'id', $strictness)) {
5907 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
5911 if ($record) {
5912 $context = new context_user($record);
5913 context::cache_add($context);
5914 return $context;
5917 return false;
5921 * Create missing context instances at user context level
5922 * @static
5924 protected static function create_level_instances() {
5925 global $DB;
5927 $sql = "INSERT INTO {context} (contextlevel, instanceid)
5928 SELECT ".CONTEXT_USER.", u.id
5929 FROM {user} u
5930 WHERE u.deleted = 0
5931 AND NOT EXISTS (SELECT 'x'
5932 FROM {context} cx
5933 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
5934 $DB->execute($sql);
5938 * Returns sql necessary for purging of stale context instances.
5940 * @static
5941 * @return string cleanup SQL
5943 protected static function get_cleanup_sql() {
5944 $sql = "
5945 SELECT c.*
5946 FROM {context} c
5947 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
5948 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
5951 return $sql;
5955 * Rebuild context paths and depths at user context level.
5957 * @static
5958 * @param bool $force
5960 protected static function build_paths($force) {
5961 global $DB;
5963 // First update normal users.
5964 $path = $DB->sql_concat('?', 'id');
5965 $pathstart = '/' . SYSCONTEXTID . '/';
5966 $params = array($pathstart);
5968 if ($force) {
5969 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
5970 $params[] = $pathstart;
5971 } else {
5972 $where = "depth = 0 OR path IS NULL";
5975 $sql = "UPDATE {context}
5976 SET depth = 2,
5977 path = {$path}
5978 WHERE contextlevel = " . CONTEXT_USER . "
5979 AND ($where)";
5980 $DB->execute($sql, $params);
5986 * Course category context class
5988 * @package core_access
5989 * @category access
5990 * @copyright Petr Skoda {@link http://skodak.org}
5991 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5992 * @since 2.2
5994 class context_coursecat extends context {
5996 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
5997 * Alternatively if you know only the context id use context::instance_by_id($contextid)
5999 * @param stdClass $record
6001 protected function __construct(stdClass $record) {
6002 parent::__construct($record);
6003 if ($record->contextlevel != CONTEXT_COURSECAT) {
6004 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6009 * Returns human readable context level name.
6011 * @static
6012 * @return string the human readable context level name.
6014 public static function get_level_name() {
6015 return get_string('category');
6019 * Returns human readable context identifier.
6021 * @param boolean $withprefix whether to prefix the name of the context with Category
6022 * @param boolean $short does not apply to course categories
6023 * @return string the human readable context name.
6025 public function get_context_name($withprefix = true, $short = false) {
6026 global $DB;
6028 $name = '';
6029 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6030 if ($withprefix){
6031 $name = get_string('category').': ';
6033 $name .= format_string($category->name, true, array('context' => $this));
6035 return $name;
6039 * Returns the most relevant URL for this context.
6041 * @return moodle_url
6043 public function get_url() {
6044 return new moodle_url('/course/category.php', array('id'=>$this->_instanceid));
6048 * Returns array of relevant context capability records.
6050 * @return array
6052 public function get_capabilities() {
6053 global $DB;
6055 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6057 $params = array();
6058 $sql = "SELECT *
6059 FROM {capabilities}
6060 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6062 return $DB->get_records_sql($sql.' '.$sort, $params);
6066 * Returns course category context instance.
6068 * @static
6069 * @param int $instanceid
6070 * @param int $strictness
6071 * @return context_coursecat context instance
6073 public static function instance($instanceid, $strictness = MUST_EXIST) {
6074 global $DB;
6076 if ($context = context::cache_get(CONTEXT_COURSECAT, $instanceid)) {
6077 return $context;
6080 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSECAT, 'instanceid'=>$instanceid))) {
6081 if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), 'id,parent', $strictness)) {
6082 if ($category->parent) {
6083 $parentcontext = context_coursecat::instance($category->parent);
6084 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6085 } else {
6086 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6091 if ($record) {
6092 $context = new context_coursecat($record);
6093 context::cache_add($context);
6094 return $context;
6097 return false;
6101 * Returns immediate child contexts of category and all subcategories,
6102 * children of subcategories and courses are not returned.
6104 * @return array
6106 public function get_child_contexts() {
6107 global $DB;
6109 $sql = "SELECT ctx.*
6110 FROM {context} ctx
6111 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6112 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6113 $records = $DB->get_records_sql($sql, $params);
6115 $result = array();
6116 foreach ($records as $record) {
6117 $result[$record->id] = context::create_instance_from_record($record);
6120 return $result;
6124 * Create missing context instances at course category context level
6125 * @static
6127 protected static function create_level_instances() {
6128 global $DB;
6130 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6131 SELECT ".CONTEXT_COURSECAT.", cc.id
6132 FROM {course_categories} cc
6133 WHERE NOT EXISTS (SELECT 'x'
6134 FROM {context} cx
6135 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6136 $DB->execute($sql);
6140 * Returns sql necessary for purging of stale context instances.
6142 * @static
6143 * @return string cleanup SQL
6145 protected static function get_cleanup_sql() {
6146 $sql = "
6147 SELECT c.*
6148 FROM {context} c
6149 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6150 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6153 return $sql;
6157 * Rebuild context paths and depths at course category context level.
6159 * @static
6160 * @param bool $force
6162 protected static function build_paths($force) {
6163 global $DB;
6165 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6166 if ($force) {
6167 $ctxemptyclause = $emptyclause = '';
6168 } else {
6169 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6170 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6173 $base = '/'.SYSCONTEXTID;
6175 // Normal top level categories
6176 $sql = "UPDATE {context}
6177 SET depth=2,
6178 path=".$DB->sql_concat("'$base/'", 'id')."
6179 WHERE contextlevel=".CONTEXT_COURSECAT."
6180 AND EXISTS (SELECT 'x'
6181 FROM {course_categories} cc
6182 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6183 $emptyclause";
6184 $DB->execute($sql);
6186 // Deeper categories - one query per depthlevel
6187 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6188 for ($n=2; $n<=$maxdepth; $n++) {
6189 $sql = "INSERT INTO {context_temp} (id, path, depth)
6190 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6191 FROM {context} ctx
6192 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6193 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6194 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6195 $ctxemptyclause";
6196 $trans = $DB->start_delegated_transaction();
6197 $DB->delete_records('context_temp');
6198 $DB->execute($sql);
6199 context::merge_context_temp_table();
6200 $DB->delete_records('context_temp');
6201 $trans->allow_commit();
6210 * Course context class
6212 * @package core_access
6213 * @category access
6214 * @copyright Petr Skoda {@link http://skodak.org}
6215 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6216 * @since 2.2
6218 class context_course extends context {
6220 * Please use context_course::instance($courseid) if you need the instance of context.
6221 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6223 * @param stdClass $record
6225 protected function __construct(stdClass $record) {
6226 parent::__construct($record);
6227 if ($record->contextlevel != CONTEXT_COURSE) {
6228 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6233 * Returns human readable context level name.
6235 * @static
6236 * @return string the human readable context level name.
6238 public static function get_level_name() {
6239 return get_string('course');
6243 * Returns human readable context identifier.
6245 * @param boolean $withprefix whether to prefix the name of the context with Course
6246 * @param boolean $short whether to use the short name of the thing.
6247 * @return string the human readable context name.
6249 public function get_context_name($withprefix = true, $short = false) {
6250 global $DB;
6252 $name = '';
6253 if ($this->_instanceid == SITEID) {
6254 $name = get_string('frontpage', 'admin');
6255 } else {
6256 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6257 if ($withprefix){
6258 $name = get_string('course').': ';
6260 if ($short){
6261 $name .= format_string($course->shortname, true, array('context' => $this));
6262 } else {
6263 $name .= format_string($course->fullname);
6267 return $name;
6271 * Returns the most relevant URL for this context.
6273 * @return moodle_url
6275 public function get_url() {
6276 if ($this->_instanceid != SITEID) {
6277 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6280 return new moodle_url('/');
6284 * Returns array of relevant context capability records.
6286 * @return array
6288 public function get_capabilities() {
6289 global $DB;
6291 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6293 $params = array();
6294 $sql = "SELECT *
6295 FROM {capabilities}
6296 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6298 return $DB->get_records_sql($sql.' '.$sort, $params);
6302 * Is this context part of any course? If yes return course context.
6304 * @param bool $strict true means throw exception if not found, false means return false if not found
6305 * @return course_context context of the enclosing course, null if not found or exception
6307 public function get_course_context($strict = true) {
6308 return $this;
6312 * Returns course context instance.
6314 * @static
6315 * @param int $instanceid
6316 * @param int $strictness
6317 * @return context_course context instance
6319 public static function instance($instanceid, $strictness = MUST_EXIST) {
6320 global $DB;
6322 if ($context = context::cache_get(CONTEXT_COURSE, $instanceid)) {
6323 return $context;
6326 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$instanceid))) {
6327 if ($course = $DB->get_record('course', array('id'=>$instanceid), 'id,category', $strictness)) {
6328 if ($course->category) {
6329 $parentcontext = context_coursecat::instance($course->category);
6330 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6331 } else {
6332 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6337 if ($record) {
6338 $context = new context_course($record);
6339 context::cache_add($context);
6340 return $context;
6343 return false;
6347 * Create missing context instances at course context level
6348 * @static
6350 protected static function create_level_instances() {
6351 global $DB;
6353 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6354 SELECT ".CONTEXT_COURSE.", c.id
6355 FROM {course} c
6356 WHERE NOT EXISTS (SELECT 'x'
6357 FROM {context} cx
6358 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6359 $DB->execute($sql);
6363 * Returns sql necessary for purging of stale context instances.
6365 * @static
6366 * @return string cleanup SQL
6368 protected static function get_cleanup_sql() {
6369 $sql = "
6370 SELECT c.*
6371 FROM {context} c
6372 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6373 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6376 return $sql;
6380 * Rebuild context paths and depths at course context level.
6382 * @static
6383 * @param bool $force
6385 protected static function build_paths($force) {
6386 global $DB;
6388 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6389 if ($force) {
6390 $ctxemptyclause = $emptyclause = '';
6391 } else {
6392 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6393 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6396 $base = '/'.SYSCONTEXTID;
6398 // Standard frontpage
6399 $sql = "UPDATE {context}
6400 SET depth = 2,
6401 path = ".$DB->sql_concat("'$base/'", 'id')."
6402 WHERE contextlevel = ".CONTEXT_COURSE."
6403 AND EXISTS (SELECT 'x'
6404 FROM {course} c
6405 WHERE c.id = {context}.instanceid AND c.category = 0)
6406 $emptyclause";
6407 $DB->execute($sql);
6409 // standard courses
6410 $sql = "INSERT INTO {context_temp} (id, path, depth)
6411 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6412 FROM {context} ctx
6413 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6414 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6415 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6416 $ctxemptyclause";
6417 $trans = $DB->start_delegated_transaction();
6418 $DB->delete_records('context_temp');
6419 $DB->execute($sql);
6420 context::merge_context_temp_table();
6421 $DB->delete_records('context_temp');
6422 $trans->allow_commit();
6429 * Course module context class
6431 * @package core_access
6432 * @category access
6433 * @copyright Petr Skoda {@link http://skodak.org}
6434 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6435 * @since 2.2
6437 class context_module extends context {
6439 * Please use context_module::instance($cmid) if you need the instance of context.
6440 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6442 * @param stdClass $record
6444 protected function __construct(stdClass $record) {
6445 parent::__construct($record);
6446 if ($record->contextlevel != CONTEXT_MODULE) {
6447 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6452 * Returns human readable context level name.
6454 * @static
6455 * @return string the human readable context level name.
6457 public static function get_level_name() {
6458 return get_string('activitymodule');
6462 * Returns human readable context identifier.
6464 * @param boolean $withprefix whether to prefix the name of the context with the
6465 * module name, e.g. Forum, Glossary, etc.
6466 * @param boolean $short does not apply to module context
6467 * @return string the human readable context name.
6469 public function get_context_name($withprefix = true, $short = false) {
6470 global $DB;
6472 $name = '';
6473 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6474 FROM {course_modules} cm
6475 JOIN {modules} md ON md.id = cm.module
6476 WHERE cm.id = ?", array($this->_instanceid))) {
6477 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6478 if ($withprefix){
6479 $name = get_string('modulename', $cm->modname).': ';
6481 $name .= $mod->name;
6484 return $name;
6488 * Returns the most relevant URL for this context.
6490 * @return moodle_url
6492 public function get_url() {
6493 global $DB;
6495 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6496 FROM {course_modules} cm
6497 JOIN {modules} md ON md.id = cm.module
6498 WHERE cm.id = ?", array($this->_instanceid))) {
6499 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6502 return new moodle_url('/');
6506 * Returns array of relevant context capability records.
6508 * @return array
6510 public function get_capabilities() {
6511 global $DB, $CFG;
6513 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6515 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6516 $module = $DB->get_record('modules', array('id'=>$cm->module));
6518 $subcaps = array();
6519 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6520 if (file_exists($subpluginsfile)) {
6521 $subplugins = array(); // should be redefined in the file
6522 include($subpluginsfile);
6523 if (!empty($subplugins)) {
6524 foreach (array_keys($subplugins) as $subplugintype) {
6525 foreach (array_keys(get_plugin_list($subplugintype)) as $subpluginname) {
6526 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6532 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6533 $extracaps = array();
6534 if (file_exists($modfile)) {
6535 include_once($modfile);
6536 $modfunction = $module->name.'_get_extra_capabilities';
6537 if (function_exists($modfunction)) {
6538 $extracaps = $modfunction();
6542 $extracaps = array_merge($subcaps, $extracaps);
6543 $extra = '';
6544 list($extra, $params) = $DB->get_in_or_equal(
6545 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
6546 if (!empty($extra)) {
6547 $extra = "OR name $extra";
6549 $sql = "SELECT *
6550 FROM {capabilities}
6551 WHERE (contextlevel = ".CONTEXT_MODULE."
6552 AND (component = :component OR component = 'moodle'))
6553 $extra";
6554 $params['component'] = "mod_$module->name";
6556 return $DB->get_records_sql($sql.' '.$sort, $params);
6560 * Is this context part of any course? If yes return course context.
6562 * @param bool $strict true means throw exception if not found, false means return false if not found
6563 * @return course_context context of the enclosing course, null if not found or exception
6565 public function get_course_context($strict = true) {
6566 return $this->get_parent_context();
6570 * Returns module context instance.
6572 * @static
6573 * @param int $instanceid
6574 * @param int $strictness
6575 * @return context_module context instance
6577 public static function instance($instanceid, $strictness = MUST_EXIST) {
6578 global $DB;
6580 if ($context = context::cache_get(CONTEXT_MODULE, $instanceid)) {
6581 return $context;
6584 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$instanceid))) {
6585 if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), 'id,course', $strictness)) {
6586 $parentcontext = context_course::instance($cm->course);
6587 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
6591 if ($record) {
6592 $context = new context_module($record);
6593 context::cache_add($context);
6594 return $context;
6597 return false;
6601 * Create missing context instances at module context level
6602 * @static
6604 protected static function create_level_instances() {
6605 global $DB;
6607 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6608 SELECT ".CONTEXT_MODULE.", cm.id
6609 FROM {course_modules} cm
6610 WHERE NOT EXISTS (SELECT 'x'
6611 FROM {context} cx
6612 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
6613 $DB->execute($sql);
6617 * Returns sql necessary for purging of stale context instances.
6619 * @static
6620 * @return string cleanup SQL
6622 protected static function get_cleanup_sql() {
6623 $sql = "
6624 SELECT c.*
6625 FROM {context} c
6626 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6627 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
6630 return $sql;
6634 * Rebuild context paths and depths at module context level.
6636 * @static
6637 * @param bool $force
6639 protected static function build_paths($force) {
6640 global $DB;
6642 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
6643 if ($force) {
6644 $ctxemptyclause = '';
6645 } else {
6646 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6649 $sql = "INSERT INTO {context_temp} (id, path, depth)
6650 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6651 FROM {context} ctx
6652 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
6653 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
6654 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6655 $ctxemptyclause";
6656 $trans = $DB->start_delegated_transaction();
6657 $DB->delete_records('context_temp');
6658 $DB->execute($sql);
6659 context::merge_context_temp_table();
6660 $DB->delete_records('context_temp');
6661 $trans->allow_commit();
6668 * Block context class
6670 * @package core_access
6671 * @category access
6672 * @copyright Petr Skoda {@link http://skodak.org}
6673 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6674 * @since 2.2
6676 class context_block extends context {
6678 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6679 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6681 * @param stdClass $record
6683 protected function __construct(stdClass $record) {
6684 parent::__construct($record);
6685 if ($record->contextlevel != CONTEXT_BLOCK) {
6686 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6691 * Returns human readable context level name.
6693 * @static
6694 * @return string the human readable context level name.
6696 public static function get_level_name() {
6697 return get_string('block');
6701 * Returns human readable context identifier.
6703 * @param boolean $withprefix whether to prefix the name of the context with Block
6704 * @param boolean $short does not apply to block context
6705 * @return string the human readable context name.
6707 public function get_context_name($withprefix = true, $short = false) {
6708 global $DB, $CFG;
6710 $name = '';
6711 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
6712 global $CFG;
6713 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
6714 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
6715 $blockname = "block_$blockinstance->blockname";
6716 if ($blockobject = new $blockname()) {
6717 if ($withprefix){
6718 $name = get_string('block').': ';
6720 $name .= $blockobject->title;
6724 return $name;
6728 * Returns the most relevant URL for this context.
6730 * @return moodle_url
6732 public function get_url() {
6733 $parentcontexts = $this->get_parent_context();
6734 return $parentcontexts->get_url();
6738 * Returns array of relevant context capability records.
6740 * @return array
6742 public function get_capabilities() {
6743 global $DB;
6745 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6747 $params = array();
6748 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
6750 $extra = '';
6751 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
6752 if ($extracaps) {
6753 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6754 $extra = "OR name $extra";
6757 $sql = "SELECT *
6758 FROM {capabilities}
6759 WHERE (contextlevel = ".CONTEXT_BLOCK."
6760 AND component = :component)
6761 $extra";
6762 $params['component'] = 'block_' . $bi->blockname;
6764 return $DB->get_records_sql($sql.' '.$sort, $params);
6768 * Is this context part of any course? If yes return course context.
6770 * @param bool $strict true means throw exception if not found, false means return false if not found
6771 * @return course_context context of the enclosing course, null if not found or exception
6773 public function get_course_context($strict = true) {
6774 $parentcontext = $this->get_parent_context();
6775 return $parentcontext->get_course_context($strict);
6779 * Returns block context instance.
6781 * @static
6782 * @param int $instanceid
6783 * @param int $strictness
6784 * @return context_block context instance
6786 public static function instance($instanceid, $strictness = MUST_EXIST) {
6787 global $DB;
6789 if ($context = context::cache_get(CONTEXT_BLOCK, $instanceid)) {
6790 return $context;
6793 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$instanceid))) {
6794 if ($bi = $DB->get_record('block_instances', array('id'=>$instanceid), 'id,parentcontextid', $strictness)) {
6795 $parentcontext = context::instance_by_id($bi->parentcontextid);
6796 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
6800 if ($record) {
6801 $context = new context_block($record);
6802 context::cache_add($context);
6803 return $context;
6806 return false;
6810 * Block do not have child contexts...
6811 * @return array
6813 public function get_child_contexts() {
6814 return array();
6818 * Create missing context instances at block context level
6819 * @static
6821 protected static function create_level_instances() {
6822 global $DB;
6824 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6825 SELECT ".CONTEXT_BLOCK.", bi.id
6826 FROM {block_instances} bi
6827 WHERE NOT EXISTS (SELECT 'x'
6828 FROM {context} cx
6829 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
6830 $DB->execute($sql);
6834 * Returns sql necessary for purging of stale context instances.
6836 * @static
6837 * @return string cleanup SQL
6839 protected static function get_cleanup_sql() {
6840 $sql = "
6841 SELECT c.*
6842 FROM {context} c
6843 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
6844 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
6847 return $sql;
6851 * Rebuild context paths and depths at block context level.
6853 * @static
6854 * @param bool $force
6856 protected static function build_paths($force) {
6857 global $DB;
6859 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
6860 if ($force) {
6861 $ctxemptyclause = '';
6862 } else {
6863 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6866 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
6867 $sql = "INSERT INTO {context_temp} (id, path, depth)
6868 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6869 FROM {context} ctx
6870 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
6871 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
6872 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
6873 $ctxemptyclause";
6874 $trans = $DB->start_delegated_transaction();
6875 $DB->delete_records('context_temp');
6876 $DB->execute($sql);
6877 context::merge_context_temp_table();
6878 $DB->delete_records('context_temp');
6879 $trans->allow_commit();
6885 // ============== DEPRECATED FUNCTIONS ==========================================
6886 // Old context related functions were deprecated in 2.0, it is recommended
6887 // to use context classes in new code. Old function can be used when
6888 // creating patches that are supposed to be backported to older stable branches.
6889 // These deprecated functions will not be removed in near future,
6890 // before removing devs will be warned with a debugging message first,
6891 // then we will add error message and only after that we can remove the functions
6892 // completely.
6896 * Not available any more, use load_temp_course_role() instead.
6898 * @deprecated since 2.2
6899 * @param stdClass $context
6900 * @param int $roleid
6901 * @param array $accessdata
6902 * @return array
6904 function load_temp_role($context, $roleid, array $accessdata) {
6905 debugging('load_temp_role() is deprecated, please use load_temp_course_role() instead, temp role not loaded.');
6906 return $accessdata;
6910 * Not available any more, use remove_temp_course_roles() instead.
6912 * @deprecated since 2.2
6913 * @param stdClass $context
6914 * @param array $accessdata
6915 * @return array access data
6917 function remove_temp_roles($context, array $accessdata) {
6918 debugging('remove_temp_role() is deprecated, please use remove_temp_course_roles() instead.');
6919 return $accessdata;
6923 * Returns system context or null if can not be created yet.
6925 * @deprecated since 2.2, use context_system::instance()
6926 * @param bool $cache use caching
6927 * @return context system context (null if context table not created yet)
6929 function get_system_context($cache = true) {
6930 return context_system::instance(0, IGNORE_MISSING, $cache);
6934 * Get the context instance as an object. This function will create the
6935 * context instance if it does not exist yet.
6937 * @deprecated since 2.2, use context_course::instance() or other relevant class instead
6938 * @param integer $contextlevel The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
6939 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
6940 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
6941 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
6942 * MUST_EXIST means throw exception if no record or multiple records found
6943 * @return context The context object.
6945 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
6946 $instances = (array)$instance;
6947 $contexts = array();
6949 $classname = context_helper::get_class_for_level($contextlevel);
6951 // we do not load multiple contexts any more, PAGE should be responsible for any preloading
6952 foreach ($instances as $inst) {
6953 $contexts[$inst] = $classname::instance($inst, $strictness);
6956 if (is_array($instance)) {
6957 return $contexts;
6958 } else {
6959 return $contexts[$instance];
6964 * Get a context instance as an object, from a given context id.
6966 * @deprecated since 2.2, use context::instance_by_id($id) instead
6967 * @param int $id context id
6968 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
6969 * MUST_EXIST means throw exception if no record or multiple records found
6970 * @return context|bool the context object or false if not found.
6972 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
6973 return context::instance_by_id($id, $strictness);
6977 * Recursive function which, given a context, find all parent context ids,
6978 * and return the array in reverse order, i.e. parent first, then grand
6979 * parent, etc.
6981 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
6982 * @param context $context
6983 * @param bool $includeself optional, defaults to false
6984 * @return array
6986 function get_parent_contexts(context $context, $includeself = false) {
6987 return $context->get_parent_context_ids($includeself);
6991 * Return the id of the parent of this context, or false if there is no parent (only happens if this
6992 * is the site context.)
6994 * @deprecated since 2.2, use $context->get_parent_context() instead
6995 * @param context $context
6996 * @return integer the id of the parent context.
6998 function get_parent_contextid(context $context) {
6999 if ($parent = $context->get_parent_context()) {
7000 return $parent->id;
7001 } else {
7002 return false;
7007 * Recursive function which, given a context, find all its children context ids.
7009 * For course category contexts it will return immediate children only categories and courses.
7010 * It will NOT recurse into courses or child categories.
7011 * If you want to do that, call it on the returned courses/categories.
7013 * When called for a course context, it will return the modules and blocks
7014 * displayed in the course page.
7016 * If called on a user/course/module context it _will_ populate the cache with the appropriate
7017 * contexts ;-)
7019 * @deprecated since 2.2, use $context->get_child_contexts() instead
7020 * @param context $context
7021 * @return array Array of child records
7023 function get_child_contexts(context $context) {
7024 return $context->get_child_contexts();
7028 * Precreates all contexts including all parents
7030 * @deprecated since 2.2
7031 * @param int $contextlevel empty means all
7032 * @param bool $buildpaths update paths and depths
7033 * @return void
7035 function create_contexts($contextlevel = null, $buildpaths = true) {
7036 context_helper::create_instances($contextlevel, $buildpaths);
7040 * Remove stale context records
7042 * @deprecated since 2.2, use context_helper::cleanup_instances() instead
7043 * @return bool
7045 function cleanup_contexts() {
7046 context_helper::cleanup_instances();
7047 return true;
7051 * Populate context.path and context.depth where missing.
7053 * @deprecated since 2.2, use context_helper::build_all_paths() instead
7054 * @param bool $force force a complete rebuild of the path and depth fields, defaults to false
7055 * @return void
7057 function build_context_path($force = false) {
7058 context_helper::build_all_paths($force);
7062 * Rebuild all related context depth and path caches
7064 * @deprecated since 2.2
7065 * @param array $fixcontexts array of contexts, strongtyped
7066 * @return void
7068 function rebuild_contexts(array $fixcontexts) {
7069 foreach ($fixcontexts as $fixcontext) {
7070 $fixcontext->reset_paths(false);
7072 context_helper::build_all_paths(false);
7076 * Preloads all contexts relating to a course: course, modules. Block contexts
7077 * are no longer loaded here. The contexts for all the blocks on the current
7078 * page are now efficiently loaded by {@link block_manager::load_blocks()}.
7080 * @deprecated since 2.2
7081 * @param int $courseid Course ID
7082 * @return void
7084 function preload_course_contexts($courseid) {
7085 context_helper::preload_course($courseid);
7089 * Preloads context information together with instances.
7090 * Use context_instance_preload() to strip the context info from the record and cache the context instance.
7092 * @deprecated since 2.2
7093 * @param string $joinon for example 'u.id'
7094 * @param string $contextlevel context level of instance in $joinon
7095 * @param string $tablealias context table alias
7096 * @return array with two values - select and join part
7098 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
7099 $select = ", ".context_helper::get_preload_record_columns_sql($tablealias);
7100 $join = "LEFT JOIN {context} $tablealias ON ($tablealias.instanceid = $joinon AND $tablealias.contextlevel = $contextlevel)";
7101 return array($select, $join);
7105 * Preloads context information from db record and strips the cached info.
7106 * The db request has to contain both the $join and $select from context_instance_preload_sql()
7108 * @deprecated since 2.2
7109 * @param stdClass $rec
7110 * @return void (modifies $rec)
7112 function context_instance_preload(stdClass $rec) {
7113 context_helper::preload_from_record($rec);
7117 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
7119 * @deprecated since 2.2, use $context->mark_dirty() instead
7120 * @param string $path context path
7122 function mark_context_dirty($path) {
7123 global $CFG, $USER, $ACCESSLIB_PRIVATE;
7125 if (during_initial_install()) {
7126 return;
7129 // only if it is a non-empty string
7130 if (is_string($path) && $path !== '') {
7131 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+$CFG->sessiontimeout);
7132 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
7133 $ACCESSLIB_PRIVATE->dirtycontexts[$path] = 1;
7134 } else {
7135 if (CLI_SCRIPT) {
7136 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
7137 } else {
7138 if (isset($USER->access['time'])) {
7139 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
7140 } else {
7141 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
7143 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
7150 * Update the path field of the context and all dep. subcontexts that follow
7152 * Update the path field of the context and
7153 * all the dependent subcontexts that follow
7154 * the move.
7156 * The most important thing here is to be as
7157 * DB efficient as possible. This op can have a
7158 * massive impact in the DB.
7160 * @deprecated since 2.2
7161 * @param context $context context obj
7162 * @param context $newparent new parent obj
7163 * @return void
7165 function context_moved(context $context, context $newparent) {
7166 $context->update_moved($newparent);
7170 * Remove a context record and any dependent entries,
7171 * removes context from static context cache too
7173 * @deprecated since 2.2, use $context->delete_content() instead
7174 * @param int $contextlevel
7175 * @param int $instanceid
7176 * @param bool $deleterecord false means keep record for now
7177 * @return bool returns true or throws an exception
7179 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
7180 if ($deleterecord) {
7181 context_helper::delete_instance($contextlevel, $instanceid);
7182 } else {
7183 $classname = context_helper::get_class_for_level($contextlevel);
7184 if ($context = $classname::instance($instanceid, IGNORE_MISSING)) {
7185 $context->delete_content();
7189 return true;
7193 * Returns context level name
7195 * @deprecated since 2.2
7196 * @param integer $contextlevel $context->context level. One of the CONTEXT_... constants.
7197 * @return string the name for this type of context.
7199 function get_contextlevel_name($contextlevel) {
7200 return context_helper::get_level_name($contextlevel);
7204 * Prints human readable context identifier.
7206 * @deprecated since 2.2
7207 * @param context $context the context.
7208 * @param boolean $withprefix whether to prefix the name of the context with the
7209 * type of context, e.g. User, Course, Forum, etc.
7210 * @param boolean $short whether to user the short name of the thing. Only applies
7211 * to course contexts
7212 * @return string the human readable context name.
7214 function print_context_name(context $context, $withprefix = true, $short = false) {
7215 return $context->get_context_name($withprefix, $short);
7219 * Get a URL for a context, if there is a natural one. For example, for
7220 * CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
7221 * user profile page.
7223 * @deprecated since 2.2
7224 * @param context $context the context.
7225 * @return moodle_url
7227 function get_context_url(context $context) {
7228 return $context->get_url();
7232 * Is this context part of any course? if yes return course context,
7233 * if not return null or throw exception.
7235 * @deprecated since 2.2, use $context->get_course_context() instead
7236 * @param context $context
7237 * @return course_context context of the enclosing course, null if not found or exception
7239 function get_course_context(context $context) {
7240 return $context->get_course_context(true);
7244 * Returns current course id or null if outside of course based on context parameter.
7246 * @deprecated since 2.2, use $context->get_course_context instead
7247 * @param context $context
7248 * @return int|bool related course id or false
7250 function get_courseid_from_context(context $context) {
7251 if ($coursecontext = $context->get_course_context(false)) {
7252 return $coursecontext->instanceid;
7253 } else {
7254 return false;
7259 * Get an array of courses where cap requested is available
7260 * and user is enrolled, this can be relatively slow.
7262 * @deprecated since 2.2, use enrol_get_users_courses() instead
7263 * @param int $userid A user id. By default (null) checks the permissions of the current user.
7264 * @param string $cap - name of the capability
7265 * @param array $accessdata_ignored
7266 * @param bool $doanything_ignored
7267 * @param string $sort - sorting fields - prefix each fieldname with "c."
7268 * @param array $fields - additional fields you are interested in...
7269 * @param int $limit_ignored
7270 * @return array $courses - ordered array of course objects - see notes above
7272 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
7274 $courses = enrol_get_users_courses($userid, true, $fields, $sort);
7275 foreach ($courses as $id=>$course) {
7276 $context = context_course::instance($id);
7277 if (!has_capability($cap, $context, $userid)) {
7278 unset($courses[$id]);
7282 return $courses;
7286 * Extracts the relevant capabilities given a contextid.
7287 * All case based, example an instance of forum context.
7288 * Will fetch all forum related capabilities, while course contexts
7289 * Will fetch all capabilities
7291 * capabilities
7292 * `name` varchar(150) NOT NULL,
7293 * `captype` varchar(50) NOT NULL,
7294 * `contextlevel` int(10) NOT NULL,
7295 * `component` varchar(100) NOT NULL,
7297 * @deprecated since 2.2
7298 * @param context $context
7299 * @return array
7301 function fetch_context_capabilities(context $context) {
7302 return $context->get_capabilities();
7306 * Runs get_records select on context table and returns the result
7307 * Does get_records_select on the context table, and returns the results ordered
7308 * by contextlevel, and then the natural sort order within each level.
7309 * for the purpose of $select, you need to know that the context table has been
7310 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7312 * @deprecated since 2.2
7313 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7314 * @param array $params any parameters required by $select.
7315 * @return array the requested context records.
7317 function get_sorted_contexts($select, $params = array()) {
7319 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7321 global $DB;
7322 if ($select) {
7323 $select = 'WHERE ' . $select;
7325 return $DB->get_records_sql("
7326 SELECT ctx.*
7327 FROM {context} ctx
7328 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7329 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7330 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7331 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7332 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7333 $select
7334 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7335 ", $params);
7339 * This is really slow!!! do not use above course context level
7341 * @deprecated since 2.2
7342 * @param int $roleid
7343 * @param context $context
7344 * @return array
7346 function get_role_context_caps($roleid, context $context) {
7347 global $DB;
7349 //this is really slow!!!! - do not use above course context level!
7350 $result = array();
7351 $result[$context->id] = array();
7353 // first emulate the parent context capabilities merging into context
7354 $searchcontexts = array_reverse($context->get_parent_context_ids(true));
7355 foreach ($searchcontexts as $cid) {
7356 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7357 foreach ($capabilities as $cap) {
7358 if (!array_key_exists($cap->capability, $result[$context->id])) {
7359 $result[$context->id][$cap->capability] = 0;
7361 $result[$context->id][$cap->capability] += $cap->permission;
7366 // now go through the contexts below given context
7367 $searchcontexts = array_keys($context->get_child_contexts());
7368 foreach ($searchcontexts as $cid) {
7369 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7370 foreach ($capabilities as $cap) {
7371 if (!array_key_exists($cap->contextid, $result)) {
7372 $result[$cap->contextid] = array();
7374 $result[$cap->contextid][$cap->capability] = $cap->permission;
7379 return $result;
7383 * Gets a string for sql calls, searching for stuff in this context or above
7385 * NOTE: use $DB->get_in_or_equal($context->get_parent_context_ids()...
7387 * @deprecated since 2.2, $context->use get_parent_context_ids() instead
7388 * @param context $context
7389 * @return string
7391 function get_related_contexts_string(context $context) {
7393 if ($parents = $context->get_parent_context_ids()) {
7394 return (' IN ('.$context->id.','.implode(',', $parents).')');
7395 } else {
7396 return (' ='.$context->id);