Merge branch 'MDL-23219_22' of git://github.com/timhunt/moodle into MOODLE_22_STABLE
[moodle.git] / lib / accesslib.php
bloba6d4828cb8fbdeab5d15142ce2a74eeed55d5ecd
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_siteadmin()
38 * What courses has this user access to?
39 * - get_enrolled_users()
41 * What users can do X in this context?
42 * - get_users_by_capability()
44 * Modify roles
45 * - role_assign()
46 * - role_unassign()
47 * - role_unassign_all()
50 * Advanced - for internal use only
51 * - load_all_capabilities()
52 * - reload_all_capabilities()
53 * - has_capability_in_accessdata()
54 * - get_user_access_sitewide()
55 * - load_course_context()
56 * - load_role_access_by_context()
57 * - etc.
59 * <b>Name conventions</b>
61 * "ctx" means context
63 * <b>accessdata</b>
65 * Access control data is held in the "accessdata" array
66 * which - for the logged-in user, will be in $USER->access
68 * For other users can be generated and passed around (but may also be cached
69 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser).
71 * $accessdata is a multidimensional array, holding
72 * role assignments (RAs), role-capabilities-perm sets
73 * (role defs) and a list of courses we have loaded
74 * data for.
76 * Things are keyed on "contextpaths" (the path field of
77 * the context table) for fast walking up/down the tree.
78 * <code>
79 * $accessdata['ra'][$contextpath] = array($roleid=>$roleid)
80 * [$contextpath] = array($roleid=>$roleid)
81 * [$contextpath] = array($roleid=>$roleid)
82 * </code>
84 * Role definitions are stored like this
85 * (no cap merge is done - so it's compact)
87 * <code>
88 * $accessdata['rdef']["$contextpath:$roleid"]['mod/forum:viewpost'] = 1
89 * ['mod/forum:editallpost'] = -1
90 * ['mod/forum:startdiscussion'] = -1000
91 * </code>
93 * See how has_capability_in_accessdata() walks up the tree.
95 * First we only load rdef and ra down to the course level, but not below.
96 * This keeps accessdata small and compact. Below-the-course ra/rdef
97 * are loaded as needed. We keep track of which courses we have loaded ra/rdef in
98 * <code>
99 * $accessdata['loaded'] = array($courseid1=>1, $courseid2=>1)
100 * </code>
102 * <b>Stale accessdata</b>
104 * For the logged-in user, accessdata is long-lived.
106 * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
107 * context paths affected by changes. Any check at-or-below
108 * a dirty context will trigger a transparent reload of accessdata.
110 * Changes at the system level will force the reload for everyone.
112 * <b>Default role caps</b>
113 * The default role assignment is not in the DB, so we
114 * add it manually to accessdata.
116 * This means that functions that work directly off the
117 * DB need to ensure that the default role caps
118 * are dealt with appropriately.
120 * @package core
121 * @subpackage role
122 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
123 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
126 defined('MOODLE_INTERNAL') || die();
128 /** No capability change */
129 define('CAP_INHERIT', 0);
130 /** Allow permission, overrides CAP_PREVENT defined in parent contexts */
131 define('CAP_ALLOW', 1);
132 /** Prevent permission, overrides CAP_ALLOW defined in parent contexts */
133 define('CAP_PREVENT', -1);
134 /** Prohibit permission, overrides everything in current and child contexts */
135 define('CAP_PROHIBIT', -1000);
137 /** System context level - only one instance in every system */
138 define('CONTEXT_SYSTEM', 10);
139 /** User context level - one instance for each user describing what others can do to user */
140 define('CONTEXT_USER', 30);
141 /** Course category context level - one instance for each category */
142 define('CONTEXT_COURSECAT', 40);
143 /** Course context level - one instances for each course */
144 define('CONTEXT_COURSE', 50);
145 /** Course module context level - one instance for each course module */
146 define('CONTEXT_MODULE', 70);
148 * Block context level - one instance for each block, sticky blocks are tricky
149 * because ppl think they should be able to override them at lower contexts.
150 * Any other context level instance can be parent of block context.
152 define('CONTEXT_BLOCK', 80);
154 /** Capability allow management of trusts - NOT IMPLEMENTED YET - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
155 define('RISK_MANAGETRUST', 0x0001);
156 /** Capability allows changes in system configuration - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
157 define('RISK_CONFIG', 0x0002);
158 /** Capability allows user to add scritped content - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
159 define('RISK_XSS', 0x0004);
160 /** Capability allows access to personal user information - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
161 define('RISK_PERSONAL', 0x0008);
162 /** Capability allows users to add content otehrs may see - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
163 define('RISK_SPAM', 0x0010);
164 /** capability allows mass delete of data belonging to other users - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
165 define('RISK_DATALOSS', 0x0020);
167 /** rolename displays - the name as defined in the role definition */
168 define('ROLENAME_ORIGINAL', 0);
169 /** rolename displays - the name as defined by a role alias */
170 define('ROLENAME_ALIAS', 1);
171 /** rolename displays - Both, like this: Role alias (Original) */
172 define('ROLENAME_BOTH', 2);
173 /** rolename displays - the name as defined in the role definition and the shortname in brackets */
174 define('ROLENAME_ORIGINALANDSHORT', 3);
175 /** rolename displays - the name as defined by a role alias, in raw form suitable for editing */
176 define('ROLENAME_ALIAS_RAW', 4);
177 /** rolename displays - the name is simply short role name */
178 define('ROLENAME_SHORT', 5);
180 /** maximum size of context cache - it is possible to tweak this config.php or in any script before inclusion of context.php */
181 if (!defined('CONTEXT_CACHE_MAX_SIZE')) {
182 define('CONTEXT_CACHE_MAX_SIZE', 2500);
186 * Although this looks like a global variable, it isn't really.
188 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
189 * It is used to cache various bits of data between function calls for performance reasons.
190 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
191 * as methods of a class, instead of functions.
193 * @private
194 * @global stdClass $ACCESSLIB_PRIVATE
195 * @name $ACCESSLIB_PRIVATE
197 global $ACCESSLIB_PRIVATE;
198 $ACCESSLIB_PRIVATE = new stdClass();
199 $ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache, loaded from DB once per page
200 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
201 $ACCESSLIB_PRIVATE->rolepermissions = array(); // role permissions cache - helps a lot with mem usage
202 $ACCESSLIB_PRIVATE->capabilities = null; // detailed information about the capabilities
205 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
207 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
208 * accesslib's private caches. You need to do this before setting up test data,
209 * and also at the end of the tests.
211 * @return void
213 function accesslib_clear_all_caches_for_unit_testing() {
214 global $UNITTEST, $USER;
215 if (empty($UNITTEST->running)) {
216 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
219 accesslib_clear_all_caches(true);
221 unset($USER->access);
225 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
227 * This reset does not touch global $USER.
229 * @private
230 * @param bool $resetcontexts
231 * @return void
233 function accesslib_clear_all_caches($resetcontexts) {
234 global $ACCESSLIB_PRIVATE;
236 $ACCESSLIB_PRIVATE->dirtycontexts = null;
237 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
238 $ACCESSLIB_PRIVATE->rolepermissions = array();
239 $ACCESSLIB_PRIVATE->capabilities = null;
241 if ($resetcontexts) {
242 context_helper::reset_caches();
247 * Gets the accessdata for role "sitewide" (system down to course)
249 * @private
250 * @param int $roleid
251 * @return array
253 function get_role_access($roleid) {
254 global $DB, $ACCESSLIB_PRIVATE;
256 /* Get it in 1 DB query...
257 * - relevant role caps at the root and down
258 * to the course level - but not below
261 //TODO: MUC - this could be cached in shared memory to speed up first page loading, web crawlers, etc.
263 $accessdata = get_empty_accessdata();
265 $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
268 // Overrides for the role IN ANY CONTEXTS
269 // down to COURSE - not below -
271 $sql = "SELECT ctx.path,
272 rc.capability, rc.permission
273 FROM {context} ctx
274 JOIN {role_capabilities} rc ON rc.contextid = ctx.id
275 LEFT JOIN {context} cctx
276 ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
277 WHERE rc.roleid = ? AND cctx.id IS NULL";
278 $params = array($roleid);
280 // we need extra caching in CLI scripts and cron
281 $rs = $DB->get_recordset_sql($sql, $params);
282 foreach ($rs as $rd) {
283 $k = "{$rd->path}:{$roleid}";
284 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
286 $rs->close();
288 // share the role definitions
289 foreach ($accessdata['rdef'] as $k=>$unused) {
290 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
291 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
293 $accessdata['rdef_count']++;
294 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
297 return $accessdata;
301 * Get the default guest role, this is used for guest account,
302 * search engine spiders, etc.
304 * @return stdClass role record
306 function get_guest_role() {
307 global $CFG, $DB;
309 if (empty($CFG->guestroleid)) {
310 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
311 $guestrole = array_shift($roles); // Pick the first one
312 set_config('guestroleid', $guestrole->id);
313 return $guestrole;
314 } else {
315 debugging('Can not find any guest role!');
316 return false;
318 } else {
319 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
320 return $guestrole;
321 } else {
322 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
323 set_config('guestroleid', '');
324 return get_guest_role();
330 * Check whether a user has a particular capability in a given context.
332 * For example:
333 * $context = get_context_instance(CONTEXT_MODULE, $cm->id);
334 * has_capability('mod/forum:replypost',$context)
336 * By default checks the capabilities of the current user, but you can pass a
337 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
339 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
340 * or capabilities with XSS, config or data loss risks.
342 * @param string $capability the name of the capability to check. For example mod/forum:view
343 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
344 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
345 * @param boolean $doanything If false, ignores effect of admin role assignment
346 * @return boolean true if the user has this capability. Otherwise false.
348 function has_capability($capability, context $context, $user = null, $doanything = true) {
349 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
351 if (during_initial_install()) {
352 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cli/install.php" or $SCRIPT === "/$CFG->admin/cli/install_database.php") {
353 // we are in an installer - roles can not work yet
354 return true;
355 } else {
356 return false;
360 if (strpos($capability, 'moodle/legacy:') === 0) {
361 throw new coding_exception('Legacy capabilities can not be used any more!');
364 if (!is_bool($doanything)) {
365 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
368 // capability must exist
369 if (!$capinfo = get_capability_info($capability)) {
370 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
371 return false;
374 if (!isset($USER->id)) {
375 // should never happen
376 $USER->id = 0;
379 // make sure there is a real user specified
380 if ($user === null) {
381 $userid = $USER->id;
382 } else {
383 $userid = is_object($user) ? $user->id : $user;
386 // make sure forcelogin cuts off not-logged-in users if enabled
387 if (!empty($CFG->forcelogin) and $userid == 0) {
388 return false;
391 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
392 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
393 if (isguestuser($userid) or $userid == 0) {
394 return false;
398 // somehow make sure the user is not deleted and actually exists
399 if ($userid != 0) {
400 if ($userid == $USER->id and isset($USER->deleted)) {
401 // this prevents one query per page, it is a bit of cheating,
402 // but hopefully session is terminated properly once user is deleted
403 if ($USER->deleted) {
404 return false;
406 } else {
407 if (!context_user::instance($userid, IGNORE_MISSING)) {
408 // no user context == invalid userid
409 return false;
414 // context path/depth must be valid
415 if (empty($context->path) or $context->depth == 0) {
416 // this should not happen often, each upgrade tries to rebuild the context paths
417 debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()');
418 if (is_siteadmin($userid)) {
419 return true;
420 } else {
421 return false;
425 // Find out if user is admin - it is not possible to override the doanything in any way
426 // and it is not possible to switch to admin role either.
427 if ($doanything) {
428 if (is_siteadmin($userid)) {
429 if ($userid != $USER->id) {
430 return true;
432 // make sure switchrole is not used in this context
433 if (empty($USER->access['rsw'])) {
434 return true;
436 $parts = explode('/', trim($context->path, '/'));
437 $path = '';
438 $switched = false;
439 foreach ($parts as $part) {
440 $path .= '/' . $part;
441 if (!empty($USER->access['rsw'][$path])) {
442 $switched = true;
443 break;
446 if (!$switched) {
447 return true;
449 //ok, admin switched role in this context, let's use normal access control rules
453 // Careful check for staleness...
454 $context->reload_if_dirty();
456 if ($USER->id == $userid) {
457 if (!isset($USER->access)) {
458 load_all_capabilities();
460 $access =& $USER->access;
462 } else {
463 // make sure user accessdata is really loaded
464 get_user_accessdata($userid, true);
465 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
469 // Load accessdata for below-the-course context if necessary,
470 // all contexts at and above all courses are already loaded
471 if ($context->contextlevel != CONTEXT_COURSE and $coursecontext = $context->get_course_context(false)) {
472 load_course_context($userid, $coursecontext, $access);
475 return has_capability_in_accessdata($capability, $context, $access);
479 * Check if the user has any one of several capabilities from a list.
481 * This is just a utility method that calls has_capability in a loop. Try to put
482 * the capabilities that most users are likely to have first in the list for best
483 * performance.
485 * @see has_capability()
486 * @param array $capabilities an array of capability names.
487 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
488 * @param integer $userid A user id. By default (null) checks the permissions of the current user.
489 * @param boolean $doanything If false, ignore effect of admin role assignment
490 * @return boolean true if the user has any of these capabilities. Otherwise false.
492 function has_any_capability(array $capabilities, context $context, $userid = null, $doanything = true) {
493 foreach ($capabilities as $capability) {
494 if (has_capability($capability, $context, $userid, $doanything)) {
495 return true;
498 return false;
502 * Check if the user has all the capabilities in a list.
504 * This is just a utility method that calls has_capability in a loop. Try to put
505 * the capabilities that fewest users are likely to have first in the list for best
506 * performance.
508 * @see has_capability()
509 * @param array $capabilities an array of capability names.
510 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
511 * @param integer $userid A user id. By default (null) checks the permissions of the current user.
512 * @param boolean $doanything If false, ignore effect of admin role assignment
513 * @return boolean true if the user has all of these capabilities. Otherwise false.
515 function has_all_capabilities(array $capabilities, context $context, $userid = null, $doanything = true) {
516 foreach ($capabilities as $capability) {
517 if (!has_capability($capability, $context, $userid, $doanything)) {
518 return false;
521 return true;
525 * Check if the user is an admin at the site level.
527 * Please note that use of proper capabilities is always encouraged,
528 * this function is supposed to be used from core or for temporary hacks.
530 * @param int|stdClass $user_or_id user id or user object
531 * @return bool true if user is one of the administrators, false otherwise
533 function is_siteadmin($user_or_id = null) {
534 global $CFG, $USER;
536 if ($user_or_id === null) {
537 $user_or_id = $USER;
540 if (empty($user_or_id)) {
541 return false;
543 if (!empty($user_or_id->id)) {
544 $userid = $user_or_id->id;
545 } else {
546 $userid = $user_or_id;
549 $siteadmins = explode(',', $CFG->siteadmins);
550 return in_array($userid, $siteadmins);
554 * Returns true if user has at least one role assign
555 * of 'coursecontact' role (is potentially listed in some course descriptions).
557 * @param int $userid
558 * @return bool
560 function has_coursecontact_role($userid) {
561 global $DB, $CFG;
563 if (empty($CFG->coursecontact)) {
564 return false;
566 $sql = "SELECT 1
567 FROM {role_assignments}
568 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
569 return $DB->record_exists_sql($sql, array('userid'=>$userid));
573 * Does the user have a capability to do something?
575 * Walk the accessdata array and return true/false.
576 * Deals with prohibits, role switching, aggregating
577 * capabilities, etc.
579 * The main feature of here is being FAST and with no
580 * side effects.
582 * Notes:
584 * Switch Role merges with default role
585 * ------------------------------------
586 * If you are a teacher in course X, you have at least
587 * teacher-in-X + defaultloggedinuser-sitewide. So in the
588 * course you'll have techer+defaultloggedinuser.
589 * We try to mimic that in switchrole.
591 * Permission evaluation
592 * ---------------------
593 * Originally there was an extremely complicated way
594 * to determine the user access that dealt with
595 * "locality" or role assignments and role overrides.
596 * Now we simply evaluate access for each role separately
597 * and then verify if user has at least one role with allow
598 * and at the same time no role with prohibit.
600 * @private
601 * @param string $capability
602 * @param context $context
603 * @param array $accessdata
604 * @return bool
606 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
607 global $CFG;
609 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
610 $path = $context->path;
611 $paths = array($path);
612 while($path = rtrim($path, '0123456789')) {
613 $path = rtrim($path, '/');
614 if ($path === '') {
615 break;
617 $paths[] = $path;
620 $roles = array();
621 $switchedrole = false;
623 // Find out if role switched
624 if (!empty($accessdata['rsw'])) {
625 // From the bottom up...
626 foreach ($paths as $path) {
627 if (isset($accessdata['rsw'][$path])) {
628 // Found a switchrole assignment - check for that role _plus_ the default user role
629 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
630 $switchedrole = true;
631 break;
636 if (!$switchedrole) {
637 // get all users roles in this context and above
638 foreach ($paths as $path) {
639 if (isset($accessdata['ra'][$path])) {
640 foreach ($accessdata['ra'][$path] as $roleid) {
641 $roles[$roleid] = null;
647 // Now find out what access is given to each role, going bottom-->up direction
648 $allowed = false;
649 foreach ($roles as $roleid => $ignored) {
650 foreach ($paths as $path) {
651 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
652 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
653 if ($perm === CAP_PROHIBIT) {
654 // any CAP_PROHIBIT found means no permission for the user
655 return false;
657 if (is_null($roles[$roleid])) {
658 $roles[$roleid] = $perm;
662 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
663 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
666 return $allowed;
670 * A convenience function that tests has_capability, and displays an error if
671 * the user does not have that capability.
673 * NOTE before Moodle 2.0, this function attempted to make an appropriate
674 * require_login call before checking the capability. This is no longer the case.
675 * You must call require_login (or one of its variants) if you want to check the
676 * user is logged in, before you call this function.
678 * @see has_capability()
680 * @param string $capability the name of the capability to check. For example mod/forum:view
681 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
682 * @param int $userid A user id. By default (null) checks the permissions of the current user.
683 * @param bool $doanything If false, ignore effect of admin role assignment
684 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
685 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
686 * @return void terminates with an error if the user does not have the given capability.
688 function require_capability($capability, context $context, $userid = null, $doanything = true,
689 $errormessage = 'nopermissions', $stringfile = '') {
690 if (!has_capability($capability, $context, $userid, $doanything)) {
691 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
696 * Return a nested array showing role assignments
697 * all relevant role capabilities for the user at
698 * site/course_category/course levels
700 * We do _not_ delve deeper than courses because the number of
701 * overrides at the module/block levels can be HUGE.
703 * [ra] => [/path][roleid]=roleid
704 * [rdef] => [/path:roleid][capability]=permission
706 * @private
707 * @param int $userid - the id of the user
708 * @return array access info array
710 function get_user_access_sitewide($userid) {
711 global $CFG, $DB, $ACCESSLIB_PRIVATE;
713 /* Get in a few cheap DB queries...
714 * - role assignments
715 * - relevant role caps
716 * - above and within this user's RAs
717 * - below this user's RAs - limited to course level
720 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
721 $raparents = array();
722 $accessdata = get_empty_accessdata();
724 // start with the default role
725 if (!empty($CFG->defaultuserroleid)) {
726 $syscontext = context_system::instance();
727 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
728 $raparents[$CFG->defaultuserroleid][$syscontext->id] = $syscontext->id;
731 // load the "default frontpage role"
732 if (!empty($CFG->defaultfrontpageroleid)) {
733 $frontpagecontext = context_course::instance(get_site()->id);
734 if ($frontpagecontext->path) {
735 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
736 $raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->id] = $frontpagecontext->id;
740 // preload every assigned role at and above course context
741 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
742 FROM {role_assignments} ra
743 JOIN {context} ctx
744 ON ctx.id = ra.contextid
745 LEFT JOIN {block_instances} bi
746 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
747 LEFT JOIN {context} bpctx
748 ON (bpctx.id = bi.parentcontextid)
749 WHERE ra.userid = :userid
750 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")";
751 $params = array('userid'=>$userid);
752 $rs = $DB->get_recordset_sql($sql, $params);
753 foreach ($rs as $ra) {
754 // RAs leafs are arrays to support multi-role assignments...
755 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
756 $raparents[$ra->roleid][$ra->contextid] = $ra->contextid;
758 $rs->close();
760 if (empty($raparents)) {
761 return $accessdata;
764 // now get overrides of interesting roles in all interesting child contexts
765 // hopefully we will not run out of SQL limits here,
766 // users would have to have very many roles at/above course context...
767 $sqls = array();
768 $params = array();
770 static $cp = 0;
771 foreach ($raparents as $roleid=>$ras) {
772 $cp++;
773 list($sqlcids, $cids) = $DB->get_in_or_equal($ras, SQL_PARAMS_NAMED, 'c'.$cp.'_');
774 $params = array_merge($params, $cids);
775 $params['r'.$cp] = $roleid;
776 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
777 FROM {role_capabilities} rc
778 JOIN {context} ctx
779 ON (ctx.id = rc.contextid)
780 JOIN {context} pctx
781 ON (pctx.id $sqlcids
782 AND (ctx.id = pctx.id
783 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
784 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
785 LEFT JOIN {block_instances} bi
786 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
787 LEFT JOIN {context} bpctx
788 ON (bpctx.id = bi.parentcontextid)
789 WHERE rc.roleid = :r{$cp}
790 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")
794 // fixed capability order is necessary for rdef dedupe
795 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
797 foreach ($rs as $rd) {
798 $k = $rd->path.':'.$rd->roleid;
799 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
801 $rs->close();
803 // share the role definitions
804 foreach ($accessdata['rdef'] as $k=>$unused) {
805 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
806 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
808 $accessdata['rdef_count']++;
809 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
812 return $accessdata;
816 * Add to the access ctrl array the data needed by a user for a given course.
818 * This function injects all course related access info into the accessdata array.
820 * @private
821 * @param int $userid the id of the user
822 * @param context_course $coursecontext course context
823 * @param array $accessdata accessdata array (modified)
824 * @return void modifies $accessdata parameter
826 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
827 global $DB, $CFG, $ACCESSLIB_PRIVATE;
829 if (empty($coursecontext->path)) {
830 // weird, this should not happen
831 return;
834 if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
835 // already loaded, great!
836 return;
839 $roles = array();
841 if (empty($userid)) {
842 if (!empty($CFG->notloggedinroleid)) {
843 $roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
846 } else if (isguestuser($userid)) {
847 if ($guestrole = get_guest_role()) {
848 $roles[$guestrole->id] = $guestrole->id;
851 } else {
852 // Interesting role assignments at, above and below the course context
853 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
854 $params['userid'] = $userid;
855 $params['children'] = $coursecontext->path."/%";
856 $sql = "SELECT ra.*, ctx.path
857 FROM {role_assignments} ra
858 JOIN {context} ctx ON ra.contextid = ctx.id
859 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
860 $rs = $DB->get_recordset_sql($sql, $params);
862 // add missing role definitions
863 foreach ($rs as $ra) {
864 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
865 $roles[$ra->roleid] = $ra->roleid;
867 $rs->close();
869 // add the "default frontpage role" when on the frontpage
870 if (!empty($CFG->defaultfrontpageroleid)) {
871 $frontpagecontext = context_course::instance(get_site()->id);
872 if ($frontpagecontext->id == $coursecontext->id) {
873 $roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
877 // do not forget the default role
878 if (!empty($CFG->defaultuserroleid)) {
879 $roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
883 if (!$roles) {
884 // weird, default roles must be missing...
885 $accessdata['loaded'][$coursecontext->instanceid] = 1;
886 return;
889 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
890 $params = array('c'=>$coursecontext->id);
891 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
892 $params = array_merge($params, $rparams);
893 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
894 $params = array_merge($params, $rparams);
896 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
897 FROM {role_capabilities} rc
898 JOIN {context} ctx
899 ON (ctx.id = rc.contextid)
900 JOIN {context} cctx
901 ON (cctx.id = :c
902 AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
903 WHERE rc.roleid $roleids
904 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
905 $rs = $DB->get_recordset_sql($sql, $params);
907 $newrdefs = array();
908 foreach ($rs as $rd) {
909 $k = $rd->path.':'.$rd->roleid;
910 if (isset($accessdata['rdef'][$k])) {
911 continue;
913 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
915 $rs->close();
917 // share new role definitions
918 foreach ($newrdefs as $k=>$unused) {
919 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
920 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
922 $accessdata['rdef_count']++;
923 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
926 $accessdata['loaded'][$coursecontext->instanceid] = 1;
928 // we want to deduplicate the USER->access from time to time, this looks like a good place,
929 // because we have to do it before the end of session
930 dedupe_user_access();
934 * Add to the access ctrl array the data needed by a role for a given context.
936 * The data is added in the rdef key.
937 * This role-centric function is useful for role_switching
938 * and temporary course roles.
940 * @private
941 * @param int $roleid the id of the user
942 * @param context $context needs path!
943 * @param array $accessdata accessdata array (is modified)
944 * @return array
946 function load_role_access_by_context($roleid, context $context, &$accessdata) {
947 global $DB, $ACCESSLIB_PRIVATE;
949 /* Get the relevant rolecaps into rdef
950 * - relevant role caps
951 * - at ctx and above
952 * - below this ctx
955 if (empty($context->path)) {
956 // weird, this should not happen
957 return;
960 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
961 $params['roleid'] = $roleid;
962 $params['childpath'] = $context->path.'/%';
964 $sql = "SELECT ctx.path, rc.capability, rc.permission
965 FROM {role_capabilities} rc
966 JOIN {context} ctx ON (rc.contextid = ctx.id)
967 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
968 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
969 $rs = $DB->get_recordset_sql($sql, $params);
971 $newrdefs = array();
972 foreach ($rs as $rd) {
973 $k = $rd->path.':'.$roleid;
974 if (isset($accessdata['rdef'][$k])) {
975 continue;
977 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
979 $rs->close();
981 // share new role definitions
982 foreach ($newrdefs as $k=>$unused) {
983 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
984 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
986 $accessdata['rdef_count']++;
987 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
992 * Returns empty accessdata structure.
994 * @private
995 * @return array empt accessdata
997 function get_empty_accessdata() {
998 $accessdata = array(); // named list
999 $accessdata['ra'] = array();
1000 $accessdata['rdef'] = array();
1001 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
1002 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
1003 $accessdata['loaded'] = array(); // loaded course contexts
1004 $accessdata['time'] = time();
1005 $accessdata['rsw'] = array();
1007 return $accessdata;
1011 * Get accessdata for a given user.
1013 * @private
1014 * @param int $userid
1015 * @param bool $preloadonly true means do not return access array
1016 * @return array accessdata
1018 function get_user_accessdata($userid, $preloadonly=false) {
1019 global $CFG, $ACCESSLIB_PRIVATE, $USER;
1021 if (!empty($USER->acces['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1022 // share rdef from USER session with rolepermissions cache in order to conserve memory
1023 foreach($USER->acces['rdef'] as $k=>$v) {
1024 $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->acces['rdef'][$k];
1026 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->acces;
1029 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
1030 if (empty($userid)) {
1031 if (!empty($CFG->notloggedinroleid)) {
1032 $accessdata = get_role_access($CFG->notloggedinroleid);
1033 } else {
1034 // weird
1035 return get_empty_accessdata();
1038 } else if (isguestuser($userid)) {
1039 if ($guestrole = get_guest_role()) {
1040 $accessdata = get_role_access($guestrole->id);
1041 } else {
1042 //weird
1043 return get_empty_accessdata();
1046 } else {
1047 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1050 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1053 if ($preloadonly) {
1054 return;
1055 } else {
1056 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1061 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1062 * this function looks for contexts with the same overrides and shares them.
1064 * @private
1065 * @return void
1067 function dedupe_user_access() {
1068 global $USER;
1070 if (CLI_SCRIPT) {
1071 // no session in CLI --> no compression necessary
1072 return;
1075 if (empty($USER->access['rdef_count'])) {
1076 // weird, this should not happen
1077 return;
1080 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1081 if ($USER->access['rdef_count'] - $USER->access['rdef_lcc'] > 10) {
1082 // do not compress after each change, wait till there is more stuff to be done
1083 return;
1086 $hashmap = array();
1087 foreach ($USER->access['rdef'] as $k=>$def) {
1088 $hash = sha1(serialize($def));
1089 if (isset($hashmap[$hash])) {
1090 $USER->access['rdef'][$k] =& $hashmap[$hash];
1091 } else {
1092 $hashmap[$hash] =& $USER->access['rdef'][$k];
1096 $USER->access['rdef_lcc'] = $USER->access['rdef_count'];
1100 * A convenience function to completely load all the capabilities
1101 * for the current user. It is called from has_capability() and functions change permissions.
1103 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1104 * @see check_enrolment_plugins()
1106 * @private
1107 * @return void
1109 function load_all_capabilities() {
1110 global $USER;
1112 // roles not installed yet - we are in the middle of installation
1113 if (during_initial_install()) {
1114 return;
1117 if (!isset($USER->id)) {
1118 // this should not happen
1119 $USER->id = 0;
1122 unset($USER->access);
1123 $USER->access = get_user_accessdata($USER->id);
1125 // deduplicate the overrides to minimize session size
1126 dedupe_user_access();
1128 // Clear to force a refresh
1129 unset($USER->mycourses);
1131 // init/reset internal enrol caches - active course enrolments and temp access
1132 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1136 * A convenience function to completely reload all the capabilities
1137 * for the current user when roles have been updated in a relevant
1138 * context -- but PRESERVING switchroles and loginas.
1139 * This function resets all accesslib and context caches.
1141 * That is - completely transparent to the user.
1143 * Note: reloads $USER->access completely.
1145 * @private
1146 * @return void
1148 function reload_all_capabilities() {
1149 global $USER, $DB, $ACCESSLIB_PRIVATE;
1151 // copy switchroles
1152 $sw = array();
1153 if (!empty($USER->access['rsw'])) {
1154 $sw = $USER->access['rsw'];
1157 accesslib_clear_all_caches(true);
1158 unset($USER->access);
1159 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
1161 load_all_capabilities();
1163 foreach ($sw as $path => $roleid) {
1164 if ($record = $DB->get_record('context', array('path'=>$path))) {
1165 $context = context::instance_by_id($record->id);
1166 role_switch($roleid, $context);
1172 * Adds a temp role to current USER->access array.
1174 * Useful for the "temporary guest" access we grant to logged-in users.
1175 * @since 2.2
1177 * @param context_course $coursecontext
1178 * @param int $roleid
1179 * @return void
1181 function load_temp_course_role(context_course $coursecontext, $roleid) {
1182 global $USER, $SITE;
1184 if (empty($roleid)) {
1185 debugging('invalid role specified in load_temp_course_role()');
1186 return;
1189 if ($coursecontext->instanceid == $SITE->id) {
1190 debugging('Can not use temp roles on the frontpage');
1191 return;
1194 if (!isset($USER->access)) {
1195 load_all_capabilities();
1198 $coursecontext->reload_if_dirty();
1200 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1201 return;
1204 // load course stuff first
1205 load_course_context($USER->id, $coursecontext, $USER->access);
1207 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1209 load_role_access_by_context($roleid, $coursecontext, $USER->access);
1213 * Removes any extra guest roles from current USER->access array.
1214 * @since 2.2
1216 * @param context_course $coursecontext
1217 * @return void
1219 function remove_temp_course_roles(context_course $coursecontext) {
1220 global $DB, $USER, $SITE;
1222 if ($coursecontext->instanceid == $SITE->id) {
1223 debugging('Can not use temp roles on the frontpage');
1224 return;
1227 if (empty($USER->access['ra'][$coursecontext->path])) {
1228 //no roles here, weird
1229 return;
1232 $sql = "SELECT DISTINCT ra.roleid AS id
1233 FROM {role_assignments} ra
1234 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1235 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1237 $USER->access['ra'][$coursecontext->path] = array();
1238 foreach($ras as $r) {
1239 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1244 * Returns array of all role archetypes.
1246 * @return array
1248 function get_role_archetypes() {
1249 return array(
1250 'manager' => 'manager',
1251 'coursecreator' => 'coursecreator',
1252 'editingteacher' => 'editingteacher',
1253 'teacher' => 'teacher',
1254 'student' => 'student',
1255 'guest' => 'guest',
1256 'user' => 'user',
1257 'frontpage' => 'frontpage'
1262 * Assign the defaults found in this capability definition to roles that have
1263 * the corresponding legacy capabilities assigned to them.
1265 * @param string $capability
1266 * @param array $legacyperms an array in the format (example):
1267 * 'guest' => CAP_PREVENT,
1268 * 'student' => CAP_ALLOW,
1269 * 'teacher' => CAP_ALLOW,
1270 * 'editingteacher' => CAP_ALLOW,
1271 * 'coursecreator' => CAP_ALLOW,
1272 * 'manager' => CAP_ALLOW
1273 * @return boolean success or failure.
1275 function assign_legacy_capabilities($capability, $legacyperms) {
1277 $archetypes = get_role_archetypes();
1279 foreach ($legacyperms as $type => $perm) {
1281 $systemcontext = context_system::instance();
1282 if ($type === 'admin') {
1283 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1284 $type = 'manager';
1287 if (!array_key_exists($type, $archetypes)) {
1288 print_error('invalidlegacy', '', '', $type);
1291 if ($roles = get_archetype_roles($type)) {
1292 foreach ($roles as $role) {
1293 // Assign a site level capability.
1294 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1295 return false;
1300 return true;
1304 * Verify capability risks.
1306 * @param object $capability a capability - a row from the capabilities table.
1307 * @return boolean whether this capability is safe - that is, whether people with the
1308 * safeoverrides capability should be allowed to change it.
1310 function is_safe_capability($capability) {
1311 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1315 * Get the local override (if any) for a given capability in a role in a context
1317 * @param int $roleid
1318 * @param int $contextid
1319 * @param string $capability
1320 * @return stdClass local capability override
1322 function get_local_override($roleid, $contextid, $capability) {
1323 global $DB;
1324 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1328 * Returns context instance plus related course and cm instances
1330 * @param int $contextid
1331 * @return array of ($context, $course, $cm)
1333 function get_context_info_array($contextid) {
1334 global $DB;
1336 $context = context::instance_by_id($contextid, MUST_EXIST);
1337 $course = null;
1338 $cm = null;
1340 if ($context->contextlevel == CONTEXT_COURSE) {
1341 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1343 } else if ($context->contextlevel == CONTEXT_MODULE) {
1344 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1345 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1347 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1348 $parent = $context->get_parent_context();
1350 if ($parent->contextlevel == CONTEXT_COURSE) {
1351 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1352 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1353 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1354 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1358 return array($context, $course, $cm);
1362 * Function that creates a role
1364 * @param string $name role name
1365 * @param string $shortname role short name
1366 * @param string $description role description
1367 * @param string $archetype
1368 * @return int id or dml_exception
1370 function create_role($name, $shortname, $description, $archetype = '') {
1371 global $DB;
1373 if (strpos($archetype, 'moodle/legacy:') !== false) {
1374 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1377 // verify role archetype actually exists
1378 $archetypes = get_role_archetypes();
1379 if (empty($archetypes[$archetype])) {
1380 $archetype = '';
1383 // Insert the role record.
1384 $role = new stdClass();
1385 $role->name = $name;
1386 $role->shortname = $shortname;
1387 $role->description = $description;
1388 $role->archetype = $archetype;
1390 //find free sortorder number
1391 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1392 if (empty($role->sortorder)) {
1393 $role->sortorder = 1;
1395 $id = $DB->insert_record('role', $role);
1397 return $id;
1401 * Function that deletes a role and cleanups up after it
1403 * @param int $roleid id of role to delete
1404 * @return bool always true
1406 function delete_role($roleid) {
1407 global $DB;
1409 // first unssign all users
1410 role_unassign_all(array('roleid'=>$roleid));
1412 // cleanup all references to this role, ignore errors
1413 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1414 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1415 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1416 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1417 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1418 $DB->delete_records('role_names', array('roleid'=>$roleid));
1419 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1421 // finally delete the role itself
1422 // get this before the name is gone for logging
1423 $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
1425 $DB->delete_records('role', array('id'=>$roleid));
1427 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
1429 return true;
1433 * Function to write context specific overrides, or default capabilities.
1435 * NOTE: use $context->mark_dirty() after this
1437 * @param string $capability string name
1438 * @param int $permission CAP_ constants
1439 * @param int $roleid role id
1440 * @param int|context $contextid context id
1441 * @param bool $overwrite
1442 * @return bool always true or exception
1444 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1445 global $USER, $DB;
1447 if ($contextid instanceof context) {
1448 $context = $contextid;
1449 } else {
1450 $context = context::instance_by_id($contextid);
1453 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1454 unassign_capability($capability, $roleid, $context->id);
1455 return true;
1458 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1460 if ($existing and !$overwrite) { // We want to keep whatever is there already
1461 return true;
1464 $cap = new stdClass();
1465 $cap->contextid = $context->id;
1466 $cap->roleid = $roleid;
1467 $cap->capability = $capability;
1468 $cap->permission = $permission;
1469 $cap->timemodified = time();
1470 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1472 if ($existing) {
1473 $cap->id = $existing->id;
1474 $DB->update_record('role_capabilities', $cap);
1475 } else {
1476 if ($DB->record_exists('context', array('id'=>$context->id))) {
1477 $DB->insert_record('role_capabilities', $cap);
1480 return true;
1484 * Unassign a capability from a role.
1486 * NOTE: use $context->mark_dirty() after this
1488 * @param string $capability the name of the capability
1489 * @param int $roleid the role id
1490 * @param int|context $contextid null means all contexts
1491 * @return boolean true or exception
1493 function unassign_capability($capability, $roleid, $contextid = null) {
1494 global $DB;
1496 if (!empty($contextid)) {
1497 if ($contextid instanceof context) {
1498 $context = $contextid;
1499 } else {
1500 $context = context::instance_by_id($contextid);
1502 // delete from context rel, if this is the last override in this context
1503 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1504 } else {
1505 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1507 return true;
1511 * Get the roles that have a given capability assigned to it
1513 * This function does not resolve the actual permission of the capability.
1514 * It just checks for permissions and overrides.
1515 * Use get_roles_with_cap_in_context() if resolution is required.
1517 * @param string $capability - capability name (string)
1518 * @param string $permission - optional, the permission defined for this capability
1519 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1520 * @param stdClass $context, null means any
1521 * @return array of role records
1523 function get_roles_with_capability($capability, $permission = null, $context = null) {
1524 global $DB;
1526 if ($context) {
1527 $contexts = $context->get_parent_context_ids(true);
1528 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1529 $contextsql = "AND rc.contextid $insql";
1530 } else {
1531 $params = array();
1532 $contextsql = '';
1535 if ($permission) {
1536 $permissionsql = " AND rc.permission = :permission";
1537 $params['permission'] = $permission;
1538 } else {
1539 $permissionsql = '';
1542 $sql = "SELECT r.*
1543 FROM {role} r
1544 WHERE r.id IN (SELECT rc.roleid
1545 FROM {role_capabilities} rc
1546 WHERE rc.capability = :capname
1547 $contextsql
1548 $permissionsql)";
1549 $params['capname'] = $capability;
1552 return $DB->get_records_sql($sql, $params);
1556 * This function makes a role-assignment (a role for a user in a particular context)
1558 * @param int $roleid the role of the id
1559 * @param int $userid userid
1560 * @param int|context $contextid id of the context
1561 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1562 * @param int $itemid id of enrolment/auth plugin
1563 * @param string $timemodified defaults to current time
1564 * @return int new/existing id of the assignment
1566 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1567 global $USER, $DB;
1569 // first of all detect if somebody is using old style parameters
1570 if ($contextid === 0 or is_numeric($component)) {
1571 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1574 // now validate all parameters
1575 if (empty($roleid)) {
1576 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1579 if (empty($userid)) {
1580 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1583 if ($itemid) {
1584 if (strpos($component, '_') === false) {
1585 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1587 } else {
1588 $itemid = 0;
1589 if ($component !== '' and strpos($component, '_') === false) {
1590 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1594 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1595 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1598 if ($contextid instanceof context) {
1599 $context = $contextid;
1600 } else {
1601 $context = context::instance_by_id($contextid, MUST_EXIST);
1604 if (!$timemodified) {
1605 $timemodified = time();
1608 // Check for existing entry
1609 // TODO: Revisit this sql_empty() use once Oracle bindings are improved. MDL-29765
1610 $component = ($component === '') ? $DB->sql_empty() : $component;
1611 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1613 if ($ras) {
1614 // role already assigned - this should not happen
1615 if (count($ras) > 1) {
1616 // very weird - remove all duplicates!
1617 $ra = array_shift($ras);
1618 foreach ($ras as $r) {
1619 $DB->delete_records('role_assignments', array('id'=>$r->id));
1621 } else {
1622 $ra = reset($ras);
1625 // actually there is no need to update, reset anything or trigger any event, so just return
1626 return $ra->id;
1629 // Create a new entry
1630 $ra = new stdClass();
1631 $ra->roleid = $roleid;
1632 $ra->contextid = $context->id;
1633 $ra->userid = $userid;
1634 $ra->component = $component;
1635 $ra->itemid = $itemid;
1636 $ra->timemodified = $timemodified;
1637 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1639 $ra->id = $DB->insert_record('role_assignments', $ra);
1641 // mark context as dirty - again expensive, but needed
1642 $context->mark_dirty();
1644 if (!empty($USER->id) && $USER->id == $userid) {
1645 // If the user is the current user, then do full reload of capabilities too.
1646 reload_all_capabilities();
1649 events_trigger('role_assigned', $ra);
1651 return $ra->id;
1655 * Removes one role assignment
1657 * @param int $roleid
1658 * @param int $userid
1659 * @param int|context $contextid
1660 * @param string $component
1661 * @param int $itemid
1662 * @return void
1664 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1665 // first make sure the params make sense
1666 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1667 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1670 if ($itemid) {
1671 if (strpos($component, '_') === false) {
1672 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1674 } else {
1675 $itemid = 0;
1676 if ($component !== '' and strpos($component, '_') === false) {
1677 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1681 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1685 * Removes multiple role assignments, parameters may contain:
1686 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1688 * @param array $params role assignment parameters
1689 * @param bool $subcontexts unassign in subcontexts too
1690 * @param bool $includemanual include manual role assignments too
1691 * @return void
1693 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1694 global $USER, $CFG, $DB;
1696 if (!$params) {
1697 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1700 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1701 foreach ($params as $key=>$value) {
1702 if (!in_array($key, $allowed)) {
1703 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1707 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1708 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1711 if ($includemanual) {
1712 if (!isset($params['component']) or $params['component'] === '') {
1713 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1717 if ($subcontexts) {
1718 if (empty($params['contextid'])) {
1719 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1723 // TODO: Revisit this sql_empty() use once Oracle bindings are improved. MDL-29765
1724 if (isset($params['component'])) {
1725 $params['component'] = ($params['component'] === '') ? $DB->sql_empty() : $params['component'];
1727 $ras = $DB->get_records('role_assignments', $params);
1728 foreach($ras as $ra) {
1729 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1730 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1731 // this is a bit expensive but necessary
1732 $context->mark_dirty();
1733 /// If the user is the current user, then do full reload of capabilities too.
1734 if (!empty($USER->id) && $USER->id == $ra->userid) {
1735 reload_all_capabilities();
1738 events_trigger('role_unassigned', $ra);
1740 unset($ras);
1742 // process subcontexts
1743 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1744 if ($params['contextid'] instanceof context) {
1745 $context = $params['contextid'];
1746 } else {
1747 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1750 if ($context) {
1751 $contexts = $context->get_child_contexts();
1752 $mparams = $params;
1753 foreach($contexts as $context) {
1754 $mparams['contextid'] = $context->id;
1755 $ras = $DB->get_records('role_assignments', $mparams);
1756 foreach($ras as $ra) {
1757 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1758 // this is a bit expensive but necessary
1759 $context->mark_dirty();
1760 /// If the user is the current user, then do full reload of capabilities too.
1761 if (!empty($USER->id) && $USER->id == $ra->userid) {
1762 reload_all_capabilities();
1764 events_trigger('role_unassigned', $ra);
1770 // do this once more for all manual role assignments
1771 if ($includemanual) {
1772 $params['component'] = '';
1773 role_unassign_all($params, $subcontexts, false);
1778 * Determines if a user is currently logged in
1780 * @return bool
1782 function isloggedin() {
1783 global $USER;
1785 return (!empty($USER->id));
1789 * Determines if a user is logged in as real guest user with username 'guest'.
1791 * @param int|object $user mixed user object or id, $USER if not specified
1792 * @return bool true if user is the real guest user, false if not logged in or other user
1794 function isguestuser($user = null) {
1795 global $USER, $DB, $CFG;
1797 // make sure we have the user id cached in config table, because we are going to use it a lot
1798 if (empty($CFG->siteguest)) {
1799 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1800 // guest does not exist yet, weird
1801 return false;
1803 set_config('siteguest', $guestid);
1805 if ($user === null) {
1806 $user = $USER;
1809 if ($user === null) {
1810 // happens when setting the $USER
1811 return false;
1813 } else if (is_numeric($user)) {
1814 return ($CFG->siteguest == $user);
1816 } else if (is_object($user)) {
1817 if (empty($user->id)) {
1818 return false; // not logged in means is not be guest
1819 } else {
1820 return ($CFG->siteguest == $user->id);
1823 } else {
1824 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1829 * Does user have a (temporary or real) guest access to course?
1831 * @param context $context
1832 * @param stdClass|int $user
1833 * @return bool
1835 function is_guest(context $context, $user = null) {
1836 global $USER;
1838 // first find the course context
1839 $coursecontext = $context->get_course_context();
1841 // make sure there is a real user specified
1842 if ($user === null) {
1843 $userid = isset($USER->id) ? $USER->id : 0;
1844 } else {
1845 $userid = is_object($user) ? $user->id : $user;
1848 if (isguestuser($userid)) {
1849 // can not inspect or be enrolled
1850 return true;
1853 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1854 // viewing users appear out of nowhere, they are neither guests nor participants
1855 return false;
1858 // consider only real active enrolments here
1859 if (is_enrolled($coursecontext, $user, '', true)) {
1860 return false;
1863 return true;
1867 * Returns true if the user has moodle/course:view capability in the course,
1868 * this is intended for admins, managers (aka small admins), inspectors, etc.
1870 * @param context $context
1871 * @param int|stdClass $user, if null $USER is used
1872 * @param string $withcapability extra capability name
1873 * @return bool
1875 function is_viewing(context $context, $user = null, $withcapability = '') {
1876 // first find the course context
1877 $coursecontext = $context->get_course_context();
1879 if (isguestuser($user)) {
1880 // can not inspect
1881 return false;
1884 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1885 // admins are allowed to inspect courses
1886 return false;
1889 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1890 // site admins always have the capability, but the enrolment above blocks
1891 return false;
1894 return true;
1898 * Returns true if user is enrolled (is participating) in course
1899 * this is intended for students and teachers.
1901 * Since 2.2 the result for active enrolments and current user are cached.
1903 * @param context $context
1904 * @param int|stdClass $user, if null $USER is used, otherwise user object or id expected
1905 * @param string $withcapability extra capability name
1906 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1907 * @return bool
1909 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1910 global $USER, $DB;
1912 // first find the course context
1913 $coursecontext = $context->get_course_context();
1915 // make sure there is a real user specified
1916 if ($user === null) {
1917 $userid = isset($USER->id) ? $USER->id : 0;
1918 } else {
1919 $userid = is_object($user) ? $user->id : $user;
1922 if (empty($userid)) {
1923 // not-logged-in!
1924 return false;
1925 } else if (isguestuser($userid)) {
1926 // guest account can not be enrolled anywhere
1927 return false;
1930 if ($coursecontext->instanceid == SITEID) {
1931 // everybody participates on frontpage
1932 } else {
1933 // try cached info first - the enrolled flag is set only when active enrolment present
1934 if ($USER->id == $userid) {
1935 $coursecontext->reload_if_dirty();
1936 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1937 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
1938 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1939 return false;
1941 return true;
1946 if ($onlyactive) {
1947 // look for active enrolments only
1948 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1950 if ($until === false) {
1951 return false;
1954 if ($USER->id == $userid) {
1955 if ($until == 0) {
1956 $until = ENROL_MAX_TIMESTAMP;
1958 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
1959 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
1960 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
1961 remove_temp_course_roles($coursecontext);
1965 } else {
1966 // any enrolment is good for us here, even outdated, disabled or inactive
1967 $sql = "SELECT 'x'
1968 FROM {user_enrolments} ue
1969 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1970 JOIN {user} u ON u.id = ue.userid
1971 WHERE ue.userid = :userid AND u.deleted = 0";
1972 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
1973 if (!$DB->record_exists_sql($sql, $params)) {
1974 return false;
1979 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1980 return false;
1983 return true;
1987 * Returns true if the user is able to access the course.
1989 * This function is in no way, shape, or form a substitute for require_login.
1990 * It should only be used in circumstances where it is not possible to call require_login
1991 * such as the navigation.
1993 * This function checks many of the methods of access to a course such as the view
1994 * capability, enrollments, and guest access. It also makes use of the cache
1995 * generated by require_login for guest access.
1997 * The flags within the $USER object that are used here should NEVER be used outside
1998 * of this function can_access_course and require_login. Doing so WILL break future
1999 * versions.
2001 * @param stdClass $course record
2002 * @param stdClass|int|null $user user record or id, current user if null
2003 * @param string $withcapability Check for this capability as well.
2004 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2005 * @return boolean Returns true if the user is able to access the course
2007 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
2008 global $DB, $USER;
2010 // this function originally accepted $coursecontext parameter
2011 if ($course instanceof context) {
2012 if ($course instanceof context_course) {
2013 debugging('deprecated context parameter, please use $course record');
2014 $coursecontext = $course;
2015 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2016 } else {
2017 debugging('Invalid context parameter, please use $course record');
2018 return false;
2020 } else {
2021 $coursecontext = context_course::instance($course->id);
2024 if (!isset($USER->id)) {
2025 // should never happen
2026 $USER->id = 0;
2029 // make sure there is a user specified
2030 if ($user === null) {
2031 $userid = $USER->id;
2032 } else {
2033 $userid = is_object($user) ? $user->id : $user;
2035 unset($user);
2037 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2038 return false;
2041 if ($userid == $USER->id) {
2042 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2043 // the fact that somebody switched role means they can access the course no matter to what role they switched
2044 return true;
2048 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2049 return false;
2052 if (is_viewing($coursecontext, $userid)) {
2053 return true;
2056 if ($userid != $USER->id) {
2057 // for performance reasons we do not verify temporary guest access for other users, sorry...
2058 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2061 // === from here we deal only with $USER ===
2063 $coursecontext->reload_if_dirty();
2065 if (isset($USER->enrol['enrolled'][$course->id])) {
2066 if ($USER->enrol['enrolled'][$course->id] > time()) {
2067 return true;
2070 if (isset($USER->enrol['tempguest'][$course->id])) {
2071 if ($USER->enrol['tempguest'][$course->id] > time()) {
2072 return true;
2076 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2077 return true;
2080 // if not enrolled try to gain temporary guest access
2081 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2082 $enrols = enrol_get_plugins(true);
2083 foreach($instances as $instance) {
2084 if (!isset($enrols[$instance->enrol])) {
2085 continue;
2087 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2088 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2089 if ($until !== false and $until > time()) {
2090 $USER->enrol['tempguest'][$course->id] = $until;
2091 return true;
2094 if (isset($USER->enrol['tempguest'][$course->id])) {
2095 unset($USER->enrol['tempguest'][$course->id]);
2096 remove_temp_course_roles($coursecontext);
2099 return false;
2103 * Returns array with sql code and parameters returning all ids
2104 * of users enrolled into course.
2106 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2108 * @param context $context
2109 * @param string $withcapability
2110 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2111 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2112 * @return array list($sql, $params)
2114 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2115 global $DB, $CFG;
2117 // use unique prefix just in case somebody makes some SQL magic with the result
2118 static $i = 0;
2119 $i++;
2120 $prefix = 'eu'.$i.'_';
2122 // first find the course context
2123 $coursecontext = $context->get_course_context();
2125 $isfrontpage = ($coursecontext->instanceid == SITEID);
2127 $joins = array();
2128 $wheres = array();
2129 $params = array();
2131 list($contextids, $contextpaths) = get_context_info_list($context);
2133 // get all relevant capability info for all roles
2134 if ($withcapability) {
2135 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2136 $cparams['cap'] = $withcapability;
2138 $defs = array();
2139 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2140 FROM {role_capabilities} rc
2141 JOIN {context} ctx on rc.contextid = ctx.id
2142 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2143 $rcs = $DB->get_records_sql($sql, $cparams);
2144 foreach ($rcs as $rc) {
2145 $defs[$rc->path][$rc->roleid] = $rc->permission;
2148 $access = array();
2149 if (!empty($defs)) {
2150 foreach ($contextpaths as $path) {
2151 if (empty($defs[$path])) {
2152 continue;
2154 foreach($defs[$path] as $roleid => $perm) {
2155 if ($perm == CAP_PROHIBIT) {
2156 $access[$roleid] = CAP_PROHIBIT;
2157 continue;
2159 if (!isset($access[$roleid])) {
2160 $access[$roleid] = (int)$perm;
2166 unset($defs);
2168 // make lists of roles that are needed and prohibited
2169 $needed = array(); // one of these is enough
2170 $prohibited = array(); // must not have any of these
2171 foreach ($access as $roleid => $perm) {
2172 if ($perm == CAP_PROHIBIT) {
2173 unset($needed[$roleid]);
2174 $prohibited[$roleid] = true;
2175 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2176 $needed[$roleid] = true;
2180 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2181 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2183 $nobody = false;
2185 if ($isfrontpage) {
2186 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2187 $nobody = true;
2188 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2189 // everybody not having prohibit has the capability
2190 $needed = array();
2191 } else if (empty($needed)) {
2192 $nobody = true;
2194 } else {
2195 if (!empty($prohibited[$defaultuserroleid])) {
2196 $nobody = true;
2197 } else if (!empty($needed[$defaultuserroleid])) {
2198 // everybody not having prohibit has the capability
2199 $needed = array();
2200 } else if (empty($needed)) {
2201 $nobody = true;
2205 if ($nobody) {
2206 // nobody can match so return some SQL that does not return any results
2207 $wheres[] = "1 = 2";
2209 } else {
2211 if ($needed) {
2212 $ctxids = implode(',', $contextids);
2213 $roleids = implode(',', array_keys($needed));
2214 $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))";
2217 if ($prohibited) {
2218 $ctxids = implode(',', $contextids);
2219 $roleids = implode(',', array_keys($prohibited));
2220 $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))";
2221 $wheres[] = "{$prefix}ra4.id IS NULL";
2224 if ($groupid) {
2225 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2226 $params["{$prefix}gmid"] = $groupid;
2230 } else {
2231 if ($groupid) {
2232 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2233 $params["{$prefix}gmid"] = $groupid;
2237 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2238 $params["{$prefix}guestid"] = $CFG->siteguest;
2240 if ($isfrontpage) {
2241 // all users are "enrolled" on the frontpage
2242 } else {
2243 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2244 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2245 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2247 if ($onlyactive) {
2248 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2249 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2250 $now = round(time(), -2); // rounding helps caching in DB
2251 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2252 $prefix.'active'=>ENROL_USER_ACTIVE,
2253 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2257 $joins = implode("\n", $joins);
2258 $wheres = "WHERE ".implode(" AND ", $wheres);
2260 $sql = "SELECT DISTINCT {$prefix}u.id
2261 FROM {user} {$prefix}u
2262 $joins
2263 $wheres";
2265 return array($sql, $params);
2269 * Returns list of users enrolled into course.
2271 * @param context $context
2272 * @param string $withcapability
2273 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2274 * @param string $userfields requested user record fields
2275 * @param string $orderby
2276 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2277 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2278 * @return array of user records
2280 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = '', $limitfrom = 0, $limitnum = 0) {
2281 global $DB;
2283 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2284 $sql = "SELECT $userfields
2285 FROM {user} u
2286 JOIN ($esql) je ON je.id = u.id
2287 WHERE u.deleted = 0";
2289 if ($orderby) {
2290 $sql = "$sql ORDER BY $orderby";
2291 } else {
2292 $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
2295 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2299 * Counts list of users enrolled into course (as per above function)
2301 * @param context $context
2302 * @param string $withcapability
2303 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2304 * @return array of user records
2306 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0) {
2307 global $DB;
2309 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2310 $sql = "SELECT count(u.id)
2311 FROM {user} u
2312 JOIN ($esql) je ON je.id = u.id
2313 WHERE u.deleted = 0";
2315 return $DB->count_records_sql($sql, $params);
2319 * Loads the capability definitions for the component (from file).
2321 * Loads the capability definitions for the component (from file). If no
2322 * capabilities are defined for the component, we simply return an empty array.
2324 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2325 * @return array array of capabilities
2327 function load_capability_def($component) {
2328 $defpath = get_component_directory($component).'/db/access.php';
2330 $capabilities = array();
2331 if (file_exists($defpath)) {
2332 require($defpath);
2333 if (!empty(${$component.'_capabilities'})) {
2334 // BC capability array name
2335 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2336 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2337 $capabilities = ${$component.'_capabilities'};
2341 return $capabilities;
2345 * Gets the capabilities that have been cached in the database for this component.
2347 * @param string $component - examples: 'moodle', 'mod_forum'
2348 * @return array array of capabilities
2350 function get_cached_capabilities($component = 'moodle') {
2351 global $DB;
2352 return $DB->get_records('capabilities', array('component'=>$component));
2356 * Returns default capabilities for given role archetype.
2358 * @param string $archetype role archetype
2359 * @return array
2361 function get_default_capabilities($archetype) {
2362 global $DB;
2364 if (!$archetype) {
2365 return array();
2368 $alldefs = array();
2369 $defaults = array();
2370 $components = array();
2371 $allcaps = $DB->get_records('capabilities');
2373 foreach ($allcaps as $cap) {
2374 if (!in_array($cap->component, $components)) {
2375 $components[] = $cap->component;
2376 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2379 foreach($alldefs as $name=>$def) {
2380 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2381 if (isset($def['archetypes'])) {
2382 if (isset($def['archetypes'][$archetype])) {
2383 $defaults[$name] = $def['archetypes'][$archetype];
2385 // 'legacy' is for backward compatibility with 1.9 access.php
2386 } else {
2387 if (isset($def['legacy'][$archetype])) {
2388 $defaults[$name] = $def['legacy'][$archetype];
2393 return $defaults;
2397 * Reset role capabilities to default according to selected role archetype.
2398 * If no archetype selected, removes all capabilities.
2400 * @param int $roleid
2401 * @return void
2403 function reset_role_capabilities($roleid) {
2404 global $DB;
2406 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2407 $defaultcaps = get_default_capabilities($role->archetype);
2409 $systemcontext = context_system::instance();
2411 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2413 foreach($defaultcaps as $cap=>$permission) {
2414 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2419 * Updates the capabilities table with the component capability definitions.
2420 * If no parameters are given, the function updates the core moodle
2421 * capabilities.
2423 * Note that the absence of the db/access.php capabilities definition file
2424 * will cause any stored capabilities for the component to be removed from
2425 * the database.
2427 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2428 * @return boolean true if success, exception in case of any problems
2430 function update_capabilities($component = 'moodle') {
2431 global $DB, $OUTPUT;
2433 $storedcaps = array();
2435 $filecaps = load_capability_def($component);
2436 foreach($filecaps as $capname=>$unused) {
2437 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2438 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2442 $cachedcaps = get_cached_capabilities($component);
2443 if ($cachedcaps) {
2444 foreach ($cachedcaps as $cachedcap) {
2445 array_push($storedcaps, $cachedcap->name);
2446 // update risk bitmasks and context levels in existing capabilities if needed
2447 if (array_key_exists($cachedcap->name, $filecaps)) {
2448 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2449 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2451 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2452 $updatecap = new stdClass();
2453 $updatecap->id = $cachedcap->id;
2454 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2455 $DB->update_record('capabilities', $updatecap);
2457 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2458 $updatecap = new stdClass();
2459 $updatecap->id = $cachedcap->id;
2460 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2461 $DB->update_record('capabilities', $updatecap);
2464 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2465 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2467 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2468 $updatecap = new stdClass();
2469 $updatecap->id = $cachedcap->id;
2470 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2471 $DB->update_record('capabilities', $updatecap);
2477 // Are there new capabilities in the file definition?
2478 $newcaps = array();
2480 foreach ($filecaps as $filecap => $def) {
2481 if (!$storedcaps ||
2482 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2483 if (!array_key_exists('riskbitmask', $def)) {
2484 $def['riskbitmask'] = 0; // no risk if not specified
2486 $newcaps[$filecap] = $def;
2489 // Add new capabilities to the stored definition.
2490 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2491 foreach ($newcaps as $capname => $capdef) {
2492 $capability = new stdClass();
2493 $capability->name = $capname;
2494 $capability->captype = $capdef['captype'];
2495 $capability->contextlevel = $capdef['contextlevel'];
2496 $capability->component = $component;
2497 $capability->riskbitmask = $capdef['riskbitmask'];
2499 $DB->insert_record('capabilities', $capability, false);
2501 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2502 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2503 foreach ($rolecapabilities as $rolecapability){
2504 //assign_capability will update rather than insert if capability exists
2505 if (!assign_capability($capname, $rolecapability->permission,
2506 $rolecapability->roleid, $rolecapability->contextid, true)){
2507 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2511 // we ignore archetype key if we have cloned permissions
2512 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2513 assign_legacy_capabilities($capname, $capdef['archetypes']);
2514 // 'legacy' is for backward compatibility with 1.9 access.php
2515 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2516 assign_legacy_capabilities($capname, $capdef['legacy']);
2519 // Are there any capabilities that have been removed from the file
2520 // definition that we need to delete from the stored capabilities and
2521 // role assignments?
2522 capabilities_cleanup($component, $filecaps);
2524 // reset static caches
2525 accesslib_clear_all_caches(false);
2527 return true;
2531 * Deletes cached capabilities that are no longer needed by the component.
2532 * Also unassigns these capabilities from any roles that have them.
2534 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2535 * @param array $newcapdef array of the new capability definitions that will be
2536 * compared with the cached capabilities
2537 * @return int number of deprecated capabilities that have been removed
2539 function capabilities_cleanup($component, $newcapdef = null) {
2540 global $DB;
2542 $removedcount = 0;
2544 if ($cachedcaps = get_cached_capabilities($component)) {
2545 foreach ($cachedcaps as $cachedcap) {
2546 if (empty($newcapdef) ||
2547 array_key_exists($cachedcap->name, $newcapdef) === false) {
2549 // Remove from capabilities cache.
2550 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2551 $removedcount++;
2552 // Delete from roles.
2553 if ($roles = get_roles_with_capability($cachedcap->name)) {
2554 foreach($roles as $role) {
2555 if (!unassign_capability($cachedcap->name, $role->id)) {
2556 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2560 } // End if.
2563 return $removedcount;
2567 * Returns an array of all the known types of risk
2568 * The array keys can be used, for example as CSS class names, or in calls to
2569 * print_risk_icon. The values are the corresponding RISK_ constants.
2571 * @return array all the known types of risk.
2573 function get_all_risks() {
2574 return array(
2575 'riskmanagetrust' => RISK_MANAGETRUST,
2576 'riskconfig' => RISK_CONFIG,
2577 'riskxss' => RISK_XSS,
2578 'riskpersonal' => RISK_PERSONAL,
2579 'riskspam' => RISK_SPAM,
2580 'riskdataloss' => RISK_DATALOSS,
2585 * Return a link to moodle docs for a given capability name
2587 * @param object $capability a capability - a row from the mdl_capabilities table.
2588 * @return string the human-readable capability name as a link to Moodle Docs.
2590 function get_capability_docs_link($capability) {
2591 $url = get_docs_url('Capabilities/' . $capability->name);
2592 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2596 * This function pulls out all the resolved capabilities (overrides and
2597 * defaults) of a role used in capability overrides in contexts at a given
2598 * context.
2600 * @param context $context
2601 * @param int $roleid
2602 * @param string $cap capability, optional, defaults to ''
2603 * @return array of capabilities
2605 function role_context_capabilities($roleid, context $context, $cap = '') {
2606 global $DB;
2608 $contexts = $context->get_parent_context_ids(true);
2609 $contexts = '('.implode(',', $contexts).')';
2611 $params = array($roleid);
2613 if ($cap) {
2614 $search = " AND rc.capability = ? ";
2615 $params[] = $cap;
2616 } else {
2617 $search = '';
2620 $sql = "SELECT rc.*
2621 FROM {role_capabilities} rc, {context} c
2622 WHERE rc.contextid in $contexts
2623 AND rc.roleid = ?
2624 AND rc.contextid = c.id $search
2625 ORDER BY c.contextlevel DESC, rc.capability DESC";
2627 $capabilities = array();
2629 if ($records = $DB->get_records_sql($sql, $params)) {
2630 // We are traversing via reverse order.
2631 foreach ($records as $record) {
2632 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2633 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2634 $capabilities[$record->capability] = $record->permission;
2638 return $capabilities;
2642 * Constructs array with contextids as first parameter and context paths,
2643 * in both cases bottom top including self.
2645 * @private
2646 * @param context $context
2647 * @return array
2649 function get_context_info_list(context $context) {
2650 $contextids = explode('/', ltrim($context->path, '/'));
2651 $contextpaths = array();
2652 $contextids2 = $contextids;
2653 while ($contextids2) {
2654 $contextpaths[] = '/' . implode('/', $contextids2);
2655 array_pop($contextids2);
2657 return array($contextids, $contextpaths);
2661 * Check if context is the front page context or a context inside it
2663 * Returns true if this context is the front page context, or a context inside it,
2664 * otherwise false.
2666 * @param context $context a context object.
2667 * @return bool
2669 function is_inside_frontpage(context $context) {
2670 $frontpagecontext = context_course::instance(SITEID);
2671 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2675 * Returns capability information (cached)
2677 * @param string $capabilityname
2678 * @return object or null if capability not found
2680 function get_capability_info($capabilityname) {
2681 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2683 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2685 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2686 $ACCESSLIB_PRIVATE->capabilities = array();
2687 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2688 foreach ($caps as $cap) {
2689 $capname = $cap->name;
2690 unset($cap->id);
2691 unset($cap->name);
2692 $cap->riskbitmask = (int)$cap->riskbitmask;
2693 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2697 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2701 * Returns the human-readable, translated version of the capability.
2702 * Basically a big switch statement.
2704 * @param string $capabilityname e.g. mod/choice:readresponses
2705 * @return string
2707 function get_capability_string($capabilityname) {
2709 // Typical capability name is 'plugintype/pluginname:capabilityname'
2710 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2712 if ($type === 'moodle') {
2713 $component = 'core_role';
2714 } else if ($type === 'quizreport') {
2715 //ugly hack!!
2716 $component = 'quiz_'.$name;
2717 } else {
2718 $component = $type.'_'.$name;
2721 $stringname = $name.':'.$capname;
2723 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2724 return get_string($stringname, $component);
2727 $dir = get_component_directory($component);
2728 if (!file_exists($dir)) {
2729 // plugin broken or does not exist, do not bother with printing of debug message
2730 return $capabilityname.' ???';
2733 // something is wrong in plugin, better print debug
2734 return get_string($stringname, $component);
2738 * This gets the mod/block/course/core etc strings.
2740 * @param string $component
2741 * @param int $contextlevel
2742 * @return string|bool String is success, false if failed
2744 function get_component_string($component, $contextlevel) {
2746 if ($component === 'moodle' or $component === 'core') {
2747 switch ($contextlevel) {
2748 // TODO: this should probably use context level names instead
2749 case CONTEXT_SYSTEM: return get_string('coresystem');
2750 case CONTEXT_USER: return get_string('users');
2751 case CONTEXT_COURSECAT: return get_string('categories');
2752 case CONTEXT_COURSE: return get_string('course');
2753 case CONTEXT_MODULE: return get_string('activities');
2754 case CONTEXT_BLOCK: return get_string('block');
2755 default: print_error('unknowncontext');
2759 list($type, $name) = normalize_component($component);
2760 $dir = get_plugin_directory($type, $name);
2761 if (!file_exists($dir)) {
2762 // plugin not installed, bad luck, there is no way to find the name
2763 return $component.' ???';
2766 switch ($type) {
2767 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2768 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2769 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2770 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2771 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2772 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2773 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2774 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2775 case 'mod':
2776 if (get_string_manager()->string_exists('pluginname', $component)) {
2777 return get_string('activity').': '.get_string('pluginname', $component);
2778 } else {
2779 return get_string('activity').': '.get_string('modulename', $component);
2781 default: return get_string('pluginname', $component);
2786 * Gets the list of roles assigned to this context and up (parents)
2787 * from the list of roles that are visible on user profile page
2788 * and participants page.
2790 * @param context $context
2791 * @return array
2793 function get_profile_roles(context $context) {
2794 global $CFG, $DB;
2796 if (empty($CFG->profileroles)) {
2797 return array();
2800 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2801 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2802 $params = array_merge($params, $cparams);
2804 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2805 FROM {role_assignments} ra, {role} r
2806 WHERE r.id = ra.roleid
2807 AND ra.contextid $contextlist
2808 AND r.id $rallowed
2809 ORDER BY r.sortorder ASC";
2811 return $DB->get_records_sql($sql, $params);
2815 * Gets the list of roles assigned to this context and up (parents)
2817 * @param context $context
2818 * @return array
2820 function get_roles_used_in_context(context $context) {
2821 global $DB;
2823 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true));
2825 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2826 FROM {role_assignments} ra, {role} r
2827 WHERE r.id = ra.roleid
2828 AND ra.contextid $contextlist
2829 ORDER BY r.sortorder ASC";
2831 return $DB->get_records_sql($sql, $params);
2835 * This function is used to print roles column in user profile page.
2836 * It is using the CFG->profileroles to limit the list to only interesting roles.
2837 * (The permission tab has full details of user role assignments.)
2839 * @param int $userid
2840 * @param int $courseid
2841 * @return string
2843 function get_user_roles_in_course($userid, $courseid) {
2844 global $CFG, $DB;
2846 if (empty($CFG->profileroles)) {
2847 return '';
2850 if ($courseid == SITEID) {
2851 $context = context_system::instance();
2852 } else {
2853 $context = context_course::instance($courseid);
2856 if (empty($CFG->profileroles)) {
2857 return array();
2860 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2861 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2862 $params = array_merge($params, $cparams);
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 AND r.id $rallowed
2869 AND ra.userid = :userid
2870 ORDER BY r.sortorder ASC";
2871 $params['userid'] = $userid;
2873 $rolestring = '';
2875 if ($roles = $DB->get_records_sql($sql, $params)) {
2876 foreach ($roles as $userrole) {
2877 $rolenames[$userrole->id] = $userrole->name;
2880 $rolenames = role_fix_names($rolenames, $context); // Substitute aliases
2882 foreach ($rolenames as $roleid => $rolename) {
2883 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
2885 $rolestring = implode(',', $rolenames);
2888 return $rolestring;
2892 * Checks if a user can assign users to a particular role in this context
2894 * @param context $context
2895 * @param int $targetroleid - the id of the role you want to assign users to
2896 * @return boolean
2898 function user_can_assign(context $context, $targetroleid) {
2899 global $DB;
2901 // first check if user has override capability
2902 // if not return false;
2903 if (!has_capability('moodle/role:assign', $context)) {
2904 return false;
2906 // pull out all active roles of this user from this context(or above)
2907 if ($userroles = get_user_roles($context)) {
2908 foreach ($userroles as $userrole) {
2909 // if any in the role_allow_override table, then it's ok
2910 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2911 return true;
2916 return false;
2920 * Returns all site roles in correct sort order.
2922 * @return array
2924 function get_all_roles() {
2925 global $DB;
2926 return $DB->get_records('role', null, 'sortorder ASC');
2930 * Returns roles of a specified archetype
2932 * @param string $archetype
2933 * @return array of full role records
2935 function get_archetype_roles($archetype) {
2936 global $DB;
2937 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2941 * Gets all the user roles assigned in this context, or higher contexts
2942 * this is mainly used when checking if a user can assign a role, or overriding a role
2943 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2944 * allow_override tables
2946 * @param context $context
2947 * @param int $userid
2948 * @param bool $checkparentcontexts defaults to true
2949 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2950 * @return array
2952 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2953 global $USER, $DB;
2955 if (empty($userid)) {
2956 if (empty($USER->id)) {
2957 return array();
2959 $userid = $USER->id;
2962 if ($checkparentcontexts) {
2963 $contextids = $context->get_parent_context_ids();
2964 } else {
2965 $contextids = array();
2967 $contextids[] = $context->id;
2969 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2971 array_unshift($params, $userid);
2973 $sql = "SELECT ra.*, r.name, r.shortname
2974 FROM {role_assignments} ra, {role} r, {context} c
2975 WHERE ra.userid = ?
2976 AND ra.roleid = r.id
2977 AND ra.contextid = c.id
2978 AND ra.contextid $contextids
2979 ORDER BY $order";
2981 return $DB->get_records_sql($sql ,$params);
2985 * Like get_user_roles, but adds in the authenticated user role, and the front
2986 * page roles, if applicable.
2988 * @param context $context the context.
2989 * @param int $userid optional. Defaults to $USER->id
2990 * @return array of objects with fields ->userid, ->contextid and ->roleid.
2992 function get_user_roles_with_special(context $context, $userid = 0) {
2993 global $CFG, $USER;
2995 if (empty($userid)) {
2996 if (empty($USER->id)) {
2997 return array();
2999 $userid = $USER->id;
3002 $ras = get_user_roles($context, $userid);
3004 // Add front-page role if relevant.
3005 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3006 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3007 is_inside_frontpage($context);
3008 if ($defaultfrontpageroleid && $isfrontpage) {
3009 $frontpagecontext = context_course::instance(SITEID);
3010 $ra = new stdClass();
3011 $ra->userid = $userid;
3012 $ra->contextid = $frontpagecontext->id;
3013 $ra->roleid = $defaultfrontpageroleid;
3014 $ras[] = $ra;
3017 // Add authenticated user role if relevant.
3018 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3019 if ($defaultuserroleid && !isguestuser($userid)) {
3020 $systemcontext = context_system::instance();
3021 $ra = new stdClass();
3022 $ra->userid = $userid;
3023 $ra->contextid = $systemcontext->id;
3024 $ra->roleid = $defaultuserroleid;
3025 $ras[] = $ra;
3028 return $ras;
3032 * Creates a record in the role_allow_override table
3034 * @param int $sroleid source roleid
3035 * @param int $troleid target roleid
3036 * @return void
3038 function allow_override($sroleid, $troleid) {
3039 global $DB;
3041 $record = new stdClass();
3042 $record->roleid = $sroleid;
3043 $record->allowoverride = $troleid;
3044 $DB->insert_record('role_allow_override', $record);
3048 * Creates a record in the role_allow_assign table
3050 * @param int $fromroleid source roleid
3051 * @param int $targetroleid target roleid
3052 * @return void
3054 function allow_assign($fromroleid, $targetroleid) {
3055 global $DB;
3057 $record = new stdClass();
3058 $record->roleid = $fromroleid;
3059 $record->allowassign = $targetroleid;
3060 $DB->insert_record('role_allow_assign', $record);
3064 * Creates a record in the role_allow_switch table
3066 * @param int $fromroleid source roleid
3067 * @param int $targetroleid target roleid
3068 * @return void
3070 function allow_switch($fromroleid, $targetroleid) {
3071 global $DB;
3073 $record = new stdClass();
3074 $record->roleid = $fromroleid;
3075 $record->allowswitch = $targetroleid;
3076 $DB->insert_record('role_allow_switch', $record);
3080 * Gets a list of roles that this user can assign in this context
3082 * @param context $context the context.
3083 * @param int $rolenamedisplay the type of role name to display. One of the
3084 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3085 * @param bool $withusercounts if true, count the number of users with each role.
3086 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3087 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3088 * if $withusercounts is true, returns a list of three arrays,
3089 * $rolenames, $rolecounts, and $nameswithcounts.
3091 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3092 global $USER, $DB;
3094 // make sure there is a real user specified
3095 if ($user === null) {
3096 $userid = isset($USER->id) ? $USER->id : 0;
3097 } else {
3098 $userid = is_object($user) ? $user->id : $user;
3101 if (!has_capability('moodle/role:assign', $context, $userid)) {
3102 if ($withusercounts) {
3103 return array(array(), array(), array());
3104 } else {
3105 return array();
3109 $parents = $context->get_parent_context_ids(true);
3110 $contexts = implode(',' , $parents);
3112 $params = array();
3113 $extrafields = '';
3114 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT or $rolenamedisplay == ROLENAME_SHORT) {
3115 $extrafields .= ', r.shortname';
3118 if ($withusercounts) {
3119 $extrafields = ', (SELECT count(u.id)
3120 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3121 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3122 ) AS usercount';
3123 $params['conid'] = $context->id;
3126 if (is_siteadmin($userid)) {
3127 // show all roles allowed in this context to admins
3128 $assignrestriction = "";
3129 } else {
3130 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3131 FROM {role_allow_assign} raa
3132 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3133 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3134 ) ar ON ar.id = r.id";
3135 $params['userid'] = $userid;
3137 $params['contextlevel'] = $context->contextlevel;
3138 $sql = "SELECT r.id, r.name $extrafields
3139 FROM {role} r
3140 $assignrestriction
3141 JOIN {role_context_levels} rcl ON r.id = rcl.roleid
3142 WHERE rcl.contextlevel = :contextlevel
3143 ORDER BY r.sortorder ASC";
3144 $roles = $DB->get_records_sql($sql, $params);
3146 $rolenames = array();
3147 foreach ($roles as $role) {
3148 if ($rolenamedisplay == ROLENAME_SHORT) {
3149 $rolenames[$role->id] = $role->shortname;
3150 continue;
3152 $rolenames[$role->id] = $role->name;
3153 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3154 $rolenames[$role->id] .= ' (' . $role->shortname . ')';
3157 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT and $rolenamedisplay != ROLENAME_SHORT) {
3158 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3161 if (!$withusercounts) {
3162 return $rolenames;
3165 $rolecounts = array();
3166 $nameswithcounts = array();
3167 foreach ($roles as $role) {
3168 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3169 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3171 return array($rolenames, $rolecounts, $nameswithcounts);
3175 * Gets a list of roles that this user can switch to in a context
3177 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3178 * This function just process the contents of the role_allow_switch table. You also need to
3179 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3181 * @param context $context a context.
3182 * @return array an array $roleid => $rolename.
3184 function get_switchable_roles(context $context) {
3185 global $USER, $DB;
3187 $params = array();
3188 $extrajoins = '';
3189 $extrawhere = '';
3190 if (!is_siteadmin()) {
3191 // Admins are allowed to switch to any role with.
3192 // Others are subject to the additional constraint that the switch-to role must be allowed by
3193 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3194 $parents = $context->get_parent_context_ids(true);
3195 $contexts = implode(',' , $parents);
3197 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3198 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3199 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3200 $params['userid'] = $USER->id;
3203 $query = "
3204 SELECT r.id, r.name
3205 FROM (SELECT DISTINCT rc.roleid
3206 FROM {role_capabilities} rc
3207 $extrajoins
3208 $extrawhere) idlist
3209 JOIN {role} r ON r.id = idlist.roleid
3210 ORDER BY r.sortorder";
3212 $rolenames = $DB->get_records_sql_menu($query, $params);
3213 return role_fix_names($rolenames, $context, ROLENAME_ALIAS);
3217 * Gets a list of roles that this user can override in this context.
3219 * @param context $context the context.
3220 * @param int $rolenamedisplay the type of role name to display. One of the
3221 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3222 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3223 * @return array if $withcounts is false, then an array $roleid => $rolename.
3224 * if $withusercounts is true, returns a list of three arrays,
3225 * $rolenames, $rolecounts, and $nameswithcounts.
3227 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3228 global $USER, $DB;
3230 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3231 if ($withcounts) {
3232 return array(array(), array(), array());
3233 } else {
3234 return array();
3238 $parents = $context->get_parent_context_ids(true);
3239 $contexts = implode(',' , $parents);
3241 $params = array();
3242 $extrafields = '';
3243 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3244 $extrafields .= ', ro.shortname';
3247 $params['userid'] = $USER->id;
3248 if ($withcounts) {
3249 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3250 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3251 $params['conid'] = $context->id;
3254 if (is_siteadmin()) {
3255 // show all roles to admins
3256 $roles = $DB->get_records_sql("
3257 SELECT ro.id, ro.name$extrafields
3258 FROM {role} ro
3259 ORDER BY ro.sortorder ASC", $params);
3261 } else {
3262 $roles = $DB->get_records_sql("
3263 SELECT ro.id, ro.name$extrafields
3264 FROM {role} ro
3265 JOIN (SELECT DISTINCT r.id
3266 FROM {role} r
3267 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3268 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3269 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3270 ) inline_view ON ro.id = inline_view.id
3271 ORDER BY ro.sortorder ASC", $params);
3274 $rolenames = array();
3275 foreach ($roles as $role) {
3276 $rolenames[$role->id] = $role->name;
3277 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3278 $rolenames[$role->id] .= ' (' . $role->shortname . ')';
3281 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT) {
3282 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3285 if (!$withcounts) {
3286 return $rolenames;
3289 $rolecounts = array();
3290 $nameswithcounts = array();
3291 foreach ($roles as $role) {
3292 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3293 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3295 return array($rolenames, $rolecounts, $nameswithcounts);
3299 * Create a role menu suitable for default role selection in enrol plugins.
3300 * @param context $context
3301 * @param int $addroleid current or default role - always added to list
3302 * @return array roleid=>localised role name
3304 function get_default_enrol_roles(context $context, $addroleid = null) {
3305 global $DB;
3307 $params = array('contextlevel'=>CONTEXT_COURSE);
3308 if ($addroleid) {
3309 $addrole = "OR r.id = :addroleid";
3310 $params['addroleid'] = $addroleid;
3311 } else {
3312 $addrole = "";
3314 $sql = "SELECT r.id, r.name
3315 FROM {role} r
3316 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3317 WHERE rcl.id IS NOT NULL $addrole
3318 ORDER BY sortorder DESC";
3320 $roles = $DB->get_records_sql_menu($sql, $params);
3321 $roles = role_fix_names($roles, $context, ROLENAME_BOTH);
3323 return $roles;
3327 * Return context levels where this role is assignable.
3328 * @param integer $roleid the id of a role.
3329 * @return array list of the context levels at which this role may be assigned.
3331 function get_role_contextlevels($roleid) {
3332 global $DB;
3333 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3334 'contextlevel', 'id,contextlevel');
3338 * Return roles suitable for assignment at the specified context level.
3340 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3342 * @param integer $contextlevel a contextlevel.
3343 * @return array list of role ids that are assignable at this context level.
3345 function get_roles_for_contextlevels($contextlevel) {
3346 global $DB;
3347 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3348 '', 'id,roleid');
3352 * Returns default context levels where roles can be assigned.
3354 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3355 * from the array returned by get_role_archetypes();
3356 * @return array list of the context levels at which this type of role may be assigned by default.
3358 function get_default_contextlevels($rolearchetype) {
3359 static $defaults = array(
3360 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3361 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3362 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3363 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3364 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3365 'guest' => array(),
3366 'user' => array(),
3367 'frontpage' => array());
3369 if (isset($defaults[$rolearchetype])) {
3370 return $defaults[$rolearchetype];
3371 } else {
3372 return array();
3377 * Set the context levels at which a particular role can be assigned.
3378 * Throws exceptions in case of error.
3380 * @param integer $roleid the id of a role.
3381 * @param array $contextlevels the context levels at which this role should be assignable,
3382 * duplicate levels are removed.
3383 * @return void
3385 function set_role_contextlevels($roleid, array $contextlevels) {
3386 global $DB;
3387 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3388 $rcl = new stdClass();
3389 $rcl->roleid = $roleid;
3390 $contextlevels = array_unique($contextlevels);
3391 foreach ($contextlevels as $level) {
3392 $rcl->contextlevel = $level;
3393 $DB->insert_record('role_context_levels', $rcl, false, true);
3398 * Who has this capability in this context?
3400 * This can be a very expensive call - use sparingly and keep
3401 * the results if you are going to need them again soon.
3403 * Note if $fields is empty this function attempts to get u.*
3404 * which can get rather large - and has a serious perf impact
3405 * on some DBs.
3407 * @param context $context
3408 * @param string|array $capability - capability name(s)
3409 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3410 * @param string $sort - the sort order. Default is lastaccess time.
3411 * @param mixed $limitfrom - number of records to skip (offset)
3412 * @param mixed $limitnum - number of records to fetch
3413 * @param string|array $groups - single group or array of groups - only return
3414 * users who are in one of these group(s).
3415 * @param string|array $exceptions - list of users to exclude, comma separated or array
3416 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3417 * @param bool $view_ignored - use get_enrolled_sql() instead
3418 * @param bool $useviewallgroups if $groups is set the return users who
3419 * have capability both $capability and moodle/site:accessallgroups
3420 * in this context, as well as users who have $capability and who are
3421 * in $groups.
3422 * @return mixed
3424 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3425 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3426 global $CFG, $DB;
3428 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3429 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3431 $ctxids = trim($context->path, '/');
3432 $ctxids = str_replace('/', ',', $ctxids);
3434 // Context is the frontpage
3435 $iscoursepage = false; // coursepage other than fp
3436 $isfrontpage = false;
3437 if ($context->contextlevel == CONTEXT_COURSE) {
3438 if ($context->instanceid == SITEID) {
3439 $isfrontpage = true;
3440 } else {
3441 $iscoursepage = true;
3444 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3446 $caps = (array)$capability;
3448 // construct list of context paths bottom-->top
3449 list($contextids, $paths) = get_context_info_list($context);
3451 // we need to find out all roles that have these capabilities either in definition or in overrides
3452 $defs = array();
3453 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3454 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3455 $params = array_merge($params, $params2);
3456 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3457 FROM {role_capabilities} rc
3458 JOIN {context} ctx on rc.contextid = ctx.id
3459 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3461 $rcs = $DB->get_records_sql($sql, $params);
3462 foreach ($rcs as $rc) {
3463 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3466 // go through the permissions bottom-->top direction to evaluate the current permission,
3467 // first one wins (prohibit is an exception that always wins)
3468 $access = array();
3469 foreach ($caps as $cap) {
3470 foreach ($paths as $path) {
3471 if (empty($defs[$cap][$path])) {
3472 continue;
3474 foreach($defs[$cap][$path] as $roleid => $perm) {
3475 if ($perm == CAP_PROHIBIT) {
3476 $access[$cap][$roleid] = CAP_PROHIBIT;
3477 continue;
3479 if (!isset($access[$cap][$roleid])) {
3480 $access[$cap][$roleid] = (int)$perm;
3486 // make lists of roles that are needed and prohibited in this context
3487 $needed = array(); // one of these is enough
3488 $prohibited = array(); // must not have any of these
3489 foreach ($caps as $cap) {
3490 if (empty($access[$cap])) {
3491 continue;
3493 foreach ($access[$cap] as $roleid => $perm) {
3494 if ($perm == CAP_PROHIBIT) {
3495 unset($needed[$cap][$roleid]);
3496 $prohibited[$cap][$roleid] = true;
3497 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3498 $needed[$cap][$roleid] = true;
3501 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3502 // easy, nobody has the permission
3503 unset($needed[$cap]);
3504 unset($prohibited[$cap]);
3505 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3506 // everybody is disqualified on the frontapge
3507 unset($needed[$cap]);
3508 unset($prohibited[$cap]);
3510 if (empty($prohibited[$cap])) {
3511 unset($prohibited[$cap]);
3515 if (empty($needed)) {
3516 // there can not be anybody if no roles match this request
3517 return array();
3520 if (empty($prohibited)) {
3521 // we can compact the needed roles
3522 $n = array();
3523 foreach ($needed as $cap) {
3524 foreach ($cap as $roleid=>$unused) {
3525 $n[$roleid] = true;
3528 $needed = array('any'=>$n);
3529 unset($n);
3532 /// ***** Set up default fields ******
3533 if (empty($fields)) {
3534 if ($iscoursepage) {
3535 $fields = 'u.*, ul.timeaccess AS lastaccess';
3536 } else {
3537 $fields = 'u.*';
3539 } else {
3540 if (debugging('', DEBUG_DEVELOPER) && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3541 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3545 /// Set up default sort
3546 if (empty($sort)) { // default to course lastaccess or just lastaccess
3547 if ($iscoursepage) {
3548 $sort = 'ul.timeaccess';
3549 } else {
3550 $sort = 'u.lastaccess';
3554 // Prepare query clauses
3555 $wherecond = array();
3556 $params = array();
3557 $joins = array();
3559 // User lastaccess JOIN
3560 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3561 // user_lastaccess is not required MDL-13810
3562 } else {
3563 if ($iscoursepage) {
3564 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3565 } else {
3566 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3570 /// We never return deleted users or guest account.
3571 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3572 $params['guestid'] = $CFG->siteguest;
3574 /// Groups
3575 if ($groups) {
3576 $groups = (array)$groups;
3577 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3578 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3579 $params = array_merge($params, $grpparams);
3581 if ($useviewallgroups) {
3582 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3583 if (!empty($viewallgroupsusers)) {
3584 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3585 } else {
3586 $wherecond[] = "($grouptest)";
3588 } else {
3589 $wherecond[] = "($grouptest)";
3593 /// User exceptions
3594 if (!empty($exceptions)) {
3595 $exceptions = (array)$exceptions;
3596 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3597 $params = array_merge($params, $exparams);
3598 $wherecond[] = "u.id $exsql";
3601 // now add the needed and prohibited roles conditions as joins
3602 if (!empty($needed['any'])) {
3603 // simple case - there are no prohibits involved
3604 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3605 // everybody
3606 } else {
3607 $joins[] = "JOIN (SELECT DISTINCT userid
3608 FROM {role_assignments}
3609 WHERE contextid IN ($ctxids)
3610 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3611 ) ra ON ra.userid = u.id";
3613 } else {
3614 $unions = array();
3615 $everybody = false;
3616 foreach ($needed as $cap=>$unused) {
3617 if (empty($prohibited[$cap])) {
3618 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3619 $everybody = true;
3620 break;
3621 } else {
3622 $unions[] = "SELECT userid
3623 FROM {role_assignments}
3624 WHERE contextid IN ($ctxids)
3625 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3627 } else {
3628 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3629 // nobody can have this cap because it is prevented in default roles
3630 continue;
3632 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3633 // everybody except the prohibitted - hiding does not matter
3634 $unions[] = "SELECT id AS userid
3635 FROM {user}
3636 WHERE id NOT IN (SELECT userid
3637 FROM {role_assignments}
3638 WHERE contextid IN ($ctxids)
3639 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3641 } else {
3642 $unions[] = "SELECT userid
3643 FROM {role_assignments}
3644 WHERE contextid IN ($ctxids)
3645 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3646 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3650 if (!$everybody) {
3651 if ($unions) {
3652 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3653 } else {
3654 // only prohibits found - nobody can be matched
3655 $wherecond[] = "1 = 2";
3660 // Collect WHERE conditions and needed joins
3661 $where = implode(' AND ', $wherecond);
3662 if ($where !== '') {
3663 $where = 'WHERE ' . $where;
3665 $joins = implode("\n", $joins);
3667 /// Ok, let's get the users!
3668 $sql = "SELECT $fields
3669 FROM {user} u
3670 $joins
3671 $where
3672 ORDER BY $sort";
3674 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3678 * Re-sort a users array based on a sorting policy
3680 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3681 * based on a sorting policy. This is to support the odd practice of
3682 * sorting teachers by 'authority', where authority was "lowest id of the role
3683 * assignment".
3685 * Will execute 1 database query. Only suitable for small numbers of users, as it
3686 * uses an u.id IN() clause.
3688 * Notes about the sorting criteria.
3690 * As a default, we cannot rely on role.sortorder because then
3691 * admins/coursecreators will always win. That is why the sane
3692 * rule "is locality matters most", with sortorder as 2nd
3693 * consideration.
3695 * If you want role.sortorder, use the 'sortorder' policy, and
3696 * name explicitly what roles you want to cover. It's probably
3697 * a good idea to see what roles have the capabilities you want
3698 * (array_diff() them against roiles that have 'can-do-anything'
3699 * to weed out admin-ish roles. Or fetch a list of roles from
3700 * variables like $CFG->coursecontact .
3702 * @param array $users Users array, keyed on userid
3703 * @param context $context
3704 * @param array $roles ids of the roles to include, optional
3705 * @param string $sortpolicy defaults to locality, more about
3706 * @return array sorted copy of the array
3708 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3709 global $DB;
3711 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3712 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3713 if (empty($roles)) {
3714 $roleswhere = '';
3715 } else {
3716 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3719 $sql = "SELECT ra.userid
3720 FROM {role_assignments} ra
3721 JOIN {role} r
3722 ON ra.roleid=r.id
3723 JOIN {context} ctx
3724 ON ra.contextid=ctx.id
3725 WHERE $userswhere
3726 $contextwhere
3727 $roleswhere";
3729 // Default 'locality' policy -- read PHPDoc notes
3730 // about sort policies...
3731 $orderby = 'ORDER BY '
3732 .'ctx.depth DESC, ' /* locality wins */
3733 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3734 .'ra.id'; /* role assignment order tie-breaker */
3735 if ($sortpolicy === 'sortorder') {
3736 $orderby = 'ORDER BY '
3737 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3738 .'ra.id'; /* role assignment order tie-breaker */
3741 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3742 $sortedusers = array();
3743 $seen = array();
3745 foreach ($sortedids as $id) {
3746 // Avoid duplicates
3747 if (isset($seen[$id])) {
3748 continue;
3750 $seen[$id] = true;
3752 // assign
3753 $sortedusers[$id] = $users[$id];
3755 return $sortedusers;
3759 * Gets all the users assigned this role in this context or higher
3761 * @param int $roleid (can also be an array of ints!)
3762 * @param context $context
3763 * @param bool $parent if true, get list of users assigned in higher context too
3764 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3765 * @param string $sort sort from user (u.) , role assignment (ra) or role (r.)
3766 * @param bool $gethidden_ignored use enrolments instead
3767 * @param string $group defaults to ''
3768 * @param mixed $limitfrom defaults to ''
3769 * @param mixed $limitnum defaults to ''
3770 * @param string $extrawheretest defaults to ''
3771 * @param string|array $whereparams defaults to ''
3772 * @return array
3774 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3775 $sort = 'u.lastname, u.firstname', $gethidden_ignored = null, $group = '',
3776 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereparams = array()) {
3777 global $DB;
3779 if (empty($fields)) {
3780 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3781 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3782 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3783 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder';
3786 $parentcontexts = '';
3787 if ($parent) {
3788 $parentcontexts = substr($context->path, 1); // kill leading slash
3789 $parentcontexts = str_replace('/', ',', $parentcontexts);
3790 if ($parentcontexts !== '') {
3791 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3795 if ($roleid) {
3796 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3797 $roleselect = "AND ra.roleid $rids";
3798 } else {
3799 $params = array();
3800 $roleselect = '';
3803 if ($group) {
3804 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3805 $groupselect = " AND gm.groupid = ? ";
3806 $params[] = $group;
3807 } else {
3808 $groupjoin = '';
3809 $groupselect = '';
3812 array_unshift($params, $context->id);
3814 if ($extrawheretest) {
3815 $extrawheretest = ' AND ' . $extrawheretest;
3816 $params = array_merge($params, $whereparams);
3819 $sql = "SELECT DISTINCT $fields, ra.roleid
3820 FROM {role_assignments} ra
3821 JOIN {user} u ON u.id = ra.userid
3822 JOIN {role} r ON ra.roleid = r.id
3823 $groupjoin
3824 WHERE (ra.contextid = ? $parentcontexts)
3825 $roleselect
3826 $groupselect
3827 $extrawheretest
3828 ORDER BY $sort"; // join now so that we can just use fullname() later
3830 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3834 * Counts all the users assigned this role in this context or higher
3836 * @param int|array $roleid either int or an array of ints
3837 * @param context $context
3838 * @param bool $parent if true, get list of users assigned in higher context too
3839 * @return int Returns the result count
3841 function count_role_users($roleid, context $context, $parent = false) {
3842 global $DB;
3844 if ($parent) {
3845 if ($contexts = $context->get_parent_context_ids()) {
3846 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3847 } else {
3848 $parentcontexts = '';
3850 } else {
3851 $parentcontexts = '';
3854 if ($roleid) {
3855 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3856 $roleselect = "AND r.roleid $rids";
3857 } else {
3858 $params = array();
3859 $roleselect = '';
3862 array_unshift($params, $context->id);
3864 $sql = "SELECT COUNT(u.id)
3865 FROM {role_assignments} r
3866 JOIN {user} u ON u.id = r.userid
3867 WHERE (r.contextid = ? $parentcontexts)
3868 $roleselect
3869 AND u.deleted = 0";
3871 return $DB->count_records_sql($sql, $params);
3875 * This function gets the list of courses that this user has a particular capability in.
3876 * It is still not very efficient.
3878 * @param string $capability Capability in question
3879 * @param int $userid User ID or null for current user
3880 * @param bool $doanything True if 'doanything' is permitted (default)
3881 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3882 * otherwise use a comma-separated list of the fields you require, not including id
3883 * @param string $orderby If set, use a comma-separated list of fields from course
3884 * table with sql modifiers (DESC) if needed
3885 * @return array Array of courses, may have zero entries. Or false if query failed.
3887 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
3888 global $DB;
3890 // Convert fields list and ordering
3891 $fieldlist = '';
3892 if ($fieldsexceptid) {
3893 $fields = explode(',', $fieldsexceptid);
3894 foreach($fields as $field) {
3895 $fieldlist .= ',c.'.$field;
3898 if ($orderby) {
3899 $fields = explode(',', $orderby);
3900 $orderby = '';
3901 foreach($fields as $field) {
3902 if ($orderby) {
3903 $orderby .= ',';
3905 $orderby .= 'c.'.$field;
3907 $orderby = 'ORDER BY '.$orderby;
3910 // Obtain a list of everything relevant about all courses including context.
3911 // Note the result can be used directly as a context (we are going to), the course
3912 // fields are just appended.
3914 $contextpreload = context_helper::get_preload_record_columns_sql('x');
3916 $courses = array();
3917 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
3918 FROM {course} c
3919 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
3920 $orderby");
3921 // Check capability for each course in turn
3922 foreach ($rs as $course) {
3923 context_helper::preload_from_record($course);
3924 $context = context_course::instance($course->id);
3925 if (has_capability($capability, $context, $userid, $doanything)) {
3926 // We've got the capability. Make the record look like a course record
3927 // and store it
3928 $courses[] = $course;
3931 $rs->close();
3932 return empty($courses) ? false : $courses;
3936 * This function finds the roles assigned directly to this context only
3937 * i.e. no roles in parent contexts
3939 * @param context $context
3940 * @return array
3942 function get_roles_on_exact_context(context $context) {
3943 global $DB;
3945 return $DB->get_records_sql("SELECT r.*
3946 FROM {role_assignments} ra, {role} r
3947 WHERE ra.roleid = r.id AND ra.contextid = ?",
3948 array($context->id));
3952 * Switches the current user to another role for the current session and only
3953 * in the given context.
3955 * The caller *must* check
3956 * - that this op is allowed
3957 * - that the requested role can be switched to in this context (use get_switchable_roles)
3958 * - that the requested role is NOT $CFG->defaultuserroleid
3960 * To "unswitch" pass 0 as the roleid.
3962 * This function *will* modify $USER->access - beware
3964 * @param integer $roleid the role to switch to.
3965 * @param context $context the context in which to perform the switch.
3966 * @return bool success or failure.
3968 function role_switch($roleid, context $context) {
3969 global $USER;
3972 // Plan of action
3974 // - Add the ghost RA to $USER->access
3975 // as $USER->access['rsw'][$path] = $roleid
3977 // - Make sure $USER->access['rdef'] has the roledefs
3978 // it needs to honour the switcherole
3980 // Roledefs will get loaded "deep" here - down to the last child
3981 // context. Note that
3983 // - When visiting subcontexts, our selective accessdata loading
3984 // will still work fine - though those ra/rdefs will be ignored
3985 // appropriately while the switch is in place
3987 // - If a switcherole happens at a category with tons of courses
3988 // (that have many overrides for switched-to role), the session
3989 // will get... quite large. Sometimes you just can't win.
3991 // To un-switch just unset($USER->access['rsw'][$path])
3993 // Note: it is not possible to switch to roles that do not have course:view
3995 if (!isset($USER->access)) {
3996 load_all_capabilities();
4000 // Add the switch RA
4001 if ($roleid == 0) {
4002 unset($USER->access['rsw'][$context->path]);
4003 return true;
4006 $USER->access['rsw'][$context->path] = $roleid;
4008 // Load roledefs
4009 load_role_access_by_context($roleid, $context, $USER->access);
4011 return true;
4015 * Checks if the user has switched roles within the given course.
4017 * Note: You can only switch roles within the course, hence it takes a courseid
4018 * rather than a context. On that note Petr volunteered to implement this across
4019 * all other contexts, all requests for this should be forwarded to him ;)
4021 * @param int $courseid The id of the course to check
4022 * @return bool True if the user has switched roles within the course.
4024 function is_role_switched($courseid) {
4025 global $USER;
4026 $context = context_course::instance($courseid, MUST_EXIST);
4027 return (!empty($USER->access['rsw'][$context->path]));
4031 * Get any role that has an override on exact context
4033 * @param context $context The context to check
4034 * @return array An array of roles
4036 function get_roles_with_override_on_context(context $context) {
4037 global $DB;
4039 return $DB->get_records_sql("SELECT r.*
4040 FROM {role_capabilities} rc, {role} r
4041 WHERE rc.roleid = r.id AND rc.contextid = ?",
4042 array($context->id));
4046 * Get all capabilities for this role on this context (overrides)
4048 * @param stdClass $role
4049 * @param context $context
4050 * @return array
4052 function get_capabilities_from_role_on_context($role, context $context) {
4053 global $DB;
4055 return $DB->get_records_sql("SELECT *
4056 FROM {role_capabilities}
4057 WHERE contextid = ? AND roleid = ?",
4058 array($context->id, $role->id));
4062 * Find out which roles has assignment on this context
4064 * @param context $context
4065 * @return array
4068 function get_roles_with_assignment_on_context(context $context) {
4069 global $DB;
4071 return $DB->get_records_sql("SELECT r.*
4072 FROM {role_assignments} ra, {role} r
4073 WHERE ra.roleid = r.id AND ra.contextid = ?",
4074 array($context->id));
4078 * Find all user assignment of users for this role, on this context
4080 * @param stdClass $role
4081 * @param context $context
4082 * @return array
4084 function get_users_from_role_on_context($role, context $context) {
4085 global $DB;
4087 return $DB->get_records_sql("SELECT *
4088 FROM {role_assignments}
4089 WHERE contextid = ? AND roleid = ?",
4090 array($context->id, $role->id));
4094 * Simple function returning a boolean true if user has roles
4095 * in context or parent contexts, otherwise false.
4097 * @param int $userid
4098 * @param int $roleid
4099 * @param int $contextid empty means any context
4100 * @return bool
4102 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4103 global $DB;
4105 if ($contextid) {
4106 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4107 return false;
4109 $parents = $context->get_parent_context_ids(true);
4110 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4111 $params['userid'] = $userid;
4112 $params['roleid'] = $roleid;
4114 $sql = "SELECT COUNT(ra.id)
4115 FROM {role_assignments} ra
4116 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4118 $count = $DB->get_field_sql($sql, $params);
4119 return ($count > 0);
4121 } else {
4122 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4127 * Get role name or alias if exists and format the text.
4129 * @param stdClass $role role object
4130 * @param context_course $coursecontext
4131 * @return string name of role in course context
4133 function role_get_name($role, context_course $coursecontext) {
4134 global $DB;
4136 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4137 return strip_tags(format_string($r->name));
4138 } else {
4139 return strip_tags(format_string($role->name));
4144 * Get all the localised role names for a context.
4145 * @param context $context the context
4146 * @param array of role objects with a ->localname field containing the context-specific role name.
4148 function role_get_names(context $context) {
4149 return role_fix_names(get_all_roles(), $context);
4153 * Prepare list of roles for display, apply aliases and format text
4155 * @param array $roleoptions array roleid => rolename or roleid => roleobject
4156 * @param context $context a context
4157 * @param int $rolenamedisplay
4158 * @return array Array of context-specific role names, or role objexts with a ->localname field added.
4160 function role_fix_names($roleoptions, context $context, $rolenamedisplay = ROLENAME_ALIAS) {
4161 global $DB;
4163 // Make sure we have a course context.
4164 $coursecontext = $context->get_course_context(false);
4166 // Make sure we are working with an array roleid => name. Normally we
4167 // want to use the unlocalised name if the localised one is not present.
4168 $newnames = array();
4169 foreach ($roleoptions as $rid => $roleorname) {
4170 if ($rolenamedisplay != ROLENAME_ALIAS_RAW) {
4171 if (is_object($roleorname)) {
4172 $newnames[$rid] = $roleorname->name;
4173 } else {
4174 $newnames[$rid] = $roleorname;
4176 } else {
4177 $newnames[$rid] = '';
4181 // If necessary, get the localised names.
4182 if ($rolenamedisplay != ROLENAME_ORIGINAL && !empty($coursecontext->id)) {
4183 // The get the relevant renames, and use them.
4184 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4185 foreach ($aliasnames as $alias) {
4186 if (isset($newnames[$alias->roleid])) {
4187 if ($rolenamedisplay == ROLENAME_ALIAS || $rolenamedisplay == ROLENAME_ALIAS_RAW) {
4188 $newnames[$alias->roleid] = $alias->name;
4189 } else if ($rolenamedisplay == ROLENAME_BOTH) {
4190 $newnames[$alias->roleid] = $alias->name . ' (' . $roleoptions[$alias->roleid] . ')';
4196 // Finally, apply format_string and put the result in the right place.
4197 foreach ($roleoptions as $rid => $roleorname) {
4198 if ($rolenamedisplay != ROLENAME_ALIAS_RAW) {
4199 $newnames[$rid] = strip_tags(format_string($newnames[$rid]));
4201 if (is_object($roleorname)) {
4202 $roleoptions[$rid]->localname = $newnames[$rid];
4203 } else {
4204 $roleoptions[$rid] = $newnames[$rid];
4207 return $roleoptions;
4211 * Aids in detecting if a new line is required when reading a new capability
4213 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4214 * when we read in a new capability.
4215 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4216 * but when we are in grade, all reports/import/export capabilities should be together
4218 * @param string $cap component string a
4219 * @param string $comp component string b
4220 * @param int $contextlevel
4221 * @return bool whether 2 component are in different "sections"
4223 function component_level_changed($cap, $comp, $contextlevel) {
4225 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4226 $compsa = explode('/', $cap->component);
4227 $compsb = explode('/', $comp);
4229 // list of system reports
4230 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4231 return false;
4234 // we are in gradebook, still
4235 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4236 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4237 return false;
4240 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4241 return false;
4245 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4249 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4250 * and return an array of roleids in order.
4252 * @param array $allroles array of roles, as returned by get_all_roles();
4253 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4255 function fix_role_sortorder($allroles) {
4256 global $DB;
4258 $rolesort = array();
4259 $i = 0;
4260 foreach ($allroles as $role) {
4261 $rolesort[$i] = $role->id;
4262 if ($role->sortorder != $i) {
4263 $r = new stdClass();
4264 $r->id = $role->id;
4265 $r->sortorder = $i;
4266 $DB->update_record('role', $r);
4267 $allroles[$role->id]->sortorder = $i;
4269 $i++;
4271 return $rolesort;
4275 * Switch the sort order of two roles (used in admin/roles/manage.php).
4277 * @param object $first The first role. Actually, only ->sortorder is used.
4278 * @param object $second The second role. Actually, only ->sortorder is used.
4279 * @return boolean success or failure
4281 function switch_roles($first, $second) {
4282 global $DB;
4283 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4284 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4285 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4286 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4287 return $result;
4291 * Duplicates all the base definitions of a role
4293 * @param object $sourcerole role to copy from
4294 * @param int $targetrole id of role to copy to
4296 function role_cap_duplicate($sourcerole, $targetrole) {
4297 global $DB;
4299 $systemcontext = context_system::instance();
4300 $caps = $DB->get_records_sql("SELECT *
4301 FROM {role_capabilities}
4302 WHERE roleid = ? AND contextid = ?",
4303 array($sourcerole->id, $systemcontext->id));
4304 // adding capabilities
4305 foreach ($caps as $cap) {
4306 unset($cap->id);
4307 $cap->roleid = $targetrole;
4308 $DB->insert_record('role_capabilities', $cap);
4313 * Returns two lists, this can be used to find out if user has capability.
4314 * Having any needed role and no forbidden role in this context means
4315 * user has this capability in this context.
4316 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4318 * @param object $context
4319 * @param string $capability
4320 * @return array($neededroles, $forbiddenroles)
4322 function get_roles_with_cap_in_context($context, $capability) {
4323 global $DB;
4325 $ctxids = trim($context->path, '/'); // kill leading slash
4326 $ctxids = str_replace('/', ',', $ctxids);
4328 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4329 FROM {role_capabilities} rc
4330 JOIN {context} ctx ON ctx.id = rc.contextid
4331 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4332 ORDER BY rc.roleid ASC, ctx.depth DESC";
4333 $params = array('cap'=>$capability);
4335 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4336 // no cap definitions --> no capability
4337 return array(array(), array());
4340 $forbidden = array();
4341 $needed = array();
4342 foreach($capdefs as $def) {
4343 if (isset($forbidden[$def->roleid])) {
4344 continue;
4346 if ($def->permission == CAP_PROHIBIT) {
4347 $forbidden[$def->roleid] = $def->roleid;
4348 unset($needed[$def->roleid]);
4349 continue;
4351 if (!isset($needed[$def->roleid])) {
4352 if ($def->permission == CAP_ALLOW) {
4353 $needed[$def->roleid] = true;
4354 } else if ($def->permission == CAP_PREVENT) {
4355 $needed[$def->roleid] = false;
4359 unset($capdefs);
4361 // remove all those roles not allowing
4362 foreach($needed as $key=>$value) {
4363 if (!$value) {
4364 unset($needed[$key]);
4365 } else {
4366 $needed[$key] = $key;
4370 return array($needed, $forbidden);
4374 * Returns an array of role IDs that have ALL of the the supplied capabilities
4375 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4377 * @param object $context
4378 * @param array $capabilities An array of capabilities
4379 * @return array of roles with all of the required capabilities
4381 function get_roles_with_caps_in_context($context, $capabilities) {
4382 $neededarr = array();
4383 $forbiddenarr = array();
4384 foreach($capabilities as $caprequired) {
4385 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4388 $rolesthatcanrate = array();
4389 if (!empty($neededarr)) {
4390 foreach ($neededarr as $needed) {
4391 if (empty($rolesthatcanrate)) {
4392 $rolesthatcanrate = $needed;
4393 } else {
4394 //only want roles that have all caps
4395 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4399 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4400 foreach ($forbiddenarr as $forbidden) {
4401 //remove any roles that are forbidden any of the caps
4402 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4405 return $rolesthatcanrate;
4409 * Returns an array of role names that have ALL of the the supplied capabilities
4410 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4412 * @param object $context
4413 * @param array $capabilities An array of capabilities
4414 * @return array of roles with all of the required capabilities
4416 function get_role_names_with_caps_in_context($context, $capabilities) {
4417 global $DB;
4419 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4421 $allroles = array();
4422 $roles = $DB->get_records('role', null, 'sortorder DESC');
4423 foreach ($roles as $roleid=>$role) {
4424 $allroles[$roleid] = $role->name;
4427 $rolenames = array();
4428 foreach ($rolesthatcanrate as $r) {
4429 $rolenames[$r] = $allroles[$r];
4431 $rolenames = role_fix_names($rolenames, $context);
4432 return $rolenames;
4436 * This function verifies the prohibit comes from this context
4437 * and there are no more prohibits in parent contexts.
4439 * @param int $roleid
4440 * @param context $context
4441 * @param string $capability name
4442 * @return bool
4444 function prohibit_is_removable($roleid, context $context, $capability) {
4445 global $DB;
4447 $ctxids = trim($context->path, '/'); // kill leading slash
4448 $ctxids = str_replace('/', ',', $ctxids);
4450 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4452 $sql = "SELECT ctx.id
4453 FROM {role_capabilities} rc
4454 JOIN {context} ctx ON ctx.id = rc.contextid
4455 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4456 ORDER BY ctx.depth DESC";
4458 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4459 // no prohibits == nothing to remove
4460 return true;
4463 if (count($prohibits) > 1) {
4464 // more prohibints can not be removed
4465 return false;
4468 return !empty($prohibits[$context->id]);
4472 * More user friendly role permission changing,
4473 * it should produce as few overrides as possible.
4474 * @param int $roleid
4475 * @param object $context
4476 * @param string $capname capability name
4477 * @param int $permission
4478 * @return void
4480 function role_change_permission($roleid, $context, $capname, $permission) {
4481 global $DB;
4483 if ($permission == CAP_INHERIT) {
4484 unassign_capability($capname, $roleid, $context->id);
4485 $context->mark_dirty();
4486 return;
4489 $ctxids = trim($context->path, '/'); // kill leading slash
4490 $ctxids = str_replace('/', ',', $ctxids);
4492 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4494 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4495 FROM {role_capabilities} rc
4496 JOIN {context} ctx ON ctx.id = rc.contextid
4497 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4498 ORDER BY ctx.depth DESC";
4500 if ($existing = $DB->get_records_sql($sql, $params)) {
4501 foreach($existing as $e) {
4502 if ($e->permission == CAP_PROHIBIT) {
4503 // prohibit can not be overridden, no point in changing anything
4504 return;
4507 $lowest = array_shift($existing);
4508 if ($lowest->permission == $permission) {
4509 // permission already set in this context or parent - nothing to do
4510 return;
4512 if ($existing) {
4513 $parent = array_shift($existing);
4514 if ($parent->permission == $permission) {
4515 // permission already set in parent context or parent - just unset in this context
4516 // we do this because we want as few overrides as possible for performance reasons
4517 unassign_capability($capname, $roleid, $context->id);
4518 $context->mark_dirty();
4519 return;
4523 } else {
4524 if ($permission == CAP_PREVENT) {
4525 // nothing means role does not have permission
4526 return;
4530 // assign the needed capability
4531 assign_capability($capname, $permission, $roleid, $context->id, true);
4533 // force cap reloading
4534 $context->mark_dirty();
4539 * Basic moodle context abstraction class.
4541 * @author Petr Skoda
4542 * @since 2.2
4544 * @property-read int $id context id
4545 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4546 * @property-read int $instanceid id of related instance in each context
4547 * @property-read string $path path to context, starts with system context
4548 * @property-read dept $depth
4550 abstract class context extends stdClass implements IteratorAggregate {
4553 * Google confirms that no other important framework is using "context" class,
4554 * we could use something else like mcontext or moodle_context, but we need to type
4555 * this very often which would be annoying and it would take too much space...
4557 * This class is derived from stdClass for backwards compatibility with
4558 * odl $context record that was returned from DML $DB->get_record()
4561 protected $_id;
4562 protected $_contextlevel;
4563 protected $_instanceid;
4564 protected $_path;
4565 protected $_depth;
4567 /* context caching info */
4569 private static $cache_contextsbyid = array();
4570 private static $cache_contexts = array();
4571 protected static $cache_count = 0; // why do we do count contexts? Because count($array) is horribly slow for large arrays
4573 protected static $cache_preloaded = array();
4574 protected static $systemcontext = null;
4577 * Resets the cache to remove all data.
4578 * @static
4580 protected static function reset_caches() {
4581 self::$cache_contextsbyid = array();
4582 self::$cache_contexts = array();
4583 self::$cache_count = 0;
4584 self::$cache_preloaded = array();
4586 self::$systemcontext = null;
4590 * Adds a context to the cache. If the cache is full, discards a batch of
4591 * older entries.
4593 * @static
4594 * @param context $context New context to add
4595 * @return void
4597 protected static function cache_add(context $context) {
4598 if (isset(self::$cache_contextsbyid[$context->id])) {
4599 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4600 return;
4603 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4604 $i = 0;
4605 foreach(self::$cache_contextsbyid as $ctx) {
4606 $i++;
4607 if ($i <= 100) {
4608 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4609 continue;
4611 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4612 // we remove oldest third of the contexts to make room for more contexts
4613 break;
4615 unset(self::$cache_contextsbyid[$ctx->id]);
4616 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4617 self::$cache_count--;
4621 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4622 self::$cache_contextsbyid[$context->id] = $context;
4623 self::$cache_count++;
4627 * Removes a context from the cache.
4629 * @static
4630 * @param context $context Context object to remove
4631 * @return void
4633 protected static function cache_remove(context $context) {
4634 if (!isset(self::$cache_contextsbyid[$context->id])) {
4635 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4636 return;
4638 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4639 unset(self::$cache_contextsbyid[$context->id]);
4641 self::$cache_count--;
4643 if (self::$cache_count < 0) {
4644 self::$cache_count = 0;
4649 * Gets a context from the cache.
4651 * @static
4652 * @param int $contextlevel Context level
4653 * @param int $instance Instance ID
4654 * @return context|bool Context or false if not in cache
4656 protected static function cache_get($contextlevel, $instance) {
4657 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4658 return self::$cache_contexts[$contextlevel][$instance];
4660 return false;
4664 * Gets a context from the cache based on its id.
4666 * @static
4667 * @param int $id Context ID
4668 * @return context|bool Context or false if not in cache
4670 protected static function cache_get_by_id($id) {
4671 if (isset(self::$cache_contextsbyid[$id])) {
4672 return self::$cache_contextsbyid[$id];
4674 return false;
4678 * Preloads context information from db record and strips the cached info.
4680 * @static
4681 * @param stdClass $rec
4682 * @return void (modifies $rec)
4684 protected static function preload_from_record(stdClass $rec) {
4685 if (empty($rec->ctxid) or empty($rec->ctxlevel) or empty($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
4686 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4687 return;
4690 // note: in PHP5 the objects are passed by reference, no need to return $rec
4691 $record = new stdClass();
4692 $record->id = $rec->ctxid; unset($rec->ctxid);
4693 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
4694 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
4695 $record->path = $rec->ctxpath; unset($rec->ctxpath);
4696 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
4698 return context::create_instance_from_record($record);
4702 // ====== magic methods =======
4705 * Magic setter method, we do not want anybody to modify properties from the outside
4706 * @param string $name
4707 * @param mixed @value
4709 public function __set($name, $value) {
4710 debugging('Can not change context instance properties!');
4714 * Magic method getter, redirects to read only values.
4715 * @param string $name
4716 * @return mixed
4718 public function __get($name) {
4719 switch ($name) {
4720 case 'id': return $this->_id;
4721 case 'contextlevel': return $this->_contextlevel;
4722 case 'instanceid': return $this->_instanceid;
4723 case 'path': return $this->_path;
4724 case 'depth': return $this->_depth;
4726 default:
4727 debugging('Invalid context property accessed! '.$name);
4728 return null;
4733 * Full support for isset on our magic read only properties.
4734 * @param $name
4735 * @return bool
4737 public function __isset($name) {
4738 switch ($name) {
4739 case 'id': return isset($this->_id);
4740 case 'contextlevel': return isset($this->_contextlevel);
4741 case 'instanceid': return isset($this->_instanceid);
4742 case 'path': return isset($this->_path);
4743 case 'depth': return isset($this->_depth);
4745 default: return false;
4751 * ALl properties are read only, sorry.
4752 * @param string $name
4754 public function __unset($name) {
4755 debugging('Can not unset context instance properties!');
4758 // ====== implementing method from interface IteratorAggregate ======
4761 * Create an iterator because magic vars can't be seen by 'foreach'.
4763 * Now we can convert context object to array using convert_to_array(),
4764 * and feed it properly to json_encode().
4766 public function getIterator() {
4767 $ret = array(
4768 'id' => $this->id,
4769 'contextlevel' => $this->contextlevel,
4770 'instanceid' => $this->instanceid,
4771 'path' => $this->path,
4772 'depth' => $this->depth
4774 return new ArrayIterator($ret);
4777 // ====== general context methods ======
4780 * Constructor is protected so that devs are forced to
4781 * use context_xxx::instance() or context::instance_by_id().
4783 * @param stdClass $record
4785 protected function __construct(stdClass $record) {
4786 $this->_id = $record->id;
4787 $this->_contextlevel = (int)$record->contextlevel;
4788 $this->_instanceid = $record->instanceid;
4789 $this->_path = $record->path;
4790 $this->_depth = $record->depth;
4794 * This function is also used to work around 'protected' keyword problems in context_helper.
4795 * @static
4796 * @param stdClass $record
4797 * @return context instance
4799 protected static function create_instance_from_record(stdClass $record) {
4800 $classname = context_helper::get_class_for_level($record->contextlevel);
4802 if ($context = context::cache_get_by_id($record->id)) {
4803 return $context;
4806 $context = new $classname($record);
4807 context::cache_add($context);
4809 return $context;
4813 * Copy prepared new contexts from temp table to context table,
4814 * we do this in db specific way for perf reasons only.
4815 * @static
4817 protected static function merge_context_temp_table() {
4818 global $DB;
4820 /* MDL-11347:
4821 * - mysql does not allow to use FROM in UPDATE statements
4822 * - using two tables after UPDATE works in mysql, but might give unexpected
4823 * results in pg 8 (depends on configuration)
4824 * - using table alias in UPDATE does not work in pg < 8.2
4826 * Different code for each database - mostly for performance reasons
4829 $dbfamily = $DB->get_dbfamily();
4830 if ($dbfamily == 'mysql') {
4831 $updatesql = "UPDATE {context} ct, {context_temp} temp
4832 SET ct.path = temp.path,
4833 ct.depth = temp.depth
4834 WHERE ct.id = temp.id";
4835 } else if ($dbfamily == 'oracle') {
4836 $updatesql = "UPDATE {context} ct
4837 SET (ct.path, ct.depth) =
4838 (SELECT temp.path, temp.depth
4839 FROM {context_temp} temp
4840 WHERE temp.id=ct.id)
4841 WHERE EXISTS (SELECT 'x'
4842 FROM {context_temp} temp
4843 WHERE temp.id = ct.id)";
4844 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
4845 $updatesql = "UPDATE {context}
4846 SET path = temp.path,
4847 depth = temp.depth
4848 FROM {context_temp} temp
4849 WHERE temp.id={context}.id";
4850 } else {
4851 // sqlite and others
4852 $updatesql = "UPDATE {context}
4853 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
4854 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
4855 WHERE id IN (SELECT id FROM {context_temp})";
4858 $DB->execute($updatesql);
4862 * Get a context instance as an object, from a given context id.
4864 * @static
4865 * @param int $id context id
4866 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
4867 * MUST_EXIST means throw exception if no record found
4868 * @return context|bool the context object or false if not found
4870 public static function instance_by_id($id, $strictness = MUST_EXIST) {
4871 global $DB;
4873 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
4874 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
4875 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
4878 if ($id == SYSCONTEXTID) {
4879 return context_system::instance(0, $strictness);
4882 if (is_array($id) or is_object($id) or empty($id)) {
4883 throw new coding_exception('Invalid context id specified context::instance_by_id()');
4886 if ($context = context::cache_get_by_id($id)) {
4887 return $context;
4890 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
4891 return context::create_instance_from_record($record);
4894 return false;
4898 * Update context info after moving context in the tree structure.
4900 * @param context $newparent
4901 * @return void
4903 public function update_moved(context $newparent) {
4904 global $DB;
4906 $frompath = $this->_path;
4907 $newpath = $newparent->path . '/' . $this->_id;
4909 $trans = $DB->start_delegated_transaction();
4911 $this->mark_dirty();
4913 $setdepth = '';
4914 if (($newparent->depth +1) != $this->_depth) {
4915 $diff = $newparent->depth - $this->_depth + 1;
4916 $setdepth = ", depth = depth + $diff";
4918 $sql = "UPDATE {context}
4919 SET path = ?
4920 $setdepth
4921 WHERE id = ?";
4922 $params = array($newpath, $this->_id);
4923 $DB->execute($sql, $params);
4925 $this->_path = $newpath;
4926 $this->_depth = $newparent->depth + 1;
4928 $sql = "UPDATE {context}
4929 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
4930 $setdepth
4931 WHERE path LIKE ?";
4932 $params = array($newpath, "{$frompath}/%");
4933 $DB->execute($sql, $params);
4935 $this->mark_dirty();
4937 context::reset_caches();
4939 $trans->allow_commit();
4943 * Remove all context path info and optionally rebuild it.
4945 * @param bool $rebuild
4946 * @return void
4948 public function reset_paths($rebuild = true) {
4949 global $DB;
4951 if ($this->_path) {
4952 $this->mark_dirty();
4954 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
4955 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
4956 if ($this->_contextlevel != CONTEXT_SYSTEM) {
4957 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
4958 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
4959 $this->_depth = 0;
4960 $this->_path = null;
4963 if ($rebuild) {
4964 context_helper::build_all_paths(false);
4967 context::reset_caches();
4971 * Delete all data linked to content, do not delete the context record itself
4973 public function delete_content() {
4974 global $CFG, $DB;
4976 blocks_delete_all_for_context($this->_id);
4977 filter_delete_all_for_context($this->_id);
4979 require_once($CFG->dirroot . '/comment/lib.php');
4980 comment::delete_comments(array('contextid'=>$this->_id));
4982 require_once($CFG->dirroot.'/rating/lib.php');
4983 $delopt = new stdclass();
4984 $delopt->contextid = $this->_id;
4985 $rm = new rating_manager();
4986 $rm->delete_ratings($delopt);
4988 // delete all files attached to this context
4989 $fs = get_file_storage();
4990 $fs->delete_area_files($this->_id);
4992 // delete all advanced grading data attached to this context
4993 require_once($CFG->dirroot.'/grade/grading/lib.php');
4994 grading_manager::delete_all_for_context($this->_id);
4996 // now delete stuff from role related tables, role_unassign_all
4997 // and unenrol should be called earlier to do proper cleanup
4998 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
4999 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5000 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5004 * Delete the context content and the context record itself
5006 public function delete() {
5007 global $DB;
5009 // double check the context still exists
5010 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5011 context::cache_remove($this);
5012 return;
5015 $this->delete_content();
5016 $DB->delete_records('context', array('id'=>$this->_id));
5017 // purge static context cache if entry present
5018 context::cache_remove($this);
5020 // do not mark dirty contexts if parents unknown
5021 if (!is_null($this->_path) and $this->_depth > 0) {
5022 $this->mark_dirty();
5026 // ====== context level related methods ======
5029 * Utility method for context creation
5031 * @static
5032 * @param int $contextlevel
5033 * @param int $instanceid
5034 * @param string $parentpath
5035 * @return stdClass context record
5037 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5038 global $DB;
5040 $record = new stdClass();
5041 $record->contextlevel = $contextlevel;
5042 $record->instanceid = $instanceid;
5043 $record->depth = 0;
5044 $record->path = null; //not known before insert
5046 $record->id = $DB->insert_record('context', $record);
5048 // now add path if known - it can be added later
5049 if (!is_null($parentpath)) {
5050 $record->path = $parentpath.'/'.$record->id;
5051 $record->depth = substr_count($record->path, '/');
5052 $DB->update_record('context', $record);
5055 return $record;
5059 * Returns human readable context identifier.
5061 * @param boolean $withprefix whether to prefix the name of the context with the
5062 * type of context, e.g. User, Course, Forum, etc.
5063 * @param boolean $short whether to use the short name of the thing. Only applies
5064 * to course contexts
5065 * @return string the human readable context name.
5067 public function get_context_name($withprefix = true, $short = false) {
5068 // must be implemented in all context levels
5069 throw new coding_exception('can not get name of abstract context');
5073 * Returns the most relevant URL for this context.
5075 * @return moodle_url
5077 public abstract function get_url();
5080 * Returns array of relevant context capability records.
5082 * @return array
5084 public abstract function get_capabilities();
5087 * Recursive function which, given a context, find all its children context ids.
5089 * For course category contexts it will return immediate children and all subcategory contexts.
5090 * It will NOT recurse into courses or subcategories categories.
5091 * If you want to do that, call it on the returned courses/categories.
5093 * When called for a course context, it will return the modules and blocks
5094 * displayed in the course page and blocks displayed on the module pages.
5096 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5097 * contexts ;-)
5099 * @return array Array of child records
5101 public function get_child_contexts() {
5102 global $DB;
5104 $sql = "SELECT ctx.*
5105 FROM {context} ctx
5106 WHERE ctx.path LIKE ?";
5107 $params = array($this->_path.'/%');
5108 $records = $DB->get_records_sql($sql, $params);
5110 $result = array();
5111 foreach ($records as $record) {
5112 $result[$record->id] = context::create_instance_from_record($record);
5115 return $result;
5119 * Returns parent contexts of this context in reversed order, i.e. parent first,
5120 * then grand parent, etc.
5122 * @param bool $includeself tre means include self too
5123 * @return array of context instances
5125 public function get_parent_contexts($includeself = false) {
5126 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5127 return array();
5130 $result = array();
5131 foreach ($contextids as $contextid) {
5132 $parent = context::instance_by_id($contextid, MUST_EXIST);
5133 $result[$parent->id] = $parent;
5136 return $result;
5140 * Returns parent contexts of this context in reversed order, i.e. parent first,
5141 * then grand parent, etc.
5143 * @param bool $includeself tre means include self too
5144 * @return array of context ids
5146 public function get_parent_context_ids($includeself = false) {
5147 if (empty($this->_path)) {
5148 return array();
5151 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5152 $parentcontexts = explode('/', $parentcontexts);
5153 if (!$includeself) {
5154 array_pop($parentcontexts); // and remove its own id
5157 return array_reverse($parentcontexts);
5161 * Returns parent context
5163 * @return context
5165 public function get_parent_context() {
5166 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5167 return false;
5170 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5171 $parentcontexts = explode('/', $parentcontexts);
5172 array_pop($parentcontexts); // self
5173 $contextid = array_pop($parentcontexts); // immediate parent
5175 return context::instance_by_id($contextid, MUST_EXIST);
5179 * Is this context part of any course? If yes return course context.
5181 * @param bool $strict true means throw exception if not found, false means return false if not found
5182 * @return course_context context of the enclosing course, null if not found or exception
5184 public function get_course_context($strict = true) {
5185 if ($strict) {
5186 throw new coding_exception('Context does not belong to any course.');
5187 } else {
5188 return false;
5193 * Returns sql necessary for purging of stale context instances.
5195 * @static
5196 * @return string cleanup SQL
5198 protected static function get_cleanup_sql() {
5199 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5203 * Rebuild context paths and depths at context level.
5205 * @static
5206 * @param $force
5207 * @return void
5209 protected static function build_paths($force) {
5210 throw new coding_exception('build_paths() method must be implemented in all context levels');
5214 * Create missing context instances at given level
5216 * @static
5217 * @return void
5219 protected static function create_level_instances() {
5220 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5224 * Reset all cached permissions and definitions if the necessary.
5225 * @return void
5227 public function reload_if_dirty() {
5228 global $ACCESSLIB_PRIVATE, $USER;
5230 // Load dirty contexts list if needed
5231 if (CLI_SCRIPT) {
5232 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5233 // we do not load dirty flags in CLI and cron
5234 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5236 } else {
5237 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5238 if (!isset($USER->access['time'])) {
5239 // nothing was loaded yet, we do not need to check dirty contexts now
5240 return;
5242 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5243 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5247 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5248 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5249 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5250 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5251 reload_all_capabilities();
5252 break;
5258 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5260 public function mark_dirty() {
5261 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5263 if (during_initial_install()) {
5264 return;
5267 // only if it is a non-empty string
5268 if (is_string($this->_path) && $this->_path !== '') {
5269 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5270 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5271 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5272 } else {
5273 if (CLI_SCRIPT) {
5274 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5275 } else {
5276 if (isset($USER->access['time'])) {
5277 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5278 } else {
5279 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5281 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5290 * Context maintenance and helper methods.
5292 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5293 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5294 * level implementation from the rest of code, the code completion returns what developers need.
5296 * Thank you Tim Hunt for helping me with this nasty trick.
5298 * @author Petr Skoda
5299 * @since 2.2
5301 class context_helper extends context {
5303 private static $alllevels = array(
5304 CONTEXT_SYSTEM => 'context_system',
5305 CONTEXT_USER => 'context_user',
5306 CONTEXT_COURSECAT => 'context_coursecat',
5307 CONTEXT_COURSE => 'context_course',
5308 CONTEXT_MODULE => 'context_module',
5309 CONTEXT_BLOCK => 'context_block',
5313 * Instance does not make sense here, only static use
5315 protected function __construct() {
5319 * Returns a class name of the context level class
5321 * @static
5322 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5323 * @return string class name of the context class
5325 public static function get_class_for_level($contextlevel) {
5326 if (isset(self::$alllevels[$contextlevel])) {
5327 return self::$alllevels[$contextlevel];
5328 } else {
5329 throw new coding_exception('Invalid context level specified');
5334 * Returns a list of all context levels
5336 * @static
5337 * @return array int=>string (level=>level class name)
5339 public static function get_all_levels() {
5340 return self::$alllevels;
5344 * Remove stale contexts that belonged to deleted instances.
5345 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5347 * @static
5348 * @return void
5350 public static function cleanup_instances() {
5351 global $DB;
5352 $sqls = array();
5353 foreach (self::$alllevels as $level=>$classname) {
5354 $sqls[] = $classname::get_cleanup_sql();
5357 $sql = implode(" UNION ", $sqls);
5359 // it is probably better to use transactions, it might be faster too
5360 $transaction = $DB->start_delegated_transaction();
5362 $rs = $DB->get_recordset_sql($sql);
5363 foreach ($rs as $record) {
5364 $context = context::create_instance_from_record($record);
5365 $context->delete();
5367 $rs->close();
5369 $transaction->allow_commit();
5373 * Create all context instances at the given level and above.
5375 * @static
5376 * @param int $contextlevel null means all levels
5377 * @param bool $buildpaths
5378 * @return void
5380 public static function create_instances($contextlevel = null, $buildpaths = true) {
5381 foreach (self::$alllevels as $level=>$classname) {
5382 if ($contextlevel and $level > $contextlevel) {
5383 // skip potential sub-contexts
5384 continue;
5386 $classname::create_level_instances();
5387 if ($buildpaths) {
5388 $classname::build_paths(false);
5394 * Rebuild paths and depths in all context levels.
5396 * @static
5397 * @param bool $force false means add missing only
5398 * @return void
5400 public static function build_all_paths($force = false) {
5401 foreach (self::$alllevels as $classname) {
5402 $classname::build_paths($force);
5405 // reset static course cache - it might have incorrect cached data
5406 accesslib_clear_all_caches(true);
5410 * Resets the cache to remove all data.
5411 * @static
5413 public static function reset_caches() {
5414 context::reset_caches();
5418 * Returns all fields necessary for context preloading from user $rec.
5420 * This helps with performance when dealing with hundreds of contexts.
5422 * @static
5423 * @param string $tablealias context table alias in the query
5424 * @return array (table.column=>alias, ...)
5426 public static function get_preload_record_columns($tablealias) {
5427 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5431 * Returns all fields necessary for context preloading from user $rec.
5433 * This helps with performance when dealing with hundreds of contexts.
5435 * @static
5436 * @param string $tablealias context table alias in the query
5437 * @return string
5439 public static function get_preload_record_columns_sql($tablealias) {
5440 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5444 * Preloads context information from db record and strips the cached info.
5446 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5448 * @static
5449 * @param stdClass $rec
5450 * @return void (modifies $rec)
5452 public static function preload_from_record(stdClass $rec) {
5453 context::preload_from_record($rec);
5457 * Preload all contexts instances from course.
5459 * To be used if you expect multiple queries for course activities...
5461 * @static
5462 * @param $courseid
5464 public static function preload_course($courseid) {
5465 // Users can call this multiple times without doing any harm
5466 if (isset(context::$cache_preloaded[$courseid])) {
5467 return;
5469 $coursecontext = context_course::instance($courseid);
5470 $coursecontext->get_child_contexts();
5472 context::$cache_preloaded[$courseid] = true;
5476 * Delete context instance
5478 * @static
5479 * @param int $contextlevel
5480 * @param int $instanceid
5481 * @return void
5483 public static function delete_instance($contextlevel, $instanceid) {
5484 global $DB;
5486 // double check the context still exists
5487 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5488 $context = context::create_instance_from_record($record);
5489 $context->delete();
5490 } else {
5491 // we should try to purge the cache anyway
5496 * Returns the name of specified context level
5498 * @static
5499 * @param int $contextlevel
5500 * @return string name of the context level
5502 public static function get_level_name($contextlevel) {
5503 $classname = context_helper::get_class_for_level($contextlevel);
5504 return $classname::get_level_name();
5508 * not used
5510 public function get_url() {
5514 * not used
5516 public function get_capabilities() {
5522 * Basic context class
5523 * @author Petr Skoda (http://skodak.org)
5524 * @since 2.2
5526 class context_system extends context {
5528 * Please use context_system::instance() if you need the instance of context.
5530 * @param stdClass $record
5532 protected function __construct(stdClass $record) {
5533 parent::__construct($record);
5534 if ($record->contextlevel != CONTEXT_SYSTEM) {
5535 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5540 * Returns human readable context level name.
5542 * @static
5543 * @return string the human readable context level name.
5545 public static function get_level_name() {
5546 return get_string('coresystem');
5550 * Returns human readable context identifier.
5552 * @param boolean $withprefix does not apply to system context
5553 * @param boolean $short does not apply to system context
5554 * @return string the human readable context name.
5556 public function get_context_name($withprefix = true, $short = false) {
5557 return self::get_level_name();
5561 * Returns the most relevant URL for this context.
5563 * @return moodle_url
5565 public function get_url() {
5566 return new moodle_url('/');
5570 * Returns array of relevant context capability records.
5572 * @return array
5574 public function get_capabilities() {
5575 global $DB;
5577 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5579 $params = array();
5580 $sql = "SELECT *
5581 FROM {capabilities}";
5583 return $DB->get_records_sql($sql.' '.$sort, $params);
5587 * Create missing context instances at system context
5588 * @static
5590 protected static function create_level_instances() {
5591 // nothing to do here, the system context is created automatically in installer
5592 self::instance(0);
5596 * Returns system context instance.
5598 * @static
5599 * @param int $instanceid
5600 * @param int $strictness
5601 * @param bool $cache
5602 * @return context_system context instance
5604 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
5605 global $DB;
5607 if ($instanceid != 0) {
5608 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5611 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5612 if (!isset(context::$systemcontext)) {
5613 $record = new stdClass();
5614 $record->id = SYSCONTEXTID;
5615 $record->contextlevel = CONTEXT_SYSTEM;
5616 $record->instanceid = 0;
5617 $record->path = '/'.SYSCONTEXTID;
5618 $record->depth = 1;
5619 context::$systemcontext = new context_system($record);
5621 return context::$systemcontext;
5625 try {
5626 // we ignore the strictness completely because system context must except except during install
5627 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5628 } catch (dml_exception $e) {
5629 //table or record does not exist
5630 if (!during_initial_install()) {
5631 // do not mess with system context after install, it simply must exist
5632 throw $e;
5634 $record = null;
5637 if (!$record) {
5638 $record = new stdClass();
5639 $record->contextlevel = CONTEXT_SYSTEM;
5640 $record->instanceid = 0;
5641 $record->depth = 1;
5642 $record->path = null; //not known before insert
5644 try {
5645 if ($DB->count_records('context')) {
5646 // contexts already exist, this is very weird, system must be first!!!
5647 return null;
5649 if (defined('SYSCONTEXTID')) {
5650 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5651 $record->id = SYSCONTEXTID;
5652 $DB->import_record('context', $record);
5653 $DB->get_manager()->reset_sequence('context');
5654 } else {
5655 $record->id = $DB->insert_record('context', $record);
5657 } catch (dml_exception $e) {
5658 // can not create context - table does not exist yet, sorry
5659 return null;
5663 if ($record->instanceid != 0) {
5664 // this is very weird, somebody must be messing with context table
5665 debugging('Invalid system context detected');
5668 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5669 // fix path if necessary, initial install or path reset
5670 $record->depth = 1;
5671 $record->path = '/'.$record->id;
5672 $DB->update_record('context', $record);
5675 if (!defined('SYSCONTEXTID')) {
5676 define('SYSCONTEXTID', $record->id);
5679 context::$systemcontext = new context_system($record);
5680 return context::$systemcontext;
5684 * Returns all site contexts except the system context, DO NOT call on production servers!!
5686 * Contexts are not cached.
5688 * @return array
5690 public function get_child_contexts() {
5691 global $DB;
5693 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
5695 // Just get all the contexts except for CONTEXT_SYSTEM level
5696 // and hope we don't OOM in the process - don't cache
5697 $sql = "SELECT c.*
5698 FROM {context} c
5699 WHERE contextlevel > ".CONTEXT_SYSTEM;
5700 $records = $DB->get_records_sql($sql);
5702 $result = array();
5703 foreach ($records as $record) {
5704 $result[$record->id] = context::create_instance_from_record($record);
5707 return $result;
5711 * Returns sql necessary for purging of stale context instances.
5713 * @static
5714 * @return string cleanup SQL
5716 protected static function get_cleanup_sql() {
5717 $sql = "
5718 SELECT c.*
5719 FROM {context} c
5720 WHERE 1=2
5723 return $sql;
5727 * Rebuild context paths and depths at system context level.
5729 * @static
5730 * @param $force
5732 protected static function build_paths($force) {
5733 global $DB;
5735 /* note: ignore $force here, we always do full test of system context */
5737 // exactly one record must exist
5738 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5740 if ($record->instanceid != 0) {
5741 debugging('Invalid system context detected');
5744 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
5745 debugging('Invalid SYSCONTEXTID detected');
5748 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5749 // fix path if necessary, initial install or path reset
5750 $record->depth = 1;
5751 $record->path = '/'.$record->id;
5752 $DB->update_record('context', $record);
5759 * User context class
5760 * @author Petr Skoda (http://skodak.org)
5761 * @since 2.2
5763 class context_user extends context {
5765 * Please use context_user::instance($userid) if you need the instance of context.
5766 * Alternatively if you know only the context id use context::instance_by_id($contextid)
5768 * @param stdClass $record
5770 protected function __construct(stdClass $record) {
5771 parent::__construct($record);
5772 if ($record->contextlevel != CONTEXT_USER) {
5773 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
5778 * Returns human readable context level name.
5780 * @static
5781 * @return string the human readable context level name.
5783 public static function get_level_name() {
5784 return get_string('user');
5788 * Returns human readable context identifier.
5790 * @param boolean $withprefix whether to prefix the name of the context with User
5791 * @param boolean $short does not apply to user context
5792 * @return string the human readable context name.
5794 public function get_context_name($withprefix = true, $short = false) {
5795 global $DB;
5797 $name = '';
5798 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
5799 if ($withprefix){
5800 $name = get_string('user').': ';
5802 $name .= fullname($user);
5804 return $name;
5808 * Returns the most relevant URL for this context.
5810 * @return moodle_url
5812 public function get_url() {
5813 global $COURSE;
5815 if ($COURSE->id == SITEID) {
5816 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
5817 } else {
5818 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
5820 return $url;
5824 * Returns array of relevant context capability records.
5826 * @return array
5828 public function get_capabilities() {
5829 global $DB;
5831 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5833 $extracaps = array('moodle/grade:viewall');
5834 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
5835 $sql = "SELECT *
5836 FROM {capabilities}
5837 WHERE contextlevel = ".CONTEXT_USER."
5838 OR name $extra";
5840 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
5844 * Returns user context instance.
5846 * @static
5847 * @param int $instanceid
5848 * @param int $strictness
5849 * @return context_user context instance
5851 public static function instance($instanceid, $strictness = MUST_EXIST) {
5852 global $DB;
5854 if ($context = context::cache_get(CONTEXT_USER, $instanceid)) {
5855 return $context;
5858 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_USER, 'instanceid'=>$instanceid))) {
5859 if ($user = $DB->get_record('user', array('id'=>$instanceid, 'deleted'=>0), 'id', $strictness)) {
5860 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
5864 if ($record) {
5865 $context = new context_user($record);
5866 context::cache_add($context);
5867 return $context;
5870 return false;
5874 * Create missing context instances at user context level
5875 * @static
5877 protected static function create_level_instances() {
5878 global $DB;
5880 $sql = "INSERT INTO {context} (contextlevel, instanceid)
5881 SELECT ".CONTEXT_USER.", u.id
5882 FROM {user} u
5883 WHERE u.deleted = 0
5884 AND NOT EXISTS (SELECT 'x'
5885 FROM {context} cx
5886 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
5887 $DB->execute($sql);
5891 * Returns sql necessary for purging of stale context instances.
5893 * @static
5894 * @return string cleanup SQL
5896 protected static function get_cleanup_sql() {
5897 $sql = "
5898 SELECT c.*
5899 FROM {context} c
5900 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
5901 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
5904 return $sql;
5908 * Rebuild context paths and depths at user context level.
5910 * @static
5911 * @param $force
5913 protected static function build_paths($force) {
5914 global $DB;
5916 // First update normal users.
5917 $path = $DB->sql_concat('?', 'id');
5918 $pathstart = '/' . SYSCONTEXTID . '/';
5919 $params = array($pathstart);
5921 if ($force) {
5922 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
5923 $params[] = $pathstart;
5924 } else {
5925 $where = "depth = 0 OR path IS NULL";
5928 $sql = "UPDATE {context}
5929 SET depth = 2,
5930 path = {$path}
5931 WHERE contextlevel = " . CONTEXT_USER . "
5932 AND ($where)";
5933 $DB->execute($sql, $params);
5939 * Course category context class
5940 * @author Petr Skoda (http://skodak.org)
5941 * @since 2.2
5943 class context_coursecat extends context {
5945 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
5946 * Alternatively if you know only the context id use context::instance_by_id($contextid)
5948 * @param stdClass $record
5950 protected function __construct(stdClass $record) {
5951 parent::__construct($record);
5952 if ($record->contextlevel != CONTEXT_COURSECAT) {
5953 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
5958 * Returns human readable context level name.
5960 * @static
5961 * @return string the human readable context level name.
5963 public static function get_level_name() {
5964 return get_string('category');
5968 * Returns human readable context identifier.
5970 * @param boolean $withprefix whether to prefix the name of the context with Category
5971 * @param boolean $short does not apply to course categories
5972 * @return string the human readable context name.
5974 public function get_context_name($withprefix = true, $short = false) {
5975 global $DB;
5977 $name = '';
5978 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
5979 if ($withprefix){
5980 $name = get_string('category').': ';
5982 $name .= format_string($category->name, true, array('context' => $this));
5984 return $name;
5988 * Returns the most relevant URL for this context.
5990 * @return moodle_url
5992 public function get_url() {
5993 return new moodle_url('/course/category.php', array('id'=>$this->_instanceid));
5997 * Returns array of relevant context capability records.
5999 * @return array
6001 public function get_capabilities() {
6002 global $DB;
6004 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6006 $params = array();
6007 $sql = "SELECT *
6008 FROM {capabilities}
6009 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6011 return $DB->get_records_sql($sql.' '.$sort, $params);
6015 * Returns course category context instance.
6017 * @static
6018 * @param int $instanceid
6019 * @param int $strictness
6020 * @return context_coursecat context instance
6022 public static function instance($instanceid, $strictness = MUST_EXIST) {
6023 global $DB;
6025 if ($context = context::cache_get(CONTEXT_COURSECAT, $instanceid)) {
6026 return $context;
6029 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSECAT, 'instanceid'=>$instanceid))) {
6030 if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), 'id,parent', $strictness)) {
6031 if ($category->parent) {
6032 $parentcontext = context_coursecat::instance($category->parent);
6033 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6034 } else {
6035 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6040 if ($record) {
6041 $context = new context_coursecat($record);
6042 context::cache_add($context);
6043 return $context;
6046 return false;
6050 * Returns immediate child contexts of category and all subcategories,
6051 * children of subcategories and courses are not returned.
6053 * @return array
6055 public function get_child_contexts() {
6056 global $DB;
6058 $sql = "SELECT ctx.*
6059 FROM {context} ctx
6060 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6061 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6062 $records = $DB->get_records_sql($sql, $params);
6064 $result = array();
6065 foreach ($records as $record) {
6066 $result[$record->id] = context::create_instance_from_record($record);
6069 return $result;
6073 * Create missing context instances at course category context level
6074 * @static
6076 protected static function create_level_instances() {
6077 global $DB;
6079 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6080 SELECT ".CONTEXT_COURSECAT.", cc.id
6081 FROM {course_categories} cc
6082 WHERE NOT EXISTS (SELECT 'x'
6083 FROM {context} cx
6084 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6085 $DB->execute($sql);
6089 * Returns sql necessary for purging of stale context instances.
6091 * @static
6092 * @return string cleanup SQL
6094 protected static function get_cleanup_sql() {
6095 $sql = "
6096 SELECT c.*
6097 FROM {context} c
6098 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6099 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6102 return $sql;
6106 * Rebuild context paths and depths at course category context level.
6108 * @static
6109 * @param $force
6111 protected static function build_paths($force) {
6112 global $DB;
6114 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6115 if ($force) {
6116 $ctxemptyclause = $emptyclause = '';
6117 } else {
6118 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6119 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6122 $base = '/'.SYSCONTEXTID;
6124 // Normal top level categories
6125 $sql = "UPDATE {context}
6126 SET depth=2,
6127 path=".$DB->sql_concat("'$base/'", 'id')."
6128 WHERE contextlevel=".CONTEXT_COURSECAT."
6129 AND EXISTS (SELECT 'x'
6130 FROM {course_categories} cc
6131 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6132 $emptyclause";
6133 $DB->execute($sql);
6135 // Deeper categories - one query per depthlevel
6136 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6137 for ($n=2; $n<=$maxdepth; $n++) {
6138 $sql = "INSERT INTO {context_temp} (id, path, depth)
6139 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6140 FROM {context} ctx
6141 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6142 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6143 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6144 $ctxemptyclause";
6145 $trans = $DB->start_delegated_transaction();
6146 $DB->delete_records('context_temp');
6147 $DB->execute($sql);
6148 context::merge_context_temp_table();
6149 $DB->delete_records('context_temp');
6150 $trans->allow_commit();
6159 * Course context class
6160 * @author Petr Skoda (http://skodak.org)
6161 * @since 2.2
6163 class context_course extends context {
6165 * Please use context_course::instance($courseid) if you need the instance of context.
6166 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6168 * @param stdClass $record
6170 protected function __construct(stdClass $record) {
6171 parent::__construct($record);
6172 if ($record->contextlevel != CONTEXT_COURSE) {
6173 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6178 * Returns human readable context level name.
6180 * @static
6181 * @return string the human readable context level name.
6183 public static function get_level_name() {
6184 return get_string('course');
6188 * Returns human readable context identifier.
6190 * @param boolean $withprefix whether to prefix the name of the context with Course
6191 * @param boolean $short whether to use the short name of the thing.
6192 * @return string the human readable context name.
6194 public function get_context_name($withprefix = true, $short = false) {
6195 global $DB;
6197 $name = '';
6198 if ($this->_instanceid == SITEID) {
6199 $name = get_string('frontpage', 'admin');
6200 } else {
6201 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6202 if ($withprefix){
6203 $name = get_string('course').': ';
6205 if ($short){
6206 $name .= format_string($course->shortname, true, array('context' => $this));
6207 } else {
6208 $name .= format_string($course->fullname);
6212 return $name;
6216 * Returns the most relevant URL for this context.
6218 * @return moodle_url
6220 public function get_url() {
6221 if ($this->_instanceid != SITEID) {
6222 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6225 return new moodle_url('/');
6229 * Returns array of relevant context capability records.
6231 * @return array
6233 public function get_capabilities() {
6234 global $DB;
6236 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6238 $params = array();
6239 $sql = "SELECT *
6240 FROM {capabilities}
6241 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6243 return $DB->get_records_sql($sql.' '.$sort, $params);
6247 * Is this context part of any course? If yes return course context.
6249 * @param bool $strict true means throw exception if not found, false means return false if not found
6250 * @return course_context context of the enclosing course, null if not found or exception
6252 public function get_course_context($strict = true) {
6253 return $this;
6257 * Returns course context instance.
6259 * @static
6260 * @param int $instanceid
6261 * @param int $strictness
6262 * @return context_course context instance
6264 public static function instance($instanceid, $strictness = MUST_EXIST) {
6265 global $DB;
6267 if ($context = context::cache_get(CONTEXT_COURSE, $instanceid)) {
6268 return $context;
6271 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$instanceid))) {
6272 if ($course = $DB->get_record('course', array('id'=>$instanceid), 'id,category', $strictness)) {
6273 if ($course->category) {
6274 $parentcontext = context_coursecat::instance($course->category);
6275 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6276 } else {
6277 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6282 if ($record) {
6283 $context = new context_course($record);
6284 context::cache_add($context);
6285 return $context;
6288 return false;
6292 * Create missing context instances at course context level
6293 * @static
6295 protected static function create_level_instances() {
6296 global $DB;
6298 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6299 SELECT ".CONTEXT_COURSE.", c.id
6300 FROM {course} c
6301 WHERE NOT EXISTS (SELECT 'x'
6302 FROM {context} cx
6303 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6304 $DB->execute($sql);
6308 * Returns sql necessary for purging of stale context instances.
6310 * @static
6311 * @return string cleanup SQL
6313 protected static function get_cleanup_sql() {
6314 $sql = "
6315 SELECT c.*
6316 FROM {context} c
6317 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6318 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6321 return $sql;
6325 * Rebuild context paths and depths at course context level.
6327 * @static
6328 * @param $force
6330 protected static function build_paths($force) {
6331 global $DB;
6333 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6334 if ($force) {
6335 $ctxemptyclause = $emptyclause = '';
6336 } else {
6337 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6338 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6341 $base = '/'.SYSCONTEXTID;
6343 // Standard frontpage
6344 $sql = "UPDATE {context}
6345 SET depth = 2,
6346 path = ".$DB->sql_concat("'$base/'", 'id')."
6347 WHERE contextlevel = ".CONTEXT_COURSE."
6348 AND EXISTS (SELECT 'x'
6349 FROM {course} c
6350 WHERE c.id = {context}.instanceid AND c.category = 0)
6351 $emptyclause";
6352 $DB->execute($sql);
6354 // standard courses
6355 $sql = "INSERT INTO {context_temp} (id, path, depth)
6356 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6357 FROM {context} ctx
6358 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6359 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6360 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6361 $ctxemptyclause";
6362 $trans = $DB->start_delegated_transaction();
6363 $DB->delete_records('context_temp');
6364 $DB->execute($sql);
6365 context::merge_context_temp_table();
6366 $DB->delete_records('context_temp');
6367 $trans->allow_commit();
6374 * Course module context class
6375 * @author Petr Skoda (http://skodak.org)
6376 * @since 2.2
6378 class context_module extends context {
6380 * Please use context_module::instance($cmid) if you need the instance of context.
6381 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6383 * @param stdClass $record
6385 protected function __construct(stdClass $record) {
6386 parent::__construct($record);
6387 if ($record->contextlevel != CONTEXT_MODULE) {
6388 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6393 * Returns human readable context level name.
6395 * @static
6396 * @return string the human readable context level name.
6398 public static function get_level_name() {
6399 return get_string('activitymodule');
6403 * Returns human readable context identifier.
6405 * @param boolean $withprefix whether to prefix the name of the context with the
6406 * module name, e.g. Forum, Glossary, etc.
6407 * @param boolean $short does not apply to module context
6408 * @return string the human readable context name.
6410 public function get_context_name($withprefix = true, $short = false) {
6411 global $DB;
6413 $name = '';
6414 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6415 FROM {course_modules} cm
6416 JOIN {modules} md ON md.id = cm.module
6417 WHERE cm.id = ?", array($this->_instanceid))) {
6418 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6419 if ($withprefix){
6420 $name = get_string('modulename', $cm->modname).': ';
6422 $name .= $mod->name;
6425 return $name;
6429 * Returns the most relevant URL for this context.
6431 * @return moodle_url
6433 public function get_url() {
6434 global $DB;
6436 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6437 FROM {course_modules} cm
6438 JOIN {modules} md ON md.id = cm.module
6439 WHERE cm.id = ?", array($this->_instanceid))) {
6440 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6443 return new moodle_url('/');
6447 * Returns array of relevant context capability records.
6449 * @return array
6451 public function get_capabilities() {
6452 global $DB, $CFG;
6454 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6456 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6457 $module = $DB->get_record('modules', array('id'=>$cm->module));
6459 $subcaps = array();
6460 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6461 if (file_exists($subpluginsfile)) {
6462 $subplugins = array(); // should be redefined in the file
6463 include($subpluginsfile);
6464 if (!empty($subplugins)) {
6465 foreach (array_keys($subplugins) as $subplugintype) {
6466 foreach (array_keys(get_plugin_list($subplugintype)) as $subpluginname) {
6467 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6473 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6474 $extracaps = array();
6475 if (file_exists($modfile)) {
6476 include_once($modfile);
6477 $modfunction = $module->name.'_get_extra_capabilities';
6478 if (function_exists($modfunction)) {
6479 $extracaps = $modfunction();
6483 $extracaps = array_merge($subcaps, $extracaps);
6484 $extra = '';
6485 list($extra, $params) = $DB->get_in_or_equal(
6486 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
6487 if (!empty($extra)) {
6488 $extra = "OR name $extra";
6490 $sql = "SELECT *
6491 FROM {capabilities}
6492 WHERE (contextlevel = ".CONTEXT_MODULE."
6493 AND (component = :component OR component = 'moodle'))
6494 $extra";
6495 $params['component'] = "mod_$module->name";
6497 return $DB->get_records_sql($sql.' '.$sort, $params);
6501 * Is this context part of any course? If yes return course context.
6503 * @param bool $strict true means throw exception if not found, false means return false if not found
6504 * @return course_context context of the enclosing course, null if not found or exception
6506 public function get_course_context($strict = true) {
6507 return $this->get_parent_context();
6511 * Returns module context instance.
6513 * @static
6514 * @param int $instanceid
6515 * @param int $strictness
6516 * @return context_module context instance
6518 public static function instance($instanceid, $strictness = MUST_EXIST) {
6519 global $DB;
6521 if ($context = context::cache_get(CONTEXT_MODULE, $instanceid)) {
6522 return $context;
6525 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$instanceid))) {
6526 if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), 'id,course', $strictness)) {
6527 $parentcontext = context_course::instance($cm->course);
6528 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
6532 if ($record) {
6533 $context = new context_module($record);
6534 context::cache_add($context);
6535 return $context;
6538 return false;
6542 * Create missing context instances at module context level
6543 * @static
6545 protected static function create_level_instances() {
6546 global $DB;
6548 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6549 SELECT ".CONTEXT_MODULE.", cm.id
6550 FROM {course_modules} cm
6551 WHERE NOT EXISTS (SELECT 'x'
6552 FROM {context} cx
6553 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
6554 $DB->execute($sql);
6558 * Returns sql necessary for purging of stale context instances.
6560 * @static
6561 * @return string cleanup SQL
6563 protected static function get_cleanup_sql() {
6564 $sql = "
6565 SELECT c.*
6566 FROM {context} c
6567 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6568 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
6571 return $sql;
6575 * Rebuild context paths and depths at module context level.
6577 * @static
6578 * @param $force
6580 protected static function build_paths($force) {
6581 global $DB;
6583 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
6584 if ($force) {
6585 $ctxemptyclause = '';
6586 } else {
6587 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6590 $sql = "INSERT INTO {context_temp} (id, path, depth)
6591 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6592 FROM {context} ctx
6593 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
6594 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
6595 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6596 $ctxemptyclause";
6597 $trans = $DB->start_delegated_transaction();
6598 $DB->delete_records('context_temp');
6599 $DB->execute($sql);
6600 context::merge_context_temp_table();
6601 $DB->delete_records('context_temp');
6602 $trans->allow_commit();
6609 * Block context class
6610 * @author Petr Skoda (http://skodak.org)
6611 * @since 2.2
6613 class context_block extends context {
6615 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6616 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6618 * @param stdClass $record
6620 protected function __construct(stdClass $record) {
6621 parent::__construct($record);
6622 if ($record->contextlevel != CONTEXT_BLOCK) {
6623 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6628 * Returns human readable context level name.
6630 * @static
6631 * @return string the human readable context level name.
6633 public static function get_level_name() {
6634 return get_string('block');
6638 * Returns human readable context identifier.
6640 * @param boolean $withprefix whether to prefix the name of the context with Block
6641 * @param boolean $short does not apply to block context
6642 * @return string the human readable context name.
6644 public function get_context_name($withprefix = true, $short = false) {
6645 global $DB, $CFG;
6647 $name = '';
6648 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
6649 global $CFG;
6650 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
6651 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
6652 $blockname = "block_$blockinstance->blockname";
6653 if ($blockobject = new $blockname()) {
6654 if ($withprefix){
6655 $name = get_string('block').': ';
6657 $name .= $blockobject->title;
6661 return $name;
6665 * Returns the most relevant URL for this context.
6667 * @return moodle_url
6669 public function get_url() {
6670 $parentcontexts = $this->get_parent_context();
6671 return $parentcontexts->get_url();
6675 * Returns array of relevant context capability records.
6677 * @return array
6679 public function get_capabilities() {
6680 global $DB;
6682 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6684 $params = array();
6685 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
6687 $extra = '';
6688 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
6689 if ($extracaps) {
6690 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6691 $extra = "OR name $extra";
6694 $sql = "SELECT *
6695 FROM {capabilities}
6696 WHERE (contextlevel = ".CONTEXT_BLOCK."
6697 AND component = :component)
6698 $extra";
6699 $params['component'] = 'block_' . $bi->blockname;
6701 return $DB->get_records_sql($sql.' '.$sort, $params);
6705 * Is this context part of any course? If yes return course context.
6707 * @param bool $strict true means throw exception if not found, false means return false if not found
6708 * @return course_context context of the enclosing course, null if not found or exception
6710 public function get_course_context($strict = true) {
6711 $parentcontext = $this->get_parent_context();
6712 return $parentcontext->get_course_context($strict);
6716 * Returns block context instance.
6718 * @static
6719 * @param int $instanceid
6720 * @param int $strictness
6721 * @return context_block context instance
6723 public static function instance($instanceid, $strictness = MUST_EXIST) {
6724 global $DB;
6726 if ($context = context::cache_get(CONTEXT_BLOCK, $instanceid)) {
6727 return $context;
6730 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$instanceid))) {
6731 if ($bi = $DB->get_record('block_instances', array('id'=>$instanceid), 'id,parentcontextid', $strictness)) {
6732 $parentcontext = context::instance_by_id($bi->parentcontextid);
6733 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
6737 if ($record) {
6738 $context = new context_block($record);
6739 context::cache_add($context);
6740 return $context;
6743 return false;
6747 * Block do not have child contexts...
6748 * @return array
6750 public function get_child_contexts() {
6751 return array();
6755 * Create missing context instances at block context level
6756 * @static
6758 protected static function create_level_instances() {
6759 global $DB;
6761 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6762 SELECT ".CONTEXT_BLOCK.", bi.id
6763 FROM {block_instances} bi
6764 WHERE NOT EXISTS (SELECT 'x'
6765 FROM {context} cx
6766 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
6767 $DB->execute($sql);
6771 * Returns sql necessary for purging of stale context instances.
6773 * @static
6774 * @return string cleanup SQL
6776 protected static function get_cleanup_sql() {
6777 $sql = "
6778 SELECT c.*
6779 FROM {context} c
6780 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
6781 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
6784 return $sql;
6788 * Rebuild context paths and depths at block context level.
6790 * @static
6791 * @param $force
6793 protected static function build_paths($force) {
6794 global $DB;
6796 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
6797 if ($force) {
6798 $ctxemptyclause = '';
6799 } else {
6800 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6803 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
6804 $sql = "INSERT INTO {context_temp} (id, path, depth)
6805 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6806 FROM {context} ctx
6807 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
6808 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
6809 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
6810 $ctxemptyclause";
6811 $trans = $DB->start_delegated_transaction();
6812 $DB->delete_records('context_temp');
6813 $DB->execute($sql);
6814 context::merge_context_temp_table();
6815 $DB->delete_records('context_temp');
6816 $trans->allow_commit();
6822 // ============== DEPRECATED FUNCTIONS ==========================================
6823 // Old context related functions were deprecated in 2.0, it is recommended
6824 // to use context classes in new code. Old function can be used when
6825 // creating patches that are supposed to be backported to older stable branches.
6826 // These deprecated functions will not be removed in near future,
6827 // before removing devs will be warned with a debugging message first,
6828 // then we will add error message and only after that we can remove the functions
6829 // completely.
6833 * Not available any more, use load_temp_course_role() instead.
6835 * @deprecated since 2.2
6836 * @param stdClass $context
6837 * @param int $roleid
6838 * @param array $accessdata
6839 * @return array
6841 function load_temp_role($context, $roleid, array $accessdata) {
6842 debugging('load_temp_role() is deprecated, please use load_temp_course_role() instead, temp role not loaded.');
6843 return $accessdata;
6847 * Not available any more, use remove_temp_course_roles() instead.
6849 * @deprecated since 2.2
6850 * @param object $context
6851 * @param array $accessdata
6852 * @return array access data
6854 function remove_temp_roles($context, array $accessdata) {
6855 debugging('remove_temp_role() is deprecated, please use remove_temp_course_roles() instead.');
6856 return $accessdata;
6860 * Returns system context or null if can not be created yet.
6862 * @deprecated since 2.2, use context_system::instance()
6863 * @param bool $cache use caching
6864 * @return context system context (null if context table not created yet)
6866 function get_system_context($cache = true) {
6867 return context_system::instance(0, IGNORE_MISSING, $cache);
6871 * Get the context instance as an object. This function will create the
6872 * context instance if it does not exist yet.
6874 * @deprecated since 2.2, use context_course::instance() or other relevant class instead
6875 * @param integer $contextlevel The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
6876 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
6877 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
6878 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
6879 * MUST_EXIST means throw exception if no record or multiple records found
6880 * @return context The context object.
6882 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
6883 $instances = (array)$instance;
6884 $contexts = array();
6886 $classname = context_helper::get_class_for_level($contextlevel);
6888 // we do not load multiple contexts any more, PAGE should be responsible for any preloading
6889 foreach ($instances as $inst) {
6890 $contexts[$inst] = $classname::instance($inst, $strictness);
6893 if (is_array($instance)) {
6894 return $contexts;
6895 } else {
6896 return $contexts[$instance];
6901 * Get a context instance as an object, from a given context id.
6903 * @deprecated since 2.2, use context::instance_by_id($id) instead
6904 * @param int $id context id
6905 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
6906 * MUST_EXIST means throw exception if no record or multiple records found
6907 * @return context|bool the context object or false if not found.
6909 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
6910 return context::instance_by_id($id, $strictness);
6914 * Recursive function which, given a context, find all parent context ids,
6915 * and return the array in reverse order, i.e. parent first, then grand
6916 * parent, etc.
6918 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
6919 * @param context $context
6920 * @param bool $includeself optional, defaults to false
6921 * @return array
6923 function get_parent_contexts(context $context, $includeself = false) {
6924 return $context->get_parent_context_ids($includeself);
6928 * Return the id of the parent of this context, or false if there is no parent (only happens if this
6929 * is the site context.)
6931 * @deprecated since 2.2, use $context->get_parent_context() instead
6932 * @param context $context
6933 * @return integer the id of the parent context.
6935 function get_parent_contextid(context $context) {
6936 if ($parent = $context->get_parent_context()) {
6937 return $parent->id;
6938 } else {
6939 return false;
6944 * Recursive function which, given a context, find all its children context ids.
6946 * For course category contexts it will return immediate children only categories and courses.
6947 * It will NOT recurse into courses or child categories.
6948 * If you want to do that, call it on the returned courses/categories.
6950 * When called for a course context, it will return the modules and blocks
6951 * displayed in the course page.
6953 * If called on a user/course/module context it _will_ populate the cache with the appropriate
6954 * contexts ;-)
6956 * @deprecated since 2.2, use $context->get_child_contexts() instead
6957 * @param context $context.
6958 * @return array Array of child records
6960 function get_child_contexts(context $context) {
6961 return $context->get_child_contexts();
6965 * Precreates all contexts including all parents
6967 * @deprecated since 2.2
6968 * @param int $contextlevel empty means all
6969 * @param bool $buildpaths update paths and depths
6970 * @return void
6972 function create_contexts($contextlevel = null, $buildpaths = true) {
6973 context_helper::create_instances($contextlevel, $buildpaths);
6977 * Remove stale context records
6979 * @deprecated since 2.2, use context_helper::cleanup_instances() instead
6980 * @return bool
6982 function cleanup_contexts() {
6983 context_helper::cleanup_instances();
6984 return true;
6988 * Populate context.path and context.depth where missing.
6990 * @deprecated since 2.2, use context_helper::build_all_paths() instead
6991 * @param bool $force force a complete rebuild of the path and depth fields, defaults to false
6992 * @return void
6994 function build_context_path($force = false) {
6995 context_helper::build_all_paths($force);
6999 * Rebuild all related context depth and path caches
7001 * @deprecated
7002 * @param array $fixcontexts array of contexts, strongtyped
7003 * @return void
7005 function rebuild_contexts(array $fixcontexts) {
7006 foreach ($fixcontexts as $fixcontext) {
7007 $fixcontext->reset_paths(false);
7009 context_helper::build_all_paths(false);
7013 * Preloads all contexts relating to a course: course, modules. Block contexts
7014 * are no longer loaded here. The contexts for all the blocks on the current
7015 * page are now efficiently loaded by {@link block_manager::load_blocks()}.
7017 * @deprecated since 2.2
7018 * @param int $courseid Course ID
7019 * @return void
7021 function preload_course_contexts($courseid) {
7022 context_helper::preload_course($courseid);
7026 * Preloads context information together with instances.
7027 * Use context_instance_preload() to strip the context info from the record and cache the context instance.
7029 * @deprecated
7030 * @param string $joinon for example 'u.id'
7031 * @param string $contextlevel context level of instance in $joinon
7032 * @param string $tablealias context table alias
7033 * @return array with two values - select and join part
7035 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
7036 $select = ", ".context_helper::get_preload_record_columns_sql($tablealias);
7037 $join = "LEFT JOIN {context} $tablealias ON ($tablealias.instanceid = $joinon AND $tablealias.contextlevel = $contextlevel)";
7038 return array($select, $join);
7042 * Preloads context information from db record and strips the cached info.
7043 * The db request has to contain both the $join and $select from context_instance_preload_sql()
7045 * @deprecated since 2.2
7046 * @param stdClass $rec
7047 * @return void (modifies $rec)
7049 function context_instance_preload(stdClass $rec) {
7050 context_helper::preload_from_record($rec);
7054 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
7056 * @deprecated since 2.2, use $context->mark_dirty() instead
7057 * @param string $path context path
7059 function mark_context_dirty($path) {
7060 global $CFG, $USER, $ACCESSLIB_PRIVATE;
7062 if (during_initial_install()) {
7063 return;
7066 // only if it is a non-empty string
7067 if (is_string($path) && $path !== '') {
7068 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+$CFG->sessiontimeout);
7069 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
7070 $ACCESSLIB_PRIVATE->dirtycontexts[$path] = 1;
7071 } else {
7072 if (CLI_SCRIPT) {
7073 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
7074 } else {
7075 if (isset($USER->access['time'])) {
7076 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
7077 } else {
7078 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
7080 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
7087 * Update the path field of the context and all dep. subcontexts that follow
7089 * Update the path field of the context and
7090 * all the dependent subcontexts that follow
7091 * the move.
7093 * The most important thing here is to be as
7094 * DB efficient as possible. This op can have a
7095 * massive impact in the DB.
7097 * @deprecated since 2.2
7098 * @param context $context context obj
7099 * @param context $newparent new parent obj
7100 * @return void
7102 function context_moved(context $context, context $newparent) {
7103 $context->update_moved($newparent);
7107 * Remove a context record and any dependent entries,
7108 * removes context from static context cache too
7110 * @deprecated since 2.2, use $context->delete_content() instead
7111 * @param int $contextlevel
7112 * @param int $instanceid
7113 * @param bool $deleterecord false means keep record for now
7114 * @return bool returns true or throws an exception
7116 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
7117 if ($deleterecord) {
7118 context_helper::delete_instance($contextlevel, $instanceid);
7119 } else {
7120 $classname = context_helper::get_class_for_level($contextlevel);
7121 if ($context = $classname::instance($instanceid, IGNORE_MISSING)) {
7122 $context->delete_content();
7126 return true;
7130 * Returns context level name
7131 * @deprecated since 2.2
7132 * @param integer $contextlevel $context->context level. One of the CONTEXT_... constants.
7133 * @return string the name for this type of context.
7135 function get_contextlevel_name($contextlevel) {
7136 return context_helper::get_level_name($contextlevel);
7140 * Prints human readable context identifier.
7142 * @deprecated since 2.2
7143 * @param context $context the context.
7144 * @param boolean $withprefix whether to prefix the name of the context with the
7145 * type of context, e.g. User, Course, Forum, etc.
7146 * @param boolean $short whether to user the short name of the thing. Only applies
7147 * to course contexts
7148 * @return string the human readable context name.
7150 function print_context_name(context $context, $withprefix = true, $short = false) {
7151 return $context->get_context_name($withprefix, $short);
7155 * Get a URL for a context, if there is a natural one. For example, for
7156 * CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
7157 * user profile page.
7159 * @deprecated since 2.2
7160 * @param context $context the context.
7161 * @return moodle_url
7163 function get_context_url(context $context) {
7164 return $context->get_url();
7168 * Is this context part of any course? if yes return course context,
7169 * if not return null or throw exception.
7171 * @deprecated since 2.2, use $context->get_course_context() instead
7172 * @param context $context
7173 * @return course_context context of the enclosing course, null if not found or exception
7175 function get_course_context(context $context) {
7176 return $context->get_course_context(true);
7180 * Returns current course id or null if outside of course based on context parameter.
7182 * @deprecated since 2.2, use $context->get_course_context instead
7183 * @param context $context
7184 * @return int|bool related course id or false
7186 function get_courseid_from_context(context $context) {
7187 if ($coursecontext = $context->get_course_context(false)) {
7188 return $coursecontext->instanceid;
7189 } else {
7190 return false;
7195 * Get an array of courses where cap requested is available
7196 * and user is enrolled, this can be relatively slow.
7198 * @deprecated since 2.2, use enrol_get_users_courses() instead
7199 * @param int $userid A user id. By default (null) checks the permissions of the current user.
7200 * @param string $cap - name of the capability
7201 * @param array $accessdata_ignored
7202 * @param bool $doanything_ignored
7203 * @param string $sort - sorting fields - prefix each fieldname with "c."
7204 * @param array $fields - additional fields you are interested in...
7205 * @param int $limit_ignored
7206 * @return array $courses - ordered array of course objects - see notes above
7208 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
7210 $courses = enrol_get_users_courses($userid, true, $fields, $sort);
7211 foreach ($courses as $id=>$course) {
7212 $context = context_course::instance($id);
7213 if (!has_capability($cap, $context, $userid)) {
7214 unset($courses[$id]);
7218 return $courses;
7222 * Extracts the relevant capabilities given a contextid.
7223 * All case based, example an instance of forum context.
7224 * Will fetch all forum related capabilities, while course contexts
7225 * Will fetch all capabilities
7227 * capabilities
7228 * `name` varchar(150) NOT NULL,
7229 * `captype` varchar(50) NOT NULL,
7230 * `contextlevel` int(10) NOT NULL,
7231 * `component` varchar(100) NOT NULL,
7233 * @deprecated since 2.2
7234 * @param context $context
7235 * @return array
7237 function fetch_context_capabilities(context $context) {
7238 return $context->get_capabilities();
7242 * Runs get_records select on context table and returns the result
7243 * Does get_records_select on the context table, and returns the results ordered
7244 * by contextlevel, and then the natural sort order within each level.
7245 * for the purpose of $select, you need to know that the context table has been
7246 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7248 * @deprecated since 2.2
7249 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7250 * @param array $params any parameters required by $select.
7251 * @return array the requested context records.
7253 function get_sorted_contexts($select, $params = array()) {
7255 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7257 global $DB;
7258 if ($select) {
7259 $select = 'WHERE ' . $select;
7261 return $DB->get_records_sql("
7262 SELECT ctx.*
7263 FROM {context} ctx
7264 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7265 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7266 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7267 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7268 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7269 $select
7270 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7271 ", $params);
7275 * This is really slow!!! do not use above course context level
7277 * @deprecated since 2.2
7278 * @param int $roleid
7279 * @param context $context
7280 * @return array
7282 function get_role_context_caps($roleid, context $context) {
7283 global $DB;
7285 //this is really slow!!!! - do not use above course context level!
7286 $result = array();
7287 $result[$context->id] = array();
7289 // first emulate the parent context capabilities merging into context
7290 $searchcontexts = array_reverse($context->get_parent_context_ids(true));
7291 foreach ($searchcontexts as $cid) {
7292 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7293 foreach ($capabilities as $cap) {
7294 if (!array_key_exists($cap->capability, $result[$context->id])) {
7295 $result[$context->id][$cap->capability] = 0;
7297 $result[$context->id][$cap->capability] += $cap->permission;
7302 // now go through the contexts below given context
7303 $searchcontexts = array_keys($context->get_child_contexts());
7304 foreach ($searchcontexts as $cid) {
7305 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7306 foreach ($capabilities as $cap) {
7307 if (!array_key_exists($cap->contextid, $result)) {
7308 $result[$cap->contextid] = array();
7310 $result[$cap->contextid][$cap->capability] = $cap->permission;
7315 return $result;
7319 * Gets a string for sql calls, searching for stuff in this context or above
7321 * NOTE: use $DB->get_in_or_equal($context->get_parent_context_ids()...
7323 * @deprecated since 2.2, $context->use get_parent_context_ids() instead
7324 * @param context $context
7325 * @return string
7327 function get_related_contexts_string(context $context) {
7329 if ($parents = $context->get_parent_context_ids()) {
7330 return (' IN ('.$context->id.','.implode(',', $parents).')');
7331 } else {
7332 return (' ='.$context->id);