Merge branch 'MDL-38424_m23' of git://github.com/kordan/moodle into MOODLE_23_STABLE
[moodle.git] / lib / accesslib.php
blob48f24df88af501ab85874110eb6d59cad1b197a2
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 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1965 return false;
1967 return true;
1972 if ($onlyactive) {
1973 // look for active enrolments only
1974 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1976 if ($until === false) {
1977 return false;
1980 if ($USER->id == $userid) {
1981 if ($until == 0) {
1982 $until = ENROL_MAX_TIMESTAMP;
1984 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
1985 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
1986 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
1987 remove_temp_course_roles($coursecontext);
1991 } else {
1992 // any enrolment is good for us here, even outdated, disabled or inactive
1993 $sql = "SELECT 'x'
1994 FROM {user_enrolments} ue
1995 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1996 JOIN {user} u ON u.id = ue.userid
1997 WHERE ue.userid = :userid AND u.deleted = 0";
1998 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
1999 if (!$DB->record_exists_sql($sql, $params)) {
2000 return false;
2005 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2006 return false;
2009 return true;
2013 * Returns true if the user is able to access the course.
2015 * This function is in no way, shape, or form a substitute for require_login.
2016 * It should only be used in circumstances where it is not possible to call require_login
2017 * such as the navigation.
2019 * This function checks many of the methods of access to a course such as the view
2020 * capability, enrollments, and guest access. It also makes use of the cache
2021 * generated by require_login for guest access.
2023 * The flags within the $USER object that are used here should NEVER be used outside
2024 * of this function can_access_course and require_login. Doing so WILL break future
2025 * versions.
2027 * @param stdClass $course record
2028 * @param stdClass|int|null $user user record or id, current user if null
2029 * @param string $withcapability Check for this capability as well.
2030 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2031 * @return boolean Returns true if the user is able to access the course
2033 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
2034 global $DB, $USER;
2036 // this function originally accepted $coursecontext parameter
2037 if ($course instanceof context) {
2038 if ($course instanceof context_course) {
2039 debugging('deprecated context parameter, please use $course record');
2040 $coursecontext = $course;
2041 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2042 } else {
2043 debugging('Invalid context parameter, please use $course record');
2044 return false;
2046 } else {
2047 $coursecontext = context_course::instance($course->id);
2050 if (!isset($USER->id)) {
2051 // should never happen
2052 $USER->id = 0;
2055 // make sure there is a user specified
2056 if ($user === null) {
2057 $userid = $USER->id;
2058 } else {
2059 $userid = is_object($user) ? $user->id : $user;
2061 unset($user);
2063 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2064 return false;
2067 if ($userid == $USER->id) {
2068 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2069 // the fact that somebody switched role means they can access the course no matter to what role they switched
2070 return true;
2074 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2075 return false;
2078 if (is_viewing($coursecontext, $userid)) {
2079 return true;
2082 if ($userid != $USER->id) {
2083 // for performance reasons we do not verify temporary guest access for other users, sorry...
2084 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2087 // === from here we deal only with $USER ===
2089 $coursecontext->reload_if_dirty();
2091 if (isset($USER->enrol['enrolled'][$course->id])) {
2092 if ($USER->enrol['enrolled'][$course->id] > time()) {
2093 return true;
2096 if (isset($USER->enrol['tempguest'][$course->id])) {
2097 if ($USER->enrol['tempguest'][$course->id] > time()) {
2098 return true;
2102 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2103 return true;
2106 // if not enrolled try to gain temporary guest access
2107 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2108 $enrols = enrol_get_plugins(true);
2109 foreach($instances as $instance) {
2110 if (!isset($enrols[$instance->enrol])) {
2111 continue;
2113 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2114 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2115 if ($until !== false and $until > time()) {
2116 $USER->enrol['tempguest'][$course->id] = $until;
2117 return true;
2120 if (isset($USER->enrol['tempguest'][$course->id])) {
2121 unset($USER->enrol['tempguest'][$course->id]);
2122 remove_temp_course_roles($coursecontext);
2125 return false;
2129 * Returns array with sql code and parameters returning all ids
2130 * of users enrolled into course.
2132 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2134 * @package core_enrol
2135 * @category access
2137 * @param context $context
2138 * @param string $withcapability
2139 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2140 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2141 * @return array list($sql, $params)
2143 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2144 global $DB, $CFG;
2146 // use unique prefix just in case somebody makes some SQL magic with the result
2147 static $i = 0;
2148 $i++;
2149 $prefix = 'eu'.$i.'_';
2151 // first find the course context
2152 $coursecontext = $context->get_course_context();
2154 $isfrontpage = ($coursecontext->instanceid == SITEID);
2156 $joins = array();
2157 $wheres = array();
2158 $params = array();
2160 list($contextids, $contextpaths) = get_context_info_list($context);
2162 // get all relevant capability info for all roles
2163 if ($withcapability) {
2164 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2165 $cparams['cap'] = $withcapability;
2167 $defs = array();
2168 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2169 FROM {role_capabilities} rc
2170 JOIN {context} ctx on rc.contextid = ctx.id
2171 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2172 $rcs = $DB->get_records_sql($sql, $cparams);
2173 foreach ($rcs as $rc) {
2174 $defs[$rc->path][$rc->roleid] = $rc->permission;
2177 $access = array();
2178 if (!empty($defs)) {
2179 foreach ($contextpaths as $path) {
2180 if (empty($defs[$path])) {
2181 continue;
2183 foreach($defs[$path] as $roleid => $perm) {
2184 if ($perm == CAP_PROHIBIT) {
2185 $access[$roleid] = CAP_PROHIBIT;
2186 continue;
2188 if (!isset($access[$roleid])) {
2189 $access[$roleid] = (int)$perm;
2195 unset($defs);
2197 // make lists of roles that are needed and prohibited
2198 $needed = array(); // one of these is enough
2199 $prohibited = array(); // must not have any of these
2200 foreach ($access as $roleid => $perm) {
2201 if ($perm == CAP_PROHIBIT) {
2202 unset($needed[$roleid]);
2203 $prohibited[$roleid] = true;
2204 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2205 $needed[$roleid] = true;
2209 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2210 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2212 $nobody = false;
2214 if ($isfrontpage) {
2215 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2216 $nobody = true;
2217 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2218 // everybody not having prohibit has the capability
2219 $needed = array();
2220 } else if (empty($needed)) {
2221 $nobody = true;
2223 } else {
2224 if (!empty($prohibited[$defaultuserroleid])) {
2225 $nobody = true;
2226 } else if (!empty($needed[$defaultuserroleid])) {
2227 // everybody not having prohibit has the capability
2228 $needed = array();
2229 } else if (empty($needed)) {
2230 $nobody = true;
2234 if ($nobody) {
2235 // nobody can match so return some SQL that does not return any results
2236 $wheres[] = "1 = 2";
2238 } else {
2240 if ($needed) {
2241 $ctxids = implode(',', $contextids);
2242 $roleids = implode(',', array_keys($needed));
2243 $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))";
2246 if ($prohibited) {
2247 $ctxids = implode(',', $contextids);
2248 $roleids = implode(',', array_keys($prohibited));
2249 $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))";
2250 $wheres[] = "{$prefix}ra4.id IS NULL";
2253 if ($groupid) {
2254 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2255 $params["{$prefix}gmid"] = $groupid;
2259 } else {
2260 if ($groupid) {
2261 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2262 $params["{$prefix}gmid"] = $groupid;
2266 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2267 $params["{$prefix}guestid"] = $CFG->siteguest;
2269 if ($isfrontpage) {
2270 // all users are "enrolled" on the frontpage
2271 } else {
2272 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2273 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2274 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2276 if ($onlyactive) {
2277 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2278 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2279 $now = round(time(), -2); // rounding helps caching in DB
2280 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2281 $prefix.'active'=>ENROL_USER_ACTIVE,
2282 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2286 $joins = implode("\n", $joins);
2287 $wheres = "WHERE ".implode(" AND ", $wheres);
2289 $sql = "SELECT DISTINCT {$prefix}u.id
2290 FROM {user} {$prefix}u
2291 $joins
2292 $wheres";
2294 return array($sql, $params);
2298 * Returns list of users enrolled into course.
2300 * @package core_enrol
2301 * @category access
2303 * @param context $context
2304 * @param string $withcapability
2305 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2306 * @param string $userfields requested user record fields
2307 * @param string $orderby
2308 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2309 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2310 * @return array of user records
2312 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = '', $limitfrom = 0, $limitnum = 0) {
2313 global $DB;
2315 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2316 $sql = "SELECT $userfields
2317 FROM {user} u
2318 JOIN ($esql) je ON je.id = u.id
2319 WHERE u.deleted = 0";
2321 if ($orderby) {
2322 $sql = "$sql ORDER BY $orderby";
2323 } else {
2324 $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
2327 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2331 * Counts list of users enrolled into course (as per above function)
2333 * @package core_enrol
2334 * @category access
2336 * @param context $context
2337 * @param string $withcapability
2338 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2339 * @return array of user records
2341 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0) {
2342 global $DB;
2344 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2345 $sql = "SELECT count(u.id)
2346 FROM {user} u
2347 JOIN ($esql) je ON je.id = u.id
2348 WHERE u.deleted = 0";
2350 return $DB->count_records_sql($sql, $params);
2354 * Loads the capability definitions for the component (from file).
2356 * Loads the capability definitions for the component (from file). If no
2357 * capabilities are defined for the component, we simply return an empty array.
2359 * @access private
2360 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2361 * @return array array of capabilities
2363 function load_capability_def($component) {
2364 $defpath = get_component_directory($component).'/db/access.php';
2366 $capabilities = array();
2367 if (file_exists($defpath)) {
2368 require($defpath);
2369 if (!empty(${$component.'_capabilities'})) {
2370 // BC capability array name
2371 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2372 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2373 $capabilities = ${$component.'_capabilities'};
2377 return $capabilities;
2381 * Gets the capabilities that have been cached in the database for this component.
2383 * @access private
2384 * @param string $component - examples: 'moodle', 'mod_forum'
2385 * @return array array of capabilities
2387 function get_cached_capabilities($component = 'moodle') {
2388 global $DB;
2389 return $DB->get_records('capabilities', array('component'=>$component));
2393 * Returns default capabilities for given role archetype.
2395 * @param string $archetype role archetype
2396 * @return array
2398 function get_default_capabilities($archetype) {
2399 global $DB;
2401 if (!$archetype) {
2402 return array();
2405 $alldefs = array();
2406 $defaults = array();
2407 $components = array();
2408 $allcaps = $DB->get_records('capabilities');
2410 foreach ($allcaps as $cap) {
2411 if (!in_array($cap->component, $components)) {
2412 $components[] = $cap->component;
2413 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2416 foreach($alldefs as $name=>$def) {
2417 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2418 if (isset($def['archetypes'])) {
2419 if (isset($def['archetypes'][$archetype])) {
2420 $defaults[$name] = $def['archetypes'][$archetype];
2422 // 'legacy' is for backward compatibility with 1.9 access.php
2423 } else {
2424 if (isset($def['legacy'][$archetype])) {
2425 $defaults[$name] = $def['legacy'][$archetype];
2430 return $defaults;
2434 * Reset role capabilities to default according to selected role archetype.
2435 * If no archetype selected, removes all capabilities.
2437 * @param int $roleid
2438 * @return void
2440 function reset_role_capabilities($roleid) {
2441 global $DB;
2443 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2444 $defaultcaps = get_default_capabilities($role->archetype);
2446 $systemcontext = context_system::instance();
2448 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2450 foreach($defaultcaps as $cap=>$permission) {
2451 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2456 * Updates the capabilities table with the component capability definitions.
2457 * If no parameters are given, the function updates the core moodle
2458 * capabilities.
2460 * Note that the absence of the db/access.php capabilities definition file
2461 * will cause any stored capabilities for the component to be removed from
2462 * the database.
2464 * @access private
2465 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2466 * @return boolean true if success, exception in case of any problems
2468 function update_capabilities($component = 'moodle') {
2469 global $DB, $OUTPUT;
2471 $storedcaps = array();
2473 $filecaps = load_capability_def($component);
2474 foreach($filecaps as $capname=>$unused) {
2475 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2476 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2480 $cachedcaps = get_cached_capabilities($component);
2481 if ($cachedcaps) {
2482 foreach ($cachedcaps as $cachedcap) {
2483 array_push($storedcaps, $cachedcap->name);
2484 // update risk bitmasks and context levels in existing capabilities if needed
2485 if (array_key_exists($cachedcap->name, $filecaps)) {
2486 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2487 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2489 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2490 $updatecap = new stdClass();
2491 $updatecap->id = $cachedcap->id;
2492 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2493 $DB->update_record('capabilities', $updatecap);
2495 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2496 $updatecap = new stdClass();
2497 $updatecap->id = $cachedcap->id;
2498 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2499 $DB->update_record('capabilities', $updatecap);
2502 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2503 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2505 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2506 $updatecap = new stdClass();
2507 $updatecap->id = $cachedcap->id;
2508 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2509 $DB->update_record('capabilities', $updatecap);
2515 // Are there new capabilities in the file definition?
2516 $newcaps = array();
2518 foreach ($filecaps as $filecap => $def) {
2519 if (!$storedcaps ||
2520 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2521 if (!array_key_exists('riskbitmask', $def)) {
2522 $def['riskbitmask'] = 0; // no risk if not specified
2524 $newcaps[$filecap] = $def;
2527 // Add new capabilities to the stored definition.
2528 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2529 foreach ($newcaps as $capname => $capdef) {
2530 $capability = new stdClass();
2531 $capability->name = $capname;
2532 $capability->captype = $capdef['captype'];
2533 $capability->contextlevel = $capdef['contextlevel'];
2534 $capability->component = $component;
2535 $capability->riskbitmask = $capdef['riskbitmask'];
2537 $DB->insert_record('capabilities', $capability, false);
2539 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2540 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2541 foreach ($rolecapabilities as $rolecapability){
2542 //assign_capability will update rather than insert if capability exists
2543 if (!assign_capability($capname, $rolecapability->permission,
2544 $rolecapability->roleid, $rolecapability->contextid, true)){
2545 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2549 // we ignore archetype key if we have cloned permissions
2550 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2551 assign_legacy_capabilities($capname, $capdef['archetypes']);
2552 // 'legacy' is for backward compatibility with 1.9 access.php
2553 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2554 assign_legacy_capabilities($capname, $capdef['legacy']);
2557 // Are there any capabilities that have been removed from the file
2558 // definition that we need to delete from the stored capabilities and
2559 // role assignments?
2560 capabilities_cleanup($component, $filecaps);
2562 // reset static caches
2563 accesslib_clear_all_caches(false);
2565 return true;
2569 * Deletes cached capabilities that are no longer needed by the component.
2570 * Also unassigns these capabilities from any roles that have them.
2572 * @access private
2573 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2574 * @param array $newcapdef array of the new capability definitions that will be
2575 * compared with the cached capabilities
2576 * @return int number of deprecated capabilities that have been removed
2578 function capabilities_cleanup($component, $newcapdef = null) {
2579 global $DB;
2581 $removedcount = 0;
2583 if ($cachedcaps = get_cached_capabilities($component)) {
2584 foreach ($cachedcaps as $cachedcap) {
2585 if (empty($newcapdef) ||
2586 array_key_exists($cachedcap->name, $newcapdef) === false) {
2588 // Remove from capabilities cache.
2589 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2590 $removedcount++;
2591 // Delete from roles.
2592 if ($roles = get_roles_with_capability($cachedcap->name)) {
2593 foreach($roles as $role) {
2594 if (!unassign_capability($cachedcap->name, $role->id)) {
2595 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2599 } // End if.
2602 return $removedcount;
2606 * Returns an array of all the known types of risk
2607 * The array keys can be used, for example as CSS class names, or in calls to
2608 * print_risk_icon. The values are the corresponding RISK_ constants.
2610 * @return array all the known types of risk.
2612 function get_all_risks() {
2613 return array(
2614 'riskmanagetrust' => RISK_MANAGETRUST,
2615 'riskconfig' => RISK_CONFIG,
2616 'riskxss' => RISK_XSS,
2617 'riskpersonal' => RISK_PERSONAL,
2618 'riskspam' => RISK_SPAM,
2619 'riskdataloss' => RISK_DATALOSS,
2624 * Return a link to moodle docs for a given capability name
2626 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2627 * @return string the human-readable capability name as a link to Moodle Docs.
2629 function get_capability_docs_link($capability) {
2630 $url = get_docs_url('Capabilities/' . $capability->name);
2631 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2635 * This function pulls out all the resolved capabilities (overrides and
2636 * defaults) of a role used in capability overrides in contexts at a given
2637 * context.
2639 * @param int $roleid
2640 * @param context $context
2641 * @param string $cap capability, optional, defaults to ''
2642 * @return array Array of capabilities
2644 function role_context_capabilities($roleid, context $context, $cap = '') {
2645 global $DB;
2647 $contexts = $context->get_parent_context_ids(true);
2648 $contexts = '('.implode(',', $contexts).')';
2650 $params = array($roleid);
2652 if ($cap) {
2653 $search = " AND rc.capability = ? ";
2654 $params[] = $cap;
2655 } else {
2656 $search = '';
2659 $sql = "SELECT rc.*
2660 FROM {role_capabilities} rc, {context} c
2661 WHERE rc.contextid in $contexts
2662 AND rc.roleid = ?
2663 AND rc.contextid = c.id $search
2664 ORDER BY c.contextlevel DESC, rc.capability DESC";
2666 $capabilities = array();
2668 if ($records = $DB->get_records_sql($sql, $params)) {
2669 // We are traversing via reverse order.
2670 foreach ($records as $record) {
2671 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2672 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2673 $capabilities[$record->capability] = $record->permission;
2677 return $capabilities;
2681 * Constructs array with contextids as first parameter and context paths,
2682 * in both cases bottom top including self.
2684 * @access private
2685 * @param context $context
2686 * @return array
2688 function get_context_info_list(context $context) {
2689 $contextids = explode('/', ltrim($context->path, '/'));
2690 $contextpaths = array();
2691 $contextids2 = $contextids;
2692 while ($contextids2) {
2693 $contextpaths[] = '/' . implode('/', $contextids2);
2694 array_pop($contextids2);
2696 return array($contextids, $contextpaths);
2700 * Check if context is the front page context or a context inside it
2702 * Returns true if this context is the front page context, or a context inside it,
2703 * otherwise false.
2705 * @param context $context a context object.
2706 * @return bool
2708 function is_inside_frontpage(context $context) {
2709 $frontpagecontext = context_course::instance(SITEID);
2710 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2714 * Returns capability information (cached)
2716 * @param string $capabilityname
2717 * @return stdClass or null if capability not found
2719 function get_capability_info($capabilityname) {
2720 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2722 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2724 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2725 $ACCESSLIB_PRIVATE->capabilities = array();
2726 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2727 foreach ($caps as $cap) {
2728 $capname = $cap->name;
2729 unset($cap->id);
2730 unset($cap->name);
2731 $cap->riskbitmask = (int)$cap->riskbitmask;
2732 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2736 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2740 * Returns the human-readable, translated version of the capability.
2741 * Basically a big switch statement.
2743 * @param string $capabilityname e.g. mod/choice:readresponses
2744 * @return string
2746 function get_capability_string($capabilityname) {
2748 // Typical capability name is 'plugintype/pluginname:capabilityname'
2749 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2751 if ($type === 'moodle') {
2752 $component = 'core_role';
2753 } else if ($type === 'quizreport') {
2754 //ugly hack!!
2755 $component = 'quiz_'.$name;
2756 } else {
2757 $component = $type.'_'.$name;
2760 $stringname = $name.':'.$capname;
2762 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2763 return get_string($stringname, $component);
2766 $dir = get_component_directory($component);
2767 if (!file_exists($dir)) {
2768 // plugin broken or does not exist, do not bother with printing of debug message
2769 return $capabilityname.' ???';
2772 // something is wrong in plugin, better print debug
2773 return get_string($stringname, $component);
2777 * This gets the mod/block/course/core etc strings.
2779 * @param string $component
2780 * @param int $contextlevel
2781 * @return string|bool String is success, false if failed
2783 function get_component_string($component, $contextlevel) {
2785 if ($component === 'moodle' or $component === 'core') {
2786 switch ($contextlevel) {
2787 // TODO: this should probably use context level names instead
2788 case CONTEXT_SYSTEM: return get_string('coresystem');
2789 case CONTEXT_USER: return get_string('users');
2790 case CONTEXT_COURSECAT: return get_string('categories');
2791 case CONTEXT_COURSE: return get_string('course');
2792 case CONTEXT_MODULE: return get_string('activities');
2793 case CONTEXT_BLOCK: return get_string('block');
2794 default: print_error('unknowncontext');
2798 list($type, $name) = normalize_component($component);
2799 $dir = get_plugin_directory($type, $name);
2800 if (!file_exists($dir)) {
2801 // plugin not installed, bad luck, there is no way to find the name
2802 return $component.' ???';
2805 switch ($type) {
2806 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2807 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2808 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2809 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2810 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2811 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2812 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2813 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2814 case 'mod':
2815 if (get_string_manager()->string_exists('pluginname', $component)) {
2816 return get_string('activity').': '.get_string('pluginname', $component);
2817 } else {
2818 return get_string('activity').': '.get_string('modulename', $component);
2820 default: return get_string('pluginname', $component);
2825 * Gets the list of roles assigned to this context and up (parents)
2826 * from the list of roles that are visible on user profile page
2827 * and participants page.
2829 * @param context $context
2830 * @return array
2832 function get_profile_roles(context $context) {
2833 global $CFG, $DB;
2835 if (empty($CFG->profileroles)) {
2836 return array();
2839 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2840 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2841 $params = array_merge($params, $cparams);
2843 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2844 FROM {role_assignments} ra, {role} r
2845 WHERE r.id = ra.roleid
2846 AND ra.contextid $contextlist
2847 AND r.id $rallowed
2848 ORDER BY r.sortorder ASC";
2850 return $DB->get_records_sql($sql, $params);
2854 * Gets the list of roles assigned to this context and up (parents)
2856 * @param context $context
2857 * @return array
2859 function get_roles_used_in_context(context $context) {
2860 global $DB;
2862 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true));
2864 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2865 FROM {role_assignments} ra, {role} r
2866 WHERE r.id = ra.roleid
2867 AND ra.contextid $contextlist
2868 ORDER BY r.sortorder ASC";
2870 return $DB->get_records_sql($sql, $params);
2874 * This function is used to print roles column in user profile page.
2875 * It is using the CFG->profileroles to limit the list to only interesting roles.
2876 * (The permission tab has full details of user role assignments.)
2878 * @param int $userid
2879 * @param int $courseid
2880 * @return string
2882 function get_user_roles_in_course($userid, $courseid) {
2883 global $CFG, $DB;
2885 if (empty($CFG->profileroles)) {
2886 return '';
2889 if ($courseid == SITEID) {
2890 $context = context_system::instance();
2891 } else {
2892 $context = context_course::instance($courseid);
2895 if (empty($CFG->profileroles)) {
2896 return array();
2899 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2900 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2901 $params = array_merge($params, $cparams);
2903 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2904 FROM {role_assignments} ra, {role} r
2905 WHERE r.id = ra.roleid
2906 AND ra.contextid $contextlist
2907 AND r.id $rallowed
2908 AND ra.userid = :userid
2909 ORDER BY r.sortorder ASC";
2910 $params['userid'] = $userid;
2912 $rolestring = '';
2914 if ($roles = $DB->get_records_sql($sql, $params)) {
2915 foreach ($roles as $userrole) {
2916 $rolenames[$userrole->id] = $userrole->name;
2919 $rolenames = role_fix_names($rolenames, $context); // Substitute aliases
2921 foreach ($rolenames as $roleid => $rolename) {
2922 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
2924 $rolestring = implode(',', $rolenames);
2927 return $rolestring;
2931 * Checks if a user can assign users to a particular role in this context
2933 * @param context $context
2934 * @param int $targetroleid - the id of the role you want to assign users to
2935 * @return boolean
2937 function user_can_assign(context $context, $targetroleid) {
2938 global $DB;
2940 // First check to see if the user is a site administrator.
2941 if (is_siteadmin()) {
2942 return true;
2945 // Check if user has override capability.
2946 // If not return false.
2947 if (!has_capability('moodle/role:assign', $context)) {
2948 return false;
2950 // pull out all active roles of this user from this context(or above)
2951 if ($userroles = get_user_roles($context)) {
2952 foreach ($userroles as $userrole) {
2953 // if any in the role_allow_override table, then it's ok
2954 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2955 return true;
2960 return false;
2964 * Returns all site roles in correct sort order.
2966 * @return array
2968 function get_all_roles() {
2969 global $DB;
2970 return $DB->get_records('role', null, 'sortorder ASC');
2974 * Returns roles of a specified archetype
2976 * @param string $archetype
2977 * @return array of full role records
2979 function get_archetype_roles($archetype) {
2980 global $DB;
2981 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2985 * Gets all the user roles assigned in this context, or higher contexts
2986 * this is mainly used when checking if a user can assign a role, or overriding a role
2987 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2988 * allow_override tables
2990 * @param context $context
2991 * @param int $userid
2992 * @param bool $checkparentcontexts defaults to true
2993 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2994 * @return array
2996 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2997 global $USER, $DB;
2999 if (empty($userid)) {
3000 if (empty($USER->id)) {
3001 return array();
3003 $userid = $USER->id;
3006 if ($checkparentcontexts) {
3007 $contextids = $context->get_parent_context_ids();
3008 } else {
3009 $contextids = array();
3011 $contextids[] = $context->id;
3013 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3015 array_unshift($params, $userid);
3017 $sql = "SELECT ra.*, r.name, r.shortname
3018 FROM {role_assignments} ra, {role} r, {context} c
3019 WHERE ra.userid = ?
3020 AND ra.roleid = r.id
3021 AND ra.contextid = c.id
3022 AND ra.contextid $contextids
3023 ORDER BY $order";
3025 return $DB->get_records_sql($sql ,$params);
3029 * Like get_user_roles, but adds in the authenticated user role, and the front
3030 * page roles, if applicable.
3032 * @param context $context the context.
3033 * @param int $userid optional. Defaults to $USER->id
3034 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3036 function get_user_roles_with_special(context $context, $userid = 0) {
3037 global $CFG, $USER;
3039 if (empty($userid)) {
3040 if (empty($USER->id)) {
3041 return array();
3043 $userid = $USER->id;
3046 $ras = get_user_roles($context, $userid);
3048 // Add front-page role if relevant.
3049 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3050 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3051 is_inside_frontpage($context);
3052 if ($defaultfrontpageroleid && $isfrontpage) {
3053 $frontpagecontext = context_course::instance(SITEID);
3054 $ra = new stdClass();
3055 $ra->userid = $userid;
3056 $ra->contextid = $frontpagecontext->id;
3057 $ra->roleid = $defaultfrontpageroleid;
3058 $ras[] = $ra;
3061 // Add authenticated user role if relevant.
3062 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3063 if ($defaultuserroleid && !isguestuser($userid)) {
3064 $systemcontext = context_system::instance();
3065 $ra = new stdClass();
3066 $ra->userid = $userid;
3067 $ra->contextid = $systemcontext->id;
3068 $ra->roleid = $defaultuserroleid;
3069 $ras[] = $ra;
3072 return $ras;
3076 * Creates a record in the role_allow_override table
3078 * @param int $sroleid source roleid
3079 * @param int $troleid target roleid
3080 * @return void
3082 function allow_override($sroleid, $troleid) {
3083 global $DB;
3085 $record = new stdClass();
3086 $record->roleid = $sroleid;
3087 $record->allowoverride = $troleid;
3088 $DB->insert_record('role_allow_override', $record);
3092 * Creates a record in the role_allow_assign table
3094 * @param int $fromroleid source roleid
3095 * @param int $targetroleid target roleid
3096 * @return void
3098 function allow_assign($fromroleid, $targetroleid) {
3099 global $DB;
3101 $record = new stdClass();
3102 $record->roleid = $fromroleid;
3103 $record->allowassign = $targetroleid;
3104 $DB->insert_record('role_allow_assign', $record);
3108 * Creates a record in the role_allow_switch table
3110 * @param int $fromroleid source roleid
3111 * @param int $targetroleid target roleid
3112 * @return void
3114 function allow_switch($fromroleid, $targetroleid) {
3115 global $DB;
3117 $record = new stdClass();
3118 $record->roleid = $fromroleid;
3119 $record->allowswitch = $targetroleid;
3120 $DB->insert_record('role_allow_switch', $record);
3124 * Gets a list of roles that this user can assign in this context
3126 * @param context $context the context.
3127 * @param int $rolenamedisplay the type of role name to display. One of the
3128 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3129 * @param bool $withusercounts if true, count the number of users with each role.
3130 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3131 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3132 * if $withusercounts is true, returns a list of three arrays,
3133 * $rolenames, $rolecounts, and $nameswithcounts.
3135 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3136 global $USER, $DB;
3138 // make sure there is a real user specified
3139 if ($user === null) {
3140 $userid = isset($USER->id) ? $USER->id : 0;
3141 } else {
3142 $userid = is_object($user) ? $user->id : $user;
3145 if (!has_capability('moodle/role:assign', $context, $userid)) {
3146 if ($withusercounts) {
3147 return array(array(), array(), array());
3148 } else {
3149 return array();
3153 $parents = $context->get_parent_context_ids(true);
3154 $contexts = implode(',' , $parents);
3156 $params = array();
3157 $extrafields = '';
3158 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT or $rolenamedisplay == ROLENAME_SHORT) {
3159 $extrafields .= ', r.shortname';
3162 if ($withusercounts) {
3163 $extrafields = ', (SELECT count(u.id)
3164 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3165 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3166 ) AS usercount';
3167 $params['conid'] = $context->id;
3170 if (is_siteadmin($userid)) {
3171 // show all roles allowed in this context to admins
3172 $assignrestriction = "";
3173 } else {
3174 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3175 FROM {role_allow_assign} raa
3176 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3177 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3178 ) ar ON ar.id = r.id";
3179 $params['userid'] = $userid;
3181 $params['contextlevel'] = $context->contextlevel;
3182 $sql = "SELECT r.id, r.name $extrafields
3183 FROM {role} r
3184 $assignrestriction
3185 JOIN {role_context_levels} rcl ON r.id = rcl.roleid
3186 WHERE rcl.contextlevel = :contextlevel
3187 ORDER BY r.sortorder ASC";
3188 $roles = $DB->get_records_sql($sql, $params);
3190 $rolenames = array();
3191 foreach ($roles as $role) {
3192 if ($rolenamedisplay == ROLENAME_SHORT) {
3193 $rolenames[$role->id] = $role->shortname;
3194 continue;
3196 $rolenames[$role->id] = $role->name;
3197 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3198 $rolenames[$role->id] .= ' (' . $role->shortname . ')';
3201 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT and $rolenamedisplay != ROLENAME_SHORT) {
3202 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3205 if (!$withusercounts) {
3206 return $rolenames;
3209 $rolecounts = array();
3210 $nameswithcounts = array();
3211 foreach ($roles as $role) {
3212 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3213 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3215 return array($rolenames, $rolecounts, $nameswithcounts);
3219 * Gets a list of roles that this user can switch to in a context
3221 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3222 * This function just process the contents of the role_allow_switch table. You also need to
3223 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3225 * @param context $context a context.
3226 * @return array an array $roleid => $rolename.
3228 function get_switchable_roles(context $context) {
3229 global $USER, $DB;
3231 $params = array();
3232 $extrajoins = '';
3233 $extrawhere = '';
3234 if (!is_siteadmin()) {
3235 // Admins are allowed to switch to any role with.
3236 // Others are subject to the additional constraint that the switch-to role must be allowed by
3237 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3238 $parents = $context->get_parent_context_ids(true);
3239 $contexts = implode(',' , $parents);
3241 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3242 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3243 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3244 $params['userid'] = $USER->id;
3247 $query = "
3248 SELECT r.id, r.name
3249 FROM (SELECT DISTINCT rc.roleid
3250 FROM {role_capabilities} rc
3251 $extrajoins
3252 $extrawhere) idlist
3253 JOIN {role} r ON r.id = idlist.roleid
3254 ORDER BY r.sortorder";
3256 $rolenames = $DB->get_records_sql_menu($query, $params);
3257 return role_fix_names($rolenames, $context, ROLENAME_ALIAS);
3261 * Gets a list of roles that this user can override in this context.
3263 * @param context $context the context.
3264 * @param int $rolenamedisplay the type of role name to display. One of the
3265 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3266 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3267 * @return array if $withcounts is false, then an array $roleid => $rolename.
3268 * if $withusercounts is true, returns a list of three arrays,
3269 * $rolenames, $rolecounts, and $nameswithcounts.
3271 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3272 global $USER, $DB;
3274 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3275 if ($withcounts) {
3276 return array(array(), array(), array());
3277 } else {
3278 return array();
3282 $parents = $context->get_parent_context_ids(true);
3283 $contexts = implode(',' , $parents);
3285 $params = array();
3286 $extrafields = '';
3287 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3288 $extrafields .= ', ro.shortname';
3291 $params['userid'] = $USER->id;
3292 if ($withcounts) {
3293 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3294 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3295 $params['conid'] = $context->id;
3298 if (is_siteadmin()) {
3299 // show all roles to admins
3300 $roles = $DB->get_records_sql("
3301 SELECT ro.id, ro.name$extrafields
3302 FROM {role} ro
3303 ORDER BY ro.sortorder ASC", $params);
3305 } else {
3306 $roles = $DB->get_records_sql("
3307 SELECT ro.id, ro.name$extrafields
3308 FROM {role} ro
3309 JOIN (SELECT DISTINCT r.id
3310 FROM {role} r
3311 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3312 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3313 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3314 ) inline_view ON ro.id = inline_view.id
3315 ORDER BY ro.sortorder ASC", $params);
3318 $rolenames = array();
3319 foreach ($roles as $role) {
3320 $rolenames[$role->id] = $role->name;
3321 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3322 $rolenames[$role->id] .= ' (' . $role->shortname . ')';
3325 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT) {
3326 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3329 if (!$withcounts) {
3330 return $rolenames;
3333 $rolecounts = array();
3334 $nameswithcounts = array();
3335 foreach ($roles as $role) {
3336 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3337 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3339 return array($rolenames, $rolecounts, $nameswithcounts);
3343 * Create a role menu suitable for default role selection in enrol plugins.
3345 * @package core_enrol
3347 * @param context $context
3348 * @param int $addroleid current or default role - always added to list
3349 * @return array roleid=>localised role name
3351 function get_default_enrol_roles(context $context, $addroleid = null) {
3352 global $DB;
3354 $params = array('contextlevel'=>CONTEXT_COURSE);
3355 if ($addroleid) {
3356 $addrole = "OR r.id = :addroleid";
3357 $params['addroleid'] = $addroleid;
3358 } else {
3359 $addrole = "";
3361 $sql = "SELECT r.id, r.name
3362 FROM {role} r
3363 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3364 WHERE rcl.id IS NOT NULL $addrole
3365 ORDER BY sortorder DESC";
3367 $roles = $DB->get_records_sql_menu($sql, $params);
3368 $roles = role_fix_names($roles, $context, ROLENAME_BOTH);
3370 return $roles;
3374 * Return context levels where this role is assignable.
3376 * @param integer $roleid the id of a role.
3377 * @return array list of the context levels at which this role may be assigned.
3379 function get_role_contextlevels($roleid) {
3380 global $DB;
3381 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3382 'contextlevel', 'id,contextlevel');
3386 * Return roles suitable for assignment at the specified context level.
3388 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3390 * @param integer $contextlevel a contextlevel.
3391 * @return array list of role ids that are assignable at this context level.
3393 function get_roles_for_contextlevels($contextlevel) {
3394 global $DB;
3395 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3396 '', 'id,roleid');
3400 * Returns default context levels where roles can be assigned.
3402 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3403 * from the array returned by get_role_archetypes();
3404 * @return array list of the context levels at which this type of role may be assigned by default.
3406 function get_default_contextlevels($rolearchetype) {
3407 static $defaults = array(
3408 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3409 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3410 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3411 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3412 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3413 'guest' => array(),
3414 'user' => array(),
3415 'frontpage' => array());
3417 if (isset($defaults[$rolearchetype])) {
3418 return $defaults[$rolearchetype];
3419 } else {
3420 return array();
3425 * Set the context levels at which a particular role can be assigned.
3426 * Throws exceptions in case of error.
3428 * @param integer $roleid the id of a role.
3429 * @param array $contextlevels the context levels at which this role should be assignable,
3430 * duplicate levels are removed.
3431 * @return void
3433 function set_role_contextlevels($roleid, array $contextlevels) {
3434 global $DB;
3435 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3436 $rcl = new stdClass();
3437 $rcl->roleid = $roleid;
3438 $contextlevels = array_unique($contextlevels);
3439 foreach ($contextlevels as $level) {
3440 $rcl->contextlevel = $level;
3441 $DB->insert_record('role_context_levels', $rcl, false, true);
3446 * Who has this capability in this context?
3448 * This can be a very expensive call - use sparingly and keep
3449 * the results if you are going to need them again soon.
3451 * Note if $fields is empty this function attempts to get u.*
3452 * which can get rather large - and has a serious perf impact
3453 * on some DBs.
3455 * @param context $context
3456 * @param string|array $capability - capability name(s)
3457 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3458 * @param string $sort - the sort order. Default is lastaccess time.
3459 * @param mixed $limitfrom - number of records to skip (offset)
3460 * @param mixed $limitnum - number of records to fetch
3461 * @param string|array $groups - single group or array of groups - only return
3462 * users who are in one of these group(s).
3463 * @param string|array $exceptions - list of users to exclude, comma separated or array
3464 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3465 * @param bool $view_ignored - use get_enrolled_sql() instead
3466 * @param bool $useviewallgroups if $groups is set the return users who
3467 * have capability both $capability and moodle/site:accessallgroups
3468 * in this context, as well as users who have $capability and who are
3469 * in $groups.
3470 * @return array of user records
3472 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3473 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3474 global $CFG, $DB;
3476 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3477 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3479 $ctxids = trim($context->path, '/');
3480 $ctxids = str_replace('/', ',', $ctxids);
3482 // Context is the frontpage
3483 $iscoursepage = false; // coursepage other than fp
3484 $isfrontpage = false;
3485 if ($context->contextlevel == CONTEXT_COURSE) {
3486 if ($context->instanceid == SITEID) {
3487 $isfrontpage = true;
3488 } else {
3489 $iscoursepage = true;
3492 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3494 $caps = (array)$capability;
3496 // construct list of context paths bottom-->top
3497 list($contextids, $paths) = get_context_info_list($context);
3499 // we need to find out all roles that have these capabilities either in definition or in overrides
3500 $defs = array();
3501 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3502 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3503 $params = array_merge($params, $params2);
3504 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3505 FROM {role_capabilities} rc
3506 JOIN {context} ctx on rc.contextid = ctx.id
3507 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3509 $rcs = $DB->get_records_sql($sql, $params);
3510 foreach ($rcs as $rc) {
3511 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3514 // go through the permissions bottom-->top direction to evaluate the current permission,
3515 // first one wins (prohibit is an exception that always wins)
3516 $access = array();
3517 foreach ($caps as $cap) {
3518 foreach ($paths as $path) {
3519 if (empty($defs[$cap][$path])) {
3520 continue;
3522 foreach($defs[$cap][$path] as $roleid => $perm) {
3523 if ($perm == CAP_PROHIBIT) {
3524 $access[$cap][$roleid] = CAP_PROHIBIT;
3525 continue;
3527 if (!isset($access[$cap][$roleid])) {
3528 $access[$cap][$roleid] = (int)$perm;
3534 // make lists of roles that are needed and prohibited in this context
3535 $needed = array(); // one of these is enough
3536 $prohibited = array(); // must not have any of these
3537 foreach ($caps as $cap) {
3538 if (empty($access[$cap])) {
3539 continue;
3541 foreach ($access[$cap] as $roleid => $perm) {
3542 if ($perm == CAP_PROHIBIT) {
3543 unset($needed[$cap][$roleid]);
3544 $prohibited[$cap][$roleid] = true;
3545 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3546 $needed[$cap][$roleid] = true;
3549 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3550 // easy, nobody has the permission
3551 unset($needed[$cap]);
3552 unset($prohibited[$cap]);
3553 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3554 // everybody is disqualified on the frontpage
3555 unset($needed[$cap]);
3556 unset($prohibited[$cap]);
3558 if (empty($prohibited[$cap])) {
3559 unset($prohibited[$cap]);
3563 if (empty($needed)) {
3564 // there can not be anybody if no roles match this request
3565 return array();
3568 if (empty($prohibited)) {
3569 // we can compact the needed roles
3570 $n = array();
3571 foreach ($needed as $cap) {
3572 foreach ($cap as $roleid=>$unused) {
3573 $n[$roleid] = true;
3576 $needed = array('any'=>$n);
3577 unset($n);
3580 // ***** Set up default fields ******
3581 if (empty($fields)) {
3582 if ($iscoursepage) {
3583 $fields = 'u.*, ul.timeaccess AS lastaccess';
3584 } else {
3585 $fields = 'u.*';
3587 } else {
3588 if (debugging('', DEBUG_DEVELOPER) && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3589 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3593 // Set up default sort
3594 if (empty($sort)) { // default to course lastaccess or just lastaccess
3595 if ($iscoursepage) {
3596 $sort = 'ul.timeaccess';
3597 } else {
3598 $sort = 'u.lastaccess';
3602 // Prepare query clauses
3603 $wherecond = array();
3604 $params = array();
3605 $joins = array();
3607 // User lastaccess JOIN
3608 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3609 // user_lastaccess is not required MDL-13810
3610 } else {
3611 if ($iscoursepage) {
3612 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3613 } else {
3614 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3618 // We never return deleted users or guest account.
3619 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3620 $params['guestid'] = $CFG->siteguest;
3622 // Groups
3623 if ($groups) {
3624 $groups = (array)$groups;
3625 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3626 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3627 $params = array_merge($params, $grpparams);
3629 if ($useviewallgroups) {
3630 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3631 if (!empty($viewallgroupsusers)) {
3632 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3633 } else {
3634 $wherecond[] = "($grouptest)";
3636 } else {
3637 $wherecond[] = "($grouptest)";
3641 // User exceptions
3642 if (!empty($exceptions)) {
3643 $exceptions = (array)$exceptions;
3644 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3645 $params = array_merge($params, $exparams);
3646 $wherecond[] = "u.id $exsql";
3649 // now add the needed and prohibited roles conditions as joins
3650 if (!empty($needed['any'])) {
3651 // simple case - there are no prohibits involved
3652 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3653 // everybody
3654 } else {
3655 $joins[] = "JOIN (SELECT DISTINCT userid
3656 FROM {role_assignments}
3657 WHERE contextid IN ($ctxids)
3658 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3659 ) ra ON ra.userid = u.id";
3661 } else {
3662 $unions = array();
3663 $everybody = false;
3664 foreach ($needed as $cap=>$unused) {
3665 if (empty($prohibited[$cap])) {
3666 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3667 $everybody = true;
3668 break;
3669 } else {
3670 $unions[] = "SELECT userid
3671 FROM {role_assignments}
3672 WHERE contextid IN ($ctxids)
3673 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3675 } else {
3676 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3677 // nobody can have this cap because it is prevented in default roles
3678 continue;
3680 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3681 // everybody except the prohibitted - hiding does not matter
3682 $unions[] = "SELECT id AS userid
3683 FROM {user}
3684 WHERE id NOT IN (SELECT userid
3685 FROM {role_assignments}
3686 WHERE contextid IN ($ctxids)
3687 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3689 } else {
3690 $unions[] = "SELECT userid
3691 FROM {role_assignments}
3692 WHERE contextid IN ($ctxids)
3693 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3694 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3698 if (!$everybody) {
3699 if ($unions) {
3700 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3701 } else {
3702 // only prohibits found - nobody can be matched
3703 $wherecond[] = "1 = 2";
3708 // Collect WHERE conditions and needed joins
3709 $where = implode(' AND ', $wherecond);
3710 if ($where !== '') {
3711 $where = 'WHERE ' . $where;
3713 $joins = implode("\n", $joins);
3715 // Ok, let's get the users!
3716 $sql = "SELECT $fields
3717 FROM {user} u
3718 $joins
3719 $where
3720 ORDER BY $sort";
3722 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3726 * Re-sort a users array based on a sorting policy
3728 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3729 * based on a sorting policy. This is to support the odd practice of
3730 * sorting teachers by 'authority', where authority was "lowest id of the role
3731 * assignment".
3733 * Will execute 1 database query. Only suitable for small numbers of users, as it
3734 * uses an u.id IN() clause.
3736 * Notes about the sorting criteria.
3738 * As a default, we cannot rely on role.sortorder because then
3739 * admins/coursecreators will always win. That is why the sane
3740 * rule "is locality matters most", with sortorder as 2nd
3741 * consideration.
3743 * If you want role.sortorder, use the 'sortorder' policy, and
3744 * name explicitly what roles you want to cover. It's probably
3745 * a good idea to see what roles have the capabilities you want
3746 * (array_diff() them against roiles that have 'can-do-anything'
3747 * to weed out admin-ish roles. Or fetch a list of roles from
3748 * variables like $CFG->coursecontact .
3750 * @param array $users Users array, keyed on userid
3751 * @param context $context
3752 * @param array $roles ids of the roles to include, optional
3753 * @param string $sortpolicy defaults to locality, more about
3754 * @return array sorted copy of the array
3756 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3757 global $DB;
3759 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3760 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3761 if (empty($roles)) {
3762 $roleswhere = '';
3763 } else {
3764 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3767 $sql = "SELECT ra.userid
3768 FROM {role_assignments} ra
3769 JOIN {role} r
3770 ON ra.roleid=r.id
3771 JOIN {context} ctx
3772 ON ra.contextid=ctx.id
3773 WHERE $userswhere
3774 $contextwhere
3775 $roleswhere";
3777 // Default 'locality' policy -- read PHPDoc notes
3778 // about sort policies...
3779 $orderby = 'ORDER BY '
3780 .'ctx.depth DESC, ' /* locality wins */
3781 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3782 .'ra.id'; /* role assignment order tie-breaker */
3783 if ($sortpolicy === 'sortorder') {
3784 $orderby = 'ORDER BY '
3785 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3786 .'ra.id'; /* role assignment order tie-breaker */
3789 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3790 $sortedusers = array();
3791 $seen = array();
3793 foreach ($sortedids as $id) {
3794 // Avoid duplicates
3795 if (isset($seen[$id])) {
3796 continue;
3798 $seen[$id] = true;
3800 // assign
3801 $sortedusers[$id] = $users[$id];
3803 return $sortedusers;
3807 * Gets all the users assigned this role in this context or higher
3809 * @param int $roleid (can also be an array of ints!)
3810 * @param context $context
3811 * @param bool $parent if true, get list of users assigned in higher context too
3812 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3813 * @param string $sort sort from user (u.) , role assignment (ra) or role (r.)
3814 * @param bool $gethidden_ignored use enrolments instead
3815 * @param string $group defaults to ''
3816 * @param mixed $limitfrom defaults to ''
3817 * @param mixed $limitnum defaults to ''
3818 * @param string $extrawheretest defaults to ''
3819 * @param string|array $whereparams defaults to ''
3820 * @return array
3822 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3823 $sort = 'u.lastname, u.firstname', $gethidden_ignored = null, $group = '',
3824 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereparams = array()) {
3825 global $DB;
3827 if (empty($fields)) {
3828 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3829 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3830 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3831 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder';
3834 $parentcontexts = '';
3835 if ($parent) {
3836 $parentcontexts = substr($context->path, 1); // kill leading slash
3837 $parentcontexts = str_replace('/', ',', $parentcontexts);
3838 if ($parentcontexts !== '') {
3839 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3843 if ($roleid) {
3844 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3845 $roleselect = "AND ra.roleid $rids";
3846 } else {
3847 $params = array();
3848 $roleselect = '';
3851 if ($group) {
3852 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3853 $groupselect = " AND gm.groupid = ? ";
3854 $params[] = $group;
3855 } else {
3856 $groupjoin = '';
3857 $groupselect = '';
3860 array_unshift($params, $context->id);
3862 if ($extrawheretest) {
3863 $extrawheretest = ' AND ' . $extrawheretest;
3864 $params = array_merge($params, $whereparams);
3867 $sql = "SELECT DISTINCT $fields, ra.roleid
3868 FROM {role_assignments} ra
3869 JOIN {user} u ON u.id = ra.userid
3870 JOIN {role} r ON ra.roleid = r.id
3871 $groupjoin
3872 WHERE (ra.contextid = ? $parentcontexts)
3873 $roleselect
3874 $groupselect
3875 $extrawheretest
3876 ORDER BY $sort"; // join now so that we can just use fullname() later
3878 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3882 * Counts all the users assigned this role in this context or higher
3884 * @param int|array $roleid either int or an array of ints
3885 * @param context $context
3886 * @param bool $parent if true, get list of users assigned in higher context too
3887 * @return int Returns the result count
3889 function count_role_users($roleid, context $context, $parent = false) {
3890 global $DB;
3892 if ($parent) {
3893 if ($contexts = $context->get_parent_context_ids()) {
3894 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3895 } else {
3896 $parentcontexts = '';
3898 } else {
3899 $parentcontexts = '';
3902 if ($roleid) {
3903 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3904 $roleselect = "AND r.roleid $rids";
3905 } else {
3906 $params = array();
3907 $roleselect = '';
3910 array_unshift($params, $context->id);
3912 $sql = "SELECT COUNT(u.id)
3913 FROM {role_assignments} r
3914 JOIN {user} u ON u.id = r.userid
3915 WHERE (r.contextid = ? $parentcontexts)
3916 $roleselect
3917 AND u.deleted = 0";
3919 return $DB->count_records_sql($sql, $params);
3923 * This function gets the list of courses that this user has a particular capability in.
3924 * It is still not very efficient.
3926 * @param string $capability Capability in question
3927 * @param int $userid User ID or null for current user
3928 * @param bool $doanything True if 'doanything' is permitted (default)
3929 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3930 * otherwise use a comma-separated list of the fields you require, not including id
3931 * @param string $orderby If set, use a comma-separated list of fields from course
3932 * table with sql modifiers (DESC) if needed
3933 * @return array Array of courses, may have zero entries. Or false if query failed.
3935 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
3936 global $DB;
3938 // Convert fields list and ordering
3939 $fieldlist = '';
3940 if ($fieldsexceptid) {
3941 $fields = explode(',', $fieldsexceptid);
3942 foreach($fields as $field) {
3943 $fieldlist .= ',c.'.$field;
3946 if ($orderby) {
3947 $fields = explode(',', $orderby);
3948 $orderby = '';
3949 foreach($fields as $field) {
3950 if ($orderby) {
3951 $orderby .= ',';
3953 $orderby .= 'c.'.$field;
3955 $orderby = 'ORDER BY '.$orderby;
3958 // Obtain a list of everything relevant about all courses including context.
3959 // Note the result can be used directly as a context (we are going to), the course
3960 // fields are just appended.
3962 $contextpreload = context_helper::get_preload_record_columns_sql('x');
3964 $courses = array();
3965 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
3966 FROM {course} c
3967 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
3968 $orderby");
3969 // Check capability for each course in turn
3970 foreach ($rs as $course) {
3971 context_helper::preload_from_record($course);
3972 $context = context_course::instance($course->id);
3973 if (has_capability($capability, $context, $userid, $doanything)) {
3974 // We've got the capability. Make the record look like a course record
3975 // and store it
3976 $courses[] = $course;
3979 $rs->close();
3980 return empty($courses) ? false : $courses;
3984 * This function finds the roles assigned directly to this context only
3985 * i.e. no roles in parent contexts
3987 * @param context $context
3988 * @return array
3990 function get_roles_on_exact_context(context $context) {
3991 global $DB;
3993 return $DB->get_records_sql("SELECT r.*
3994 FROM {role_assignments} ra, {role} r
3995 WHERE ra.roleid = r.id AND ra.contextid = ?",
3996 array($context->id));
4000 * Switches the current user to another role for the current session and only
4001 * in the given context.
4003 * The caller *must* check
4004 * - that this op is allowed
4005 * - that the requested role can be switched to in this context (use get_switchable_roles)
4006 * - that the requested role is NOT $CFG->defaultuserroleid
4008 * To "unswitch" pass 0 as the roleid.
4010 * This function *will* modify $USER->access - beware
4012 * @param integer $roleid the role to switch to.
4013 * @param context $context the context in which to perform the switch.
4014 * @return bool success or failure.
4016 function role_switch($roleid, context $context) {
4017 global $USER;
4020 // Plan of action
4022 // - Add the ghost RA to $USER->access
4023 // as $USER->access['rsw'][$path] = $roleid
4025 // - Make sure $USER->access['rdef'] has the roledefs
4026 // it needs to honour the switcherole
4028 // Roledefs will get loaded "deep" here - down to the last child
4029 // context. Note that
4031 // - When visiting subcontexts, our selective accessdata loading
4032 // will still work fine - though those ra/rdefs will be ignored
4033 // appropriately while the switch is in place
4035 // - If a switcherole happens at a category with tons of courses
4036 // (that have many overrides for switched-to role), the session
4037 // will get... quite large. Sometimes you just can't win.
4039 // To un-switch just unset($USER->access['rsw'][$path])
4041 // Note: it is not possible to switch to roles that do not have course:view
4043 if (!isset($USER->access)) {
4044 load_all_capabilities();
4048 // Add the switch RA
4049 if ($roleid == 0) {
4050 unset($USER->access['rsw'][$context->path]);
4051 return true;
4054 $USER->access['rsw'][$context->path] = $roleid;
4056 // Load roledefs
4057 load_role_access_by_context($roleid, $context, $USER->access);
4059 return true;
4063 * Checks if the user has switched roles within the given course.
4065 * Note: You can only switch roles within the course, hence it takes a course id
4066 * rather than a context. On that note Petr volunteered to implement this across
4067 * all other contexts, all requests for this should be forwarded to him ;)
4069 * @param int $courseid The id of the course to check
4070 * @return bool True if the user has switched roles within the course.
4072 function is_role_switched($courseid) {
4073 global $USER;
4074 $context = context_course::instance($courseid, MUST_EXIST);
4075 return (!empty($USER->access['rsw'][$context->path]));
4079 * Get any role that has an override on exact context
4081 * @param context $context The context to check
4082 * @return array An array of roles
4084 function get_roles_with_override_on_context(context $context) {
4085 global $DB;
4087 return $DB->get_records_sql("SELECT r.*
4088 FROM {role_capabilities} rc, {role} r
4089 WHERE rc.roleid = r.id AND rc.contextid = ?",
4090 array($context->id));
4094 * Get all capabilities for this role on this context (overrides)
4096 * @param stdClass $role
4097 * @param context $context
4098 * @return array
4100 function get_capabilities_from_role_on_context($role, context $context) {
4101 global $DB;
4103 return $DB->get_records_sql("SELECT *
4104 FROM {role_capabilities}
4105 WHERE contextid = ? AND roleid = ?",
4106 array($context->id, $role->id));
4110 * Find out which roles has assignment on this context
4112 * @param context $context
4113 * @return array
4116 function get_roles_with_assignment_on_context(context $context) {
4117 global $DB;
4119 return $DB->get_records_sql("SELECT r.*
4120 FROM {role_assignments} ra, {role} r
4121 WHERE ra.roleid = r.id AND ra.contextid = ?",
4122 array($context->id));
4126 * Find all user assignment of users for this role, on this context
4128 * @param stdClass $role
4129 * @param context $context
4130 * @return array
4132 function get_users_from_role_on_context($role, context $context) {
4133 global $DB;
4135 return $DB->get_records_sql("SELECT *
4136 FROM {role_assignments}
4137 WHERE contextid = ? AND roleid = ?",
4138 array($context->id, $role->id));
4142 * Simple function returning a boolean true if user has roles
4143 * in context or parent contexts, otherwise false.
4145 * @param int $userid
4146 * @param int $roleid
4147 * @param int $contextid empty means any context
4148 * @return bool
4150 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4151 global $DB;
4153 if ($contextid) {
4154 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4155 return false;
4157 $parents = $context->get_parent_context_ids(true);
4158 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4159 $params['userid'] = $userid;
4160 $params['roleid'] = $roleid;
4162 $sql = "SELECT COUNT(ra.id)
4163 FROM {role_assignments} ra
4164 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4166 $count = $DB->get_field_sql($sql, $params);
4167 return ($count > 0);
4169 } else {
4170 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4175 * Get role name or alias if exists and format the text.
4177 * @param stdClass $role role object
4178 * @param context_course $coursecontext
4179 * @return string name of role in course context
4181 function role_get_name($role, context_course $coursecontext) {
4182 global $DB;
4184 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4185 return strip_tags(format_string($r->name));
4186 } else {
4187 return strip_tags(format_string($role->name));
4192 * Get all the localised role names for a context.
4193 * @param context $context the context
4194 * @param array of role objects with a ->localname field containing the context-specific role name.
4196 function role_get_names(context $context) {
4197 return role_fix_names(get_all_roles(), $context);
4201 * Prepare list of roles for display, apply aliases and format text
4203 * @param array $roleoptions array roleid => rolename or roleid => roleobject
4204 * @param context $context a context
4205 * @param int $rolenamedisplay
4206 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4208 function role_fix_names($roleoptions, context $context, $rolenamedisplay = ROLENAME_ALIAS) {
4209 global $DB;
4211 // Make sure we have a course context.
4212 $coursecontext = $context->get_course_context(false);
4214 // Make sure we are working with an array roleid => name. Normally we
4215 // want to use the unlocalised name if the localised one is not present.
4216 $newnames = array();
4217 foreach ($roleoptions as $rid => $roleorname) {
4218 if ($rolenamedisplay != ROLENAME_ALIAS_RAW) {
4219 if (is_object($roleorname)) {
4220 $newnames[$rid] = $roleorname->name;
4221 } else {
4222 $newnames[$rid] = $roleorname;
4224 } else {
4225 $newnames[$rid] = '';
4229 // If necessary, get the localised names.
4230 if ($rolenamedisplay != ROLENAME_ORIGINAL && !empty($coursecontext->id)) {
4231 // The get the relevant renames, and use them.
4232 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4233 foreach ($aliasnames as $alias) {
4234 if (isset($newnames[$alias->roleid])) {
4235 if ($rolenamedisplay == ROLENAME_ALIAS || $rolenamedisplay == ROLENAME_ALIAS_RAW) {
4236 $newnames[$alias->roleid] = $alias->name;
4237 } else if ($rolenamedisplay == ROLENAME_BOTH) {
4238 $newnames[$alias->roleid] = $alias->name . ' (' . $roleoptions[$alias->roleid] . ')';
4244 // Finally, apply format_string and put the result in the right place.
4245 foreach ($roleoptions as $rid => $roleorname) {
4246 if ($rolenamedisplay != ROLENAME_ALIAS_RAW) {
4247 $newnames[$rid] = strip_tags(format_string($newnames[$rid]));
4249 if (is_object($roleorname)) {
4250 $roleoptions[$rid]->localname = $newnames[$rid];
4251 } else {
4252 $roleoptions[$rid] = $newnames[$rid];
4255 return $roleoptions;
4259 * Aids in detecting if a new line is required when reading a new capability
4261 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4262 * when we read in a new capability.
4263 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4264 * but when we are in grade, all reports/import/export capabilities should be together
4266 * @param string $cap component string a
4267 * @param string $comp component string b
4268 * @param int $contextlevel
4269 * @return bool whether 2 component are in different "sections"
4271 function component_level_changed($cap, $comp, $contextlevel) {
4273 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4274 $compsa = explode('/', $cap->component);
4275 $compsb = explode('/', $comp);
4277 // list of system reports
4278 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4279 return false;
4282 // we are in gradebook, still
4283 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4284 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4285 return false;
4288 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4289 return false;
4293 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4297 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4298 * and return an array of roleids in order.
4300 * @param array $allroles array of roles, as returned by get_all_roles();
4301 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4303 function fix_role_sortorder($allroles) {
4304 global $DB;
4306 $rolesort = array();
4307 $i = 0;
4308 foreach ($allroles as $role) {
4309 $rolesort[$i] = $role->id;
4310 if ($role->sortorder != $i) {
4311 $r = new stdClass();
4312 $r->id = $role->id;
4313 $r->sortorder = $i;
4314 $DB->update_record('role', $r);
4315 $allroles[$role->id]->sortorder = $i;
4317 $i++;
4319 return $rolesort;
4323 * Switch the sort order of two roles (used in admin/roles/manage.php).
4325 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4326 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4327 * @return boolean success or failure
4329 function switch_roles($first, $second) {
4330 global $DB;
4331 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4332 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4333 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4334 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4335 return $result;
4339 * Duplicates all the base definitions of a role
4341 * @param stdClass $sourcerole role to copy from
4342 * @param int $targetrole id of role to copy to
4344 function role_cap_duplicate($sourcerole, $targetrole) {
4345 global $DB;
4347 $systemcontext = context_system::instance();
4348 $caps = $DB->get_records_sql("SELECT *
4349 FROM {role_capabilities}
4350 WHERE roleid = ? AND contextid = ?",
4351 array($sourcerole->id, $systemcontext->id));
4352 // adding capabilities
4353 foreach ($caps as $cap) {
4354 unset($cap->id);
4355 $cap->roleid = $targetrole;
4356 $DB->insert_record('role_capabilities', $cap);
4361 * Returns two lists, this can be used to find out if user has capability.
4362 * Having any needed role and no forbidden role in this context means
4363 * user has this capability in this context.
4364 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4366 * @param stdClass $context
4367 * @param string $capability
4368 * @return array($neededroles, $forbiddenroles)
4370 function get_roles_with_cap_in_context($context, $capability) {
4371 global $DB;
4373 $ctxids = trim($context->path, '/'); // kill leading slash
4374 $ctxids = str_replace('/', ',', $ctxids);
4376 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4377 FROM {role_capabilities} rc
4378 JOIN {context} ctx ON ctx.id = rc.contextid
4379 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4380 ORDER BY rc.roleid ASC, ctx.depth DESC";
4381 $params = array('cap'=>$capability);
4383 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4384 // no cap definitions --> no capability
4385 return array(array(), array());
4388 $forbidden = array();
4389 $needed = array();
4390 foreach($capdefs as $def) {
4391 if (isset($forbidden[$def->roleid])) {
4392 continue;
4394 if ($def->permission == CAP_PROHIBIT) {
4395 $forbidden[$def->roleid] = $def->roleid;
4396 unset($needed[$def->roleid]);
4397 continue;
4399 if (!isset($needed[$def->roleid])) {
4400 if ($def->permission == CAP_ALLOW) {
4401 $needed[$def->roleid] = true;
4402 } else if ($def->permission == CAP_PREVENT) {
4403 $needed[$def->roleid] = false;
4407 unset($capdefs);
4409 // remove all those roles not allowing
4410 foreach($needed as $key=>$value) {
4411 if (!$value) {
4412 unset($needed[$key]);
4413 } else {
4414 $needed[$key] = $key;
4418 return array($needed, $forbidden);
4422 * Returns an array of role IDs that have ALL of the the supplied capabilities
4423 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4425 * @param stdClass $context
4426 * @param array $capabilities An array of capabilities
4427 * @return array of roles with all of the required capabilities
4429 function get_roles_with_caps_in_context($context, $capabilities) {
4430 $neededarr = array();
4431 $forbiddenarr = array();
4432 foreach($capabilities as $caprequired) {
4433 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4436 $rolesthatcanrate = array();
4437 if (!empty($neededarr)) {
4438 foreach ($neededarr as $needed) {
4439 if (empty($rolesthatcanrate)) {
4440 $rolesthatcanrate = $needed;
4441 } else {
4442 //only want roles that have all caps
4443 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4447 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4448 foreach ($forbiddenarr as $forbidden) {
4449 //remove any roles that are forbidden any of the caps
4450 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4453 return $rolesthatcanrate;
4457 * Returns an array of role names that have ALL of the the supplied capabilities
4458 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4460 * @param stdClass $context
4461 * @param array $capabilities An array of capabilities
4462 * @return array of roles with all of the required capabilities
4464 function get_role_names_with_caps_in_context($context, $capabilities) {
4465 global $DB;
4467 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4469 $allroles = array();
4470 $roles = $DB->get_records('role', null, 'sortorder DESC');
4471 foreach ($roles as $roleid=>$role) {
4472 $allroles[$roleid] = $role->name;
4475 $rolenames = array();
4476 foreach ($rolesthatcanrate as $r) {
4477 $rolenames[$r] = $allroles[$r];
4479 $rolenames = role_fix_names($rolenames, $context);
4480 return $rolenames;
4484 * This function verifies the prohibit comes from this context
4485 * and there are no more prohibits in parent contexts.
4487 * @param int $roleid
4488 * @param context $context
4489 * @param string $capability name
4490 * @return bool
4492 function prohibit_is_removable($roleid, context $context, $capability) {
4493 global $DB;
4495 $ctxids = trim($context->path, '/'); // kill leading slash
4496 $ctxids = str_replace('/', ',', $ctxids);
4498 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4500 $sql = "SELECT ctx.id
4501 FROM {role_capabilities} rc
4502 JOIN {context} ctx ON ctx.id = rc.contextid
4503 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4504 ORDER BY ctx.depth DESC";
4506 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4507 // no prohibits == nothing to remove
4508 return true;
4511 if (count($prohibits) > 1) {
4512 // more prohibits can not be removed
4513 return false;
4516 return !empty($prohibits[$context->id]);
4520 * More user friendly role permission changing,
4521 * it should produce as few overrides as possible.
4523 * @param int $roleid
4524 * @param stdClass $context
4525 * @param string $capname capability name
4526 * @param int $permission
4527 * @return void
4529 function role_change_permission($roleid, $context, $capname, $permission) {
4530 global $DB;
4532 if ($permission == CAP_INHERIT) {
4533 unassign_capability($capname, $roleid, $context->id);
4534 $context->mark_dirty();
4535 return;
4538 $ctxids = trim($context->path, '/'); // kill leading slash
4539 $ctxids = str_replace('/', ',', $ctxids);
4541 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4543 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4544 FROM {role_capabilities} rc
4545 JOIN {context} ctx ON ctx.id = rc.contextid
4546 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4547 ORDER BY ctx.depth DESC";
4549 if ($existing = $DB->get_records_sql($sql, $params)) {
4550 foreach($existing as $e) {
4551 if ($e->permission == CAP_PROHIBIT) {
4552 // prohibit can not be overridden, no point in changing anything
4553 return;
4556 $lowest = array_shift($existing);
4557 if ($lowest->permission == $permission) {
4558 // permission already set in this context or parent - nothing to do
4559 return;
4561 if ($existing) {
4562 $parent = array_shift($existing);
4563 if ($parent->permission == $permission) {
4564 // permission already set in parent context or parent - just unset in this context
4565 // we do this because we want as few overrides as possible for performance reasons
4566 unassign_capability($capname, $roleid, $context->id);
4567 $context->mark_dirty();
4568 return;
4572 } else {
4573 if ($permission == CAP_PREVENT) {
4574 // nothing means role does not have permission
4575 return;
4579 // assign the needed capability
4580 assign_capability($capname, $permission, $roleid, $context->id, true);
4582 // force cap reloading
4583 $context->mark_dirty();
4588 * Basic moodle context abstraction class.
4590 * Google confirms that no other important framework is using "context" class,
4591 * we could use something else like mcontext or moodle_context, but we need to type
4592 * this very often which would be annoying and it would take too much space...
4594 * This class is derived from stdClass for backwards compatibility with
4595 * odl $context record that was returned from DML $DB->get_record()
4597 * @package core_access
4598 * @category access
4599 * @copyright Petr Skoda {@link http://skodak.org}
4600 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4601 * @since 2.2
4603 * @property-read int $id context id
4604 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4605 * @property-read int $instanceid id of related instance in each context
4606 * @property-read string $path path to context, starts with system context
4607 * @property-read int $depth
4609 abstract class context extends stdClass implements IteratorAggregate {
4612 * The context id
4613 * Can be accessed publicly through $context->id
4614 * @var int
4616 protected $_id;
4619 * The context level
4620 * Can be accessed publicly through $context->contextlevel
4621 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4623 protected $_contextlevel;
4626 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4627 * Can be accessed publicly through $context->instanceid
4628 * @var int
4630 protected $_instanceid;
4633 * The path to the context always starting from the system context
4634 * Can be accessed publicly through $context->path
4635 * @var string
4637 protected $_path;
4640 * The depth of the context in relation to parent contexts
4641 * Can be accessed publicly through $context->depth
4642 * @var int
4644 protected $_depth;
4647 * @var array Context caching info
4649 private static $cache_contextsbyid = array();
4652 * @var array Context caching info
4654 private static $cache_contexts = array();
4657 * Context count
4658 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4659 * @var int
4661 protected static $cache_count = 0;
4664 * @var array Context caching info
4666 protected static $cache_preloaded = array();
4669 * @var context_system The system context once initialised
4671 protected static $systemcontext = null;
4674 * Resets the cache to remove all data.
4675 * @static
4677 protected static function reset_caches() {
4678 self::$cache_contextsbyid = array();
4679 self::$cache_contexts = array();
4680 self::$cache_count = 0;
4681 self::$cache_preloaded = array();
4683 self::$systemcontext = null;
4687 * Adds a context to the cache. If the cache is full, discards a batch of
4688 * older entries.
4690 * @static
4691 * @param context $context New context to add
4692 * @return void
4694 protected static function cache_add(context $context) {
4695 if (isset(self::$cache_contextsbyid[$context->id])) {
4696 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4697 return;
4700 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4701 $i = 0;
4702 foreach(self::$cache_contextsbyid as $ctx) {
4703 $i++;
4704 if ($i <= 100) {
4705 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4706 continue;
4708 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4709 // we remove oldest third of the contexts to make room for more contexts
4710 break;
4712 unset(self::$cache_contextsbyid[$ctx->id]);
4713 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4714 self::$cache_count--;
4718 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4719 self::$cache_contextsbyid[$context->id] = $context;
4720 self::$cache_count++;
4724 * Removes a context from the cache.
4726 * @static
4727 * @param context $context Context object to remove
4728 * @return void
4730 protected static function cache_remove(context $context) {
4731 if (!isset(self::$cache_contextsbyid[$context->id])) {
4732 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4733 return;
4735 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4736 unset(self::$cache_contextsbyid[$context->id]);
4738 self::$cache_count--;
4740 if (self::$cache_count < 0) {
4741 self::$cache_count = 0;
4746 * Gets a context from the cache.
4748 * @static
4749 * @param int $contextlevel Context level
4750 * @param int $instance Instance ID
4751 * @return context|bool Context or false if not in cache
4753 protected static function cache_get($contextlevel, $instance) {
4754 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4755 return self::$cache_contexts[$contextlevel][$instance];
4757 return false;
4761 * Gets a context from the cache based on its id.
4763 * @static
4764 * @param int $id Context ID
4765 * @return context|bool Context or false if not in cache
4767 protected static function cache_get_by_id($id) {
4768 if (isset(self::$cache_contextsbyid[$id])) {
4769 return self::$cache_contextsbyid[$id];
4771 return false;
4775 * Preloads context information from db record and strips the cached info.
4777 * @static
4778 * @param stdClass $rec
4779 * @return void (modifies $rec)
4781 protected static function preload_from_record(stdClass $rec) {
4782 if (empty($rec->ctxid) or empty($rec->ctxlevel) or empty($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
4783 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4784 return;
4787 // note: in PHP5 the objects are passed by reference, no need to return $rec
4788 $record = new stdClass();
4789 $record->id = $rec->ctxid; unset($rec->ctxid);
4790 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
4791 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
4792 $record->path = $rec->ctxpath; unset($rec->ctxpath);
4793 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
4795 return context::create_instance_from_record($record);
4799 // ====== magic methods =======
4802 * Magic setter method, we do not want anybody to modify properties from the outside
4803 * @param string $name
4804 * @param mixed $value
4806 public function __set($name, $value) {
4807 debugging('Can not change context instance properties!');
4811 * Magic method getter, redirects to read only values.
4812 * @param string $name
4813 * @return mixed
4815 public function __get($name) {
4816 switch ($name) {
4817 case 'id': return $this->_id;
4818 case 'contextlevel': return $this->_contextlevel;
4819 case 'instanceid': return $this->_instanceid;
4820 case 'path': return $this->_path;
4821 case 'depth': return $this->_depth;
4823 default:
4824 debugging('Invalid context property accessed! '.$name);
4825 return null;
4830 * Full support for isset on our magic read only properties.
4831 * @param string $name
4832 * @return bool
4834 public function __isset($name) {
4835 switch ($name) {
4836 case 'id': return isset($this->_id);
4837 case 'contextlevel': return isset($this->_contextlevel);
4838 case 'instanceid': return isset($this->_instanceid);
4839 case 'path': return isset($this->_path);
4840 case 'depth': return isset($this->_depth);
4842 default: return false;
4848 * ALl properties are read only, sorry.
4849 * @param string $name
4851 public function __unset($name) {
4852 debugging('Can not unset context instance properties!');
4855 // ====== implementing method from interface IteratorAggregate ======
4858 * Create an iterator because magic vars can't be seen by 'foreach'.
4860 * Now we can convert context object to array using convert_to_array(),
4861 * and feed it properly to json_encode().
4863 public function getIterator() {
4864 $ret = array(
4865 'id' => $this->id,
4866 'contextlevel' => $this->contextlevel,
4867 'instanceid' => $this->instanceid,
4868 'path' => $this->path,
4869 'depth' => $this->depth
4871 return new ArrayIterator($ret);
4874 // ====== general context methods ======
4877 * Constructor is protected so that devs are forced to
4878 * use context_xxx::instance() or context::instance_by_id().
4880 * @param stdClass $record
4882 protected function __construct(stdClass $record) {
4883 $this->_id = $record->id;
4884 $this->_contextlevel = (int)$record->contextlevel;
4885 $this->_instanceid = $record->instanceid;
4886 $this->_path = $record->path;
4887 $this->_depth = $record->depth;
4891 * This function is also used to work around 'protected' keyword problems in context_helper.
4892 * @static
4893 * @param stdClass $record
4894 * @return context instance
4896 protected static function create_instance_from_record(stdClass $record) {
4897 $classname = context_helper::get_class_for_level($record->contextlevel);
4899 if ($context = context::cache_get_by_id($record->id)) {
4900 return $context;
4903 $context = new $classname($record);
4904 context::cache_add($context);
4906 return $context;
4910 * Copy prepared new contexts from temp table to context table,
4911 * we do this in db specific way for perf reasons only.
4912 * @static
4914 protected static function merge_context_temp_table() {
4915 global $DB;
4917 /* MDL-11347:
4918 * - mysql does not allow to use FROM in UPDATE statements
4919 * - using two tables after UPDATE works in mysql, but might give unexpected
4920 * results in pg 8 (depends on configuration)
4921 * - using table alias in UPDATE does not work in pg < 8.2
4923 * Different code for each database - mostly for performance reasons
4926 $dbfamily = $DB->get_dbfamily();
4927 if ($dbfamily == 'mysql') {
4928 $updatesql = "UPDATE {context} ct, {context_temp} temp
4929 SET ct.path = temp.path,
4930 ct.depth = temp.depth
4931 WHERE ct.id = temp.id";
4932 } else if ($dbfamily == 'oracle') {
4933 $updatesql = "UPDATE {context} ct
4934 SET (ct.path, ct.depth) =
4935 (SELECT temp.path, temp.depth
4936 FROM {context_temp} temp
4937 WHERE temp.id=ct.id)
4938 WHERE EXISTS (SELECT 'x'
4939 FROM {context_temp} temp
4940 WHERE temp.id = ct.id)";
4941 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
4942 $updatesql = "UPDATE {context}
4943 SET path = temp.path,
4944 depth = temp.depth
4945 FROM {context_temp} temp
4946 WHERE temp.id={context}.id";
4947 } else {
4948 // sqlite and others
4949 $updatesql = "UPDATE {context}
4950 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
4951 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
4952 WHERE id IN (SELECT id FROM {context_temp})";
4955 $DB->execute($updatesql);
4959 * Get a context instance as an object, from a given context id.
4961 * @static
4962 * @param int $id context id
4963 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
4964 * MUST_EXIST means throw exception if no record found
4965 * @return context|bool the context object or false if not found
4967 public static function instance_by_id($id, $strictness = MUST_EXIST) {
4968 global $DB;
4970 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
4971 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
4972 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
4975 if ($id == SYSCONTEXTID) {
4976 return context_system::instance(0, $strictness);
4979 if (is_array($id) or is_object($id) or empty($id)) {
4980 throw new coding_exception('Invalid context id specified context::instance_by_id()');
4983 if ($context = context::cache_get_by_id($id)) {
4984 return $context;
4987 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
4988 return context::create_instance_from_record($record);
4991 return false;
4995 * Update context info after moving context in the tree structure.
4997 * @param context $newparent
4998 * @return void
5000 public function update_moved(context $newparent) {
5001 global $DB;
5003 $frompath = $this->_path;
5004 $newpath = $newparent->path . '/' . $this->_id;
5006 $trans = $DB->start_delegated_transaction();
5008 $this->mark_dirty();
5010 $setdepth = '';
5011 if (($newparent->depth +1) != $this->_depth) {
5012 $diff = $newparent->depth - $this->_depth + 1;
5013 $setdepth = ", depth = depth + $diff";
5015 $sql = "UPDATE {context}
5016 SET path = ?
5017 $setdepth
5018 WHERE id = ?";
5019 $params = array($newpath, $this->_id);
5020 $DB->execute($sql, $params);
5022 $this->_path = $newpath;
5023 $this->_depth = $newparent->depth + 1;
5025 $sql = "UPDATE {context}
5026 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5027 $setdepth
5028 WHERE path LIKE ?";
5029 $params = array($newpath, "{$frompath}/%");
5030 $DB->execute($sql, $params);
5032 $this->mark_dirty();
5034 context::reset_caches();
5036 $trans->allow_commit();
5040 * Remove all context path info and optionally rebuild it.
5042 * @param bool $rebuild
5043 * @return void
5045 public function reset_paths($rebuild = true) {
5046 global $DB;
5048 if ($this->_path) {
5049 $this->mark_dirty();
5051 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5052 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5053 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5054 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5055 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5056 $this->_depth = 0;
5057 $this->_path = null;
5060 if ($rebuild) {
5061 context_helper::build_all_paths(false);
5064 context::reset_caches();
5068 * Delete all data linked to content, do not delete the context record itself
5070 public function delete_content() {
5071 global $CFG, $DB;
5073 blocks_delete_all_for_context($this->_id);
5074 filter_delete_all_for_context($this->_id);
5076 require_once($CFG->dirroot . '/comment/lib.php');
5077 comment::delete_comments(array('contextid'=>$this->_id));
5079 require_once($CFG->dirroot.'/rating/lib.php');
5080 $delopt = new stdclass();
5081 $delopt->contextid = $this->_id;
5082 $rm = new rating_manager();
5083 $rm->delete_ratings($delopt);
5085 // delete all files attached to this context
5086 $fs = get_file_storage();
5087 $fs->delete_area_files($this->_id);
5089 // delete all advanced grading data attached to this context
5090 require_once($CFG->dirroot.'/grade/grading/lib.php');
5091 grading_manager::delete_all_for_context($this->_id);
5093 // now delete stuff from role related tables, role_unassign_all
5094 // and unenrol should be called earlier to do proper cleanup
5095 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5096 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5097 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5101 * Delete the context content and the context record itself
5103 public function delete() {
5104 global $DB;
5106 // double check the context still exists
5107 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5108 context::cache_remove($this);
5109 return;
5112 $this->delete_content();
5113 $DB->delete_records('context', array('id'=>$this->_id));
5114 // purge static context cache if entry present
5115 context::cache_remove($this);
5117 // do not mark dirty contexts if parents unknown
5118 if (!is_null($this->_path) and $this->_depth > 0) {
5119 $this->mark_dirty();
5123 // ====== context level related methods ======
5126 * Utility method for context creation
5128 * @static
5129 * @param int $contextlevel
5130 * @param int $instanceid
5131 * @param string $parentpath
5132 * @return stdClass context record
5134 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5135 global $DB;
5137 $record = new stdClass();
5138 $record->contextlevel = $contextlevel;
5139 $record->instanceid = $instanceid;
5140 $record->depth = 0;
5141 $record->path = null; //not known before insert
5143 $record->id = $DB->insert_record('context', $record);
5145 // now add path if known - it can be added later
5146 if (!is_null($parentpath)) {
5147 $record->path = $parentpath.'/'.$record->id;
5148 $record->depth = substr_count($record->path, '/');
5149 $DB->update_record('context', $record);
5152 return $record;
5156 * Returns human readable context identifier.
5158 * @param boolean $withprefix whether to prefix the name of the context with the
5159 * type of context, e.g. User, Course, Forum, etc.
5160 * @param boolean $short whether to use the short name of the thing. Only applies
5161 * to course contexts
5162 * @return string the human readable context name.
5164 public function get_context_name($withprefix = true, $short = false) {
5165 // must be implemented in all context levels
5166 throw new coding_exception('can not get name of abstract context');
5170 * Returns the most relevant URL for this context.
5172 * @return moodle_url
5174 public abstract function get_url();
5177 * Returns array of relevant context capability records.
5179 * @return array
5181 public abstract function get_capabilities();
5184 * Recursive function which, given a context, find all its children context ids.
5186 * For course category contexts it will return immediate children and all subcategory contexts.
5187 * It will NOT recurse into courses or subcategories categories.
5188 * If you want to do that, call it on the returned courses/categories.
5190 * When called for a course context, it will return the modules and blocks
5191 * displayed in the course page and blocks displayed on the module pages.
5193 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5194 * contexts ;-)
5196 * @return array Array of child records
5198 public function get_child_contexts() {
5199 global $DB;
5201 $sql = "SELECT ctx.*
5202 FROM {context} ctx
5203 WHERE ctx.path LIKE ?";
5204 $params = array($this->_path.'/%');
5205 $records = $DB->get_records_sql($sql, $params);
5207 $result = array();
5208 foreach ($records as $record) {
5209 $result[$record->id] = context::create_instance_from_record($record);
5212 return $result;
5216 * Returns parent contexts of this context in reversed order, i.e. parent first,
5217 * then grand parent, etc.
5219 * @param bool $includeself tre means include self too
5220 * @return array of context instances
5222 public function get_parent_contexts($includeself = false) {
5223 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5224 return array();
5227 $result = array();
5228 foreach ($contextids as $contextid) {
5229 $parent = context::instance_by_id($contextid, MUST_EXIST);
5230 $result[$parent->id] = $parent;
5233 return $result;
5237 * Returns parent contexts of this context in reversed order, i.e. parent first,
5238 * then grand parent, etc.
5240 * @param bool $includeself tre means include self too
5241 * @return array of context ids
5243 public function get_parent_context_ids($includeself = false) {
5244 if (empty($this->_path)) {
5245 return array();
5248 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5249 $parentcontexts = explode('/', $parentcontexts);
5250 if (!$includeself) {
5251 array_pop($parentcontexts); // and remove its own id
5254 return array_reverse($parentcontexts);
5258 * Returns parent context
5260 * @return context
5262 public function get_parent_context() {
5263 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5264 return false;
5267 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5268 $parentcontexts = explode('/', $parentcontexts);
5269 array_pop($parentcontexts); // self
5270 $contextid = array_pop($parentcontexts); // immediate parent
5272 return context::instance_by_id($contextid, MUST_EXIST);
5276 * Is this context part of any course? If yes return course context.
5278 * @param bool $strict true means throw exception if not found, false means return false if not found
5279 * @return course_context context of the enclosing course, null if not found or exception
5281 public function get_course_context($strict = true) {
5282 if ($strict) {
5283 throw new coding_exception('Context does not belong to any course.');
5284 } else {
5285 return false;
5290 * Returns sql necessary for purging of stale context instances.
5292 * @static
5293 * @return string cleanup SQL
5295 protected static function get_cleanup_sql() {
5296 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5300 * Rebuild context paths and depths at context level.
5302 * @static
5303 * @param bool $force
5304 * @return void
5306 protected static function build_paths($force) {
5307 throw new coding_exception('build_paths() method must be implemented in all context levels');
5311 * Create missing context instances at given level
5313 * @static
5314 * @return void
5316 protected static function create_level_instances() {
5317 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5321 * Reset all cached permissions and definitions if the necessary.
5322 * @return void
5324 public function reload_if_dirty() {
5325 global $ACCESSLIB_PRIVATE, $USER;
5327 // Load dirty contexts list if needed
5328 if (CLI_SCRIPT) {
5329 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5330 // we do not load dirty flags in CLI and cron
5331 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5333 } else {
5334 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5335 if (!isset($USER->access['time'])) {
5336 // nothing was loaded yet, we do not need to check dirty contexts now
5337 return;
5339 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5340 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5344 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5345 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5346 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5347 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5348 reload_all_capabilities();
5349 break;
5355 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5357 public function mark_dirty() {
5358 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5360 if (during_initial_install()) {
5361 return;
5364 // only if it is a non-empty string
5365 if (is_string($this->_path) && $this->_path !== '') {
5366 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5367 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5368 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5369 } else {
5370 if (CLI_SCRIPT) {
5371 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5372 } else {
5373 if (isset($USER->access['time'])) {
5374 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5375 } else {
5376 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5378 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5387 * Context maintenance and helper methods.
5389 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5390 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5391 * level implementation from the rest of code, the code completion returns what developers need.
5393 * Thank you Tim Hunt for helping me with this nasty trick.
5395 * @package core_access
5396 * @category access
5397 * @copyright Petr Skoda {@link http://skodak.org}
5398 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5399 * @since 2.2
5401 class context_helper extends context {
5404 * @var array An array mapping context levels to classes
5406 private static $alllevels = array(
5407 CONTEXT_SYSTEM => 'context_system',
5408 CONTEXT_USER => 'context_user',
5409 CONTEXT_COURSECAT => 'context_coursecat',
5410 CONTEXT_COURSE => 'context_course',
5411 CONTEXT_MODULE => 'context_module',
5412 CONTEXT_BLOCK => 'context_block',
5416 * Instance does not make sense here, only static use
5418 protected function __construct() {
5422 * Returns a class name of the context level class
5424 * @static
5425 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5426 * @return string class name of the context class
5428 public static function get_class_for_level($contextlevel) {
5429 if (isset(self::$alllevels[$contextlevel])) {
5430 return self::$alllevels[$contextlevel];
5431 } else {
5432 throw new coding_exception('Invalid context level specified');
5437 * Returns a list of all context levels
5439 * @static
5440 * @return array int=>string (level=>level class name)
5442 public static function get_all_levels() {
5443 return self::$alllevels;
5447 * Remove stale contexts that belonged to deleted instances.
5448 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5450 * @static
5451 * @return void
5453 public static function cleanup_instances() {
5454 global $DB;
5455 $sqls = array();
5456 foreach (self::$alllevels as $level=>$classname) {
5457 $sqls[] = $classname::get_cleanup_sql();
5460 $sql = implode(" UNION ", $sqls);
5462 // it is probably better to use transactions, it might be faster too
5463 $transaction = $DB->start_delegated_transaction();
5465 $rs = $DB->get_recordset_sql($sql);
5466 foreach ($rs as $record) {
5467 $context = context::create_instance_from_record($record);
5468 $context->delete();
5470 $rs->close();
5472 $transaction->allow_commit();
5476 * Create all context instances at the given level and above.
5478 * @static
5479 * @param int $contextlevel null means all levels
5480 * @param bool $buildpaths
5481 * @return void
5483 public static function create_instances($contextlevel = null, $buildpaths = true) {
5484 foreach (self::$alllevels as $level=>$classname) {
5485 if ($contextlevel and $level > $contextlevel) {
5486 // skip potential sub-contexts
5487 continue;
5489 $classname::create_level_instances();
5490 if ($buildpaths) {
5491 $classname::build_paths(false);
5497 * Rebuild paths and depths in all context levels.
5499 * @static
5500 * @param bool $force false means add missing only
5501 * @return void
5503 public static function build_all_paths($force = false) {
5504 foreach (self::$alllevels as $classname) {
5505 $classname::build_paths($force);
5508 // reset static course cache - it might have incorrect cached data
5509 accesslib_clear_all_caches(true);
5513 * Resets the cache to remove all data.
5514 * @static
5516 public static function reset_caches() {
5517 context::reset_caches();
5521 * Returns all fields necessary for context preloading from user $rec.
5523 * This helps with performance when dealing with hundreds of contexts.
5525 * @static
5526 * @param string $tablealias context table alias in the query
5527 * @return array (table.column=>alias, ...)
5529 public static function get_preload_record_columns($tablealias) {
5530 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5534 * Returns all fields necessary for context preloading from user $rec.
5536 * This helps with performance when dealing with hundreds of contexts.
5538 * @static
5539 * @param string $tablealias context table alias in the query
5540 * @return string
5542 public static function get_preload_record_columns_sql($tablealias) {
5543 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5547 * Preloads context information from db record and strips the cached info.
5549 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5551 * @static
5552 * @param stdClass $rec
5553 * @return void (modifies $rec)
5555 public static function preload_from_record(stdClass $rec) {
5556 context::preload_from_record($rec);
5560 * Preload all contexts instances from course.
5562 * To be used if you expect multiple queries for course activities...
5564 * @static
5565 * @param int $courseid
5567 public static function preload_course($courseid) {
5568 // Users can call this multiple times without doing any harm
5569 if (isset(context::$cache_preloaded[$courseid])) {
5570 return;
5572 $coursecontext = context_course::instance($courseid);
5573 $coursecontext->get_child_contexts();
5575 context::$cache_preloaded[$courseid] = true;
5579 * Delete context instance
5581 * @static
5582 * @param int $contextlevel
5583 * @param int $instanceid
5584 * @return void
5586 public static function delete_instance($contextlevel, $instanceid) {
5587 global $DB;
5589 // double check the context still exists
5590 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5591 $context = context::create_instance_from_record($record);
5592 $context->delete();
5593 } else {
5594 // we should try to purge the cache anyway
5599 * Returns the name of specified context level
5601 * @static
5602 * @param int $contextlevel
5603 * @return string name of the context level
5605 public static function get_level_name($contextlevel) {
5606 $classname = context_helper::get_class_for_level($contextlevel);
5607 return $classname::get_level_name();
5611 * not used
5613 public function get_url() {
5617 * not used
5619 public function get_capabilities() {
5625 * System context class
5627 * @package core_access
5628 * @category access
5629 * @copyright Petr Skoda {@link http://skodak.org}
5630 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5631 * @since 2.2
5633 class context_system extends context {
5635 * Please use context_system::instance() if you need the instance of context.
5637 * @param stdClass $record
5639 protected function __construct(stdClass $record) {
5640 parent::__construct($record);
5641 if ($record->contextlevel != CONTEXT_SYSTEM) {
5642 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5647 * Returns human readable context level name.
5649 * @static
5650 * @return string the human readable context level name.
5652 public static function get_level_name() {
5653 return get_string('coresystem');
5657 * Returns human readable context identifier.
5659 * @param boolean $withprefix does not apply to system context
5660 * @param boolean $short does not apply to system context
5661 * @return string the human readable context name.
5663 public function get_context_name($withprefix = true, $short = false) {
5664 return self::get_level_name();
5668 * Returns the most relevant URL for this context.
5670 * @return moodle_url
5672 public function get_url() {
5673 return new moodle_url('/');
5677 * Returns array of relevant context capability records.
5679 * @return array
5681 public function get_capabilities() {
5682 global $DB;
5684 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5686 $params = array();
5687 $sql = "SELECT *
5688 FROM {capabilities}";
5690 return $DB->get_records_sql($sql.' '.$sort, $params);
5694 * Create missing context instances at system context
5695 * @static
5697 protected static function create_level_instances() {
5698 // nothing to do here, the system context is created automatically in installer
5699 self::instance(0);
5703 * Returns system context instance.
5705 * @static
5706 * @param int $instanceid
5707 * @param int $strictness
5708 * @param bool $cache
5709 * @return context_system context instance
5711 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
5712 global $DB;
5714 if ($instanceid != 0) {
5715 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5718 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5719 if (!isset(context::$systemcontext)) {
5720 $record = new stdClass();
5721 $record->id = SYSCONTEXTID;
5722 $record->contextlevel = CONTEXT_SYSTEM;
5723 $record->instanceid = 0;
5724 $record->path = '/'.SYSCONTEXTID;
5725 $record->depth = 1;
5726 context::$systemcontext = new context_system($record);
5728 return context::$systemcontext;
5732 try {
5733 // we ignore the strictness completely because system context must except except during install
5734 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5735 } catch (dml_exception $e) {
5736 //table or record does not exist
5737 if (!during_initial_install()) {
5738 // do not mess with system context after install, it simply must exist
5739 throw $e;
5741 $record = null;
5744 if (!$record) {
5745 $record = new stdClass();
5746 $record->contextlevel = CONTEXT_SYSTEM;
5747 $record->instanceid = 0;
5748 $record->depth = 1;
5749 $record->path = null; //not known before insert
5751 try {
5752 if ($DB->count_records('context')) {
5753 // contexts already exist, this is very weird, system must be first!!!
5754 return null;
5756 if (defined('SYSCONTEXTID')) {
5757 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5758 $record->id = SYSCONTEXTID;
5759 $DB->import_record('context', $record);
5760 $DB->get_manager()->reset_sequence('context');
5761 } else {
5762 $record->id = $DB->insert_record('context', $record);
5764 } catch (dml_exception $e) {
5765 // can not create context - table does not exist yet, sorry
5766 return null;
5770 if ($record->instanceid != 0) {
5771 // this is very weird, somebody must be messing with context table
5772 debugging('Invalid system context detected');
5775 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5776 // fix path if necessary, initial install or path reset
5777 $record->depth = 1;
5778 $record->path = '/'.$record->id;
5779 $DB->update_record('context', $record);
5782 if (!defined('SYSCONTEXTID')) {
5783 define('SYSCONTEXTID', $record->id);
5786 context::$systemcontext = new context_system($record);
5787 return context::$systemcontext;
5791 * Returns all site contexts except the system context, DO NOT call on production servers!!
5793 * Contexts are not cached.
5795 * @return array
5797 public function get_child_contexts() {
5798 global $DB;
5800 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
5802 // Just get all the contexts except for CONTEXT_SYSTEM level
5803 // and hope we don't OOM in the process - don't cache
5804 $sql = "SELECT c.*
5805 FROM {context} c
5806 WHERE contextlevel > ".CONTEXT_SYSTEM;
5807 $records = $DB->get_records_sql($sql);
5809 $result = array();
5810 foreach ($records as $record) {
5811 $result[$record->id] = context::create_instance_from_record($record);
5814 return $result;
5818 * Returns sql necessary for purging of stale context instances.
5820 * @static
5821 * @return string cleanup SQL
5823 protected static function get_cleanup_sql() {
5824 $sql = "
5825 SELECT c.*
5826 FROM {context} c
5827 WHERE 1=2
5830 return $sql;
5834 * Rebuild context paths and depths at system context level.
5836 * @static
5837 * @param bool $force
5839 protected static function build_paths($force) {
5840 global $DB;
5842 /* note: ignore $force here, we always do full test of system context */
5844 // exactly one record must exist
5845 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5847 if ($record->instanceid != 0) {
5848 debugging('Invalid system context detected');
5851 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
5852 debugging('Invalid SYSCONTEXTID detected');
5855 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5856 // fix path if necessary, initial install or path reset
5857 $record->depth = 1;
5858 $record->path = '/'.$record->id;
5859 $DB->update_record('context', $record);
5866 * User context class
5868 * @package core_access
5869 * @category access
5870 * @copyright Petr Skoda {@link http://skodak.org}
5871 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5872 * @since 2.2
5874 class context_user extends context {
5876 * Please use context_user::instance($userid) if you need the instance of context.
5877 * Alternatively if you know only the context id use context::instance_by_id($contextid)
5879 * @param stdClass $record
5881 protected function __construct(stdClass $record) {
5882 parent::__construct($record);
5883 if ($record->contextlevel != CONTEXT_USER) {
5884 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
5889 * Returns human readable context level name.
5891 * @static
5892 * @return string the human readable context level name.
5894 public static function get_level_name() {
5895 return get_string('user');
5899 * Returns human readable context identifier.
5901 * @param boolean $withprefix whether to prefix the name of the context with User
5902 * @param boolean $short does not apply to user context
5903 * @return string the human readable context name.
5905 public function get_context_name($withprefix = true, $short = false) {
5906 global $DB;
5908 $name = '';
5909 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
5910 if ($withprefix){
5911 $name = get_string('user').': ';
5913 $name .= fullname($user);
5915 return $name;
5919 * Returns the most relevant URL for this context.
5921 * @return moodle_url
5923 public function get_url() {
5924 global $COURSE;
5926 if ($COURSE->id == SITEID) {
5927 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
5928 } else {
5929 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
5931 return $url;
5935 * Returns array of relevant context capability records.
5937 * @return array
5939 public function get_capabilities() {
5940 global $DB;
5942 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5944 $extracaps = array('moodle/grade:viewall');
5945 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
5946 $sql = "SELECT *
5947 FROM {capabilities}
5948 WHERE contextlevel = ".CONTEXT_USER."
5949 OR name $extra";
5951 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
5955 * Returns user context instance.
5957 * @static
5958 * @param int $instanceid
5959 * @param int $strictness
5960 * @return context_user context instance
5962 public static function instance($instanceid, $strictness = MUST_EXIST) {
5963 global $DB;
5965 if ($context = context::cache_get(CONTEXT_USER, $instanceid)) {
5966 return $context;
5969 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_USER, 'instanceid'=>$instanceid))) {
5970 if ($user = $DB->get_record('user', array('id'=>$instanceid, 'deleted'=>0), 'id', $strictness)) {
5971 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
5975 if ($record) {
5976 $context = new context_user($record);
5977 context::cache_add($context);
5978 return $context;
5981 return false;
5985 * Create missing context instances at user context level
5986 * @static
5988 protected static function create_level_instances() {
5989 global $DB;
5991 $sql = "INSERT INTO {context} (contextlevel, instanceid)
5992 SELECT ".CONTEXT_USER.", u.id
5993 FROM {user} u
5994 WHERE u.deleted = 0
5995 AND NOT EXISTS (SELECT 'x'
5996 FROM {context} cx
5997 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
5998 $DB->execute($sql);
6002 * Returns sql necessary for purging of stale context instances.
6004 * @static
6005 * @return string cleanup SQL
6007 protected static function get_cleanup_sql() {
6008 $sql = "
6009 SELECT c.*
6010 FROM {context} c
6011 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6012 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6015 return $sql;
6019 * Rebuild context paths and depths at user context level.
6021 * @static
6022 * @param bool $force
6024 protected static function build_paths($force) {
6025 global $DB;
6027 // First update normal users.
6028 $path = $DB->sql_concat('?', 'id');
6029 $pathstart = '/' . SYSCONTEXTID . '/';
6030 $params = array($pathstart);
6032 if ($force) {
6033 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6034 $params[] = $pathstart;
6035 } else {
6036 $where = "depth = 0 OR path IS NULL";
6039 $sql = "UPDATE {context}
6040 SET depth = 2,
6041 path = {$path}
6042 WHERE contextlevel = " . CONTEXT_USER . "
6043 AND ($where)";
6044 $DB->execute($sql, $params);
6050 * Course category context class
6052 * @package core_access
6053 * @category access
6054 * @copyright Petr Skoda {@link http://skodak.org}
6055 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6056 * @since 2.2
6058 class context_coursecat extends context {
6060 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6061 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6063 * @param stdClass $record
6065 protected function __construct(stdClass $record) {
6066 parent::__construct($record);
6067 if ($record->contextlevel != CONTEXT_COURSECAT) {
6068 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6073 * Returns human readable context level name.
6075 * @static
6076 * @return string the human readable context level name.
6078 public static function get_level_name() {
6079 return get_string('category');
6083 * Returns human readable context identifier.
6085 * @param boolean $withprefix whether to prefix the name of the context with Category
6086 * @param boolean $short does not apply to course categories
6087 * @return string the human readable context name.
6089 public function get_context_name($withprefix = true, $short = false) {
6090 global $DB;
6092 $name = '';
6093 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6094 if ($withprefix){
6095 $name = get_string('category').': ';
6097 $name .= format_string($category->name, true, array('context' => $this));
6099 return $name;
6103 * Returns the most relevant URL for this context.
6105 * @return moodle_url
6107 public function get_url() {
6108 return new moodle_url('/course/category.php', array('id'=>$this->_instanceid));
6112 * Returns array of relevant context capability records.
6114 * @return array
6116 public function get_capabilities() {
6117 global $DB;
6119 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6121 $params = array();
6122 $sql = "SELECT *
6123 FROM {capabilities}
6124 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6126 return $DB->get_records_sql($sql.' '.$sort, $params);
6130 * Returns course category context instance.
6132 * @static
6133 * @param int $instanceid
6134 * @param int $strictness
6135 * @return context_coursecat context instance
6137 public static function instance($instanceid, $strictness = MUST_EXIST) {
6138 global $DB;
6140 if ($context = context::cache_get(CONTEXT_COURSECAT, $instanceid)) {
6141 return $context;
6144 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSECAT, 'instanceid'=>$instanceid))) {
6145 if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), 'id,parent', $strictness)) {
6146 if ($category->parent) {
6147 $parentcontext = context_coursecat::instance($category->parent);
6148 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6149 } else {
6150 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6155 if ($record) {
6156 $context = new context_coursecat($record);
6157 context::cache_add($context);
6158 return $context;
6161 return false;
6165 * Returns immediate child contexts of category and all subcategories,
6166 * children of subcategories and courses are not returned.
6168 * @return array
6170 public function get_child_contexts() {
6171 global $DB;
6173 $sql = "SELECT ctx.*
6174 FROM {context} ctx
6175 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6176 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6177 $records = $DB->get_records_sql($sql, $params);
6179 $result = array();
6180 foreach ($records as $record) {
6181 $result[$record->id] = context::create_instance_from_record($record);
6184 return $result;
6188 * Create missing context instances at course category context level
6189 * @static
6191 protected static function create_level_instances() {
6192 global $DB;
6194 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6195 SELECT ".CONTEXT_COURSECAT.", cc.id
6196 FROM {course_categories} cc
6197 WHERE NOT EXISTS (SELECT 'x'
6198 FROM {context} cx
6199 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6200 $DB->execute($sql);
6204 * Returns sql necessary for purging of stale context instances.
6206 * @static
6207 * @return string cleanup SQL
6209 protected static function get_cleanup_sql() {
6210 $sql = "
6211 SELECT c.*
6212 FROM {context} c
6213 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6214 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6217 return $sql;
6221 * Rebuild context paths and depths at course category context level.
6223 * @static
6224 * @param bool $force
6226 protected static function build_paths($force) {
6227 global $DB;
6229 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6230 if ($force) {
6231 $ctxemptyclause = $emptyclause = '';
6232 } else {
6233 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6234 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6237 $base = '/'.SYSCONTEXTID;
6239 // Normal top level categories
6240 $sql = "UPDATE {context}
6241 SET depth=2,
6242 path=".$DB->sql_concat("'$base/'", 'id')."
6243 WHERE contextlevel=".CONTEXT_COURSECAT."
6244 AND EXISTS (SELECT 'x'
6245 FROM {course_categories} cc
6246 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6247 $emptyclause";
6248 $DB->execute($sql);
6250 // Deeper categories - one query per depthlevel
6251 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6252 for ($n=2; $n<=$maxdepth; $n++) {
6253 $sql = "INSERT INTO {context_temp} (id, path, depth)
6254 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6255 FROM {context} ctx
6256 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6257 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6258 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6259 $ctxemptyclause";
6260 $trans = $DB->start_delegated_transaction();
6261 $DB->delete_records('context_temp');
6262 $DB->execute($sql);
6263 context::merge_context_temp_table();
6264 $DB->delete_records('context_temp');
6265 $trans->allow_commit();
6274 * Course context class
6276 * @package core_access
6277 * @category access
6278 * @copyright Petr Skoda {@link http://skodak.org}
6279 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6280 * @since 2.2
6282 class context_course extends context {
6284 * Please use context_course::instance($courseid) if you need the instance of context.
6285 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6287 * @param stdClass $record
6289 protected function __construct(stdClass $record) {
6290 parent::__construct($record);
6291 if ($record->contextlevel != CONTEXT_COURSE) {
6292 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6297 * Returns human readable context level name.
6299 * @static
6300 * @return string the human readable context level name.
6302 public static function get_level_name() {
6303 return get_string('course');
6307 * Returns human readable context identifier.
6309 * @param boolean $withprefix whether to prefix the name of the context with Course
6310 * @param boolean $short whether to use the short name of the thing.
6311 * @return string the human readable context name.
6313 public function get_context_name($withprefix = true, $short = false) {
6314 global $DB;
6316 $name = '';
6317 if ($this->_instanceid == SITEID) {
6318 $name = get_string('frontpage', 'admin');
6319 } else {
6320 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6321 if ($withprefix){
6322 $name = get_string('course').': ';
6324 if ($short){
6325 $name .= format_string($course->shortname, true, array('context' => $this));
6326 } else {
6327 $name .= format_string(get_course_display_name_for_list($course));
6331 return $name;
6335 * Returns the most relevant URL for this context.
6337 * @return moodle_url
6339 public function get_url() {
6340 if ($this->_instanceid != SITEID) {
6341 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6344 return new moodle_url('/');
6348 * Returns array of relevant context capability records.
6350 * @return array
6352 public function get_capabilities() {
6353 global $DB;
6355 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6357 $params = array();
6358 $sql = "SELECT *
6359 FROM {capabilities}
6360 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6362 return $DB->get_records_sql($sql.' '.$sort, $params);
6366 * Is this context part of any course? If yes return course context.
6368 * @param bool $strict true means throw exception if not found, false means return false if not found
6369 * @return course_context context of the enclosing course, null if not found or exception
6371 public function get_course_context($strict = true) {
6372 return $this;
6376 * Returns course context instance.
6378 * @static
6379 * @param int $instanceid
6380 * @param int $strictness
6381 * @return context_course context instance
6383 public static function instance($instanceid, $strictness = MUST_EXIST) {
6384 global $DB;
6386 if ($context = context::cache_get(CONTEXT_COURSE, $instanceid)) {
6387 return $context;
6390 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$instanceid))) {
6391 if ($course = $DB->get_record('course', array('id'=>$instanceid), 'id,category', $strictness)) {
6392 if ($course->category) {
6393 $parentcontext = context_coursecat::instance($course->category);
6394 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6395 } else {
6396 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6401 if ($record) {
6402 $context = new context_course($record);
6403 context::cache_add($context);
6404 return $context;
6407 return false;
6411 * Create missing context instances at course context level
6412 * @static
6414 protected static function create_level_instances() {
6415 global $DB;
6417 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6418 SELECT ".CONTEXT_COURSE.", c.id
6419 FROM {course} c
6420 WHERE NOT EXISTS (SELECT 'x'
6421 FROM {context} cx
6422 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6423 $DB->execute($sql);
6427 * Returns sql necessary for purging of stale context instances.
6429 * @static
6430 * @return string cleanup SQL
6432 protected static function get_cleanup_sql() {
6433 $sql = "
6434 SELECT c.*
6435 FROM {context} c
6436 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6437 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6440 return $sql;
6444 * Rebuild context paths and depths at course context level.
6446 * @static
6447 * @param bool $force
6449 protected static function build_paths($force) {
6450 global $DB;
6452 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6453 if ($force) {
6454 $ctxemptyclause = $emptyclause = '';
6455 } else {
6456 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6457 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6460 $base = '/'.SYSCONTEXTID;
6462 // Standard frontpage
6463 $sql = "UPDATE {context}
6464 SET depth = 2,
6465 path = ".$DB->sql_concat("'$base/'", 'id')."
6466 WHERE contextlevel = ".CONTEXT_COURSE."
6467 AND EXISTS (SELECT 'x'
6468 FROM {course} c
6469 WHERE c.id = {context}.instanceid AND c.category = 0)
6470 $emptyclause";
6471 $DB->execute($sql);
6473 // standard courses
6474 $sql = "INSERT INTO {context_temp} (id, path, depth)
6475 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6476 FROM {context} ctx
6477 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6478 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6479 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6480 $ctxemptyclause";
6481 $trans = $DB->start_delegated_transaction();
6482 $DB->delete_records('context_temp');
6483 $DB->execute($sql);
6484 context::merge_context_temp_table();
6485 $DB->delete_records('context_temp');
6486 $trans->allow_commit();
6493 * Course module context class
6495 * @package core_access
6496 * @category access
6497 * @copyright Petr Skoda {@link http://skodak.org}
6498 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6499 * @since 2.2
6501 class context_module extends context {
6503 * Please use context_module::instance($cmid) if you need the instance of context.
6504 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6506 * @param stdClass $record
6508 protected function __construct(stdClass $record) {
6509 parent::__construct($record);
6510 if ($record->contextlevel != CONTEXT_MODULE) {
6511 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6516 * Returns human readable context level name.
6518 * @static
6519 * @return string the human readable context level name.
6521 public static function get_level_name() {
6522 return get_string('activitymodule');
6526 * Returns human readable context identifier.
6528 * @param boolean $withprefix whether to prefix the name of the context with the
6529 * module name, e.g. Forum, Glossary, etc.
6530 * @param boolean $short does not apply to module context
6531 * @return string the human readable context name.
6533 public function get_context_name($withprefix = true, $short = false) {
6534 global $DB;
6536 $name = '';
6537 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6538 FROM {course_modules} cm
6539 JOIN {modules} md ON md.id = cm.module
6540 WHERE cm.id = ?", array($this->_instanceid))) {
6541 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6542 if ($withprefix){
6543 $name = get_string('modulename', $cm->modname).': ';
6545 $name .= format_string($mod->name, true, array('context' => $this));
6548 return $name;
6552 * Returns the most relevant URL for this context.
6554 * @return moodle_url
6556 public function get_url() {
6557 global $DB;
6559 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6560 FROM {course_modules} cm
6561 JOIN {modules} md ON md.id = cm.module
6562 WHERE cm.id = ?", array($this->_instanceid))) {
6563 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6566 return new moodle_url('/');
6570 * Returns array of relevant context capability records.
6572 * @return array
6574 public function get_capabilities() {
6575 global $DB, $CFG;
6577 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6579 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6580 $module = $DB->get_record('modules', array('id'=>$cm->module));
6582 $subcaps = array();
6583 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6584 if (file_exists($subpluginsfile)) {
6585 $subplugins = array(); // should be redefined in the file
6586 include($subpluginsfile);
6587 if (!empty($subplugins)) {
6588 foreach (array_keys($subplugins) as $subplugintype) {
6589 foreach (array_keys(get_plugin_list($subplugintype)) as $subpluginname) {
6590 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6596 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6597 $extracaps = array();
6598 if (file_exists($modfile)) {
6599 include_once($modfile);
6600 $modfunction = $module->name.'_get_extra_capabilities';
6601 if (function_exists($modfunction)) {
6602 $extracaps = $modfunction();
6606 $extracaps = array_merge($subcaps, $extracaps);
6607 $extra = '';
6608 list($extra, $params) = $DB->get_in_or_equal(
6609 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
6610 if (!empty($extra)) {
6611 $extra = "OR name $extra";
6613 $sql = "SELECT *
6614 FROM {capabilities}
6615 WHERE (contextlevel = ".CONTEXT_MODULE."
6616 AND (component = :component OR component = 'moodle'))
6617 $extra";
6618 $params['component'] = "mod_$module->name";
6620 return $DB->get_records_sql($sql.' '.$sort, $params);
6624 * Is this context part of any course? If yes return course context.
6626 * @param bool $strict true means throw exception if not found, false means return false if not found
6627 * @return course_context context of the enclosing course, null if not found or exception
6629 public function get_course_context($strict = true) {
6630 return $this->get_parent_context();
6634 * Returns module context instance.
6636 * @static
6637 * @param int $instanceid
6638 * @param int $strictness
6639 * @return context_module context instance
6641 public static function instance($instanceid, $strictness = MUST_EXIST) {
6642 global $DB;
6644 if ($context = context::cache_get(CONTEXT_MODULE, $instanceid)) {
6645 return $context;
6648 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$instanceid))) {
6649 if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), 'id,course', $strictness)) {
6650 $parentcontext = context_course::instance($cm->course);
6651 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
6655 if ($record) {
6656 $context = new context_module($record);
6657 context::cache_add($context);
6658 return $context;
6661 return false;
6665 * Create missing context instances at module context level
6666 * @static
6668 protected static function create_level_instances() {
6669 global $DB;
6671 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6672 SELECT ".CONTEXT_MODULE.", cm.id
6673 FROM {course_modules} cm
6674 WHERE NOT EXISTS (SELECT 'x'
6675 FROM {context} cx
6676 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
6677 $DB->execute($sql);
6681 * Returns sql necessary for purging of stale context instances.
6683 * @static
6684 * @return string cleanup SQL
6686 protected static function get_cleanup_sql() {
6687 $sql = "
6688 SELECT c.*
6689 FROM {context} c
6690 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6691 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
6694 return $sql;
6698 * Rebuild context paths and depths at module context level.
6700 * @static
6701 * @param bool $force
6703 protected static function build_paths($force) {
6704 global $DB;
6706 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
6707 if ($force) {
6708 $ctxemptyclause = '';
6709 } else {
6710 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6713 $sql = "INSERT INTO {context_temp} (id, path, depth)
6714 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6715 FROM {context} ctx
6716 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
6717 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
6718 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6719 $ctxemptyclause";
6720 $trans = $DB->start_delegated_transaction();
6721 $DB->delete_records('context_temp');
6722 $DB->execute($sql);
6723 context::merge_context_temp_table();
6724 $DB->delete_records('context_temp');
6725 $trans->allow_commit();
6732 * Block context class
6734 * @package core_access
6735 * @category access
6736 * @copyright Petr Skoda {@link http://skodak.org}
6737 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6738 * @since 2.2
6740 class context_block extends context {
6742 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6743 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6745 * @param stdClass $record
6747 protected function __construct(stdClass $record) {
6748 parent::__construct($record);
6749 if ($record->contextlevel != CONTEXT_BLOCK) {
6750 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6755 * Returns human readable context level name.
6757 * @static
6758 * @return string the human readable context level name.
6760 public static function get_level_name() {
6761 return get_string('block');
6765 * Returns human readable context identifier.
6767 * @param boolean $withprefix whether to prefix the name of the context with Block
6768 * @param boolean $short does not apply to block context
6769 * @return string the human readable context name.
6771 public function get_context_name($withprefix = true, $short = false) {
6772 global $DB, $CFG;
6774 $name = '';
6775 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
6776 global $CFG;
6777 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
6778 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
6779 $blockname = "block_$blockinstance->blockname";
6780 if ($blockobject = new $blockname()) {
6781 if ($withprefix){
6782 $name = get_string('block').': ';
6784 $name .= $blockobject->title;
6788 return $name;
6792 * Returns the most relevant URL for this context.
6794 * @return moodle_url
6796 public function get_url() {
6797 $parentcontexts = $this->get_parent_context();
6798 return $parentcontexts->get_url();
6802 * Returns array of relevant context capability records.
6804 * @return array
6806 public function get_capabilities() {
6807 global $DB;
6809 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6811 $params = array();
6812 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
6814 $extra = '';
6815 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
6816 if ($extracaps) {
6817 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6818 $extra = "OR name $extra";
6821 $sql = "SELECT *
6822 FROM {capabilities}
6823 WHERE (contextlevel = ".CONTEXT_BLOCK."
6824 AND component = :component)
6825 $extra";
6826 $params['component'] = 'block_' . $bi->blockname;
6828 return $DB->get_records_sql($sql.' '.$sort, $params);
6832 * Is this context part of any course? If yes return course context.
6834 * @param bool $strict true means throw exception if not found, false means return false if not found
6835 * @return course_context context of the enclosing course, null if not found or exception
6837 public function get_course_context($strict = true) {
6838 $parentcontext = $this->get_parent_context();
6839 return $parentcontext->get_course_context($strict);
6843 * Returns block context instance.
6845 * @static
6846 * @param int $instanceid
6847 * @param int $strictness
6848 * @return context_block context instance
6850 public static function instance($instanceid, $strictness = MUST_EXIST) {
6851 global $DB;
6853 if ($context = context::cache_get(CONTEXT_BLOCK, $instanceid)) {
6854 return $context;
6857 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$instanceid))) {
6858 if ($bi = $DB->get_record('block_instances', array('id'=>$instanceid), 'id,parentcontextid', $strictness)) {
6859 $parentcontext = context::instance_by_id($bi->parentcontextid);
6860 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
6864 if ($record) {
6865 $context = new context_block($record);
6866 context::cache_add($context);
6867 return $context;
6870 return false;
6874 * Block do not have child contexts...
6875 * @return array
6877 public function get_child_contexts() {
6878 return array();
6882 * Create missing context instances at block context level
6883 * @static
6885 protected static function create_level_instances() {
6886 global $DB;
6888 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6889 SELECT ".CONTEXT_BLOCK.", bi.id
6890 FROM {block_instances} bi
6891 WHERE NOT EXISTS (SELECT 'x'
6892 FROM {context} cx
6893 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
6894 $DB->execute($sql);
6898 * Returns sql necessary for purging of stale context instances.
6900 * @static
6901 * @return string cleanup SQL
6903 protected static function get_cleanup_sql() {
6904 $sql = "
6905 SELECT c.*
6906 FROM {context} c
6907 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
6908 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
6911 return $sql;
6915 * Rebuild context paths and depths at block context level.
6917 * @static
6918 * @param bool $force
6920 protected static function build_paths($force) {
6921 global $DB;
6923 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
6924 if ($force) {
6925 $ctxemptyclause = '';
6926 } else {
6927 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6930 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
6931 $sql = "INSERT INTO {context_temp} (id, path, depth)
6932 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6933 FROM {context} ctx
6934 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
6935 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
6936 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
6937 $ctxemptyclause";
6938 $trans = $DB->start_delegated_transaction();
6939 $DB->delete_records('context_temp');
6940 $DB->execute($sql);
6941 context::merge_context_temp_table();
6942 $DB->delete_records('context_temp');
6943 $trans->allow_commit();
6949 // ============== DEPRECATED FUNCTIONS ==========================================
6950 // Old context related functions were deprecated in 2.0, it is recommended
6951 // to use context classes in new code. Old function can be used when
6952 // creating patches that are supposed to be backported to older stable branches.
6953 // These deprecated functions will not be removed in near future,
6954 // before removing devs will be warned with a debugging message first,
6955 // then we will add error message and only after that we can remove the functions
6956 // completely.
6960 * Not available any more, use load_temp_course_role() instead.
6962 * @deprecated since 2.2
6963 * @param stdClass $context
6964 * @param int $roleid
6965 * @param array $accessdata
6966 * @return array
6968 function load_temp_role($context, $roleid, array $accessdata) {
6969 debugging('load_temp_role() is deprecated, please use load_temp_course_role() instead, temp role not loaded.');
6970 return $accessdata;
6974 * Not available any more, use remove_temp_course_roles() instead.
6976 * @deprecated since 2.2
6977 * @param stdClass $context
6978 * @param array $accessdata
6979 * @return array access data
6981 function remove_temp_roles($context, array $accessdata) {
6982 debugging('remove_temp_role() is deprecated, please use remove_temp_course_roles() instead.');
6983 return $accessdata;
6987 * Returns system context or null if can not be created yet.
6989 * @deprecated since 2.2, use context_system::instance()
6990 * @param bool $cache use caching
6991 * @return context system context (null if context table not created yet)
6993 function get_system_context($cache = true) {
6994 return context_system::instance(0, IGNORE_MISSING, $cache);
6998 * Get the context instance as an object. This function will create the
6999 * context instance if it does not exist yet.
7001 * @deprecated since 2.2, use context_course::instance() or other relevant class instead
7002 * @param integer $contextlevel The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
7003 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
7004 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
7005 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
7006 * MUST_EXIST means throw exception if no record or multiple records found
7007 * @return context The context object.
7009 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
7010 $instances = (array)$instance;
7011 $contexts = array();
7013 $classname = context_helper::get_class_for_level($contextlevel);
7015 // we do not load multiple contexts any more, PAGE should be responsible for any preloading
7016 foreach ($instances as $inst) {
7017 $contexts[$inst] = $classname::instance($inst, $strictness);
7020 if (is_array($instance)) {
7021 return $contexts;
7022 } else {
7023 return $contexts[$instance];
7028 * Get a context instance as an object, from a given context id.
7030 * @deprecated since 2.2, use context::instance_by_id($id) instead
7031 * @param int $id context id
7032 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
7033 * MUST_EXIST means throw exception if no record or multiple records found
7034 * @return context|bool the context object or false if not found.
7036 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
7037 return context::instance_by_id($id, $strictness);
7041 * Recursive function which, given a context, find all parent context ids,
7042 * and return the array in reverse order, i.e. parent first, then grand
7043 * parent, etc.
7045 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
7046 * @param context $context
7047 * @param bool $includeself optional, defaults to false
7048 * @return array
7050 function get_parent_contexts(context $context, $includeself = false) {
7051 return $context->get_parent_context_ids($includeself);
7055 * Return the id of the parent of this context, or false if there is no parent (only happens if this
7056 * is the site context.)
7058 * @deprecated since 2.2, use $context->get_parent_context() instead
7059 * @param context $context
7060 * @return integer the id of the parent context.
7062 function get_parent_contextid(context $context) {
7063 if ($parent = $context->get_parent_context()) {
7064 return $parent->id;
7065 } else {
7066 return false;
7071 * Recursive function which, given a context, find all its children context ids.
7073 * For course category contexts it will return immediate children only categories and courses.
7074 * It will NOT recurse into courses or child categories.
7075 * If you want to do that, call it on the returned courses/categories.
7077 * When called for a course context, it will return the modules and blocks
7078 * displayed in the course page.
7080 * If called on a user/course/module context it _will_ populate the cache with the appropriate
7081 * contexts ;-)
7083 * @deprecated since 2.2, use $context->get_child_contexts() instead
7084 * @param context $context
7085 * @return array Array of child records
7087 function get_child_contexts(context $context) {
7088 return $context->get_child_contexts();
7092 * Precreates all contexts including all parents
7094 * @deprecated since 2.2
7095 * @param int $contextlevel empty means all
7096 * @param bool $buildpaths update paths and depths
7097 * @return void
7099 function create_contexts($contextlevel = null, $buildpaths = true) {
7100 context_helper::create_instances($contextlevel, $buildpaths);
7104 * Remove stale context records
7106 * @deprecated since 2.2, use context_helper::cleanup_instances() instead
7107 * @return bool
7109 function cleanup_contexts() {
7110 context_helper::cleanup_instances();
7111 return true;
7115 * Populate context.path and context.depth where missing.
7117 * @deprecated since 2.2, use context_helper::build_all_paths() instead
7118 * @param bool $force force a complete rebuild of the path and depth fields, defaults to false
7119 * @return void
7121 function build_context_path($force = false) {
7122 context_helper::build_all_paths($force);
7126 * Rebuild all related context depth and path caches
7128 * @deprecated since 2.2
7129 * @param array $fixcontexts array of contexts, strongtyped
7130 * @return void
7132 function rebuild_contexts(array $fixcontexts) {
7133 foreach ($fixcontexts as $fixcontext) {
7134 $fixcontext->reset_paths(false);
7136 context_helper::build_all_paths(false);
7140 * Preloads all contexts relating to a course: course, modules. Block contexts
7141 * are no longer loaded here. The contexts for all the blocks on the current
7142 * page are now efficiently loaded by {@link block_manager::load_blocks()}.
7144 * @deprecated since 2.2
7145 * @param int $courseid Course ID
7146 * @return void
7148 function preload_course_contexts($courseid) {
7149 context_helper::preload_course($courseid);
7153 * Preloads context information together with instances.
7154 * Use context_instance_preload() to strip the context info from the record and cache the context instance.
7156 * @deprecated since 2.2
7157 * @param string $joinon for example 'u.id'
7158 * @param string $contextlevel context level of instance in $joinon
7159 * @param string $tablealias context table alias
7160 * @return array with two values - select and join part
7162 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
7163 $select = ", ".context_helper::get_preload_record_columns_sql($tablealias);
7164 $join = "LEFT JOIN {context} $tablealias ON ($tablealias.instanceid = $joinon AND $tablealias.contextlevel = $contextlevel)";
7165 return array($select, $join);
7169 * Preloads context information from db record and strips the cached info.
7170 * The db request has to contain both the $join and $select from context_instance_preload_sql()
7172 * @deprecated since 2.2
7173 * @param stdClass $rec
7174 * @return void (modifies $rec)
7176 function context_instance_preload(stdClass $rec) {
7177 context_helper::preload_from_record($rec);
7181 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
7183 * @deprecated since 2.2, use $context->mark_dirty() instead
7184 * @param string $path context path
7186 function mark_context_dirty($path) {
7187 global $CFG, $USER, $ACCESSLIB_PRIVATE;
7189 if (during_initial_install()) {
7190 return;
7193 // only if it is a non-empty string
7194 if (is_string($path) && $path !== '') {
7195 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+$CFG->sessiontimeout);
7196 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
7197 $ACCESSLIB_PRIVATE->dirtycontexts[$path] = 1;
7198 } else {
7199 if (CLI_SCRIPT) {
7200 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
7201 } else {
7202 if (isset($USER->access['time'])) {
7203 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
7204 } else {
7205 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
7207 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
7214 * Update the path field of the context and all dep. subcontexts that follow
7216 * Update the path field of the context and
7217 * all the dependent subcontexts that follow
7218 * the move.
7220 * The most important thing here is to be as
7221 * DB efficient as possible. This op can have a
7222 * massive impact in the DB.
7224 * @deprecated since 2.2
7225 * @param context $context context obj
7226 * @param context $newparent new parent obj
7227 * @return void
7229 function context_moved(context $context, context $newparent) {
7230 $context->update_moved($newparent);
7234 * Remove a context record and any dependent entries,
7235 * removes context from static context cache too
7237 * @deprecated since 2.2, use $context->delete_content() instead
7238 * @param int $contextlevel
7239 * @param int $instanceid
7240 * @param bool $deleterecord false means keep record for now
7241 * @return bool returns true or throws an exception
7243 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
7244 if ($deleterecord) {
7245 context_helper::delete_instance($contextlevel, $instanceid);
7246 } else {
7247 $classname = context_helper::get_class_for_level($contextlevel);
7248 if ($context = $classname::instance($instanceid, IGNORE_MISSING)) {
7249 $context->delete_content();
7253 return true;
7257 * Returns context level name
7259 * @deprecated since 2.2
7260 * @param integer $contextlevel $context->context level. One of the CONTEXT_... constants.
7261 * @return string the name for this type of context.
7263 function get_contextlevel_name($contextlevel) {
7264 return context_helper::get_level_name($contextlevel);
7268 * Prints human readable context identifier.
7270 * @deprecated since 2.2
7271 * @param context $context the context.
7272 * @param boolean $withprefix whether to prefix the name of the context with the
7273 * type of context, e.g. User, Course, Forum, etc.
7274 * @param boolean $short whether to user the short name of the thing. Only applies
7275 * to course contexts
7276 * @return string the human readable context name.
7278 function print_context_name(context $context, $withprefix = true, $short = false) {
7279 return $context->get_context_name($withprefix, $short);
7283 * Get a URL for a context, if there is a natural one. For example, for
7284 * CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
7285 * user profile page.
7287 * @deprecated since 2.2
7288 * @param context $context the context.
7289 * @return moodle_url
7291 function get_context_url(context $context) {
7292 return $context->get_url();
7296 * Is this context part of any course? if yes return course context,
7297 * if not return null or throw exception.
7299 * @deprecated since 2.2, use $context->get_course_context() instead
7300 * @param context $context
7301 * @return course_context context of the enclosing course, null if not found or exception
7303 function get_course_context(context $context) {
7304 return $context->get_course_context(true);
7308 * Returns current course id or null if outside of course based on context parameter.
7310 * @deprecated since 2.2, use $context->get_course_context instead
7311 * @param context $context
7312 * @return int|bool related course id or false
7314 function get_courseid_from_context(context $context) {
7315 if ($coursecontext = $context->get_course_context(false)) {
7316 return $coursecontext->instanceid;
7317 } else {
7318 return false;
7323 * Get an array of courses where cap requested is available
7324 * and user is enrolled, this can be relatively slow.
7326 * @deprecated since 2.2, use enrol_get_users_courses() instead
7327 * @param int $userid A user id. By default (null) checks the permissions of the current user.
7328 * @param string $cap - name of the capability
7329 * @param array $accessdata_ignored
7330 * @param bool $doanything_ignored
7331 * @param string $sort - sorting fields - prefix each fieldname with "c."
7332 * @param array $fields - additional fields you are interested in...
7333 * @param int $limit_ignored
7334 * @return array $courses - ordered array of course objects - see notes above
7336 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
7338 $courses = enrol_get_users_courses($userid, true, $fields, $sort);
7339 foreach ($courses as $id=>$course) {
7340 $context = context_course::instance($id);
7341 if (!has_capability($cap, $context, $userid)) {
7342 unset($courses[$id]);
7346 return $courses;
7350 * Extracts the relevant capabilities given a contextid.
7351 * All case based, example an instance of forum context.
7352 * Will fetch all forum related capabilities, while course contexts
7353 * Will fetch all capabilities
7355 * capabilities
7356 * `name` varchar(150) NOT NULL,
7357 * `captype` varchar(50) NOT NULL,
7358 * `contextlevel` int(10) NOT NULL,
7359 * `component` varchar(100) NOT NULL,
7361 * @deprecated since 2.2
7362 * @param context $context
7363 * @return array
7365 function fetch_context_capabilities(context $context) {
7366 return $context->get_capabilities();
7370 * Runs get_records select on context table and returns the result
7371 * Does get_records_select on the context table, and returns the results ordered
7372 * by contextlevel, and then the natural sort order within each level.
7373 * for the purpose of $select, you need to know that the context table has been
7374 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7376 * @deprecated since 2.2
7377 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7378 * @param array $params any parameters required by $select.
7379 * @return array the requested context records.
7381 function get_sorted_contexts($select, $params = array()) {
7383 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7385 global $DB;
7386 if ($select) {
7387 $select = 'WHERE ' . $select;
7389 return $DB->get_records_sql("
7390 SELECT ctx.*
7391 FROM {context} ctx
7392 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7393 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7394 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7395 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7396 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7397 $select
7398 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7399 ", $params);
7403 * This is really slow!!! do not use above course context level
7405 * @deprecated since 2.2
7406 * @param int $roleid
7407 * @param context $context
7408 * @return array
7410 function get_role_context_caps($roleid, context $context) {
7411 global $DB;
7413 //this is really slow!!!! - do not use above course context level!
7414 $result = array();
7415 $result[$context->id] = array();
7417 // first emulate the parent context capabilities merging into context
7418 $searchcontexts = array_reverse($context->get_parent_context_ids(true));
7419 foreach ($searchcontexts as $cid) {
7420 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7421 foreach ($capabilities as $cap) {
7422 if (!array_key_exists($cap->capability, $result[$context->id])) {
7423 $result[$context->id][$cap->capability] = 0;
7425 $result[$context->id][$cap->capability] += $cap->permission;
7430 // now go through the contexts below given context
7431 $searchcontexts = array_keys($context->get_child_contexts());
7432 foreach ($searchcontexts as $cid) {
7433 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7434 foreach ($capabilities as $cap) {
7435 if (!array_key_exists($cap->contextid, $result)) {
7436 $result[$cap->contextid] = array();
7438 $result[$cap->contextid][$cap->capability] = $cap->permission;
7443 return $result;
7447 * Gets a string for sql calls, searching for stuff in this context or above
7449 * NOTE: use $DB->get_in_or_equal($context->get_parent_context_ids()...
7451 * @deprecated since 2.2, $context->use get_parent_context_ids() instead
7452 * @param context $context
7453 * @return string
7455 function get_related_contexts_string(context $context) {
7457 if ($parents = $context->get_parent_context_ids()) {
7458 return (' IN ('.$context->id.','.implode(',', $parents).')');
7459 } else {
7460 return (' ='.$context->id);