2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * This file contains functions for managing user access
20 * <b>Public API vs internals</b>
22 * General users probably only care about
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...
32 * - has_any_capability()
33 * - has_all_capabilities()
34 * - require_capability()
35 * - require_login() (from moodlelib)
43 * What courses has this user access to?
44 * - get_enrolled_users()
46 * What users can do X in this context?
47 * - get_enrolled_users() - at and bellow course context
48 * - get_users_by_capability() - above course context
53 * - role_unassign_all()
55 * Advanced - for internal use only
56 * - load_all_capabilities()
57 * - reload_all_capabilities()
58 * - has_capability_in_accessdata()
59 * - get_user_access_sitewide()
60 * - load_course_context()
61 * - load_role_access_by_context()
64 * <b>Name conventions</b>
70 * Access control data is held in the "accessdata" array
71 * which - for the logged-in user, will be in $USER->access
73 * For other users can be generated and passed around (but may also be cached
74 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser).
76 * $accessdata is a multidimensional array, holding
77 * role assignments (RAs), role-capabilities-perm sets
78 * (role defs) and a list of courses we have loaded
81 * Things are keyed on "contextpaths" (the path field of
82 * the context table) for fast walking up/down the tree.
84 * $accessdata['ra'][$contextpath] = array($roleid=>$roleid)
85 * [$contextpath] = array($roleid=>$roleid)
86 * [$contextpath] = array($roleid=>$roleid)
89 * Role definitions are stored like this
90 * (no cap merge is done - so it's compact)
93 * $accessdata['rdef']["$contextpath:$roleid"]['mod/forum:viewpost'] = 1
94 * ['mod/forum:editallpost'] = -1
95 * ['mod/forum:startdiscussion'] = -1000
98 * See how has_capability_in_accessdata() walks up the tree.
100 * First we only load rdef and ra down to the course level, but not below.
101 * This keeps accessdata small and compact. Below-the-course ra/rdef
102 * are loaded as needed. We keep track of which courses we have loaded ra/rdef in
104 * $accessdata['loaded'] = array($courseid1=>1, $courseid2=>1)
107 * <b>Stale accessdata</b>
109 * For the logged-in user, accessdata is long-lived.
111 * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
112 * context paths affected by changes. Any check at-or-below
113 * a dirty context will trigger a transparent reload of accessdata.
115 * Changes at the system level will force the reload for everyone.
117 * <b>Default role caps</b>
118 * The default role assignment is not in the DB, so we
119 * add it manually to accessdata.
121 * This means that functions that work directly off the
122 * DB need to ensure that the default role caps
123 * are dealt with appropriately.
125 * @package core_access
126 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
127 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
130 defined('MOODLE_INTERNAL') ||
die();
132 /** No capability change */
133 define('CAP_INHERIT', 0);
134 /** Allow permission, overrides CAP_PREVENT defined in parent contexts */
135 define('CAP_ALLOW', 1);
136 /** Prevent permission, overrides CAP_ALLOW defined in parent contexts */
137 define('CAP_PREVENT', -1);
138 /** Prohibit permission, overrides everything in current and child contexts */
139 define('CAP_PROHIBIT', -1000);
141 /** System context level - only one instance in every system */
142 define('CONTEXT_SYSTEM', 10);
143 /** User context level - one instance for each user describing what others can do to user */
144 define('CONTEXT_USER', 30);
145 /** Course category context level - one instance for each category */
146 define('CONTEXT_COURSECAT', 40);
147 /** Course context level - one instances for each course */
148 define('CONTEXT_COURSE', 50);
149 /** Course module context level - one instance for each course module */
150 define('CONTEXT_MODULE', 70);
152 * Block context level - one instance for each block, sticky blocks are tricky
153 * because ppl think they should be able to override them at lower contexts.
154 * Any other context level instance can be parent of block context.
156 define('CONTEXT_BLOCK', 80);
158 /** Capability allow management of trusts - NOT IMPLEMENTED YET - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
159 define('RISK_MANAGETRUST', 0x0001);
160 /** Capability allows changes in system configuration - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
161 define('RISK_CONFIG', 0x0002);
162 /** Capability allows user to add scripted content - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
163 define('RISK_XSS', 0x0004);
164 /** Capability allows access to personal user information - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
165 define('RISK_PERSONAL', 0x0008);
166 /** Capability allows users to add content others may see - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
167 define('RISK_SPAM', 0x0010);
168 /** capability allows mass delete of data belonging to other users - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
169 define('RISK_DATALOSS', 0x0020);
171 /** rolename displays - the name as defined in the role definition */
172 define('ROLENAME_ORIGINAL', 0);
173 /** rolename displays - the name as defined by a role alias */
174 define('ROLENAME_ALIAS', 1);
175 /** rolename displays - Both, like this: Role alias (Original) */
176 define('ROLENAME_BOTH', 2);
177 /** rolename displays - the name as defined in the role definition and the shortname in brackets */
178 define('ROLENAME_ORIGINALANDSHORT', 3);
179 /** rolename displays - the name as defined by a role alias, in raw form suitable for editing */
180 define('ROLENAME_ALIAS_RAW', 4);
181 /** rolename displays - the name is simply short role name */
182 define('ROLENAME_SHORT', 5);
184 if (!defined('CONTEXT_CACHE_MAX_SIZE')) {
185 /** maximum size of context cache - it is possible to tweak this config.php or in any script before inclusion of context.php */
186 define('CONTEXT_CACHE_MAX_SIZE', 2500);
190 * Although this looks like a global variable, it isn't really.
192 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
193 * It is used to cache various bits of data between function calls for performance reasons.
194 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
195 * as methods of a class, instead of functions.
198 * @global stdClass $ACCESSLIB_PRIVATE
199 * @name $ACCESSLIB_PRIVATE
201 global $ACCESSLIB_PRIVATE;
202 $ACCESSLIB_PRIVATE = new stdClass();
203 $ACCESSLIB_PRIVATE->dirtycontexts
= null; // Dirty contexts cache, loaded from DB once per page
204 $ACCESSLIB_PRIVATE->accessdatabyuser
= array(); // Holds the cache of $accessdata structure for users (including $USER)
205 $ACCESSLIB_PRIVATE->rolepermissions
= array(); // role permissions cache - helps a lot with mem usage
206 $ACCESSLIB_PRIVATE->capabilities
= null; // detailed information about the capabilities
209 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
211 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
212 * accesslib's private caches. You need to do this before setting up test data,
213 * and also at the end of the tests.
218 function accesslib_clear_all_caches_for_unit_testing() {
219 global $UNITTEST, $USER;
220 if (empty($UNITTEST->running
) and !PHPUNIT_TEST
) {
221 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
224 accesslib_clear_all_caches(true);
226 unset($USER->access
);
230 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
232 * This reset does not touch global $USER.
235 * @param bool $resetcontexts
238 function accesslib_clear_all_caches($resetcontexts) {
239 global $ACCESSLIB_PRIVATE;
241 $ACCESSLIB_PRIVATE->dirtycontexts
= null;
242 $ACCESSLIB_PRIVATE->accessdatabyuser
= array();
243 $ACCESSLIB_PRIVATE->rolepermissions
= array();
244 $ACCESSLIB_PRIVATE->capabilities
= null;
246 if ($resetcontexts) {
247 context_helper
::reset_caches();
252 * Gets the accessdata for role "sitewide" (system down to course)
258 function get_role_access($roleid) {
259 global $DB, $ACCESSLIB_PRIVATE;
261 /* Get it in 1 DB query...
262 * - relevant role caps at the root and down
263 * to the course level - but not below
266 //TODO: MUC - this could be cached in shared memory to speed up first page loading, web crawlers, etc.
268 $accessdata = get_empty_accessdata();
270 $accessdata['ra']['/'.SYSCONTEXTID
] = array((int)$roleid => (int)$roleid);
273 // Overrides for the role IN ANY CONTEXTS
274 // down to COURSE - not below -
276 $sql = "SELECT ctx.path,
277 rc.capability, rc.permission
279 JOIN {role_capabilities} rc ON rc.contextid = ctx.id
280 LEFT JOIN {context} cctx
281 ON (cctx.contextlevel = ".CONTEXT_COURSE
." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
282 WHERE rc.roleid = ? AND cctx.id IS NULL";
283 $params = array($roleid);
285 // we need extra caching in CLI scripts and cron
286 $rs = $DB->get_recordset_sql($sql, $params);
287 foreach ($rs as $rd) {
288 $k = "{$rd->path}:{$roleid}";
289 $accessdata['rdef'][$k][$rd->capability
] = (int)$rd->permission
;
293 // share the role definitions
294 foreach ($accessdata['rdef'] as $k=>$unused) {
295 if (!isset($ACCESSLIB_PRIVATE->rolepermissions
[$k])) {
296 $ACCESSLIB_PRIVATE->rolepermissions
[$k] = $accessdata['rdef'][$k];
298 $accessdata['rdef_count']++
;
299 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions
[$k];
306 * Get the default guest role, this is used for guest account,
307 * search engine spiders, etc.
309 * @return stdClass role record
311 function get_guest_role() {
314 if (empty($CFG->guestroleid
)) {
315 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
316 $guestrole = array_shift($roles); // Pick the first one
317 set_config('guestroleid', $guestrole->id
);
320 debugging('Can not find any guest role!');
324 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid
))) {
327 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
328 set_config('guestroleid', '');
329 return get_guest_role();
335 * Check whether a user has a particular capability in a given context.
338 * $context = context_module::instance($cm->id);
339 * has_capability('mod/forum:replypost', $context)
341 * By default checks the capabilities of the current user, but you can pass a
342 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
344 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
345 * or capabilities with XSS, config or data loss risks.
349 * @param string $capability the name of the capability to check. For example mod/forum:view
350 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
351 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
352 * @param boolean $doanything If false, ignores effect of admin role assignment
353 * @return boolean true if the user has this capability. Otherwise false.
355 function has_capability($capability, context
$context, $user = null, $doanything = true) {
356 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
358 if (during_initial_install()) {
359 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cli/install.php" or $SCRIPT === "/$CFG->admin/cli/install_database.php") {
360 // we are in an installer - roles can not work yet
367 if (strpos($capability, 'moodle/legacy:') === 0) {
368 throw new coding_exception('Legacy capabilities can not be used any more!');
371 if (!is_bool($doanything)) {
372 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
375 // capability must exist
376 if (!$capinfo = get_capability_info($capability)) {
377 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
381 if (!isset($USER->id
)) {
382 // should never happen
386 // make sure there is a real user specified
387 if ($user === null) {
390 $userid = is_object($user) ?
$user->id
: $user;
393 // make sure forcelogin cuts off not-logged-in users if enabled
394 if (!empty($CFG->forcelogin
) and $userid == 0) {
398 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
399 if (($capinfo->captype
=== 'write') or ($capinfo->riskbitmask
& (RISK_XSS | RISK_CONFIG | RISK_DATALOSS
))) {
400 if (isguestuser($userid) or $userid == 0) {
405 // somehow make sure the user is not deleted and actually exists
407 if ($userid == $USER->id
and isset($USER->deleted
)) {
408 // this prevents one query per page, it is a bit of cheating,
409 // but hopefully session is terminated properly once user is deleted
410 if ($USER->deleted
) {
414 if (!context_user
::instance($userid, IGNORE_MISSING
)) {
415 // no user context == invalid userid
421 // context path/depth must be valid
422 if (empty($context->path
) or $context->depth
== 0) {
423 // this should not happen often, each upgrade tries to rebuild the context paths
424 debugging('Context id '.$context->id
.' does not have valid path, please use build_context_path()');
425 if (is_siteadmin($userid)) {
432 // Find out if user is admin - it is not possible to override the doanything in any way
433 // and it is not possible to switch to admin role either.
435 if (is_siteadmin($userid)) {
436 if ($userid != $USER->id
) {
439 // make sure switchrole is not used in this context
440 if (empty($USER->access
['rsw'])) {
443 $parts = explode('/', trim($context->path
, '/'));
446 foreach ($parts as $part) {
447 $path .= '/' . $part;
448 if (!empty($USER->access
['rsw'][$path])) {
456 //ok, admin switched role in this context, let's use normal access control rules
460 // Careful check for staleness...
461 $context->reload_if_dirty();
463 if ($USER->id
== $userid) {
464 if (!isset($USER->access
)) {
465 load_all_capabilities();
467 $access =& $USER->access
;
470 // make sure user accessdata is really loaded
471 get_user_accessdata($userid, true);
472 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser
[$userid];
476 // Load accessdata for below-the-course context if necessary,
477 // all contexts at and above all courses are already loaded
478 if ($context->contextlevel
!= CONTEXT_COURSE
and $coursecontext = $context->get_course_context(false)) {
479 load_course_context($userid, $coursecontext, $access);
482 return has_capability_in_accessdata($capability, $context, $access);
486 * Check if the user has any one of several capabilities from a list.
488 * This is just a utility method that calls has_capability in a loop. Try to put
489 * the capabilities that most users are likely to have first in the list for best
493 * @see has_capability()
495 * @param array $capabilities an array of capability names.
496 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
497 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
498 * @param boolean $doanything If false, ignore effect of admin role assignment
499 * @return boolean true if the user has any of these capabilities. Otherwise false.
501 function has_any_capability(array $capabilities, context
$context, $user = null, $doanything = true) {
502 foreach ($capabilities as $capability) {
503 if (has_capability($capability, $context, $user, $doanything)) {
511 * Check if the user has all the capabilities in a list.
513 * This is just a utility method that calls has_capability in a loop. Try to put
514 * the capabilities that fewest users are likely to have first in the list for best
518 * @see has_capability()
520 * @param array $capabilities an array of capability names.
521 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
522 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
523 * @param boolean $doanything If false, ignore effect of admin role assignment
524 * @return boolean true if the user has all of these capabilities. Otherwise false.
526 function has_all_capabilities(array $capabilities, context
$context, $user = null, $doanything = true) {
527 foreach ($capabilities as $capability) {
528 if (!has_capability($capability, $context, $user, $doanything)) {
536 * Check if the user is an admin at the site level.
538 * Please note that use of proper capabilities is always encouraged,
539 * this function is supposed to be used from core or for temporary hacks.
543 * @param int|stdClass $user_or_id user id or user object
544 * @return bool true if user is one of the administrators, false otherwise
546 function is_siteadmin($user_or_id = null) {
549 if ($user_or_id === null) {
553 if (empty($user_or_id)) {
556 if (!empty($user_or_id->id
)) {
557 $userid = $user_or_id->id
;
559 $userid = $user_or_id;
562 $siteadmins = explode(',', $CFG->siteadmins
);
563 return in_array($userid, $siteadmins);
567 * Returns true if user has at least one role assign
568 * of 'coursecontact' role (is potentially listed in some course descriptions).
573 function has_coursecontact_role($userid) {
576 if (empty($CFG->coursecontact
)) {
580 FROM {role_assignments}
581 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
582 return $DB->record_exists_sql($sql, array('userid'=>$userid));
586 * Does the user have a capability to do something?
588 * Walk the accessdata array and return true/false.
589 * Deals with prohibits, role switching, aggregating
592 * The main feature of here is being FAST and with no
597 * Switch Role merges with default role
598 * ------------------------------------
599 * If you are a teacher in course X, you have at least
600 * teacher-in-X + defaultloggedinuser-sitewide. So in the
601 * course you'll have techer+defaultloggedinuser.
602 * We try to mimic that in switchrole.
604 * Permission evaluation
605 * ---------------------
606 * Originally there was an extremely complicated way
607 * to determine the user access that dealt with
608 * "locality" or role assignments and role overrides.
609 * Now we simply evaluate access for each role separately
610 * and then verify if user has at least one role with allow
611 * and at the same time no role with prohibit.
614 * @param string $capability
615 * @param context $context
616 * @param array $accessdata
619 function has_capability_in_accessdata($capability, context
$context, array &$accessdata) {
622 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
623 $path = $context->path
;
624 $paths = array($path);
625 while($path = rtrim($path, '0123456789')) {
626 $path = rtrim($path, '/');
634 $switchedrole = false;
636 // Find out if role switched
637 if (!empty($accessdata['rsw'])) {
638 // From the bottom up...
639 foreach ($paths as $path) {
640 if (isset($accessdata['rsw'][$path])) {
641 // Found a switchrole assignment - check for that role _plus_ the default user role
642 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid
=>null);
643 $switchedrole = true;
649 if (!$switchedrole) {
650 // get all users roles in this context and above
651 foreach ($paths as $path) {
652 if (isset($accessdata['ra'][$path])) {
653 foreach ($accessdata['ra'][$path] as $roleid) {
654 $roles[$roleid] = null;
660 // Now find out what access is given to each role, going bottom-->up direction
662 foreach ($roles as $roleid => $ignored) {
663 foreach ($paths as $path) {
664 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
665 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
666 if ($perm === CAP_PROHIBIT
) {
667 // any CAP_PROHIBIT found means no permission for the user
670 if (is_null($roles[$roleid])) {
671 $roles[$roleid] = $perm;
675 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
676 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW
);
683 * A convenience function that tests has_capability, and displays an error if
684 * the user does not have that capability.
686 * NOTE before Moodle 2.0, this function attempted to make an appropriate
687 * require_login call before checking the capability. This is no longer the case.
688 * You must call require_login (or one of its variants) if you want to check the
689 * user is logged in, before you call this function.
691 * @see has_capability()
693 * @param string $capability the name of the capability to check. For example mod/forum:view
694 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
695 * @param int $userid A user id. By default (null) checks the permissions of the current user.
696 * @param bool $doanything If false, ignore effect of admin role assignment
697 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
698 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
699 * @return void terminates with an error if the user does not have the given capability.
701 function require_capability($capability, context
$context, $userid = null, $doanything = true,
702 $errormessage = 'nopermissions', $stringfile = '') {
703 if (!has_capability($capability, $context, $userid, $doanything)) {
704 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
709 * Return a nested array showing role assignments
710 * all relevant role capabilities for the user at
711 * site/course_category/course levels
713 * We do _not_ delve deeper than courses because the number of
714 * overrides at the module/block levels can be HUGE.
716 * [ra] => [/path][roleid]=roleid
717 * [rdef] => [/path:roleid][capability]=permission
720 * @param int $userid - the id of the user
721 * @return array access info array
723 function get_user_access_sitewide($userid) {
724 global $CFG, $DB, $ACCESSLIB_PRIVATE;
726 /* Get in a few cheap DB queries...
728 * - relevant role caps
729 * - above and within this user's RAs
730 * - below this user's RAs - limited to course level
733 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
734 $raparents = array();
735 $accessdata = get_empty_accessdata();
737 // start with the default role
738 if (!empty($CFG->defaultuserroleid
)) {
739 $syscontext = context_system
::instance();
740 $accessdata['ra'][$syscontext->path
][(int)$CFG->defaultuserroleid
] = (int)$CFG->defaultuserroleid
;
741 $raparents[$CFG->defaultuserroleid
][$syscontext->id
] = $syscontext->id
;
744 // load the "default frontpage role"
745 if (!empty($CFG->defaultfrontpageroleid
)) {
746 $frontpagecontext = context_course
::instance(get_site()->id
);
747 if ($frontpagecontext->path
) {
748 $accessdata['ra'][$frontpagecontext->path
][(int)$CFG->defaultfrontpageroleid
] = (int)$CFG->defaultfrontpageroleid
;
749 $raparents[$CFG->defaultfrontpageroleid
][$frontpagecontext->id
] = $frontpagecontext->id
;
753 // preload every assigned role at and above course context
754 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
755 FROM {role_assignments} ra
757 ON ctx.id = ra.contextid
758 LEFT JOIN {block_instances} bi
759 ON (ctx.contextlevel = ".CONTEXT_BLOCK
." AND bi.id = ctx.instanceid)
760 LEFT JOIN {context} bpctx
761 ON (bpctx.id = bi.parentcontextid)
762 WHERE ra.userid = :userid
763 AND (ctx.contextlevel <= ".CONTEXT_COURSE
." OR bpctx.contextlevel < ".CONTEXT_COURSE
.")";
764 $params = array('userid'=>$userid);
765 $rs = $DB->get_recordset_sql($sql, $params);
766 foreach ($rs as $ra) {
767 // RAs leafs are arrays to support multi-role assignments...
768 $accessdata['ra'][$ra->path
][(int)$ra->roleid
] = (int)$ra->roleid
;
769 $raparents[$ra->roleid
][$ra->contextid
] = $ra->contextid
;
773 if (empty($raparents)) {
777 // now get overrides of interesting roles in all interesting child contexts
778 // hopefully we will not run out of SQL limits here,
779 // users would have to have very many roles at/above course context...
784 foreach ($raparents as $roleid=>$ras) {
786 list($sqlcids, $cids) = $DB->get_in_or_equal($ras, SQL_PARAMS_NAMED
, 'c'.$cp.'_');
787 $params = array_merge($params, $cids);
788 $params['r'.$cp] = $roleid;
789 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
790 FROM {role_capabilities} rc
792 ON (ctx.id = rc.contextid)
795 AND (ctx.id = pctx.id
796 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
797 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
798 LEFT JOIN {block_instances} bi
799 ON (ctx.contextlevel = ".CONTEXT_BLOCK
." AND bi.id = ctx.instanceid)
800 LEFT JOIN {context} bpctx
801 ON (bpctx.id = bi.parentcontextid)
802 WHERE rc.roleid = :r{$cp}
803 AND (ctx.contextlevel <= ".CONTEXT_COURSE
." OR bpctx.contextlevel < ".CONTEXT_COURSE
.")
807 // fixed capability order is necessary for rdef dedupe
808 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
810 foreach ($rs as $rd) {
811 $k = $rd->path
.':'.$rd->roleid
;
812 $accessdata['rdef'][$k][$rd->capability
] = (int)$rd->permission
;
816 // share the role definitions
817 foreach ($accessdata['rdef'] as $k=>$unused) {
818 if (!isset($ACCESSLIB_PRIVATE->rolepermissions
[$k])) {
819 $ACCESSLIB_PRIVATE->rolepermissions
[$k] = $accessdata['rdef'][$k];
821 $accessdata['rdef_count']++
;
822 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions
[$k];
829 * Add to the access ctrl array the data needed by a user for a given course.
831 * This function injects all course related access info into the accessdata array.
834 * @param int $userid the id of the user
835 * @param context_course $coursecontext course context
836 * @param array $accessdata accessdata array (modified)
837 * @return void modifies $accessdata parameter
839 function load_course_context($userid, context_course
$coursecontext, &$accessdata) {
840 global $DB, $CFG, $ACCESSLIB_PRIVATE;
842 if (empty($coursecontext->path
)) {
843 // weird, this should not happen
847 if (isset($accessdata['loaded'][$coursecontext->instanceid
])) {
848 // already loaded, great!
854 if (empty($userid)) {
855 if (!empty($CFG->notloggedinroleid
)) {
856 $roles[$CFG->notloggedinroleid
] = $CFG->notloggedinroleid
;
859 } else if (isguestuser($userid)) {
860 if ($guestrole = get_guest_role()) {
861 $roles[$guestrole->id
] = $guestrole->id
;
865 // Interesting role assignments at, above and below the course context
866 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'pc_');
867 $params['userid'] = $userid;
868 $params['children'] = $coursecontext->path
."/%";
869 $sql = "SELECT ra.*, ctx.path
870 FROM {role_assignments} ra
871 JOIN {context} ctx ON ra.contextid = ctx.id
872 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
873 $rs = $DB->get_recordset_sql($sql, $params);
875 // add missing role definitions
876 foreach ($rs as $ra) {
877 $accessdata['ra'][$ra->path
][(int)$ra->roleid
] = (int)$ra->roleid
;
878 $roles[$ra->roleid
] = $ra->roleid
;
882 // add the "default frontpage role" when on the frontpage
883 if (!empty($CFG->defaultfrontpageroleid
)) {
884 $frontpagecontext = context_course
::instance(get_site()->id
);
885 if ($frontpagecontext->id
== $coursecontext->id
) {
886 $roles[$CFG->defaultfrontpageroleid
] = $CFG->defaultfrontpageroleid
;
890 // do not forget the default role
891 if (!empty($CFG->defaultuserroleid
)) {
892 $roles[$CFG->defaultuserroleid
] = $CFG->defaultuserroleid
;
897 // weird, default roles must be missing...
898 $accessdata['loaded'][$coursecontext->instanceid
] = 1;
902 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
903 $params = array('c'=>$coursecontext->id
);
904 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'pc_');
905 $params = array_merge($params, $rparams);
906 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED
, 'r_');
907 $params = array_merge($params, $rparams);
909 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
910 FROM {role_capabilities} rc
912 ON (ctx.id = rc.contextid)
915 AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
916 WHERE rc.roleid $roleids
917 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
918 $rs = $DB->get_recordset_sql($sql, $params);
921 foreach ($rs as $rd) {
922 $k = $rd->path
.':'.$rd->roleid
;
923 if (isset($accessdata['rdef'][$k])) {
926 $newrdefs[$k][$rd->capability
] = (int)$rd->permission
;
930 // share new role definitions
931 foreach ($newrdefs as $k=>$unused) {
932 if (!isset($ACCESSLIB_PRIVATE->rolepermissions
[$k])) {
933 $ACCESSLIB_PRIVATE->rolepermissions
[$k] = $newrdefs[$k];
935 $accessdata['rdef_count']++
;
936 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions
[$k];
939 $accessdata['loaded'][$coursecontext->instanceid
] = 1;
941 // we want to deduplicate the USER->access from time to time, this looks like a good place,
942 // because we have to do it before the end of session
943 dedupe_user_access();
947 * Add to the access ctrl array the data needed by a role for a given context.
949 * The data is added in the rdef key.
950 * This role-centric function is useful for role_switching
951 * and temporary course roles.
954 * @param int $roleid the id of the user
955 * @param context $context needs path!
956 * @param array $accessdata accessdata array (is modified)
959 function load_role_access_by_context($roleid, context
$context, &$accessdata) {
960 global $DB, $ACCESSLIB_PRIVATE;
962 /* Get the relevant rolecaps into rdef
963 * - relevant role caps
968 if (empty($context->path
)) {
969 // weird, this should not happen
973 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'pc_');
974 $params['roleid'] = $roleid;
975 $params['childpath'] = $context->path
.'/%';
977 $sql = "SELECT ctx.path, rc.capability, rc.permission
978 FROM {role_capabilities} rc
979 JOIN {context} ctx ON (rc.contextid = ctx.id)
980 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
981 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
982 $rs = $DB->get_recordset_sql($sql, $params);
985 foreach ($rs as $rd) {
986 $k = $rd->path
.':'.$roleid;
987 if (isset($accessdata['rdef'][$k])) {
990 $newrdefs[$k][$rd->capability
] = (int)$rd->permission
;
994 // share new role definitions
995 foreach ($newrdefs as $k=>$unused) {
996 if (!isset($ACCESSLIB_PRIVATE->rolepermissions
[$k])) {
997 $ACCESSLIB_PRIVATE->rolepermissions
[$k] = $newrdefs[$k];
999 $accessdata['rdef_count']++
;
1000 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions
[$k];
1005 * Returns empty accessdata structure.
1008 * @return array empt accessdata
1010 function get_empty_accessdata() {
1011 $accessdata = array(); // named list
1012 $accessdata['ra'] = array();
1013 $accessdata['rdef'] = array();
1014 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
1015 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
1016 $accessdata['loaded'] = array(); // loaded course contexts
1017 $accessdata['time'] = time();
1018 $accessdata['rsw'] = array();
1024 * Get accessdata for a given user.
1027 * @param int $userid
1028 * @param bool $preloadonly true means do not return access array
1029 * @return array accessdata
1031 function get_user_accessdata($userid, $preloadonly=false) {
1032 global $CFG, $ACCESSLIB_PRIVATE, $USER;
1034 if (!empty($USER->acces
['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions
)) {
1035 // share rdef from USER session with rolepermissions cache in order to conserve memory
1036 foreach($USER->acces
['rdef'] as $k=>$v) {
1037 $ACCESSLIB_PRIVATE->rolepermissions
[$k] =& $USER->acces
['rdef'][$k];
1039 $ACCESSLIB_PRIVATE->accessdatabyuser
[$USER->id
] = $USER->acces
;
1042 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser
[$userid])) {
1043 if (empty($userid)) {
1044 if (!empty($CFG->notloggedinroleid
)) {
1045 $accessdata = get_role_access($CFG->notloggedinroleid
);
1048 return get_empty_accessdata();
1051 } else if (isguestuser($userid)) {
1052 if ($guestrole = get_guest_role()) {
1053 $accessdata = get_role_access($guestrole->id
);
1056 return get_empty_accessdata();
1060 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1063 $ACCESSLIB_PRIVATE->accessdatabyuser
[$userid] = $accessdata;
1069 return $ACCESSLIB_PRIVATE->accessdatabyuser
[$userid];
1074 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1075 * this function looks for contexts with the same overrides and shares them.
1080 function dedupe_user_access() {
1084 // no session in CLI --> no compression necessary
1088 if (empty($USER->access
['rdef_count'])) {
1089 // weird, this should not happen
1093 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1094 if ($USER->access
['rdef_count'] - $USER->access
['rdef_lcc'] > 10) {
1095 // do not compress after each change, wait till there is more stuff to be done
1100 foreach ($USER->access
['rdef'] as $k=>$def) {
1101 $hash = sha1(serialize($def));
1102 if (isset($hashmap[$hash])) {
1103 $USER->access
['rdef'][$k] =& $hashmap[$hash];
1105 $hashmap[$hash] =& $USER->access
['rdef'][$k];
1109 $USER->access
['rdef_lcc'] = $USER->access
['rdef_count'];
1113 * A convenience function to completely load all the capabilities
1114 * for the current user. It is called from has_capability() and functions change permissions.
1116 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1117 * @see check_enrolment_plugins()
1122 function load_all_capabilities() {
1125 // roles not installed yet - we are in the middle of installation
1126 if (during_initial_install()) {
1130 if (!isset($USER->id
)) {
1131 // this should not happen
1135 unset($USER->access
);
1136 $USER->access
= get_user_accessdata($USER->id
);
1138 // deduplicate the overrides to minimize session size
1139 dedupe_user_access();
1141 // Clear to force a refresh
1142 unset($USER->mycourses
);
1144 // init/reset internal enrol caches - active course enrolments and temp access
1145 $USER->enrol
= array('enrolled'=>array(), 'tempguest'=>array());
1149 * A convenience function to completely reload all the capabilities
1150 * for the current user when roles have been updated in a relevant
1151 * context -- but PRESERVING switchroles and loginas.
1152 * This function resets all accesslib and context caches.
1154 * That is - completely transparent to the user.
1156 * Note: reloads $USER->access completely.
1161 function reload_all_capabilities() {
1162 global $USER, $DB, $ACCESSLIB_PRIVATE;
1166 if (!empty($USER->access
['rsw'])) {
1167 $sw = $USER->access
['rsw'];
1170 accesslib_clear_all_caches(true);
1171 unset($USER->access
);
1172 $ACCESSLIB_PRIVATE->dirtycontexts
= array(); // prevent dirty flags refetching on this page
1174 load_all_capabilities();
1176 foreach ($sw as $path => $roleid) {
1177 if ($record = $DB->get_record('context', array('path'=>$path))) {
1178 $context = context
::instance_by_id($record->id
);
1179 role_switch($roleid, $context);
1185 * Adds a temp role to current USER->access array.
1187 * Useful for the "temporary guest" access we grant to logged-in users.
1188 * This is useful for enrol plugins only.
1191 * @param context_course $coursecontext
1192 * @param int $roleid
1195 function load_temp_course_role(context_course
$coursecontext, $roleid) {
1196 global $USER, $SITE;
1198 if (empty($roleid)) {
1199 debugging('invalid role specified in load_temp_course_role()');
1203 if ($coursecontext->instanceid
== $SITE->id
) {
1204 debugging('Can not use temp roles on the frontpage');
1208 if (!isset($USER->access
)) {
1209 load_all_capabilities();
1212 $coursecontext->reload_if_dirty();
1214 if (isset($USER->access
['ra'][$coursecontext->path
][$roleid])) {
1218 // load course stuff first
1219 load_course_context($USER->id
, $coursecontext, $USER->access
);
1221 $USER->access
['ra'][$coursecontext->path
][(int)$roleid] = (int)$roleid;
1223 load_role_access_by_context($roleid, $coursecontext, $USER->access
);
1227 * Removes any extra guest roles from current USER->access array.
1228 * This is useful for enrol plugins only.
1231 * @param context_course $coursecontext
1234 function remove_temp_course_roles(context_course
$coursecontext) {
1235 global $DB, $USER, $SITE;
1237 if ($coursecontext->instanceid
== $SITE->id
) {
1238 debugging('Can not use temp roles on the frontpage');
1242 if (empty($USER->access
['ra'][$coursecontext->path
])) {
1243 //no roles here, weird
1247 $sql = "SELECT DISTINCT ra.roleid AS id
1248 FROM {role_assignments} ra
1249 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1250 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id
, 'userid'=>$USER->id
));
1252 $USER->access
['ra'][$coursecontext->path
] = array();
1253 foreach($ras as $r) {
1254 $USER->access
['ra'][$coursecontext->path
][(int)$r->id
] = (int)$r->id
;
1259 * Returns array of all role archetypes.
1263 function get_role_archetypes() {
1265 'manager' => 'manager',
1266 'coursecreator' => 'coursecreator',
1267 'editingteacher' => 'editingteacher',
1268 'teacher' => 'teacher',
1269 'student' => 'student',
1272 'frontpage' => 'frontpage'
1277 * Assign the defaults found in this capability definition to roles that have
1278 * the corresponding legacy capabilities assigned to them.
1280 * @param string $capability
1281 * @param array $legacyperms an array in the format (example):
1282 * 'guest' => CAP_PREVENT,
1283 * 'student' => CAP_ALLOW,
1284 * 'teacher' => CAP_ALLOW,
1285 * 'editingteacher' => CAP_ALLOW,
1286 * 'coursecreator' => CAP_ALLOW,
1287 * 'manager' => CAP_ALLOW
1288 * @return boolean success or failure.
1290 function assign_legacy_capabilities($capability, $legacyperms) {
1292 $archetypes = get_role_archetypes();
1294 foreach ($legacyperms as $type => $perm) {
1296 $systemcontext = context_system
::instance();
1297 if ($type === 'admin') {
1298 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1302 if (!array_key_exists($type, $archetypes)) {
1303 print_error('invalidlegacy', '', '', $type);
1306 if ($roles = get_archetype_roles($type)) {
1307 foreach ($roles as $role) {
1308 // Assign a site level capability.
1309 if (!assign_capability($capability, $perm, $role->id
, $systemcontext->id
)) {
1319 * Verify capability risks.
1321 * @param stdClass $capability a capability - a row from the capabilities table.
1322 * @return boolean whether this capability is safe - that is, whether people with the
1323 * safeoverrides capability should be allowed to change it.
1325 function is_safe_capability($capability) {
1326 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL
) & $capability->riskbitmask
);
1330 * Get the local override (if any) for a given capability in a role in a context
1332 * @param int $roleid
1333 * @param int $contextid
1334 * @param string $capability
1335 * @return stdClass local capability override
1337 function get_local_override($roleid, $contextid, $capability) {
1339 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1343 * Returns context instance plus related course and cm instances
1345 * @param int $contextid
1346 * @return array of ($context, $course, $cm)
1348 function get_context_info_array($contextid) {
1351 $context = context
::instance_by_id($contextid, MUST_EXIST
);
1355 if ($context->contextlevel
== CONTEXT_COURSE
) {
1356 $course = $DB->get_record('course', array('id'=>$context->instanceid
), '*', MUST_EXIST
);
1358 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
1359 $cm = get_coursemodule_from_id('', $context->instanceid
, 0, false, MUST_EXIST
);
1360 $course = $DB->get_record('course', array('id'=>$cm->course
), '*', MUST_EXIST
);
1362 } else if ($context->contextlevel
== CONTEXT_BLOCK
) {
1363 $parent = $context->get_parent_context();
1365 if ($parent->contextlevel
== CONTEXT_COURSE
) {
1366 $course = $DB->get_record('course', array('id'=>$parent->instanceid
), '*', MUST_EXIST
);
1367 } else if ($parent->contextlevel
== CONTEXT_MODULE
) {
1368 $cm = get_coursemodule_from_id('', $parent->instanceid
, 0, false, MUST_EXIST
);
1369 $course = $DB->get_record('course', array('id'=>$cm->course
), '*', MUST_EXIST
);
1373 return array($context, $course, $cm);
1377 * Function that creates a role
1379 * @param string $name role name
1380 * @param string $shortname role short name
1381 * @param string $description role description
1382 * @param string $archetype
1383 * @return int id or dml_exception
1385 function create_role($name, $shortname, $description, $archetype = '') {
1388 if (strpos($archetype, 'moodle/legacy:') !== false) {
1389 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1392 // verify role archetype actually exists
1393 $archetypes = get_role_archetypes();
1394 if (empty($archetypes[$archetype])) {
1398 // Insert the role record.
1399 $role = new stdClass();
1400 $role->name
= $name;
1401 $role->shortname
= $shortname;
1402 $role->description
= $description;
1403 $role->archetype
= $archetype;
1405 //find free sortorder number
1406 $role->sortorder
= $DB->get_field('role', 'MAX(sortorder) + 1', array());
1407 if (empty($role->sortorder
)) {
1408 $role->sortorder
= 1;
1410 $id = $DB->insert_record('role', $role);
1416 * Function that deletes a role and cleanups up after it
1418 * @param int $roleid id of role to delete
1419 * @return bool always true
1421 function delete_role($roleid) {
1424 // first unssign all users
1425 role_unassign_all(array('roleid'=>$roleid));
1427 // cleanup all references to this role, ignore errors
1428 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1429 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1430 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1431 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1432 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1433 $DB->delete_records('role_names', array('roleid'=>$roleid));
1434 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1436 // finally delete the role itself
1437 // get this before the name is gone for logging
1438 $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
1440 $DB->delete_records('role', array('id'=>$roleid));
1442 add_to_log(SITEID
, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
1448 * Function to write context specific overrides, or default capabilities.
1450 * NOTE: use $context->mark_dirty() after this
1452 * @param string $capability string name
1453 * @param int $permission CAP_ constants
1454 * @param int $roleid role id
1455 * @param int|context $contextid context id
1456 * @param bool $overwrite
1457 * @return bool always true or exception
1459 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1462 if ($contextid instanceof context
) {
1463 $context = $contextid;
1465 $context = context
::instance_by_id($contextid);
1468 if (empty($permission) ||
$permission == CAP_INHERIT
) { // if permission is not set
1469 unassign_capability($capability, $roleid, $context->id
);
1473 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id
, 'roleid'=>$roleid, 'capability'=>$capability));
1475 if ($existing and !$overwrite) { // We want to keep whatever is there already
1479 $cap = new stdClass();
1480 $cap->contextid
= $context->id
;
1481 $cap->roleid
= $roleid;
1482 $cap->capability
= $capability;
1483 $cap->permission
= $permission;
1484 $cap->timemodified
= time();
1485 $cap->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
1488 $cap->id
= $existing->id
;
1489 $DB->update_record('role_capabilities', $cap);
1491 if ($DB->record_exists('context', array('id'=>$context->id
))) {
1492 $DB->insert_record('role_capabilities', $cap);
1499 * Unassign a capability from a role.
1501 * NOTE: use $context->mark_dirty() after this
1503 * @param string $capability the name of the capability
1504 * @param int $roleid the role id
1505 * @param int|context $contextid null means all contexts
1506 * @return boolean true or exception
1508 function unassign_capability($capability, $roleid, $contextid = null) {
1511 if (!empty($contextid)) {
1512 if ($contextid instanceof context
) {
1513 $context = $contextid;
1515 $context = context
::instance_by_id($contextid);
1517 // delete from context rel, if this is the last override in this context
1518 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id
));
1520 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1526 * Get the roles that have a given capability assigned to it
1528 * This function does not resolve the actual permission of the capability.
1529 * It just checks for permissions and overrides.
1530 * Use get_roles_with_cap_in_context() if resolution is required.
1532 * @param string $capability capability name (string)
1533 * @param string $permission optional, the permission defined for this capability
1534 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1535 * @param stdClass $context null means any
1536 * @return array of role records
1538 function get_roles_with_capability($capability, $permission = null, $context = null) {
1542 $contexts = $context->get_parent_context_ids(true);
1543 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED
, 'ctx');
1544 $contextsql = "AND rc.contextid $insql";
1551 $permissionsql = " AND rc.permission = :permission";
1552 $params['permission'] = $permission;
1554 $permissionsql = '';
1559 WHERE r.id IN (SELECT rc.roleid
1560 FROM {role_capabilities} rc
1561 WHERE rc.capability = :capname
1564 $params['capname'] = $capability;
1567 return $DB->get_records_sql($sql, $params);
1571 * This function makes a role-assignment (a role for a user in a particular context)
1573 * @param int $roleid the role of the id
1574 * @param int $userid userid
1575 * @param int|context $contextid id of the context
1576 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1577 * @param int $itemid id of enrolment/auth plugin
1578 * @param string $timemodified defaults to current time
1579 * @return int new/existing id of the assignment
1581 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1584 // first of all detect if somebody is using old style parameters
1585 if ($contextid === 0 or is_numeric($component)) {
1586 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1589 // now validate all parameters
1590 if (empty($roleid)) {
1591 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1594 if (empty($userid)) {
1595 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1599 if (strpos($component, '_') === false) {
1600 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1604 if ($component !== '' and strpos($component, '_') === false) {
1605 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1609 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1610 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1613 if ($contextid instanceof context
) {
1614 $context = $contextid;
1616 $context = context
::instance_by_id($contextid, MUST_EXIST
);
1619 if (!$timemodified) {
1620 $timemodified = time();
1623 // Check for existing entry
1624 // TODO: Revisit this sql_empty() use once Oracle bindings are improved. MDL-29765
1625 $component = ($component === '') ?
$DB->sql_empty() : $component;
1626 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id
, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1629 // role already assigned - this should not happen
1630 if (count($ras) > 1) {
1631 // very weird - remove all duplicates!
1632 $ra = array_shift($ras);
1633 foreach ($ras as $r) {
1634 $DB->delete_records('role_assignments', array('id'=>$r->id
));
1640 // actually there is no need to update, reset anything or trigger any event, so just return
1644 // Create a new entry
1645 $ra = new stdClass();
1646 $ra->roleid
= $roleid;
1647 $ra->contextid
= $context->id
;
1648 $ra->userid
= $userid;
1649 $ra->component
= $component;
1650 $ra->itemid
= $itemid;
1651 $ra->timemodified
= $timemodified;
1652 $ra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
1654 $ra->id
= $DB->insert_record('role_assignments', $ra);
1656 // mark context as dirty - again expensive, but needed
1657 $context->mark_dirty();
1659 if (!empty($USER->id
) && $USER->id
== $userid) {
1660 // If the user is the current user, then do full reload of capabilities too.
1661 reload_all_capabilities();
1664 events_trigger('role_assigned', $ra);
1670 * Removes one role assignment
1672 * @param int $roleid
1673 * @param int $userid
1674 * @param int|context $contextid
1675 * @param string $component
1676 * @param int $itemid
1679 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1680 // first make sure the params make sense
1681 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1682 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1686 if (strpos($component, '_') === false) {
1687 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1691 if ($component !== '' and strpos($component, '_') === false) {
1692 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1696 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1700 * Removes multiple role assignments, parameters may contain:
1701 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1703 * @param array $params role assignment parameters
1704 * @param bool $subcontexts unassign in subcontexts too
1705 * @param bool $includemanual include manual role assignments too
1708 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1709 global $USER, $CFG, $DB;
1712 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1715 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1716 foreach ($params as $key=>$value) {
1717 if (!in_array($key, $allowed)) {
1718 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1722 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1723 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1726 if ($includemanual) {
1727 if (!isset($params['component']) or $params['component'] === '') {
1728 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1733 if (empty($params['contextid'])) {
1734 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1738 // TODO: Revisit this sql_empty() use once Oracle bindings are improved. MDL-29765
1739 if (isset($params['component'])) {
1740 $params['component'] = ($params['component'] === '') ?
$DB->sql_empty() : $params['component'];
1742 $ras = $DB->get_records('role_assignments', $params);
1743 foreach($ras as $ra) {
1744 $DB->delete_records('role_assignments', array('id'=>$ra->id
));
1745 if ($context = context
::instance_by_id($ra->contextid
, IGNORE_MISSING
)) {
1746 // this is a bit expensive but necessary
1747 $context->mark_dirty();
1748 // If the user is the current user, then do full reload of capabilities too.
1749 if (!empty($USER->id
) && $USER->id
== $ra->userid
) {
1750 reload_all_capabilities();
1753 events_trigger('role_unassigned', $ra);
1757 // process subcontexts
1758 if ($subcontexts and $context = context
::instance_by_id($params['contextid'], IGNORE_MISSING
)) {
1759 if ($params['contextid'] instanceof context
) {
1760 $context = $params['contextid'];
1762 $context = context
::instance_by_id($params['contextid'], IGNORE_MISSING
);
1766 $contexts = $context->get_child_contexts();
1768 foreach($contexts as $context) {
1769 $mparams['contextid'] = $context->id
;
1770 $ras = $DB->get_records('role_assignments', $mparams);
1771 foreach($ras as $ra) {
1772 $DB->delete_records('role_assignments', array('id'=>$ra->id
));
1773 // this is a bit expensive but necessary
1774 $context->mark_dirty();
1775 // If the user is the current user, then do full reload of capabilities too.
1776 if (!empty($USER->id
) && $USER->id
== $ra->userid
) {
1777 reload_all_capabilities();
1779 events_trigger('role_unassigned', $ra);
1785 // do this once more for all manual role assignments
1786 if ($includemanual) {
1787 $params['component'] = '';
1788 role_unassign_all($params, $subcontexts, false);
1793 * Determines if a user is currently logged in
1799 function isloggedin() {
1802 return (!empty($USER->id
));
1806 * Determines if a user is logged in as real guest user with username 'guest'.
1810 * @param int|object $user mixed user object or id, $USER if not specified
1811 * @return bool true if user is the real guest user, false if not logged in or other user
1813 function isguestuser($user = null) {
1814 global $USER, $DB, $CFG;
1816 // make sure we have the user id cached in config table, because we are going to use it a lot
1817 if (empty($CFG->siteguest
)) {
1818 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id
))) {
1819 // guest does not exist yet, weird
1822 set_config('siteguest', $guestid);
1824 if ($user === null) {
1828 if ($user === null) {
1829 // happens when setting the $USER
1832 } else if (is_numeric($user)) {
1833 return ($CFG->siteguest
== $user);
1835 } else if (is_object($user)) {
1836 if (empty($user->id
)) {
1837 return false; // not logged in means is not be guest
1839 return ($CFG->siteguest
== $user->id
);
1843 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1848 * Does user have a (temporary or real) guest access to course?
1852 * @param context $context
1853 * @param stdClass|int $user
1856 function is_guest(context
$context, $user = null) {
1859 // first find the course context
1860 $coursecontext = $context->get_course_context();
1862 // make sure there is a real user specified
1863 if ($user === null) {
1864 $userid = isset($USER->id
) ?
$USER->id
: 0;
1866 $userid = is_object($user) ?
$user->id
: $user;
1869 if (isguestuser($userid)) {
1870 // can not inspect or be enrolled
1874 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1875 // viewing users appear out of nowhere, they are neither guests nor participants
1879 // consider only real active enrolments here
1880 if (is_enrolled($coursecontext, $user, '', true)) {
1888 * Returns true if the user has moodle/course:view capability in the course,
1889 * this is intended for admins, managers (aka small admins), inspectors, etc.
1893 * @param context $context
1894 * @param int|stdClass $user if null $USER is used
1895 * @param string $withcapability extra capability name
1898 function is_viewing(context
$context, $user = null, $withcapability = '') {
1899 // first find the course context
1900 $coursecontext = $context->get_course_context();
1902 if (isguestuser($user)) {
1907 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1908 // admins are allowed to inspect courses
1912 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1913 // site admins always have the capability, but the enrolment above blocks
1921 * Returns true if user is enrolled (is participating) in course
1922 * this is intended for students and teachers.
1924 * Since 2.2 the result for active enrolments and current user are cached.
1926 * @package core_enrol
1929 * @param context $context
1930 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1931 * @param string $withcapability extra capability name
1932 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1935 function is_enrolled(context
$context, $user = null, $withcapability = '', $onlyactive = false) {
1938 // first find the course context
1939 $coursecontext = $context->get_course_context();
1941 // make sure there is a real user specified
1942 if ($user === null) {
1943 $userid = isset($USER->id
) ?
$USER->id
: 0;
1945 $userid = is_object($user) ?
$user->id
: $user;
1948 if (empty($userid)) {
1951 } else if (isguestuser($userid)) {
1952 // guest account can not be enrolled anywhere
1956 if ($coursecontext->instanceid
== SITEID
) {
1957 // everybody participates on frontpage
1959 // try cached info first - the enrolled flag is set only when active enrolment present
1960 if ($USER->id
== $userid) {
1961 $coursecontext->reload_if_dirty();
1962 if (isset($USER->enrol
['enrolled'][$coursecontext->instanceid
])) {
1963 if ($USER->enrol
['enrolled'][$coursecontext->instanceid
] > time()) {
1964 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1973 // look for active enrolments only
1974 $until = enrol_get_enrolment_end($coursecontext->instanceid
, $userid);
1976 if ($until === false) {
1980 if ($USER->id
== $userid) {
1982 $until = ENROL_MAX_TIMESTAMP
;
1984 $USER->enrol
['enrolled'][$coursecontext->instanceid
] = $until;
1985 if (isset($USER->enrol
['tempguest'][$coursecontext->instanceid
])) {
1986 unset($USER->enrol
['tempguest'][$coursecontext->instanceid
]);
1987 remove_temp_course_roles($coursecontext);
1992 // any enrolment is good for us here, even outdated, disabled or inactive
1994 FROM {user_enrolments} ue
1995 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1996 JOIN {user} u ON u.id = ue.userid
1997 WHERE ue.userid = :userid AND u.deleted = 0";
1998 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid
);
1999 if (!$DB->record_exists_sql($sql, $params)) {
2005 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2013 * Returns true if the user is able to access the course.
2015 * This function is in no way, shape, or form a substitute for require_login.
2016 * It should only be used in circumstances where it is not possible to call require_login
2017 * such as the navigation.
2019 * This function checks many of the methods of access to a course such as the view
2020 * capability, enrollments, and guest access. It also makes use of the cache
2021 * generated by require_login for guest access.
2023 * The flags within the $USER object that are used here should NEVER be used outside
2024 * of this function can_access_course and require_login. Doing so WILL break future
2027 * @param stdClass $course record
2028 * @param stdClass|int|null $user user record or id, current user if null
2029 * @param string $withcapability Check for this capability as well.
2030 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2031 * @return boolean Returns true if the user is able to access the course
2033 function can_access_course(stdClass
$course, $user = null, $withcapability = '', $onlyactive = false) {
2036 // this function originally accepted $coursecontext parameter
2037 if ($course instanceof context
) {
2038 if ($course instanceof context_course
) {
2039 debugging('deprecated context parameter, please use $course record');
2040 $coursecontext = $course;
2041 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid
));
2043 debugging('Invalid context parameter, please use $course record');
2047 $coursecontext = context_course
::instance($course->id
);
2050 if (!isset($USER->id
)) {
2051 // should never happen
2055 // make sure there is a user specified
2056 if ($user === null) {
2057 $userid = $USER->id
;
2059 $userid = is_object($user) ?
$user->id
: $user;
2063 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2067 if ($userid == $USER->id
) {
2068 if (!empty($USER->access
['rsw'][$coursecontext->path
])) {
2069 // the fact that somebody switched role means they can access the course no matter to what role they switched
2074 if (!$course->visible
and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2078 if (is_viewing($coursecontext, $userid)) {
2082 if ($userid != $USER->id
) {
2083 // for performance reasons we do not verify temporary guest access for other users, sorry...
2084 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2087 // === from here we deal only with $USER ===
2089 $coursecontext->reload_if_dirty();
2091 if (isset($USER->enrol
['enrolled'][$course->id
])) {
2092 if ($USER->enrol
['enrolled'][$course->id
] > time()) {
2096 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2097 if ($USER->enrol
['tempguest'][$course->id
] > time()) {
2102 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2106 // if not enrolled try to gain temporary guest access
2107 $instances = $DB->get_records('enrol', array('courseid'=>$course->id
, 'status'=>ENROL_INSTANCE_ENABLED
), 'sortorder, id ASC');
2108 $enrols = enrol_get_plugins(true);
2109 foreach($instances as $instance) {
2110 if (!isset($enrols[$instance->enrol
])) {
2113 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2114 $until = $enrols[$instance->enrol
]->try_guestaccess($instance);
2115 if ($until !== false and $until > time()) {
2116 $USER->enrol
['tempguest'][$course->id
] = $until;
2120 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2121 unset($USER->enrol
['tempguest'][$course->id
]);
2122 remove_temp_course_roles($coursecontext);
2129 * Returns array with sql code and parameters returning all ids
2130 * of users enrolled into course.
2132 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2134 * @package core_enrol
2137 * @param context $context
2138 * @param string $withcapability
2139 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2140 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2141 * @return array list($sql, $params)
2143 function get_enrolled_sql(context
$context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2146 // use unique prefix just in case somebody makes some SQL magic with the result
2149 $prefix = 'eu'.$i.'_';
2151 // first find the course context
2152 $coursecontext = $context->get_course_context();
2154 $isfrontpage = ($coursecontext->instanceid
== SITEID
);
2160 list($contextids, $contextpaths) = get_context_info_list($context);
2162 // get all relevant capability info for all roles
2163 if ($withcapability) {
2164 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED
, 'ctx');
2165 $cparams['cap'] = $withcapability;
2168 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2169 FROM {role_capabilities} rc
2170 JOIN {context} ctx on rc.contextid = ctx.id
2171 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2172 $rcs = $DB->get_records_sql($sql, $cparams);
2173 foreach ($rcs as $rc) {
2174 $defs[$rc->path
][$rc->roleid
] = $rc->permission
;
2178 if (!empty($defs)) {
2179 foreach ($contextpaths as $path) {
2180 if (empty($defs[$path])) {
2183 foreach($defs[$path] as $roleid => $perm) {
2184 if ($perm == CAP_PROHIBIT
) {
2185 $access[$roleid] = CAP_PROHIBIT
;
2188 if (!isset($access[$roleid])) {
2189 $access[$roleid] = (int)$perm;
2197 // make lists of roles that are needed and prohibited
2198 $needed = array(); // one of these is enough
2199 $prohibited = array(); // must not have any of these
2200 foreach ($access as $roleid => $perm) {
2201 if ($perm == CAP_PROHIBIT
) {
2202 unset($needed[$roleid]);
2203 $prohibited[$roleid] = true;
2204 } else if ($perm == CAP_ALLOW
and empty($prohibited[$roleid])) {
2205 $needed[$roleid] = true;
2209 $defaultuserroleid = isset($CFG->defaultuserroleid
) ?
$CFG->defaultuserroleid
: 0;
2210 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid
) ?
$CFG->defaultfrontpageroleid
: 0;
2215 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2217 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2218 // everybody not having prohibit has the capability
2220 } else if (empty($needed)) {
2224 if (!empty($prohibited[$defaultuserroleid])) {
2226 } else if (!empty($needed[$defaultuserroleid])) {
2227 // everybody not having prohibit has the capability
2229 } else if (empty($needed)) {
2235 // nobody can match so return some SQL that does not return any results
2236 $wheres[] = "1 = 2";
2241 $ctxids = implode(',', $contextids);
2242 $roleids = implode(',', array_keys($needed));
2243 $joins[] = "JOIN {role_assignments} {$prefix}ra3 ON ({$prefix}ra3.userid = {$prefix}u.id AND {$prefix}ra3.roleid IN ($roleids) AND {$prefix}ra3.contextid IN ($ctxids))";
2247 $ctxids = implode(',', $contextids);
2248 $roleids = implode(',', array_keys($prohibited));
2249 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4 ON ({$prefix}ra4.userid = {$prefix}u.id AND {$prefix}ra4.roleid IN ($roleids) AND {$prefix}ra4.contextid IN ($ctxids))";
2250 $wheres[] = "{$prefix}ra4.id IS NULL";
2254 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2255 $params["{$prefix}gmid"] = $groupid;
2261 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2262 $params["{$prefix}gmid"] = $groupid;
2266 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2267 $params["{$prefix}guestid"] = $CFG->siteguest
;
2270 // all users are "enrolled" on the frontpage
2272 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2273 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2274 $params[$prefix.'courseid'] = $coursecontext->instanceid
;
2277 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2278 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2279 $now = round(time(), -2); // rounding helps caching in DB
2280 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED
,
2281 $prefix.'active'=>ENROL_USER_ACTIVE
,
2282 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2286 $joins = implode("\n", $joins);
2287 $wheres = "WHERE ".implode(" AND ", $wheres);
2289 $sql = "SELECT DISTINCT {$prefix}u.id
2290 FROM {user} {$prefix}u
2294 return array($sql, $params);
2298 * Returns list of users enrolled into course.
2300 * @package core_enrol
2303 * @param context $context
2304 * @param string $withcapability
2305 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2306 * @param string $userfields requested user record fields
2307 * @param string $orderby
2308 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2309 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2310 * @return array of user records
2312 function get_enrolled_users(context
$context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = '', $limitfrom = 0, $limitnum = 0) {
2315 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2316 $sql = "SELECT $userfields
2318 JOIN ($esql) je ON je.id = u.id
2319 WHERE u.deleted = 0";
2322 $sql = "$sql ORDER BY $orderby";
2324 $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
2327 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2331 * Counts list of users enrolled into course (as per above function)
2333 * @package core_enrol
2336 * @param context $context
2337 * @param string $withcapability
2338 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2339 * @return array of user records
2341 function count_enrolled_users(context
$context, $withcapability = '', $groupid = 0) {
2344 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2345 $sql = "SELECT count(u.id)
2347 JOIN ($esql) je ON je.id = u.id
2348 WHERE u.deleted = 0";
2350 return $DB->count_records_sql($sql, $params);
2354 * Loads the capability definitions for the component (from file).
2356 * Loads the capability definitions for the component (from file). If no
2357 * capabilities are defined for the component, we simply return an empty array.
2360 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2361 * @return array array of capabilities
2363 function load_capability_def($component) {
2364 $defpath = get_component_directory($component).'/db/access.php';
2366 $capabilities = array();
2367 if (file_exists($defpath)) {
2369 if (!empty($
{$component.'_capabilities'})) {
2370 // BC capability array name
2371 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2372 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2373 $capabilities = $
{$component.'_capabilities'};
2377 return $capabilities;
2381 * Gets the capabilities that have been cached in the database for this component.
2384 * @param string $component - examples: 'moodle', 'mod_forum'
2385 * @return array array of capabilities
2387 function get_cached_capabilities($component = 'moodle') {
2389 return $DB->get_records('capabilities', array('component'=>$component));
2393 * Returns default capabilities for given role archetype.
2395 * @param string $archetype role archetype
2398 function get_default_capabilities($archetype) {
2406 $defaults = array();
2407 $components = array();
2408 $allcaps = $DB->get_records('capabilities');
2410 foreach ($allcaps as $cap) {
2411 if (!in_array($cap->component
, $components)) {
2412 $components[] = $cap->component
;
2413 $alldefs = array_merge($alldefs, load_capability_def($cap->component
));
2416 foreach($alldefs as $name=>$def) {
2417 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2418 if (isset($def['archetypes'])) {
2419 if (isset($def['archetypes'][$archetype])) {
2420 $defaults[$name] = $def['archetypes'][$archetype];
2422 // 'legacy' is for backward compatibility with 1.9 access.php
2424 if (isset($def['legacy'][$archetype])) {
2425 $defaults[$name] = $def['legacy'][$archetype];
2434 * Reset role capabilities to default according to selected role archetype.
2435 * If no archetype selected, removes all capabilities.
2437 * @param int $roleid
2440 function reset_role_capabilities($roleid) {
2443 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST
);
2444 $defaultcaps = get_default_capabilities($role->archetype
);
2446 $systemcontext = context_system
::instance();
2448 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2450 foreach($defaultcaps as $cap=>$permission) {
2451 assign_capability($cap, $permission, $roleid, $systemcontext->id
);
2456 * Updates the capabilities table with the component capability definitions.
2457 * If no parameters are given, the function updates the core moodle
2460 * Note that the absence of the db/access.php capabilities definition file
2461 * will cause any stored capabilities for the component to be removed from
2465 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2466 * @return boolean true if success, exception in case of any problems
2468 function update_capabilities($component = 'moodle') {
2469 global $DB, $OUTPUT;
2471 $storedcaps = array();
2473 $filecaps = load_capability_def($component);
2474 foreach($filecaps as $capname=>$unused) {
2475 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2476 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2480 $cachedcaps = get_cached_capabilities($component);
2482 foreach ($cachedcaps as $cachedcap) {
2483 array_push($storedcaps, $cachedcap->name
);
2484 // update risk bitmasks and context levels in existing capabilities if needed
2485 if (array_key_exists($cachedcap->name
, $filecaps)) {
2486 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name
])) {
2487 $filecaps[$cachedcap->name
]['riskbitmask'] = 0; // no risk if not specified
2489 if ($cachedcap->captype
!= $filecaps[$cachedcap->name
]['captype']) {
2490 $updatecap = new stdClass();
2491 $updatecap->id
= $cachedcap->id
;
2492 $updatecap->captype
= $filecaps[$cachedcap->name
]['captype'];
2493 $DB->update_record('capabilities', $updatecap);
2495 if ($cachedcap->riskbitmask
!= $filecaps[$cachedcap->name
]['riskbitmask']) {
2496 $updatecap = new stdClass();
2497 $updatecap->id
= $cachedcap->id
;
2498 $updatecap->riskbitmask
= $filecaps[$cachedcap->name
]['riskbitmask'];
2499 $DB->update_record('capabilities', $updatecap);
2502 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name
])) {
2503 $filecaps[$cachedcap->name
]['contextlevel'] = 0; // no context level defined
2505 if ($cachedcap->contextlevel
!= $filecaps[$cachedcap->name
]['contextlevel']) {
2506 $updatecap = new stdClass();
2507 $updatecap->id
= $cachedcap->id
;
2508 $updatecap->contextlevel
= $filecaps[$cachedcap->name
]['contextlevel'];
2509 $DB->update_record('capabilities', $updatecap);
2515 // Are there new capabilities in the file definition?
2518 foreach ($filecaps as $filecap => $def) {
2520 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2521 if (!array_key_exists('riskbitmask', $def)) {
2522 $def['riskbitmask'] = 0; // no risk if not specified
2524 $newcaps[$filecap] = $def;
2527 // Add new capabilities to the stored definition.
2528 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2529 foreach ($newcaps as $capname => $capdef) {
2530 $capability = new stdClass();
2531 $capability->name
= $capname;
2532 $capability->captype
= $capdef['captype'];
2533 $capability->contextlevel
= $capdef['contextlevel'];
2534 $capability->component
= $component;
2535 $capability->riskbitmask
= $capdef['riskbitmask'];
2537 $DB->insert_record('capabilities', $capability, false);
2539 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2540 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2541 foreach ($rolecapabilities as $rolecapability){
2542 //assign_capability will update rather than insert if capability exists
2543 if (!assign_capability($capname, $rolecapability->permission
,
2544 $rolecapability->roleid
, $rolecapability->contextid
, true)){
2545 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2549 // we ignore archetype key if we have cloned permissions
2550 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2551 assign_legacy_capabilities($capname, $capdef['archetypes']);
2552 // 'legacy' is for backward compatibility with 1.9 access.php
2553 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2554 assign_legacy_capabilities($capname, $capdef['legacy']);
2557 // Are there any capabilities that have been removed from the file
2558 // definition that we need to delete from the stored capabilities and
2559 // role assignments?
2560 capabilities_cleanup($component, $filecaps);
2562 // reset static caches
2563 accesslib_clear_all_caches(false);
2569 * Deletes cached capabilities that are no longer needed by the component.
2570 * Also unassigns these capabilities from any roles that have them.
2573 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2574 * @param array $newcapdef array of the new capability definitions that will be
2575 * compared with the cached capabilities
2576 * @return int number of deprecated capabilities that have been removed
2578 function capabilities_cleanup($component, $newcapdef = null) {
2583 if ($cachedcaps = get_cached_capabilities($component)) {
2584 foreach ($cachedcaps as $cachedcap) {
2585 if (empty($newcapdef) ||
2586 array_key_exists($cachedcap->name
, $newcapdef) === false) {
2588 // Remove from capabilities cache.
2589 $DB->delete_records('capabilities', array('name'=>$cachedcap->name
));
2591 // Delete from roles.
2592 if ($roles = get_roles_with_capability($cachedcap->name
)) {
2593 foreach($roles as $role) {
2594 if (!unassign_capability($cachedcap->name
, $role->id
)) {
2595 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name
, 'role'=>$role->name
));
2602 return $removedcount;
2606 * Returns an array of all the known types of risk
2607 * The array keys can be used, for example as CSS class names, or in calls to
2608 * print_risk_icon. The values are the corresponding RISK_ constants.
2610 * @return array all the known types of risk.
2612 function get_all_risks() {
2614 'riskmanagetrust' => RISK_MANAGETRUST
,
2615 'riskconfig' => RISK_CONFIG
,
2616 'riskxss' => RISK_XSS
,
2617 'riskpersonal' => RISK_PERSONAL
,
2618 'riskspam' => RISK_SPAM
,
2619 'riskdataloss' => RISK_DATALOSS
,
2624 * Return a link to moodle docs for a given capability name
2626 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2627 * @return string the human-readable capability name as a link to Moodle Docs.
2629 function get_capability_docs_link($capability) {
2630 $url = get_docs_url('Capabilities/' . $capability->name
);
2631 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name
) . '</a>';
2635 * This function pulls out all the resolved capabilities (overrides and
2636 * defaults) of a role used in capability overrides in contexts at a given
2639 * @param int $roleid
2640 * @param context $context
2641 * @param string $cap capability, optional, defaults to ''
2642 * @return array Array of capabilities
2644 function role_context_capabilities($roleid, context
$context, $cap = '') {
2647 $contexts = $context->get_parent_context_ids(true);
2648 $contexts = '('.implode(',', $contexts).')';
2650 $params = array($roleid);
2653 $search = " AND rc.capability = ? ";
2660 FROM {role_capabilities} rc, {context} c
2661 WHERE rc.contextid in $contexts
2663 AND rc.contextid = c.id $search
2664 ORDER BY c.contextlevel DESC, rc.capability DESC";
2666 $capabilities = array();
2668 if ($records = $DB->get_records_sql($sql, $params)) {
2669 // We are traversing via reverse order.
2670 foreach ($records as $record) {
2671 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2672 if (!isset($capabilities[$record->capability
]) ||
$record->permission
<-500) {
2673 $capabilities[$record->capability
] = $record->permission
;
2677 return $capabilities;
2681 * Constructs array with contextids as first parameter and context paths,
2682 * in both cases bottom top including self.
2685 * @param context $context
2688 function get_context_info_list(context
$context) {
2689 $contextids = explode('/', ltrim($context->path
, '/'));
2690 $contextpaths = array();
2691 $contextids2 = $contextids;
2692 while ($contextids2) {
2693 $contextpaths[] = '/' . implode('/', $contextids2);
2694 array_pop($contextids2);
2696 return array($contextids, $contextpaths);
2700 * Check if context is the front page context or a context inside it
2702 * Returns true if this context is the front page context, or a context inside it,
2705 * @param context $context a context object.
2708 function is_inside_frontpage(context
$context) {
2709 $frontpagecontext = context_course
::instance(SITEID
);
2710 return strpos($context->path
. '/', $frontpagecontext->path
. '/') === 0;
2714 * Returns capability information (cached)
2716 * @param string $capabilityname
2717 * @return stdClass or null if capability not found
2719 function get_capability_info($capabilityname) {
2720 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2722 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2724 if (empty($ACCESSLIB_PRIVATE->capabilities
)) {
2725 $ACCESSLIB_PRIVATE->capabilities
= array();
2726 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2727 foreach ($caps as $cap) {
2728 $capname = $cap->name
;
2731 $cap->riskbitmask
= (int)$cap->riskbitmask
;
2732 $ACCESSLIB_PRIVATE->capabilities
[$capname] = $cap;
2736 return isset($ACCESSLIB_PRIVATE->capabilities
[$capabilityname]) ?
$ACCESSLIB_PRIVATE->capabilities
[$capabilityname] : null;
2740 * Returns the human-readable, translated version of the capability.
2741 * Basically a big switch statement.
2743 * @param string $capabilityname e.g. mod/choice:readresponses
2746 function get_capability_string($capabilityname) {
2748 // Typical capability name is 'plugintype/pluginname:capabilityname'
2749 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2751 if ($type === 'moodle') {
2752 $component = 'core_role';
2753 } else if ($type === 'quizreport') {
2755 $component = 'quiz_'.$name;
2757 $component = $type.'_'.$name;
2760 $stringname = $name.':'.$capname;
2762 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2763 return get_string($stringname, $component);
2766 $dir = get_component_directory($component);
2767 if (!file_exists($dir)) {
2768 // plugin broken or does not exist, do not bother with printing of debug message
2769 return $capabilityname.' ???';
2772 // something is wrong in plugin, better print debug
2773 return get_string($stringname, $component);
2777 * This gets the mod/block/course/core etc strings.
2779 * @param string $component
2780 * @param int $contextlevel
2781 * @return string|bool String is success, false if failed
2783 function get_component_string($component, $contextlevel) {
2785 if ($component === 'moodle' or $component === 'core') {
2786 switch ($contextlevel) {
2787 // TODO: this should probably use context level names instead
2788 case CONTEXT_SYSTEM
: return get_string('coresystem');
2789 case CONTEXT_USER
: return get_string('users');
2790 case CONTEXT_COURSECAT
: return get_string('categories');
2791 case CONTEXT_COURSE
: return get_string('course');
2792 case CONTEXT_MODULE
: return get_string('activities');
2793 case CONTEXT_BLOCK
: return get_string('block');
2794 default: print_error('unknowncontext');
2798 list($type, $name) = normalize_component($component);
2799 $dir = get_plugin_directory($type, $name);
2800 if (!file_exists($dir)) {
2801 // plugin not installed, bad luck, there is no way to find the name
2802 return $component.' ???';
2806 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2807 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2808 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2809 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2810 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2811 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2812 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2813 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2815 if (get_string_manager()->string_exists('pluginname', $component)) {
2816 return get_string('activity').': '.get_string('pluginname', $component);
2818 return get_string('activity').': '.get_string('modulename', $component);
2820 default: return get_string('pluginname', $component);
2825 * Gets the list of roles assigned to this context and up (parents)
2826 * from the list of roles that are visible on user profile page
2827 * and participants page.
2829 * @param context $context
2832 function get_profile_roles(context
$context) {
2835 if (empty($CFG->profileroles
)) {
2839 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles
), SQL_PARAMS_NAMED
, 'a');
2840 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'p');
2841 $params = array_merge($params, $cparams);
2843 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2844 FROM {role_assignments} ra, {role} r
2845 WHERE r.id = ra.roleid
2846 AND ra.contextid $contextlist
2848 ORDER BY r.sortorder ASC";
2850 return $DB->get_records_sql($sql, $params);
2854 * Gets the list of roles assigned to this context and up (parents)
2856 * @param context $context
2859 function get_roles_used_in_context(context
$context) {
2862 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true));
2864 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2865 FROM {role_assignments} ra, {role} r
2866 WHERE r.id = ra.roleid
2867 AND ra.contextid $contextlist
2868 ORDER BY r.sortorder ASC";
2870 return $DB->get_records_sql($sql, $params);
2874 * This function is used to print roles column in user profile page.
2875 * It is using the CFG->profileroles to limit the list to only interesting roles.
2876 * (The permission tab has full details of user role assignments.)
2878 * @param int $userid
2879 * @param int $courseid
2882 function get_user_roles_in_course($userid, $courseid) {
2885 if (empty($CFG->profileroles
)) {
2889 if ($courseid == SITEID
) {
2890 $context = context_system
::instance();
2892 $context = context_course
::instance($courseid);
2895 if (empty($CFG->profileroles
)) {
2899 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles
), SQL_PARAMS_NAMED
, 'a');
2900 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'p');
2901 $params = array_merge($params, $cparams);
2903 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2904 FROM {role_assignments} ra, {role} r
2905 WHERE r.id = ra.roleid
2906 AND ra.contextid $contextlist
2908 AND ra.userid = :userid
2909 ORDER BY r.sortorder ASC";
2910 $params['userid'] = $userid;
2914 if ($roles = $DB->get_records_sql($sql, $params)) {
2915 foreach ($roles as $userrole) {
2916 $rolenames[$userrole->id
] = $userrole->name
;
2919 $rolenames = role_fix_names($rolenames, $context); // Substitute aliases
2921 foreach ($rolenames as $roleid => $rolename) {
2922 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot
.'/user/index.php?contextid='.$context->id
.'&roleid='.$roleid.'">'.$rolename.'</a>';
2924 $rolestring = implode(',', $rolenames);
2931 * Checks if a user can assign users to a particular role in this context
2933 * @param context $context
2934 * @param int $targetroleid - the id of the role you want to assign users to
2937 function user_can_assign(context
$context, $targetroleid) {
2940 // First check to see if the user is a site administrator.
2941 if (is_siteadmin()) {
2945 // Check if user has override capability.
2946 // If not return false.
2947 if (!has_capability('moodle/role:assign', $context)) {
2950 // pull out all active roles of this user from this context(or above)
2951 if ($userroles = get_user_roles($context)) {
2952 foreach ($userroles as $userrole) {
2953 // if any in the role_allow_override table, then it's ok
2954 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid
, 'allowassign'=>$targetroleid))) {
2964 * Returns all site roles in correct sort order.
2968 function get_all_roles() {
2970 return $DB->get_records('role', null, 'sortorder ASC');
2974 * Returns roles of a specified archetype
2976 * @param string $archetype
2977 * @return array of full role records
2979 function get_archetype_roles($archetype) {
2981 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2985 * Gets all the user roles assigned in this context, or higher contexts
2986 * this is mainly used when checking if a user can assign a role, or overriding a role
2987 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2988 * allow_override tables
2990 * @param context $context
2991 * @param int $userid
2992 * @param bool $checkparentcontexts defaults to true
2993 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2996 function get_user_roles(context
$context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2999 if (empty($userid)) {
3000 if (empty($USER->id
)) {
3003 $userid = $USER->id
;
3006 if ($checkparentcontexts) {
3007 $contextids = $context->get_parent_context_ids();
3009 $contextids = array();
3011 $contextids[] = $context->id
;
3013 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM
);
3015 array_unshift($params, $userid);
3017 $sql = "SELECT ra.*, r.name, r.shortname
3018 FROM {role_assignments} ra, {role} r, {context} c
3020 AND ra.roleid = r.id
3021 AND ra.contextid = c.id
3022 AND ra.contextid $contextids
3025 return $DB->get_records_sql($sql ,$params);
3029 * Like get_user_roles, but adds in the authenticated user role, and the front
3030 * page roles, if applicable.
3032 * @param context $context the context.
3033 * @param int $userid optional. Defaults to $USER->id
3034 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3036 function get_user_roles_with_special(context
$context, $userid = 0) {
3039 if (empty($userid)) {
3040 if (empty($USER->id
)) {
3043 $userid = $USER->id
;
3046 $ras = get_user_roles($context, $userid);
3048 // Add front-page role if relevant.
3049 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid
) ?
$CFG->defaultfrontpageroleid
: 0;
3050 $isfrontpage = ($context->contextlevel
== CONTEXT_COURSE
&& $context->instanceid
== SITEID
) ||
3051 is_inside_frontpage($context);
3052 if ($defaultfrontpageroleid && $isfrontpage) {
3053 $frontpagecontext = context_course
::instance(SITEID
);
3054 $ra = new stdClass();
3055 $ra->userid
= $userid;
3056 $ra->contextid
= $frontpagecontext->id
;
3057 $ra->roleid
= $defaultfrontpageroleid;
3061 // Add authenticated user role if relevant.
3062 $defaultuserroleid = isset($CFG->defaultuserroleid
) ?
$CFG->defaultuserroleid
: 0;
3063 if ($defaultuserroleid && !isguestuser($userid)) {
3064 $systemcontext = context_system
::instance();
3065 $ra = new stdClass();
3066 $ra->userid
= $userid;
3067 $ra->contextid
= $systemcontext->id
;
3068 $ra->roleid
= $defaultuserroleid;
3076 * Creates a record in the role_allow_override table
3078 * @param int $sroleid source roleid
3079 * @param int $troleid target roleid
3082 function allow_override($sroleid, $troleid) {
3085 $record = new stdClass();
3086 $record->roleid
= $sroleid;
3087 $record->allowoverride
= $troleid;
3088 $DB->insert_record('role_allow_override', $record);
3092 * Creates a record in the role_allow_assign table
3094 * @param int $fromroleid source roleid
3095 * @param int $targetroleid target roleid
3098 function allow_assign($fromroleid, $targetroleid) {
3101 $record = new stdClass();
3102 $record->roleid
= $fromroleid;
3103 $record->allowassign
= $targetroleid;
3104 $DB->insert_record('role_allow_assign', $record);
3108 * Creates a record in the role_allow_switch table
3110 * @param int $fromroleid source roleid
3111 * @param int $targetroleid target roleid
3114 function allow_switch($fromroleid, $targetroleid) {
3117 $record = new stdClass();
3118 $record->roleid
= $fromroleid;
3119 $record->allowswitch
= $targetroleid;
3120 $DB->insert_record('role_allow_switch', $record);
3124 * Gets a list of roles that this user can assign in this context
3126 * @param context $context the context.
3127 * @param int $rolenamedisplay the type of role name to display. One of the
3128 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3129 * @param bool $withusercounts if true, count the number of users with each role.
3130 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3131 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3132 * if $withusercounts is true, returns a list of three arrays,
3133 * $rolenames, $rolecounts, and $nameswithcounts.
3135 function get_assignable_roles(context
$context, $rolenamedisplay = ROLENAME_ALIAS
, $withusercounts = false, $user = null) {
3138 // make sure there is a real user specified
3139 if ($user === null) {
3140 $userid = isset($USER->id
) ?
$USER->id
: 0;
3142 $userid = is_object($user) ?
$user->id
: $user;
3145 if (!has_capability('moodle/role:assign', $context, $userid)) {
3146 if ($withusercounts) {
3147 return array(array(), array(), array());
3153 $parents = $context->get_parent_context_ids(true);
3154 $contexts = implode(',' , $parents);
3158 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT
or $rolenamedisplay == ROLENAME_SHORT
) {
3159 $extrafields .= ', r.shortname';
3162 if ($withusercounts) {
3163 $extrafields = ', (SELECT count(u.id)
3164 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3165 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3167 $params['conid'] = $context->id
;
3170 if (is_siteadmin($userid)) {
3171 // show all roles allowed in this context to admins
3172 $assignrestriction = "";
3174 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3175 FROM {role_allow_assign} raa
3176 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3177 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3178 ) ar ON ar.id = r.id";
3179 $params['userid'] = $userid;
3181 $params['contextlevel'] = $context->contextlevel
;
3182 $sql = "SELECT r.id, r.name $extrafields
3185 JOIN {role_context_levels} rcl ON r.id = rcl.roleid
3186 WHERE rcl.contextlevel = :contextlevel
3187 ORDER BY r.sortorder ASC";
3188 $roles = $DB->get_records_sql($sql, $params);
3190 $rolenames = array();
3191 foreach ($roles as $role) {
3192 if ($rolenamedisplay == ROLENAME_SHORT
) {
3193 $rolenames[$role->id
] = $role->shortname
;
3196 $rolenames[$role->id
] = $role->name
;
3197 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT
) {
3198 $rolenames[$role->id
] .= ' (' . $role->shortname
. ')';
3201 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT
and $rolenamedisplay != ROLENAME_SHORT
) {
3202 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3205 if (!$withusercounts) {
3209 $rolecounts = array();
3210 $nameswithcounts = array();
3211 foreach ($roles as $role) {
3212 $nameswithcounts[$role->id
] = $rolenames[$role->id
] . ' (' . $roles[$role->id
]->usercount
. ')';
3213 $rolecounts[$role->id
] = $roles[$role->id
]->usercount
;
3215 return array($rolenames, $rolecounts, $nameswithcounts);
3219 * Gets a list of roles that this user can switch to in a context
3221 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3222 * This function just process the contents of the role_allow_switch table. You also need to
3223 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3225 * @param context $context a context.
3226 * @return array an array $roleid => $rolename.
3228 function get_switchable_roles(context
$context) {
3234 if (!is_siteadmin()) {
3235 // Admins are allowed to switch to any role with.
3236 // Others are subject to the additional constraint that the switch-to role must be allowed by
3237 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3238 $parents = $context->get_parent_context_ids(true);
3239 $contexts = implode(',' , $parents);
3241 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3242 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3243 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3244 $params['userid'] = $USER->id
;
3249 FROM (SELECT DISTINCT rc.roleid
3250 FROM {role_capabilities} rc
3253 JOIN {role} r ON r.id = idlist.roleid
3254 ORDER BY r.sortorder";
3256 $rolenames = $DB->get_records_sql_menu($query, $params);
3257 return role_fix_names($rolenames, $context, ROLENAME_ALIAS
);
3261 * Gets a list of roles that this user can override in this context.
3263 * @param context $context the context.
3264 * @param int $rolenamedisplay the type of role name to display. One of the
3265 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3266 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3267 * @return array if $withcounts is false, then an array $roleid => $rolename.
3268 * if $withusercounts is true, returns a list of three arrays,
3269 * $rolenames, $rolecounts, and $nameswithcounts.
3271 function get_overridable_roles(context
$context, $rolenamedisplay = ROLENAME_ALIAS
, $withcounts = false) {
3274 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3276 return array(array(), array(), array());
3282 $parents = $context->get_parent_context_ids(true);
3283 $contexts = implode(',' , $parents);
3287 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT
) {
3288 $extrafields .= ', ro.shortname';
3291 $params['userid'] = $USER->id
;
3293 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3294 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3295 $params['conid'] = $context->id
;
3298 if (is_siteadmin()) {
3299 // show all roles to admins
3300 $roles = $DB->get_records_sql("
3301 SELECT ro.id, ro.name$extrafields
3303 ORDER BY ro.sortorder ASC", $params);
3306 $roles = $DB->get_records_sql("
3307 SELECT ro.id, ro.name$extrafields
3309 JOIN (SELECT DISTINCT r.id
3311 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3312 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3313 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3314 ) inline_view ON ro.id = inline_view.id
3315 ORDER BY ro.sortorder ASC", $params);
3318 $rolenames = array();
3319 foreach ($roles as $role) {
3320 $rolenames[$role->id
] = $role->name
;
3321 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT
) {
3322 $rolenames[$role->id
] .= ' (' . $role->shortname
. ')';
3325 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT
) {
3326 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3333 $rolecounts = array();
3334 $nameswithcounts = array();
3335 foreach ($roles as $role) {
3336 $nameswithcounts[$role->id
] = $rolenames[$role->id
] . ' (' . $roles[$role->id
]->overridecount
. ')';
3337 $rolecounts[$role->id
] = $roles[$role->id
]->overridecount
;
3339 return array($rolenames, $rolecounts, $nameswithcounts);
3343 * Create a role menu suitable for default role selection in enrol plugins.
3345 * @package core_enrol
3347 * @param context $context
3348 * @param int $addroleid current or default role - always added to list
3349 * @return array roleid=>localised role name
3351 function get_default_enrol_roles(context
$context, $addroleid = null) {
3354 $params = array('contextlevel'=>CONTEXT_COURSE
);
3356 $addrole = "OR r.id = :addroleid";
3357 $params['addroleid'] = $addroleid;
3361 $sql = "SELECT r.id, r.name
3363 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3364 WHERE rcl.id IS NOT NULL $addrole
3365 ORDER BY sortorder DESC";
3367 $roles = $DB->get_records_sql_menu($sql, $params);
3368 $roles = role_fix_names($roles, $context, ROLENAME_BOTH
);
3374 * Return context levels where this role is assignable.
3376 * @param integer $roleid the id of a role.
3377 * @return array list of the context levels at which this role may be assigned.
3379 function get_role_contextlevels($roleid) {
3381 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3382 'contextlevel', 'id,contextlevel');
3386 * Return roles suitable for assignment at the specified context level.
3388 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3390 * @param integer $contextlevel a contextlevel.
3391 * @return array list of role ids that are assignable at this context level.
3393 function get_roles_for_contextlevels($contextlevel) {
3395 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3400 * Returns default context levels where roles can be assigned.
3402 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3403 * from the array returned by get_role_archetypes();
3404 * @return array list of the context levels at which this type of role may be assigned by default.
3406 function get_default_contextlevels($rolearchetype) {
3407 static $defaults = array(
3408 'manager' => array(CONTEXT_SYSTEM
, CONTEXT_COURSECAT
, CONTEXT_COURSE
),
3409 'coursecreator' => array(CONTEXT_SYSTEM
, CONTEXT_COURSECAT
),
3410 'editingteacher' => array(CONTEXT_COURSE
, CONTEXT_MODULE
),
3411 'teacher' => array(CONTEXT_COURSE
, CONTEXT_MODULE
),
3412 'student' => array(CONTEXT_COURSE
, CONTEXT_MODULE
),
3415 'frontpage' => array());
3417 if (isset($defaults[$rolearchetype])) {
3418 return $defaults[$rolearchetype];
3425 * Set the context levels at which a particular role can be assigned.
3426 * Throws exceptions in case of error.
3428 * @param integer $roleid the id of a role.
3429 * @param array $contextlevels the context levels at which this role should be assignable,
3430 * duplicate levels are removed.
3433 function set_role_contextlevels($roleid, array $contextlevels) {
3435 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3436 $rcl = new stdClass();
3437 $rcl->roleid
= $roleid;
3438 $contextlevels = array_unique($contextlevels);
3439 foreach ($contextlevels as $level) {
3440 $rcl->contextlevel
= $level;
3441 $DB->insert_record('role_context_levels', $rcl, false, true);
3446 * Who has this capability in this context?
3448 * This can be a very expensive call - use sparingly and keep
3449 * the results if you are going to need them again soon.
3451 * Note if $fields is empty this function attempts to get u.*
3452 * which can get rather large - and has a serious perf impact
3455 * @param context $context
3456 * @param string|array $capability - capability name(s)
3457 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3458 * @param string $sort - the sort order. Default is lastaccess time.
3459 * @param mixed $limitfrom - number of records to skip (offset)
3460 * @param mixed $limitnum - number of records to fetch
3461 * @param string|array $groups - single group or array of groups - only return
3462 * users who are in one of these group(s).
3463 * @param string|array $exceptions - list of users to exclude, comma separated or array
3464 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3465 * @param bool $view_ignored - use get_enrolled_sql() instead
3466 * @param bool $useviewallgroups if $groups is set the return users who
3467 * have capability both $capability and moodle/site:accessallgroups
3468 * in this context, as well as users who have $capability and who are
3470 * @return array of user records
3472 function get_users_by_capability(context
$context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3473 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3476 $defaultuserroleid = isset($CFG->defaultuserroleid
) ?
$CFG->defaultuserroleid
: 0;
3477 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid
) ?
$CFG->defaultfrontpageroleid
: 0;
3479 $ctxids = trim($context->path
, '/');
3480 $ctxids = str_replace('/', ',', $ctxids);
3482 // Context is the frontpage
3483 $iscoursepage = false; // coursepage other than fp
3484 $isfrontpage = false;
3485 if ($context->contextlevel
== CONTEXT_COURSE
) {
3486 if ($context->instanceid
== SITEID
) {
3487 $isfrontpage = true;
3489 $iscoursepage = true;
3492 $isfrontpage = ($isfrontpage ||
is_inside_frontpage($context));
3494 $caps = (array)$capability;
3496 // construct list of context paths bottom-->top
3497 list($contextids, $paths) = get_context_info_list($context);
3499 // we need to find out all roles that have these capabilities either in definition or in overrides
3501 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED
, 'con');
3502 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED
, 'cap');
3503 $params = array_merge($params, $params2);
3504 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3505 FROM {role_capabilities} rc
3506 JOIN {context} ctx on rc.contextid = ctx.id
3507 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3509 $rcs = $DB->get_records_sql($sql, $params);
3510 foreach ($rcs as $rc) {
3511 $defs[$rc->capability
][$rc->path
][$rc->roleid
] = $rc->permission
;
3514 // go through the permissions bottom-->top direction to evaluate the current permission,
3515 // first one wins (prohibit is an exception that always wins)
3517 foreach ($caps as $cap) {
3518 foreach ($paths as $path) {
3519 if (empty($defs[$cap][$path])) {
3522 foreach($defs[$cap][$path] as $roleid => $perm) {
3523 if ($perm == CAP_PROHIBIT
) {
3524 $access[$cap][$roleid] = CAP_PROHIBIT
;
3527 if (!isset($access[$cap][$roleid])) {
3528 $access[$cap][$roleid] = (int)$perm;
3534 // make lists of roles that are needed and prohibited in this context
3535 $needed = array(); // one of these is enough
3536 $prohibited = array(); // must not have any of these
3537 foreach ($caps as $cap) {
3538 if (empty($access[$cap])) {
3541 foreach ($access[$cap] as $roleid => $perm) {
3542 if ($perm == CAP_PROHIBIT
) {
3543 unset($needed[$cap][$roleid]);
3544 $prohibited[$cap][$roleid] = true;
3545 } else if ($perm == CAP_ALLOW
and empty($prohibited[$cap][$roleid])) {
3546 $needed[$cap][$roleid] = true;
3549 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3550 // easy, nobody has the permission
3551 unset($needed[$cap]);
3552 unset($prohibited[$cap]);
3553 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3554 // everybody is disqualified on the frontpage
3555 unset($needed[$cap]);
3556 unset($prohibited[$cap]);
3558 if (empty($prohibited[$cap])) {
3559 unset($prohibited[$cap]);
3563 if (empty($needed)) {
3564 // there can not be anybody if no roles match this request
3568 if (empty($prohibited)) {
3569 // we can compact the needed roles
3571 foreach ($needed as $cap) {
3572 foreach ($cap as $roleid=>$unused) {
3576 $needed = array('any'=>$n);
3580 // ***** Set up default fields ******
3581 if (empty($fields)) {
3582 if ($iscoursepage) {
3583 $fields = 'u.*, ul.timeaccess AS lastaccess';
3588 if (debugging('', DEBUG_DEVELOPER
) && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3589 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER
);
3593 // Set up default sort
3594 if (empty($sort)) { // default to course lastaccess or just lastaccess
3595 if ($iscoursepage) {
3596 $sort = 'ul.timeaccess';
3598 $sort = 'u.lastaccess';
3602 // Prepare query clauses
3603 $wherecond = array();
3607 // User lastaccess JOIN
3608 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3609 // user_lastaccess is not required MDL-13810
3611 if ($iscoursepage) {
3612 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3614 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3618 // We never return deleted users or guest account.
3619 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3620 $params['guestid'] = $CFG->siteguest
;
3624 $groups = (array)$groups;
3625 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED
, 'grp');
3626 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3627 $params = array_merge($params, $grpparams);
3629 if ($useviewallgroups) {
3630 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3631 if (!empty($viewallgroupsusers)) {
3632 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3634 $wherecond[] = "($grouptest)";
3637 $wherecond[] = "($grouptest)";
3642 if (!empty($exceptions)) {
3643 $exceptions = (array)$exceptions;
3644 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED
, 'exc', false);
3645 $params = array_merge($params, $exparams);
3646 $wherecond[] = "u.id $exsql";
3649 // now add the needed and prohibited roles conditions as joins
3650 if (!empty($needed['any'])) {
3651 // simple case - there are no prohibits involved
3652 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3655 $joins[] = "JOIN (SELECT DISTINCT userid
3656 FROM {role_assignments}
3657 WHERE contextid IN ($ctxids)
3658 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3659 ) ra ON ra.userid = u.id";
3664 foreach ($needed as $cap=>$unused) {
3665 if (empty($prohibited[$cap])) {
3666 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3670 $unions[] = "SELECT userid
3671 FROM {role_assignments}
3672 WHERE contextid IN ($ctxids)
3673 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3676 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3677 // nobody can have this cap because it is prevented in default roles
3680 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3681 // everybody except the prohibitted - hiding does not matter
3682 $unions[] = "SELECT id AS userid
3684 WHERE id NOT IN (SELECT userid
3685 FROM {role_assignments}
3686 WHERE contextid IN ($ctxids)
3687 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3690 $unions[] = "SELECT userid
3691 FROM {role_assignments}
3692 WHERE contextid IN ($ctxids)
3693 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3694 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3700 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3702 // only prohibits found - nobody can be matched
3703 $wherecond[] = "1 = 2";
3708 // Collect WHERE conditions and needed joins
3709 $where = implode(' AND ', $wherecond);
3710 if ($where !== '') {
3711 $where = 'WHERE ' . $where;
3713 $joins = implode("\n", $joins);
3715 // Ok, let's get the users!
3716 $sql = "SELECT $fields
3722 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3726 * Re-sort a users array based on a sorting policy
3728 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3729 * based on a sorting policy. This is to support the odd practice of
3730 * sorting teachers by 'authority', where authority was "lowest id of the role
3733 * Will execute 1 database query. Only suitable for small numbers of users, as it
3734 * uses an u.id IN() clause.
3736 * Notes about the sorting criteria.
3738 * As a default, we cannot rely on role.sortorder because then
3739 * admins/coursecreators will always win. That is why the sane
3740 * rule "is locality matters most", with sortorder as 2nd
3743 * If you want role.sortorder, use the 'sortorder' policy, and
3744 * name explicitly what roles you want to cover. It's probably
3745 * a good idea to see what roles have the capabilities you want
3746 * (array_diff() them against roiles that have 'can-do-anything'
3747 * to weed out admin-ish roles. Or fetch a list of roles from
3748 * variables like $CFG->coursecontact .
3750 * @param array $users Users array, keyed on userid
3751 * @param context $context
3752 * @param array $roles ids of the roles to include, optional
3753 * @param string $sortpolicy defaults to locality, more about
3754 * @return array sorted copy of the array
3756 function sort_by_roleassignment_authority($users, context
$context, $roles = array(), $sortpolicy = 'locality') {
3759 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3760 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path
, 1)).')';
3761 if (empty($roles)) {
3764 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3767 $sql = "SELECT ra.userid
3768 FROM {role_assignments} ra
3772 ON ra.contextid=ctx.id
3777 // Default 'locality' policy -- read PHPDoc notes
3778 // about sort policies...
3779 $orderby = 'ORDER BY '
3780 .'ctx.depth DESC, ' /* locality wins */
3781 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3782 .'ra.id'; /* role assignment order tie-breaker */
3783 if ($sortpolicy === 'sortorder') {
3784 $orderby = 'ORDER BY '
3785 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3786 .'ra.id'; /* role assignment order tie-breaker */
3789 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3790 $sortedusers = array();
3793 foreach ($sortedids as $id) {
3795 if (isset($seen[$id])) {
3801 $sortedusers[$id] = $users[$id];
3803 return $sortedusers;
3807 * Gets all the users assigned this role in this context or higher
3809 * @param int $roleid (can also be an array of ints!)
3810 * @param context $context
3811 * @param bool $parent if true, get list of users assigned in higher context too
3812 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3813 * @param string $sort sort from user (u.) , role assignment (ra) or role (r.)
3814 * @param bool $gethidden_ignored use enrolments instead
3815 * @param string $group defaults to ''
3816 * @param mixed $limitfrom defaults to ''
3817 * @param mixed $limitnum defaults to ''
3818 * @param string $extrawheretest defaults to ''
3819 * @param string|array $whereparams defaults to ''
3822 function get_role_users($roleid, context
$context, $parent = false, $fields = '',
3823 $sort = 'u.lastname, u.firstname', $gethidden_ignored = null, $group = '',
3824 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereparams = array()) {
3827 if (empty($fields)) {
3828 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3829 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3830 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3831 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder';
3834 $parentcontexts = '';
3836 $parentcontexts = substr($context->path
, 1); // kill leading slash
3837 $parentcontexts = str_replace('/', ',', $parentcontexts);
3838 if ($parentcontexts !== '') {
3839 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3844 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM
);
3845 $roleselect = "AND ra.roleid $rids";
3852 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3853 $groupselect = " AND gm.groupid = ? ";
3860 array_unshift($params, $context->id
);
3862 if ($extrawheretest) {
3863 $extrawheretest = ' AND ' . $extrawheretest;
3864 $params = array_merge($params, $whereparams);
3867 $sql = "SELECT DISTINCT $fields, ra.roleid
3868 FROM {role_assignments} ra
3869 JOIN {user} u ON u.id = ra.userid
3870 JOIN {role} r ON ra.roleid = r.id
3872 WHERE (ra.contextid = ? $parentcontexts)
3876 ORDER BY $sort"; // join now so that we can just use fullname() later
3878 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3882 * Counts all the users assigned this role in this context or higher
3884 * @param int|array $roleid either int or an array of ints
3885 * @param context $context
3886 * @param bool $parent if true, get list of users assigned in higher context too
3887 * @return int Returns the result count
3889 function count_role_users($roleid, context
$context, $parent = false) {
3893 if ($contexts = $context->get_parent_context_ids()) {
3894 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3896 $parentcontexts = '';
3899 $parentcontexts = '';
3903 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM
);
3904 $roleselect = "AND r.roleid $rids";
3910 array_unshift($params, $context->id
);
3912 $sql = "SELECT COUNT(u.id)
3913 FROM {role_assignments} r
3914 JOIN {user} u ON u.id = r.userid
3915 WHERE (r.contextid = ? $parentcontexts)
3919 return $DB->count_records_sql($sql, $params);
3923 * This function gets the list of courses that this user has a particular capability in.
3924 * It is still not very efficient.
3926 * @param string $capability Capability in question
3927 * @param int $userid User ID or null for current user
3928 * @param bool $doanything True if 'doanything' is permitted (default)
3929 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3930 * otherwise use a comma-separated list of the fields you require, not including id
3931 * @param string $orderby If set, use a comma-separated list of fields from course
3932 * table with sql modifiers (DESC) if needed
3933 * @return array Array of courses, may have zero entries. Or false if query failed.
3935 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
3938 // Convert fields list and ordering
3940 if ($fieldsexceptid) {
3941 $fields = explode(',', $fieldsexceptid);
3942 foreach($fields as $field) {
3943 $fieldlist .= ',c.'.$field;
3947 $fields = explode(',', $orderby);
3949 foreach($fields as $field) {
3953 $orderby .= 'c.'.$field;
3955 $orderby = 'ORDER BY '.$orderby;
3958 // Obtain a list of everything relevant about all courses including context.
3959 // Note the result can be used directly as a context (we are going to), the course
3960 // fields are just appended.
3962 $contextpreload = context_helper
::get_preload_record_columns_sql('x');
3965 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
3967 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE
.")
3969 // Check capability for each course in turn
3970 foreach ($rs as $course) {
3971 context_helper
::preload_from_record($course);
3972 $context = context_course
::instance($course->id
);
3973 if (has_capability($capability, $context, $userid, $doanything)) {
3974 // We've got the capability. Make the record look like a course record
3976 $courses[] = $course;
3980 return empty($courses) ?
false : $courses;
3984 * This function finds the roles assigned directly to this context only
3985 * i.e. no roles in parent contexts
3987 * @param context $context
3990 function get_roles_on_exact_context(context
$context) {
3993 return $DB->get_records_sql("SELECT r.*
3994 FROM {role_assignments} ra, {role} r
3995 WHERE ra.roleid = r.id AND ra.contextid = ?",
3996 array($context->id
));
4000 * Switches the current user to another role for the current session and only
4001 * in the given context.
4003 * The caller *must* check
4004 * - that this op is allowed
4005 * - that the requested role can be switched to in this context (use get_switchable_roles)
4006 * - that the requested role is NOT $CFG->defaultuserroleid
4008 * To "unswitch" pass 0 as the roleid.
4010 * This function *will* modify $USER->access - beware
4012 * @param integer $roleid the role to switch to.
4013 * @param context $context the context in which to perform the switch.
4014 * @return bool success or failure.
4016 function role_switch($roleid, context
$context) {
4022 // - Add the ghost RA to $USER->access
4023 // as $USER->access['rsw'][$path] = $roleid
4025 // - Make sure $USER->access['rdef'] has the roledefs
4026 // it needs to honour the switcherole
4028 // Roledefs will get loaded "deep" here - down to the last child
4029 // context. Note that
4031 // - When visiting subcontexts, our selective accessdata loading
4032 // will still work fine - though those ra/rdefs will be ignored
4033 // appropriately while the switch is in place
4035 // - If a switcherole happens at a category with tons of courses
4036 // (that have many overrides for switched-to role), the session
4037 // will get... quite large. Sometimes you just can't win.
4039 // To un-switch just unset($USER->access['rsw'][$path])
4041 // Note: it is not possible to switch to roles that do not have course:view
4043 if (!isset($USER->access
)) {
4044 load_all_capabilities();
4048 // Add the switch RA
4050 unset($USER->access
['rsw'][$context->path
]);
4054 $USER->access
['rsw'][$context->path
] = $roleid;
4057 load_role_access_by_context($roleid, $context, $USER->access
);
4063 * Checks if the user has switched roles within the given course.
4065 * Note: You can only switch roles within the course, hence it takes a course id
4066 * rather than a context. On that note Petr volunteered to implement this across
4067 * all other contexts, all requests for this should be forwarded to him ;)
4069 * @param int $courseid The id of the course to check
4070 * @return bool True if the user has switched roles within the course.
4072 function is_role_switched($courseid) {
4074 $context = context_course
::instance($courseid, MUST_EXIST
);
4075 return (!empty($USER->access
['rsw'][$context->path
]));
4079 * Get any role that has an override on exact context
4081 * @param context $context The context to check
4082 * @return array An array of roles
4084 function get_roles_with_override_on_context(context
$context) {
4087 return $DB->get_records_sql("SELECT r.*
4088 FROM {role_capabilities} rc, {role} r
4089 WHERE rc.roleid = r.id AND rc.contextid = ?",
4090 array($context->id
));
4094 * Get all capabilities for this role on this context (overrides)
4096 * @param stdClass $role
4097 * @param context $context
4100 function get_capabilities_from_role_on_context($role, context
$context) {
4103 return $DB->get_records_sql("SELECT *
4104 FROM {role_capabilities}
4105 WHERE contextid = ? AND roleid = ?",
4106 array($context->id
, $role->id
));
4110 * Find out which roles has assignment on this context
4112 * @param context $context
4116 function get_roles_with_assignment_on_context(context
$context) {
4119 return $DB->get_records_sql("SELECT r.*
4120 FROM {role_assignments} ra, {role} r
4121 WHERE ra.roleid = r.id AND ra.contextid = ?",
4122 array($context->id
));
4126 * Find all user assignment of users for this role, on this context
4128 * @param stdClass $role
4129 * @param context $context
4132 function get_users_from_role_on_context($role, context
$context) {
4135 return $DB->get_records_sql("SELECT *
4136 FROM {role_assignments}
4137 WHERE contextid = ? AND roleid = ?",
4138 array($context->id
, $role->id
));
4142 * Simple function returning a boolean true if user has roles
4143 * in context or parent contexts, otherwise false.
4145 * @param int $userid
4146 * @param int $roleid
4147 * @param int $contextid empty means any context
4150 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4154 if (!$context = context
::instance_by_id($contextid, IGNORE_MISSING
)) {
4157 $parents = $context->get_parent_context_ids(true);
4158 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED
, 'r');
4159 $params['userid'] = $userid;
4160 $params['roleid'] = $roleid;
4162 $sql = "SELECT COUNT(ra.id)
4163 FROM {role_assignments} ra
4164 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4166 $count = $DB->get_field_sql($sql, $params);
4167 return ($count > 0);
4170 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4175 * Get role name or alias if exists and format the text.
4177 * @param stdClass $role role object
4178 * @param context_course $coursecontext
4179 * @return string name of role in course context
4181 function role_get_name($role, context_course
$coursecontext) {
4184 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id
, 'contextid'=>$coursecontext->id
))) {
4185 return strip_tags(format_string($r->name
));
4187 return strip_tags(format_string($role->name
));
4192 * Get all the localised role names for a context.
4193 * @param context $context the context
4194 * @param array of role objects with a ->localname field containing the context-specific role name.
4196 function role_get_names(context
$context) {
4197 return role_fix_names(get_all_roles(), $context);
4201 * Prepare list of roles for display, apply aliases and format text
4203 * @param array $roleoptions array roleid => rolename or roleid => roleobject
4204 * @param context $context a context
4205 * @param int $rolenamedisplay
4206 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4208 function role_fix_names($roleoptions, context
$context, $rolenamedisplay = ROLENAME_ALIAS
) {
4211 // Make sure we have a course context.
4212 $coursecontext = $context->get_course_context(false);
4214 // Make sure we are working with an array roleid => name. Normally we
4215 // want to use the unlocalised name if the localised one is not present.
4216 $newnames = array();
4217 foreach ($roleoptions as $rid => $roleorname) {
4218 if ($rolenamedisplay != ROLENAME_ALIAS_RAW
) {
4219 if (is_object($roleorname)) {
4220 $newnames[$rid] = $roleorname->name
;
4222 $newnames[$rid] = $roleorname;
4225 $newnames[$rid] = '';
4229 // If necessary, get the localised names.
4230 if ($rolenamedisplay != ROLENAME_ORIGINAL
&& !empty($coursecontext->id
)) {
4231 // The get the relevant renames, and use them.
4232 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id
));
4233 foreach ($aliasnames as $alias) {
4234 if (isset($newnames[$alias->roleid
])) {
4235 if ($rolenamedisplay == ROLENAME_ALIAS ||
$rolenamedisplay == ROLENAME_ALIAS_RAW
) {
4236 $newnames[$alias->roleid
] = $alias->name
;
4237 } else if ($rolenamedisplay == ROLENAME_BOTH
) {
4238 $newnames[$alias->roleid
] = $alias->name
. ' (' . $roleoptions[$alias->roleid
] . ')';
4244 // Finally, apply format_string and put the result in the right place.
4245 foreach ($roleoptions as $rid => $roleorname) {
4246 if ($rolenamedisplay != ROLENAME_ALIAS_RAW
) {
4247 $newnames[$rid] = strip_tags(format_string($newnames[$rid]));
4249 if (is_object($roleorname)) {
4250 $roleoptions[$rid]->localname
= $newnames[$rid];
4252 $roleoptions[$rid] = $newnames[$rid];
4255 return $roleoptions;
4259 * Aids in detecting if a new line is required when reading a new capability
4261 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4262 * when we read in a new capability.
4263 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4264 * but when we are in grade, all reports/import/export capabilities should be together
4266 * @param string $cap component string a
4267 * @param string $comp component string b
4268 * @param int $contextlevel
4269 * @return bool whether 2 component are in different "sections"
4271 function component_level_changed($cap, $comp, $contextlevel) {
4273 if (strstr($cap->component
, '/') && strstr($comp, '/')) {
4274 $compsa = explode('/', $cap->component
);
4275 $compsb = explode('/', $comp);
4277 // list of system reports
4278 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4282 // we are in gradebook, still
4283 if (($compsa[0] == 'gradeexport' ||
$compsa[0] == 'gradeimport' ||
$compsa[0] == 'gradereport') &&
4284 ($compsb[0] == 'gradeexport' ||
$compsb[0] == 'gradeimport' ||
$compsb[0] == 'gradereport')) {
4288 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4293 return ($cap->component
!= $comp ||
$cap->contextlevel
!= $contextlevel);
4297 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4298 * and return an array of roleids in order.
4300 * @param array $allroles array of roles, as returned by get_all_roles();
4301 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4303 function fix_role_sortorder($allroles) {
4306 $rolesort = array();
4308 foreach ($allroles as $role) {
4309 $rolesort[$i] = $role->id
;
4310 if ($role->sortorder
!= $i) {
4311 $r = new stdClass();
4314 $DB->update_record('role', $r);
4315 $allroles[$role->id
]->sortorder
= $i;
4323 * Switch the sort order of two roles (used in admin/roles/manage.php).
4325 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4326 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4327 * @return boolean success or failure
4329 function switch_roles($first, $second) {
4331 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4332 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder
));
4333 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder
, array('sortorder' => $second->sortorder
));
4334 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder
, array('sortorder' => $temp));
4339 * Duplicates all the base definitions of a role
4341 * @param stdClass $sourcerole role to copy from
4342 * @param int $targetrole id of role to copy to
4344 function role_cap_duplicate($sourcerole, $targetrole) {
4347 $systemcontext = context_system
::instance();
4348 $caps = $DB->get_records_sql("SELECT *
4349 FROM {role_capabilities}
4350 WHERE roleid = ? AND contextid = ?",
4351 array($sourcerole->id
, $systemcontext->id
));
4352 // adding capabilities
4353 foreach ($caps as $cap) {
4355 $cap->roleid
= $targetrole;
4356 $DB->insert_record('role_capabilities', $cap);
4361 * Returns two lists, this can be used to find out if user has capability.
4362 * Having any needed role and no forbidden role in this context means
4363 * user has this capability in this context.
4364 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4366 * @param stdClass $context
4367 * @param string $capability
4368 * @return array($neededroles, $forbiddenroles)
4370 function get_roles_with_cap_in_context($context, $capability) {
4373 $ctxids = trim($context->path
, '/'); // kill leading slash
4374 $ctxids = str_replace('/', ',', $ctxids);
4376 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4377 FROM {role_capabilities} rc
4378 JOIN {context} ctx ON ctx.id = rc.contextid
4379 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4380 ORDER BY rc.roleid ASC, ctx.depth DESC";
4381 $params = array('cap'=>$capability);
4383 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4384 // no cap definitions --> no capability
4385 return array(array(), array());
4388 $forbidden = array();
4390 foreach($capdefs as $def) {
4391 if (isset($forbidden[$def->roleid
])) {
4394 if ($def->permission
== CAP_PROHIBIT
) {
4395 $forbidden[$def->roleid
] = $def->roleid
;
4396 unset($needed[$def->roleid
]);
4399 if (!isset($needed[$def->roleid
])) {
4400 if ($def->permission
== CAP_ALLOW
) {
4401 $needed[$def->roleid
] = true;
4402 } else if ($def->permission
== CAP_PREVENT
) {
4403 $needed[$def->roleid
] = false;
4409 // remove all those roles not allowing
4410 foreach($needed as $key=>$value) {
4412 unset($needed[$key]);
4414 $needed[$key] = $key;
4418 return array($needed, $forbidden);
4422 * Returns an array of role IDs that have ALL of the the supplied capabilities
4423 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4425 * @param stdClass $context
4426 * @param array $capabilities An array of capabilities
4427 * @return array of roles with all of the required capabilities
4429 function get_roles_with_caps_in_context($context, $capabilities) {
4430 $neededarr = array();
4431 $forbiddenarr = array();
4432 foreach($capabilities as $caprequired) {
4433 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4436 $rolesthatcanrate = array();
4437 if (!empty($neededarr)) {
4438 foreach ($neededarr as $needed) {
4439 if (empty($rolesthatcanrate)) {
4440 $rolesthatcanrate = $needed;
4442 //only want roles that have all caps
4443 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4447 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4448 foreach ($forbiddenarr as $forbidden) {
4449 //remove any roles that are forbidden any of the caps
4450 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4453 return $rolesthatcanrate;
4457 * Returns an array of role names that have ALL of the the supplied capabilities
4458 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4460 * @param stdClass $context
4461 * @param array $capabilities An array of capabilities
4462 * @return array of roles with all of the required capabilities
4464 function get_role_names_with_caps_in_context($context, $capabilities) {
4467 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4469 $allroles = array();
4470 $roles = $DB->get_records('role', null, 'sortorder DESC');
4471 foreach ($roles as $roleid=>$role) {
4472 $allroles[$roleid] = $role->name
;
4475 $rolenames = array();
4476 foreach ($rolesthatcanrate as $r) {
4477 $rolenames[$r] = $allroles[$r];
4479 $rolenames = role_fix_names($rolenames, $context);
4484 * This function verifies the prohibit comes from this context
4485 * and there are no more prohibits in parent contexts.
4487 * @param int $roleid
4488 * @param context $context
4489 * @param string $capability name
4492 function prohibit_is_removable($roleid, context
$context, $capability) {
4495 $ctxids = trim($context->path
, '/'); // kill leading slash
4496 $ctxids = str_replace('/', ',', $ctxids);
4498 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT
);
4500 $sql = "SELECT ctx.id
4501 FROM {role_capabilities} rc
4502 JOIN {context} ctx ON ctx.id = rc.contextid
4503 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4504 ORDER BY ctx.depth DESC";
4506 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4507 // no prohibits == nothing to remove
4511 if (count($prohibits) > 1) {
4512 // more prohibits can not be removed
4516 return !empty($prohibits[$context->id
]);
4520 * More user friendly role permission changing,
4521 * it should produce as few overrides as possible.
4523 * @param int $roleid
4524 * @param stdClass $context
4525 * @param string $capname capability name
4526 * @param int $permission
4529 function role_change_permission($roleid, $context, $capname, $permission) {
4532 if ($permission == CAP_INHERIT
) {
4533 unassign_capability($capname, $roleid, $context->id
);
4534 $context->mark_dirty();
4538 $ctxids = trim($context->path
, '/'); // kill leading slash
4539 $ctxids = str_replace('/', ',', $ctxids);
4541 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4543 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4544 FROM {role_capabilities} rc
4545 JOIN {context} ctx ON ctx.id = rc.contextid
4546 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4547 ORDER BY ctx.depth DESC";
4549 if ($existing = $DB->get_records_sql($sql, $params)) {
4550 foreach($existing as $e) {
4551 if ($e->permission
== CAP_PROHIBIT
) {
4552 // prohibit can not be overridden, no point in changing anything
4556 $lowest = array_shift($existing);
4557 if ($lowest->permission
== $permission) {
4558 // permission already set in this context or parent - nothing to do
4562 $parent = array_shift($existing);
4563 if ($parent->permission
== $permission) {
4564 // permission already set in parent context or parent - just unset in this context
4565 // we do this because we want as few overrides as possible for performance reasons
4566 unassign_capability($capname, $roleid, $context->id
);
4567 $context->mark_dirty();
4573 if ($permission == CAP_PREVENT
) {
4574 // nothing means role does not have permission
4579 // assign the needed capability
4580 assign_capability($capname, $permission, $roleid, $context->id
, true);
4582 // force cap reloading
4583 $context->mark_dirty();
4588 * Basic moodle context abstraction class.
4590 * Google confirms that no other important framework is using "context" class,
4591 * we could use something else like mcontext or moodle_context, but we need to type
4592 * this very often which would be annoying and it would take too much space...
4594 * This class is derived from stdClass for backwards compatibility with
4595 * odl $context record that was returned from DML $DB->get_record()
4597 * @package core_access
4599 * @copyright Petr Skoda {@link http://skodak.org}
4600 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4603 * @property-read int $id context id
4604 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4605 * @property-read int $instanceid id of related instance in each context
4606 * @property-read string $path path to context, starts with system context
4607 * @property-read int $depth
4609 abstract class context
extends stdClass
implements IteratorAggregate
{
4613 * Can be accessed publicly through $context->id
4620 * Can be accessed publicly through $context->contextlevel
4621 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4623 protected $_contextlevel;
4626 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4627 * Can be accessed publicly through $context->instanceid
4630 protected $_instanceid;
4633 * The path to the context always starting from the system context
4634 * Can be accessed publicly through $context->path
4640 * The depth of the context in relation to parent contexts
4641 * Can be accessed publicly through $context->depth
4647 * @var array Context caching info
4649 private static $cache_contextsbyid = array();
4652 * @var array Context caching info
4654 private static $cache_contexts = array();
4658 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4661 protected static $cache_count = 0;
4664 * @var array Context caching info
4666 protected static $cache_preloaded = array();
4669 * @var context_system The system context once initialised
4671 protected static $systemcontext = null;
4674 * Resets the cache to remove all data.
4677 protected static function reset_caches() {
4678 self
::$cache_contextsbyid = array();
4679 self
::$cache_contexts = array();
4680 self
::$cache_count = 0;
4681 self
::$cache_preloaded = array();
4683 self
::$systemcontext = null;
4687 * Adds a context to the cache. If the cache is full, discards a batch of
4691 * @param context $context New context to add
4694 protected static function cache_add(context
$context) {
4695 if (isset(self
::$cache_contextsbyid[$context->id
])) {
4696 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4700 if (self
::$cache_count >= CONTEXT_CACHE_MAX_SIZE
) {
4702 foreach(self
::$cache_contextsbyid as $ctx) {
4705 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4708 if ($i > (CONTEXT_CACHE_MAX_SIZE
/ 3)) {
4709 // we remove oldest third of the contexts to make room for more contexts
4712 unset(self
::$cache_contextsbyid[$ctx->id
]);
4713 unset(self
::$cache_contexts[$ctx->contextlevel
][$ctx->instanceid
]);
4714 self
::$cache_count--;
4718 self
::$cache_contexts[$context->contextlevel
][$context->instanceid
] = $context;
4719 self
::$cache_contextsbyid[$context->id
] = $context;
4720 self
::$cache_count++
;
4724 * Removes a context from the cache.
4727 * @param context $context Context object to remove
4730 protected static function cache_remove(context
$context) {
4731 if (!isset(self
::$cache_contextsbyid[$context->id
])) {
4732 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4735 unset(self
::$cache_contexts[$context->contextlevel
][$context->instanceid
]);
4736 unset(self
::$cache_contextsbyid[$context->id
]);
4738 self
::$cache_count--;
4740 if (self
::$cache_count < 0) {
4741 self
::$cache_count = 0;
4746 * Gets a context from the cache.
4749 * @param int $contextlevel Context level
4750 * @param int $instance Instance ID
4751 * @return context|bool Context or false if not in cache
4753 protected static function cache_get($contextlevel, $instance) {
4754 if (isset(self
::$cache_contexts[$contextlevel][$instance])) {
4755 return self
::$cache_contexts[$contextlevel][$instance];
4761 * Gets a context from the cache based on its id.
4764 * @param int $id Context ID
4765 * @return context|bool Context or false if not in cache
4767 protected static function cache_get_by_id($id) {
4768 if (isset(self
::$cache_contextsbyid[$id])) {
4769 return self
::$cache_contextsbyid[$id];
4775 * Preloads context information from db record and strips the cached info.
4778 * @param stdClass $rec
4779 * @return void (modifies $rec)
4781 protected static function preload_from_record(stdClass
$rec) {
4782 if (empty($rec->ctxid
) or empty($rec->ctxlevel
) or empty($rec->ctxinstance
) or empty($rec->ctxpath
) or empty($rec->ctxdepth
)) {
4783 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4787 // note: in PHP5 the objects are passed by reference, no need to return $rec
4788 $record = new stdClass();
4789 $record->id
= $rec->ctxid
; unset($rec->ctxid
);
4790 $record->contextlevel
= $rec->ctxlevel
; unset($rec->ctxlevel
);
4791 $record->instanceid
= $rec->ctxinstance
; unset($rec->ctxinstance
);
4792 $record->path
= $rec->ctxpath
; unset($rec->ctxpath
);
4793 $record->depth
= $rec->ctxdepth
; unset($rec->ctxdepth
);
4795 return context
::create_instance_from_record($record);
4799 // ====== magic methods =======
4802 * Magic setter method, we do not want anybody to modify properties from the outside
4803 * @param string $name
4804 * @param mixed $value
4806 public function __set($name, $value) {
4807 debugging('Can not change context instance properties!');
4811 * Magic method getter, redirects to read only values.
4812 * @param string $name
4815 public function __get($name) {
4817 case 'id': return $this->_id
;
4818 case 'contextlevel': return $this->_contextlevel
;
4819 case 'instanceid': return $this->_instanceid
;
4820 case 'path': return $this->_path
;
4821 case 'depth': return $this->_depth
;
4824 debugging('Invalid context property accessed! '.$name);
4830 * Full support for isset on our magic read only properties.
4831 * @param string $name
4834 public function __isset($name) {
4836 case 'id': return isset($this->_id
);
4837 case 'contextlevel': return isset($this->_contextlevel
);
4838 case 'instanceid': return isset($this->_instanceid
);
4839 case 'path': return isset($this->_path
);
4840 case 'depth': return isset($this->_depth
);
4842 default: return false;
4848 * ALl properties are read only, sorry.
4849 * @param string $name
4851 public function __unset($name) {
4852 debugging('Can not unset context instance properties!');
4855 // ====== implementing method from interface IteratorAggregate ======
4858 * Create an iterator because magic vars can't be seen by 'foreach'.
4860 * Now we can convert context object to array using convert_to_array(),
4861 * and feed it properly to json_encode().
4863 public function getIterator() {
4866 'contextlevel' => $this->contextlevel
,
4867 'instanceid' => $this->instanceid
,
4868 'path' => $this->path
,
4869 'depth' => $this->depth
4871 return new ArrayIterator($ret);
4874 // ====== general context methods ======
4877 * Constructor is protected so that devs are forced to
4878 * use context_xxx::instance() or context::instance_by_id().
4880 * @param stdClass $record
4882 protected function __construct(stdClass
$record) {
4883 $this->_id
= $record->id
;
4884 $this->_contextlevel
= (int)$record->contextlevel
;
4885 $this->_instanceid
= $record->instanceid
;
4886 $this->_path
= $record->path
;
4887 $this->_depth
= $record->depth
;
4891 * This function is also used to work around 'protected' keyword problems in context_helper.
4893 * @param stdClass $record
4894 * @return context instance
4896 protected static function create_instance_from_record(stdClass
$record) {
4897 $classname = context_helper
::get_class_for_level($record->contextlevel
);
4899 if ($context = context
::cache_get_by_id($record->id
)) {
4903 $context = new $classname($record);
4904 context
::cache_add($context);
4910 * Copy prepared new contexts from temp table to context table,
4911 * we do this in db specific way for perf reasons only.
4914 protected static function merge_context_temp_table() {
4918 * - mysql does not allow to use FROM in UPDATE statements
4919 * - using two tables after UPDATE works in mysql, but might give unexpected
4920 * results in pg 8 (depends on configuration)
4921 * - using table alias in UPDATE does not work in pg < 8.2
4923 * Different code for each database - mostly for performance reasons
4926 $dbfamily = $DB->get_dbfamily();
4927 if ($dbfamily == 'mysql') {
4928 $updatesql = "UPDATE {context} ct, {context_temp} temp
4929 SET ct.path = temp.path,
4930 ct.depth = temp.depth
4931 WHERE ct.id = temp.id";
4932 } else if ($dbfamily == 'oracle') {
4933 $updatesql = "UPDATE {context} ct
4934 SET (ct.path, ct.depth) =
4935 (SELECT temp.path, temp.depth
4936 FROM {context_temp} temp
4937 WHERE temp.id=ct.id)
4938 WHERE EXISTS (SELECT 'x'
4939 FROM {context_temp} temp
4940 WHERE temp.id = ct.id)";
4941 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
4942 $updatesql = "UPDATE {context}
4943 SET path = temp.path,
4945 FROM {context_temp} temp
4946 WHERE temp.id={context}.id";
4948 // sqlite and others
4949 $updatesql = "UPDATE {context}
4950 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
4951 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
4952 WHERE id IN (SELECT id FROM {context_temp})";
4955 $DB->execute($updatesql);
4959 * Get a context instance as an object, from a given context id.
4962 * @param int $id context id
4963 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
4964 * MUST_EXIST means throw exception if no record found
4965 * @return context|bool the context object or false if not found
4967 public static function instance_by_id($id, $strictness = MUST_EXIST
) {
4970 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
4971 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
4972 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
4975 if ($id == SYSCONTEXTID
) {
4976 return context_system
::instance(0, $strictness);
4979 if (is_array($id) or is_object($id) or empty($id)) {
4980 throw new coding_exception('Invalid context id specified context::instance_by_id()');
4983 if ($context = context
::cache_get_by_id($id)) {
4987 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
4988 return context
::create_instance_from_record($record);
4995 * Update context info after moving context in the tree structure.
4997 * @param context $newparent
5000 public function update_moved(context
$newparent) {
5003 $frompath = $this->_path
;
5004 $newpath = $newparent->path
. '/' . $this->_id
;
5006 $trans = $DB->start_delegated_transaction();
5008 $this->mark_dirty();
5011 if (($newparent->depth +
1) != $this->_depth
) {
5012 $diff = $newparent->depth
- $this->_depth +
1;
5013 $setdepth = ", depth = depth + $diff";
5015 $sql = "UPDATE {context}
5019 $params = array($newpath, $this->_id
);
5020 $DB->execute($sql, $params);
5022 $this->_path
= $newpath;
5023 $this->_depth
= $newparent->depth +
1;
5025 $sql = "UPDATE {context}
5026 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+
1))."
5029 $params = array($newpath, "{$frompath}/%");
5030 $DB->execute($sql, $params);
5032 $this->mark_dirty();
5034 context
::reset_caches();
5036 $trans->allow_commit();
5040 * Remove all context path info and optionally rebuild it.
5042 * @param bool $rebuild
5045 public function reset_paths($rebuild = true) {
5049 $this->mark_dirty();
5051 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5052 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5053 if ($this->_contextlevel
!= CONTEXT_SYSTEM
) {
5054 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id
));
5055 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id
));
5057 $this->_path
= null;
5061 context_helper
::build_all_paths(false);
5064 context
::reset_caches();
5068 * Delete all data linked to content, do not delete the context record itself
5070 public function delete_content() {
5073 blocks_delete_all_for_context($this->_id
);
5074 filter_delete_all_for_context($this->_id
);
5076 require_once($CFG->dirroot
. '/comment/lib.php');
5077 comment
::delete_comments(array('contextid'=>$this->_id
));
5079 require_once($CFG->dirroot
.'/rating/lib.php');
5080 $delopt = new stdclass();
5081 $delopt->contextid
= $this->_id
;
5082 $rm = new rating_manager();
5083 $rm->delete_ratings($delopt);
5085 // delete all files attached to this context
5086 $fs = get_file_storage();
5087 $fs->delete_area_files($this->_id
);
5089 // delete all advanced grading data attached to this context
5090 require_once($CFG->dirroot
.'/grade/grading/lib.php');
5091 grading_manager
::delete_all_for_context($this->_id
);
5093 // now delete stuff from role related tables, role_unassign_all
5094 // and unenrol should be called earlier to do proper cleanup
5095 $DB->delete_records('role_assignments', array('contextid'=>$this->_id
));
5096 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id
));
5097 $DB->delete_records('role_names', array('contextid'=>$this->_id
));
5101 * Delete the context content and the context record itself
5103 public function delete() {
5106 // double check the context still exists
5107 if (!$DB->record_exists('context', array('id'=>$this->_id
))) {
5108 context
::cache_remove($this);
5112 $this->delete_content();
5113 $DB->delete_records('context', array('id'=>$this->_id
));
5114 // purge static context cache if entry present
5115 context
::cache_remove($this);
5117 // do not mark dirty contexts if parents unknown
5118 if (!is_null($this->_path
) and $this->_depth
> 0) {
5119 $this->mark_dirty();
5123 // ====== context level related methods ======
5126 * Utility method for context creation
5129 * @param int $contextlevel
5130 * @param int $instanceid
5131 * @param string $parentpath
5132 * @return stdClass context record
5134 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5137 $record = new stdClass();
5138 $record->contextlevel
= $contextlevel;
5139 $record->instanceid
= $instanceid;
5141 $record->path
= null; //not known before insert
5143 $record->id
= $DB->insert_record('context', $record);
5145 // now add path if known - it can be added later
5146 if (!is_null($parentpath)) {
5147 $record->path
= $parentpath.'/'.$record->id
;
5148 $record->depth
= substr_count($record->path
, '/');
5149 $DB->update_record('context', $record);
5156 * Returns human readable context identifier.
5158 * @param boolean $withprefix whether to prefix the name of the context with the
5159 * type of context, e.g. User, Course, Forum, etc.
5160 * @param boolean $short whether to use the short name of the thing. Only applies
5161 * to course contexts
5162 * @return string the human readable context name.
5164 public function get_context_name($withprefix = true, $short = false) {
5165 // must be implemented in all context levels
5166 throw new coding_exception('can not get name of abstract context');
5170 * Returns the most relevant URL for this context.
5172 * @return moodle_url
5174 public abstract function get_url();
5177 * Returns array of relevant context capability records.
5181 public abstract function get_capabilities();
5184 * Recursive function which, given a context, find all its children context ids.
5186 * For course category contexts it will return immediate children and all subcategory contexts.
5187 * It will NOT recurse into courses or subcategories categories.
5188 * If you want to do that, call it on the returned courses/categories.
5190 * When called for a course context, it will return the modules and blocks
5191 * displayed in the course page and blocks displayed on the module pages.
5193 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5196 * @return array Array of child records
5198 public function get_child_contexts() {
5201 $sql = "SELECT ctx.*
5203 WHERE ctx.path LIKE ?";
5204 $params = array($this->_path
.'/%');
5205 $records = $DB->get_records_sql($sql, $params);
5208 foreach ($records as $record) {
5209 $result[$record->id
] = context
::create_instance_from_record($record);
5216 * Returns parent contexts of this context in reversed order, i.e. parent first,
5217 * then grand parent, etc.
5219 * @param bool $includeself tre means include self too
5220 * @return array of context instances
5222 public function get_parent_contexts($includeself = false) {
5223 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5228 foreach ($contextids as $contextid) {
5229 $parent = context
::instance_by_id($contextid, MUST_EXIST
);
5230 $result[$parent->id
] = $parent;
5237 * Returns parent contexts of this context in reversed order, i.e. parent first,
5238 * then grand parent, etc.
5240 * @param bool $includeself tre means include self too
5241 * @return array of context ids
5243 public function get_parent_context_ids($includeself = false) {
5244 if (empty($this->_path
)) {
5248 $parentcontexts = trim($this->_path
, '/'); // kill leading slash
5249 $parentcontexts = explode('/', $parentcontexts);
5250 if (!$includeself) {
5251 array_pop($parentcontexts); // and remove its own id
5254 return array_reverse($parentcontexts);
5258 * Returns parent context
5262 public function get_parent_context() {
5263 if (empty($this->_path
) or $this->_id
== SYSCONTEXTID
) {
5267 $parentcontexts = trim($this->_path
, '/'); // kill leading slash
5268 $parentcontexts = explode('/', $parentcontexts);
5269 array_pop($parentcontexts); // self
5270 $contextid = array_pop($parentcontexts); // immediate parent
5272 return context
::instance_by_id($contextid, MUST_EXIST
);
5276 * Is this context part of any course? If yes return course context.
5278 * @param bool $strict true means throw exception if not found, false means return false if not found
5279 * @return course_context context of the enclosing course, null if not found or exception
5281 public function get_course_context($strict = true) {
5283 throw new coding_exception('Context does not belong to any course.');
5290 * Returns sql necessary for purging of stale context instances.
5293 * @return string cleanup SQL
5295 protected static function get_cleanup_sql() {
5296 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5300 * Rebuild context paths and depths at context level.
5303 * @param bool $force
5306 protected static function build_paths($force) {
5307 throw new coding_exception('build_paths() method must be implemented in all context levels');
5311 * Create missing context instances at given level
5316 protected static function create_level_instances() {
5317 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5321 * Reset all cached permissions and definitions if the necessary.
5324 public function reload_if_dirty() {
5325 global $ACCESSLIB_PRIVATE, $USER;
5327 // Load dirty contexts list if needed
5329 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts
)) {
5330 // we do not load dirty flags in CLI and cron
5331 $ACCESSLIB_PRIVATE->dirtycontexts
= array();
5334 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts
)) {
5335 if (!isset($USER->access
['time'])) {
5336 // nothing was loaded yet, we do not need to check dirty contexts now
5339 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5340 $ACCESSLIB_PRIVATE->dirtycontexts
= get_cache_flags('accesslib/dirtycontexts', $USER->access
['time']-2);
5344 foreach ($ACCESSLIB_PRIVATE->dirtycontexts
as $path=>$unused) {
5345 if ($path === $this->_path
or strpos($this->_path
, $path.'/') === 0) {
5346 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5347 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5348 reload_all_capabilities();
5355 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5357 public function mark_dirty() {
5358 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5360 if (during_initial_install()) {
5364 // only if it is a non-empty string
5365 if (is_string($this->_path
) && $this->_path
!== '') {
5366 set_cache_flag('accesslib/dirtycontexts', $this->_path
, 1, time()+
$CFG->sessiontimeout
);
5367 if (isset($ACCESSLIB_PRIVATE->dirtycontexts
)) {
5368 $ACCESSLIB_PRIVATE->dirtycontexts
[$this->_path
] = 1;
5371 $ACCESSLIB_PRIVATE->dirtycontexts
= array($this->_path
=> 1);
5373 if (isset($USER->access
['time'])) {
5374 $ACCESSLIB_PRIVATE->dirtycontexts
= get_cache_flags('accesslib/dirtycontexts', $USER->access
['time']-2);
5376 $ACCESSLIB_PRIVATE->dirtycontexts
= array($this->_path
=> 1);
5378 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5387 * Context maintenance and helper methods.
5389 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5390 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5391 * level implementation from the rest of code, the code completion returns what developers need.
5393 * Thank you Tim Hunt for helping me with this nasty trick.
5395 * @package core_access
5397 * @copyright Petr Skoda {@link http://skodak.org}
5398 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5401 class context_helper
extends context
{
5404 * @var array An array mapping context levels to classes
5406 private static $alllevels = array(
5407 CONTEXT_SYSTEM
=> 'context_system',
5408 CONTEXT_USER
=> 'context_user',
5409 CONTEXT_COURSECAT
=> 'context_coursecat',
5410 CONTEXT_COURSE
=> 'context_course',
5411 CONTEXT_MODULE
=> 'context_module',
5412 CONTEXT_BLOCK
=> 'context_block',
5416 * Instance does not make sense here, only static use
5418 protected function __construct() {
5422 * Returns a class name of the context level class
5425 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5426 * @return string class name of the context class
5428 public static function get_class_for_level($contextlevel) {
5429 if (isset(self
::$alllevels[$contextlevel])) {
5430 return self
::$alllevels[$contextlevel];
5432 throw new coding_exception('Invalid context level specified');
5437 * Returns a list of all context levels
5440 * @return array int=>string (level=>level class name)
5442 public static function get_all_levels() {
5443 return self
::$alllevels;
5447 * Remove stale contexts that belonged to deleted instances.
5448 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5453 public static function cleanup_instances() {
5456 foreach (self
::$alllevels as $level=>$classname) {
5457 $sqls[] = $classname::get_cleanup_sql();
5460 $sql = implode(" UNION ", $sqls);
5462 // it is probably better to use transactions, it might be faster too
5463 $transaction = $DB->start_delegated_transaction();
5465 $rs = $DB->get_recordset_sql($sql);
5466 foreach ($rs as $record) {
5467 $context = context
::create_instance_from_record($record);
5472 $transaction->allow_commit();
5476 * Create all context instances at the given level and above.
5479 * @param int $contextlevel null means all levels
5480 * @param bool $buildpaths
5483 public static function create_instances($contextlevel = null, $buildpaths = true) {
5484 foreach (self
::$alllevels as $level=>$classname) {
5485 if ($contextlevel and $level > $contextlevel) {
5486 // skip potential sub-contexts
5489 $classname::create_level_instances();
5491 $classname::build_paths(false);
5497 * Rebuild paths and depths in all context levels.
5500 * @param bool $force false means add missing only
5503 public static function build_all_paths($force = false) {
5504 foreach (self
::$alllevels as $classname) {
5505 $classname::build_paths($force);
5508 // reset static course cache - it might have incorrect cached data
5509 accesslib_clear_all_caches(true);
5513 * Resets the cache to remove all data.
5516 public static function reset_caches() {
5517 context
::reset_caches();
5521 * Returns all fields necessary for context preloading from user $rec.
5523 * This helps with performance when dealing with hundreds of contexts.
5526 * @param string $tablealias context table alias in the query
5527 * @return array (table.column=>alias, ...)
5529 public static function get_preload_record_columns($tablealias) {
5530 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5534 * Returns all fields necessary for context preloading from user $rec.
5536 * This helps with performance when dealing with hundreds of contexts.
5539 * @param string $tablealias context table alias in the query
5542 public static function get_preload_record_columns_sql($tablealias) {
5543 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5547 * Preloads context information from db record and strips the cached info.
5549 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5552 * @param stdClass $rec
5553 * @return void (modifies $rec)
5555 public static function preload_from_record(stdClass
$rec) {
5556 context
::preload_from_record($rec);
5560 * Preload all contexts instances from course.
5562 * To be used if you expect multiple queries for course activities...
5565 * @param int $courseid
5567 public static function preload_course($courseid) {
5568 // Users can call this multiple times without doing any harm
5569 if (isset(context
::$cache_preloaded[$courseid])) {
5572 $coursecontext = context_course
::instance($courseid);
5573 $coursecontext->get_child_contexts();
5575 context
::$cache_preloaded[$courseid] = true;
5579 * Delete context instance
5582 * @param int $contextlevel
5583 * @param int $instanceid
5586 public static function delete_instance($contextlevel, $instanceid) {
5589 // double check the context still exists
5590 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5591 $context = context
::create_instance_from_record($record);
5594 // we should try to purge the cache anyway
5599 * Returns the name of specified context level
5602 * @param int $contextlevel
5603 * @return string name of the context level
5605 public static function get_level_name($contextlevel) {
5606 $classname = context_helper
::get_class_for_level($contextlevel);
5607 return $classname::get_level_name();
5613 public function get_url() {
5619 public function get_capabilities() {
5625 * System context class
5627 * @package core_access
5629 * @copyright Petr Skoda {@link http://skodak.org}
5630 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5633 class context_system
extends context
{
5635 * Please use context_system::instance() if you need the instance of context.
5637 * @param stdClass $record
5639 protected function __construct(stdClass
$record) {
5640 parent
::__construct($record);
5641 if ($record->contextlevel
!= CONTEXT_SYSTEM
) {
5642 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5647 * Returns human readable context level name.
5650 * @return string the human readable context level name.
5652 public static function get_level_name() {
5653 return get_string('coresystem');
5657 * Returns human readable context identifier.
5659 * @param boolean $withprefix does not apply to system context
5660 * @param boolean $short does not apply to system context
5661 * @return string the human readable context name.
5663 public function get_context_name($withprefix = true, $short = false) {
5664 return self
::get_level_name();
5668 * Returns the most relevant URL for this context.
5670 * @return moodle_url
5672 public function get_url() {
5673 return new moodle_url('/');
5677 * Returns array of relevant context capability records.
5681 public function get_capabilities() {
5684 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5688 FROM {capabilities}";
5690 return $DB->get_records_sql($sql.' '.$sort, $params);
5694 * Create missing context instances at system context
5697 protected static function create_level_instances() {
5698 // nothing to do here, the system context is created automatically in installer
5703 * Returns system context instance.
5706 * @param int $instanceid
5707 * @param int $strictness
5708 * @param bool $cache
5709 * @return context_system context instance
5711 public static function instance($instanceid = 0, $strictness = MUST_EXIST
, $cache = true) {
5714 if ($instanceid != 0) {
5715 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5718 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5719 if (!isset(context
::$systemcontext)) {
5720 $record = new stdClass();
5721 $record->id
= SYSCONTEXTID
;
5722 $record->contextlevel
= CONTEXT_SYSTEM
;
5723 $record->instanceid
= 0;
5724 $record->path
= '/'.SYSCONTEXTID
;
5726 context
::$systemcontext = new context_system($record);
5728 return context
::$systemcontext;
5733 // we ignore the strictness completely because system context must except except during install
5734 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM
), '*', MUST_EXIST
);
5735 } catch (dml_exception
$e) {
5736 //table or record does not exist
5737 if (!during_initial_install()) {
5738 // do not mess with system context after install, it simply must exist
5745 $record = new stdClass();
5746 $record->contextlevel
= CONTEXT_SYSTEM
;
5747 $record->instanceid
= 0;
5749 $record->path
= null; //not known before insert
5752 if ($DB->count_records('context')) {
5753 // contexts already exist, this is very weird, system must be first!!!
5756 if (defined('SYSCONTEXTID')) {
5757 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5758 $record->id
= SYSCONTEXTID
;
5759 $DB->import_record('context', $record);
5760 $DB->get_manager()->reset_sequence('context');
5762 $record->id
= $DB->insert_record('context', $record);
5764 } catch (dml_exception
$e) {
5765 // can not create context - table does not exist yet, sorry
5770 if ($record->instanceid
!= 0) {
5771 // this is very weird, somebody must be messing with context table
5772 debugging('Invalid system context detected');
5775 if ($record->depth
!= 1 or $record->path
!= '/'.$record->id
) {
5776 // fix path if necessary, initial install or path reset
5778 $record->path
= '/'.$record->id
;
5779 $DB->update_record('context', $record);
5782 if (!defined('SYSCONTEXTID')) {
5783 define('SYSCONTEXTID', $record->id
);
5786 context
::$systemcontext = new context_system($record);
5787 return context
::$systemcontext;
5791 * Returns all site contexts except the system context, DO NOT call on production servers!!
5793 * Contexts are not cached.
5797 public function get_child_contexts() {
5800 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
5802 // Just get all the contexts except for CONTEXT_SYSTEM level
5803 // and hope we don't OOM in the process - don't cache
5806 WHERE contextlevel > ".CONTEXT_SYSTEM
;
5807 $records = $DB->get_records_sql($sql);
5810 foreach ($records as $record) {
5811 $result[$record->id
] = context
::create_instance_from_record($record);
5818 * Returns sql necessary for purging of stale context instances.
5821 * @return string cleanup SQL
5823 protected static function get_cleanup_sql() {
5834 * Rebuild context paths and depths at system context level.
5837 * @param bool $force
5839 protected static function build_paths($force) {
5842 /* note: ignore $force here, we always do full test of system context */
5844 // exactly one record must exist
5845 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM
), '*', MUST_EXIST
);
5847 if ($record->instanceid
!= 0) {
5848 debugging('Invalid system context detected');
5851 if (defined('SYSCONTEXTID') and $record->id
!= SYSCONTEXTID
) {
5852 debugging('Invalid SYSCONTEXTID detected');
5855 if ($record->depth
!= 1 or $record->path
!= '/'.$record->id
) {
5856 // fix path if necessary, initial install or path reset
5858 $record->path
= '/'.$record->id
;
5859 $DB->update_record('context', $record);
5866 * User context class
5868 * @package core_access
5870 * @copyright Petr Skoda {@link http://skodak.org}
5871 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5874 class context_user
extends context
{
5876 * Please use context_user::instance($userid) if you need the instance of context.
5877 * Alternatively if you know only the context id use context::instance_by_id($contextid)
5879 * @param stdClass $record
5881 protected function __construct(stdClass
$record) {
5882 parent
::__construct($record);
5883 if ($record->contextlevel
!= CONTEXT_USER
) {
5884 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
5889 * Returns human readable context level name.
5892 * @return string the human readable context level name.
5894 public static function get_level_name() {
5895 return get_string('user');
5899 * Returns human readable context identifier.
5901 * @param boolean $withprefix whether to prefix the name of the context with User
5902 * @param boolean $short does not apply to user context
5903 * @return string the human readable context name.
5905 public function get_context_name($withprefix = true, $short = false) {
5909 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid
, 'deleted'=>0))) {
5911 $name = get_string('user').': ';
5913 $name .= fullname($user);
5919 * Returns the most relevant URL for this context.
5921 * @return moodle_url
5923 public function get_url() {
5926 if ($COURSE->id
== SITEID
) {
5927 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid
));
5929 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid
, 'courseid'=>$COURSE->id
));
5935 * Returns array of relevant context capability records.
5939 public function get_capabilities() {
5942 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5944 $extracaps = array('moodle/grade:viewall');
5945 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED
, 'cap');
5948 WHERE contextlevel = ".CONTEXT_USER
."
5951 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
5955 * Returns user context instance.
5958 * @param int $instanceid
5959 * @param int $strictness
5960 * @return context_user context instance
5962 public static function instance($instanceid, $strictness = MUST_EXIST
) {
5965 if ($context = context
::cache_get(CONTEXT_USER
, $instanceid)) {
5969 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_USER
, 'instanceid'=>$instanceid))) {
5970 if ($user = $DB->get_record('user', array('id'=>$instanceid, 'deleted'=>0), 'id', $strictness)) {
5971 $record = context
::insert_context_record(CONTEXT_USER
, $user->id
, '/'.SYSCONTEXTID
, 0);
5976 $context = new context_user($record);
5977 context
::cache_add($context);
5985 * Create missing context instances at user context level
5988 protected static function create_level_instances() {
5991 $sql = "INSERT INTO {context} (contextlevel, instanceid)
5992 SELECT ".CONTEXT_USER
.", u.id
5995 AND NOT EXISTS (SELECT 'x'
5997 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER
.")";
6002 * Returns sql necessary for purging of stale context instances.
6005 * @return string cleanup SQL
6007 protected static function get_cleanup_sql() {
6011 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6012 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER
."
6019 * Rebuild context paths and depths at user context level.
6022 * @param bool $force
6024 protected static function build_paths($force) {
6027 // First update normal users.
6028 $path = $DB->sql_concat('?', 'id');
6029 $pathstart = '/' . SYSCONTEXTID
. '/';
6030 $params = array($pathstart);
6033 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6034 $params[] = $pathstart;
6036 $where = "depth = 0 OR path IS NULL";
6039 $sql = "UPDATE {context}
6042 WHERE contextlevel = " . CONTEXT_USER
. "
6044 $DB->execute($sql, $params);
6050 * Course category context class
6052 * @package core_access
6054 * @copyright Petr Skoda {@link http://skodak.org}
6055 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6058 class context_coursecat
extends context
{
6060 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6061 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6063 * @param stdClass $record
6065 protected function __construct(stdClass
$record) {
6066 parent
::__construct($record);
6067 if ($record->contextlevel
!= CONTEXT_COURSECAT
) {
6068 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6073 * Returns human readable context level name.
6076 * @return string the human readable context level name.
6078 public static function get_level_name() {
6079 return get_string('category');
6083 * Returns human readable context identifier.
6085 * @param boolean $withprefix whether to prefix the name of the context with Category
6086 * @param boolean $short does not apply to course categories
6087 * @return string the human readable context name.
6089 public function get_context_name($withprefix = true, $short = false) {
6093 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid
))) {
6095 $name = get_string('category').': ';
6097 $name .= format_string($category->name
, true, array('context' => $this));
6103 * Returns the most relevant URL for this context.
6105 * @return moodle_url
6107 public function get_url() {
6108 return new moodle_url('/course/category.php', array('id'=>$this->_instanceid
));
6112 * Returns array of relevant context capability records.
6116 public function get_capabilities() {
6119 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6124 WHERE contextlevel IN (".CONTEXT_COURSECAT
.",".CONTEXT_COURSE
.",".CONTEXT_MODULE
.",".CONTEXT_BLOCK
.")";
6126 return $DB->get_records_sql($sql.' '.$sort, $params);
6130 * Returns course category context instance.
6133 * @param int $instanceid
6134 * @param int $strictness
6135 * @return context_coursecat context instance
6137 public static function instance($instanceid, $strictness = MUST_EXIST
) {
6140 if ($context = context
::cache_get(CONTEXT_COURSECAT
, $instanceid)) {
6144 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSECAT
, 'instanceid'=>$instanceid))) {
6145 if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), 'id,parent', $strictness)) {
6146 if ($category->parent
) {
6147 $parentcontext = context_coursecat
::instance($category->parent
);
6148 $record = context
::insert_context_record(CONTEXT_COURSECAT
, $category->id
, $parentcontext->path
);
6150 $record = context
::insert_context_record(CONTEXT_COURSECAT
, $category->id
, '/'.SYSCONTEXTID
, 0);
6156 $context = new context_coursecat($record);
6157 context
::cache_add($context);
6165 * Returns immediate child contexts of category and all subcategories,
6166 * children of subcategories and courses are not returned.
6170 public function get_child_contexts() {
6173 $sql = "SELECT ctx.*
6175 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6176 $params = array($this->_path
.'/%', $this->depth+
1, CONTEXT_COURSECAT
);
6177 $records = $DB->get_records_sql($sql, $params);
6180 foreach ($records as $record) {
6181 $result[$record->id
] = context
::create_instance_from_record($record);
6188 * Create missing context instances at course category context level
6191 protected static function create_level_instances() {
6194 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6195 SELECT ".CONTEXT_COURSECAT
.", cc.id
6196 FROM {course_categories} cc
6197 WHERE NOT EXISTS (SELECT 'x'
6199 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT
.")";
6204 * Returns sql necessary for purging of stale context instances.
6207 * @return string cleanup SQL
6209 protected static function get_cleanup_sql() {
6213 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6214 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT
."
6221 * Rebuild context paths and depths at course category context level.
6224 * @param bool $force
6226 protected static function build_paths($force) {
6229 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT
." AND (depth = 0 OR path IS NULL)")) {
6231 $ctxemptyclause = $emptyclause = '';
6233 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6234 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6237 $base = '/'.SYSCONTEXTID
;
6239 // Normal top level categories
6240 $sql = "UPDATE {context}
6242 path=".$DB->sql_concat("'$base/'", 'id')."
6243 WHERE contextlevel=".CONTEXT_COURSECAT
."
6244 AND EXISTS (SELECT 'x'
6245 FROM {course_categories} cc
6246 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6250 // Deeper categories - one query per depthlevel
6251 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6252 for ($n=2; $n<=$maxdepth; $n++
) {
6253 $sql = "INSERT INTO {context_temp} (id, path, depth)
6254 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6256 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT
." AND cc.depth = $n)
6257 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT
.")
6258 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6260 $trans = $DB->start_delegated_transaction();
6261 $DB->delete_records('context_temp');
6263 context
::merge_context_temp_table();
6264 $DB->delete_records('context_temp');
6265 $trans->allow_commit();
6274 * Course context class
6276 * @package core_access
6278 * @copyright Petr Skoda {@link http://skodak.org}
6279 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6282 class context_course
extends context
{
6284 * Please use context_course::instance($courseid) if you need the instance of context.
6285 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6287 * @param stdClass $record
6289 protected function __construct(stdClass
$record) {
6290 parent
::__construct($record);
6291 if ($record->contextlevel
!= CONTEXT_COURSE
) {
6292 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6297 * Returns human readable context level name.
6300 * @return string the human readable context level name.
6302 public static function get_level_name() {
6303 return get_string('course');
6307 * Returns human readable context identifier.
6309 * @param boolean $withprefix whether to prefix the name of the context with Course
6310 * @param boolean $short whether to use the short name of the thing.
6311 * @return string the human readable context name.
6313 public function get_context_name($withprefix = true, $short = false) {
6317 if ($this->_instanceid
== SITEID
) {
6318 $name = get_string('frontpage', 'admin');
6320 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid
))) {
6322 $name = get_string('course').': ';
6325 $name .= format_string($course->shortname
, true, array('context' => $this));
6327 $name .= format_string(get_course_display_name_for_list($course));
6335 * Returns the most relevant URL for this context.
6337 * @return moodle_url
6339 public function get_url() {
6340 if ($this->_instanceid
!= SITEID
) {
6341 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid
));
6344 return new moodle_url('/');
6348 * Returns array of relevant context capability records.
6352 public function get_capabilities() {
6355 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6360 WHERE contextlevel IN (".CONTEXT_COURSE
.",".CONTEXT_MODULE
.",".CONTEXT_BLOCK
.")";
6362 return $DB->get_records_sql($sql.' '.$sort, $params);
6366 * Is this context part of any course? If yes return course context.
6368 * @param bool $strict true means throw exception if not found, false means return false if not found
6369 * @return course_context context of the enclosing course, null if not found or exception
6371 public function get_course_context($strict = true) {
6376 * Returns course context instance.
6379 * @param int $instanceid
6380 * @param int $strictness
6381 * @return context_course context instance
6383 public static function instance($instanceid, $strictness = MUST_EXIST
) {
6386 if ($context = context
::cache_get(CONTEXT_COURSE
, $instanceid)) {
6390 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE
, 'instanceid'=>$instanceid))) {
6391 if ($course = $DB->get_record('course', array('id'=>$instanceid), 'id,category', $strictness)) {
6392 if ($course->category
) {
6393 $parentcontext = context_coursecat
::instance($course->category
);
6394 $record = context
::insert_context_record(CONTEXT_COURSE
, $course->id
, $parentcontext->path
);
6396 $record = context
::insert_context_record(CONTEXT_COURSE
, $course->id
, '/'.SYSCONTEXTID
, 0);
6402 $context = new context_course($record);
6403 context
::cache_add($context);
6411 * Create missing context instances at course context level
6414 protected static function create_level_instances() {
6417 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6418 SELECT ".CONTEXT_COURSE
.", c.id
6420 WHERE NOT EXISTS (SELECT 'x'
6422 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE
.")";
6427 * Returns sql necessary for purging of stale context instances.
6430 * @return string cleanup SQL
6432 protected static function get_cleanup_sql() {
6436 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6437 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE
."
6444 * Rebuild context paths and depths at course context level.
6447 * @param bool $force
6449 protected static function build_paths($force) {
6452 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE
." AND (depth = 0 OR path IS NULL)")) {
6454 $ctxemptyclause = $emptyclause = '';
6456 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6457 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6460 $base = '/'.SYSCONTEXTID
;
6462 // Standard frontpage
6463 $sql = "UPDATE {context}
6465 path = ".$DB->sql_concat("'$base/'", 'id')."
6466 WHERE contextlevel = ".CONTEXT_COURSE
."
6467 AND EXISTS (SELECT 'x'
6469 WHERE c.id = {context}.instanceid AND c.category = 0)
6474 $sql = "INSERT INTO {context_temp} (id, path, depth)
6475 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6477 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE
." AND c.category <> 0)
6478 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT
.")
6479 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6481 $trans = $DB->start_delegated_transaction();
6482 $DB->delete_records('context_temp');
6484 context
::merge_context_temp_table();
6485 $DB->delete_records('context_temp');
6486 $trans->allow_commit();
6493 * Course module context class
6495 * @package core_access
6497 * @copyright Petr Skoda {@link http://skodak.org}
6498 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6501 class context_module
extends context
{
6503 * Please use context_module::instance($cmid) if you need the instance of context.
6504 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6506 * @param stdClass $record
6508 protected function __construct(stdClass
$record) {
6509 parent
::__construct($record);
6510 if ($record->contextlevel
!= CONTEXT_MODULE
) {
6511 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6516 * Returns human readable context level name.
6519 * @return string the human readable context level name.
6521 public static function get_level_name() {
6522 return get_string('activitymodule');
6526 * Returns human readable context identifier.
6528 * @param boolean $withprefix whether to prefix the name of the context with the
6529 * module name, e.g. Forum, Glossary, etc.
6530 * @param boolean $short does not apply to module context
6531 * @return string the human readable context name.
6533 public function get_context_name($withprefix = true, $short = false) {
6537 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6538 FROM {course_modules} cm
6539 JOIN {modules} md ON md.id = cm.module
6540 WHERE cm.id = ?", array($this->_instanceid
))) {
6541 if ($mod = $DB->get_record($cm->modname
, array('id' => $cm->instance
))) {
6543 $name = get_string('modulename', $cm->modname
).': ';
6545 $name .= format_string($mod->name
, true, array('context' => $this));
6552 * Returns the most relevant URL for this context.
6554 * @return moodle_url
6556 public function get_url() {
6559 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6560 FROM {course_modules} cm
6561 JOIN {modules} md ON md.id = cm.module
6562 WHERE cm.id = ?", array($this->_instanceid
))) {
6563 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid
));
6566 return new moodle_url('/');
6570 * Returns array of relevant context capability records.
6574 public function get_capabilities() {
6577 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6579 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid
));
6580 $module = $DB->get_record('modules', array('id'=>$cm->module
));
6583 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6584 if (file_exists($subpluginsfile)) {
6585 $subplugins = array(); // should be redefined in the file
6586 include($subpluginsfile);
6587 if (!empty($subplugins)) {
6588 foreach (array_keys($subplugins) as $subplugintype) {
6589 foreach (array_keys(get_plugin_list($subplugintype)) as $subpluginname) {
6590 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6596 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6597 $extracaps = array();
6598 if (file_exists($modfile)) {
6599 include_once($modfile);
6600 $modfunction = $module->name
.'_get_extra_capabilities';
6601 if (function_exists($modfunction)) {
6602 $extracaps = $modfunction();
6606 $extracaps = array_merge($subcaps, $extracaps);
6608 list($extra, $params) = $DB->get_in_or_equal(
6609 $extracaps, SQL_PARAMS_NAMED
, 'cap0', true, '');
6610 if (!empty($extra)) {
6611 $extra = "OR name $extra";
6615 WHERE (contextlevel = ".CONTEXT_MODULE
."
6616 AND (component = :component OR component = 'moodle'))
6618 $params['component'] = "mod_$module->name";
6620 return $DB->get_records_sql($sql.' '.$sort, $params);
6624 * Is this context part of any course? If yes return course context.
6626 * @param bool $strict true means throw exception if not found, false means return false if not found
6627 * @return course_context context of the enclosing course, null if not found or exception
6629 public function get_course_context($strict = true) {
6630 return $this->get_parent_context();
6634 * Returns module context instance.
6637 * @param int $instanceid
6638 * @param int $strictness
6639 * @return context_module context instance
6641 public static function instance($instanceid, $strictness = MUST_EXIST
) {
6644 if ($context = context
::cache_get(CONTEXT_MODULE
, $instanceid)) {
6648 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_MODULE
, 'instanceid'=>$instanceid))) {
6649 if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), 'id,course', $strictness)) {
6650 $parentcontext = context_course
::instance($cm->course
);
6651 $record = context
::insert_context_record(CONTEXT_MODULE
, $cm->id
, $parentcontext->path
);
6656 $context = new context_module($record);
6657 context
::cache_add($context);
6665 * Create missing context instances at module context level
6668 protected static function create_level_instances() {
6671 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6672 SELECT ".CONTEXT_MODULE
.", cm.id
6673 FROM {course_modules} cm
6674 WHERE NOT EXISTS (SELECT 'x'
6676 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE
.")";
6681 * Returns sql necessary for purging of stale context instances.
6684 * @return string cleanup SQL
6686 protected static function get_cleanup_sql() {
6690 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6691 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE
."
6698 * Rebuild context paths and depths at module context level.
6701 * @param bool $force
6703 protected static function build_paths($force) {
6706 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE
." AND (depth = 0 OR path IS NULL)")) {
6708 $ctxemptyclause = '';
6710 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6713 $sql = "INSERT INTO {context_temp} (id, path, depth)
6714 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6716 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE
.")
6717 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE
.")
6718 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6720 $trans = $DB->start_delegated_transaction();
6721 $DB->delete_records('context_temp');
6723 context
::merge_context_temp_table();
6724 $DB->delete_records('context_temp');
6725 $trans->allow_commit();
6732 * Block context class
6734 * @package core_access
6736 * @copyright Petr Skoda {@link http://skodak.org}
6737 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6740 class context_block
extends context
{
6742 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6743 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6745 * @param stdClass $record
6747 protected function __construct(stdClass
$record) {
6748 parent
::__construct($record);
6749 if ($record->contextlevel
!= CONTEXT_BLOCK
) {
6750 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6755 * Returns human readable context level name.
6758 * @return string the human readable context level name.
6760 public static function get_level_name() {
6761 return get_string('block');
6765 * Returns human readable context identifier.
6767 * @param boolean $withprefix whether to prefix the name of the context with Block
6768 * @param boolean $short does not apply to block context
6769 * @return string the human readable context name.
6771 public function get_context_name($withprefix = true, $short = false) {
6775 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid
))) {
6777 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
6778 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
6779 $blockname = "block_$blockinstance->blockname";
6780 if ($blockobject = new $blockname()) {
6782 $name = get_string('block').': ';
6784 $name .= $blockobject->title
;
6792 * Returns the most relevant URL for this context.
6794 * @return moodle_url
6796 public function get_url() {
6797 $parentcontexts = $this->get_parent_context();
6798 return $parentcontexts->get_url();
6802 * Returns array of relevant context capability records.
6806 public function get_capabilities() {
6809 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6812 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid
));
6815 $extracaps = block_method_result($bi->blockname
, 'get_extra_capabilities');
6817 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED
, 'cap');
6818 $extra = "OR name $extra";
6823 WHERE (contextlevel = ".CONTEXT_BLOCK
."
6824 AND component = :component)
6826 $params['component'] = 'block_' . $bi->blockname
;
6828 return $DB->get_records_sql($sql.' '.$sort, $params);
6832 * Is this context part of any course? If yes return course context.
6834 * @param bool $strict true means throw exception if not found, false means return false if not found
6835 * @return course_context context of the enclosing course, null if not found or exception
6837 public function get_course_context($strict = true) {
6838 $parentcontext = $this->get_parent_context();
6839 return $parentcontext->get_course_context($strict);
6843 * Returns block context instance.
6846 * @param int $instanceid
6847 * @param int $strictness
6848 * @return context_block context instance
6850 public static function instance($instanceid, $strictness = MUST_EXIST
) {
6853 if ($context = context
::cache_get(CONTEXT_BLOCK
, $instanceid)) {
6857 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_BLOCK
, 'instanceid'=>$instanceid))) {
6858 if ($bi = $DB->get_record('block_instances', array('id'=>$instanceid), 'id,parentcontextid', $strictness)) {
6859 $parentcontext = context
::instance_by_id($bi->parentcontextid
);
6860 $record = context
::insert_context_record(CONTEXT_BLOCK
, $bi->id
, $parentcontext->path
);
6865 $context = new context_block($record);
6866 context
::cache_add($context);
6874 * Block do not have child contexts...
6877 public function get_child_contexts() {
6882 * Create missing context instances at block context level
6885 protected static function create_level_instances() {
6888 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6889 SELECT ".CONTEXT_BLOCK
.", bi.id
6890 FROM {block_instances} bi
6891 WHERE NOT EXISTS (SELECT 'x'
6893 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK
.")";
6898 * Returns sql necessary for purging of stale context instances.
6901 * @return string cleanup SQL
6903 protected static function get_cleanup_sql() {
6907 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
6908 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK
."
6915 * Rebuild context paths and depths at block context level.
6918 * @param bool $force
6920 protected static function build_paths($force) {
6923 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK
." AND (depth = 0 OR path IS NULL)")) {
6925 $ctxemptyclause = '';
6927 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6930 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
6931 $sql = "INSERT INTO {context_temp} (id, path, depth)
6932 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6934 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK
.")
6935 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
6936 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
6938 $trans = $DB->start_delegated_transaction();
6939 $DB->delete_records('context_temp');
6941 context
::merge_context_temp_table();
6942 $DB->delete_records('context_temp');
6943 $trans->allow_commit();
6949 // ============== DEPRECATED FUNCTIONS ==========================================
6950 // Old context related functions were deprecated in 2.0, it is recommended
6951 // to use context classes in new code. Old function can be used when
6952 // creating patches that are supposed to be backported to older stable branches.
6953 // These deprecated functions will not be removed in near future,
6954 // before removing devs will be warned with a debugging message first,
6955 // then we will add error message and only after that we can remove the functions
6960 * Not available any more, use load_temp_course_role() instead.
6962 * @deprecated since 2.2
6963 * @param stdClass $context
6964 * @param int $roleid
6965 * @param array $accessdata
6968 function load_temp_role($context, $roleid, array $accessdata) {
6969 debugging('load_temp_role() is deprecated, please use load_temp_course_role() instead, temp role not loaded.');
6974 * Not available any more, use remove_temp_course_roles() instead.
6976 * @deprecated since 2.2
6977 * @param stdClass $context
6978 * @param array $accessdata
6979 * @return array access data
6981 function remove_temp_roles($context, array $accessdata) {
6982 debugging('remove_temp_role() is deprecated, please use remove_temp_course_roles() instead.');
6987 * Returns system context or null if can not be created yet.
6989 * @deprecated since 2.2, use context_system::instance()
6990 * @param bool $cache use caching
6991 * @return context system context (null if context table not created yet)
6993 function get_system_context($cache = true) {
6994 return context_system
::instance(0, IGNORE_MISSING
, $cache);
6998 * Get the context instance as an object. This function will create the
6999 * context instance if it does not exist yet.
7001 * @deprecated since 2.2, use context_course::instance() or other relevant class instead
7002 * @param integer $contextlevel The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
7003 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
7004 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
7005 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
7006 * MUST_EXIST means throw exception if no record or multiple records found
7007 * @return context The context object.
7009 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING
) {
7010 $instances = (array)$instance;
7011 $contexts = array();
7013 $classname = context_helper
::get_class_for_level($contextlevel);
7015 // we do not load multiple contexts any more, PAGE should be responsible for any preloading
7016 foreach ($instances as $inst) {
7017 $contexts[$inst] = $classname::instance($inst, $strictness);
7020 if (is_array($instance)) {
7023 return $contexts[$instance];
7028 * Get a context instance as an object, from a given context id.
7030 * @deprecated since 2.2, use context::instance_by_id($id) instead
7031 * @param int $id context id
7032 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
7033 * MUST_EXIST means throw exception if no record or multiple records found
7034 * @return context|bool the context object or false if not found.
7036 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING
) {
7037 return context
::instance_by_id($id, $strictness);
7041 * Recursive function which, given a context, find all parent context ids,
7042 * and return the array in reverse order, i.e. parent first, then grand
7045 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
7046 * @param context $context
7047 * @param bool $includeself optional, defaults to false
7050 function get_parent_contexts(context
$context, $includeself = false) {
7051 return $context->get_parent_context_ids($includeself);
7055 * Return the id of the parent of this context, or false if there is no parent (only happens if this
7056 * is the site context.)
7058 * @deprecated since 2.2, use $context->get_parent_context() instead
7059 * @param context $context
7060 * @return integer the id of the parent context.
7062 function get_parent_contextid(context
$context) {
7063 if ($parent = $context->get_parent_context()) {
7071 * Recursive function which, given a context, find all its children context ids.
7073 * For course category contexts it will return immediate children only categories and courses.
7074 * It will NOT recurse into courses or child categories.
7075 * If you want to do that, call it on the returned courses/categories.
7077 * When called for a course context, it will return the modules and blocks
7078 * displayed in the course page.
7080 * If called on a user/course/module context it _will_ populate the cache with the appropriate
7083 * @deprecated since 2.2, use $context->get_child_contexts() instead
7084 * @param context $context
7085 * @return array Array of child records
7087 function get_child_contexts(context
$context) {
7088 return $context->get_child_contexts();
7092 * Precreates all contexts including all parents
7094 * @deprecated since 2.2
7095 * @param int $contextlevel empty means all
7096 * @param bool $buildpaths update paths and depths
7099 function create_contexts($contextlevel = null, $buildpaths = true) {
7100 context_helper
::create_instances($contextlevel, $buildpaths);
7104 * Remove stale context records
7106 * @deprecated since 2.2, use context_helper::cleanup_instances() instead
7109 function cleanup_contexts() {
7110 context_helper
::cleanup_instances();
7115 * Populate context.path and context.depth where missing.
7117 * @deprecated since 2.2, use context_helper::build_all_paths() instead
7118 * @param bool $force force a complete rebuild of the path and depth fields, defaults to false
7121 function build_context_path($force = false) {
7122 context_helper
::build_all_paths($force);
7126 * Rebuild all related context depth and path caches
7128 * @deprecated since 2.2
7129 * @param array $fixcontexts array of contexts, strongtyped
7132 function rebuild_contexts(array $fixcontexts) {
7133 foreach ($fixcontexts as $fixcontext) {
7134 $fixcontext->reset_paths(false);
7136 context_helper
::build_all_paths(false);
7140 * Preloads all contexts relating to a course: course, modules. Block contexts
7141 * are no longer loaded here. The contexts for all the blocks on the current
7142 * page are now efficiently loaded by {@link block_manager::load_blocks()}.
7144 * @deprecated since 2.2
7145 * @param int $courseid Course ID
7148 function preload_course_contexts($courseid) {
7149 context_helper
::preload_course($courseid);
7153 * Preloads context information together with instances.
7154 * Use context_instance_preload() to strip the context info from the record and cache the context instance.
7156 * @deprecated since 2.2
7157 * @param string $joinon for example 'u.id'
7158 * @param string $contextlevel context level of instance in $joinon
7159 * @param string $tablealias context table alias
7160 * @return array with two values - select and join part
7162 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
7163 $select = ", ".context_helper
::get_preload_record_columns_sql($tablealias);
7164 $join = "LEFT JOIN {context} $tablealias ON ($tablealias.instanceid = $joinon AND $tablealias.contextlevel = $contextlevel)";
7165 return array($select, $join);
7169 * Preloads context information from db record and strips the cached info.
7170 * The db request has to contain both the $join and $select from context_instance_preload_sql()
7172 * @deprecated since 2.2
7173 * @param stdClass $rec
7174 * @return void (modifies $rec)
7176 function context_instance_preload(stdClass
$rec) {
7177 context_helper
::preload_from_record($rec);
7181 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
7183 * @deprecated since 2.2, use $context->mark_dirty() instead
7184 * @param string $path context path
7186 function mark_context_dirty($path) {
7187 global $CFG, $USER, $ACCESSLIB_PRIVATE;
7189 if (during_initial_install()) {
7193 // only if it is a non-empty string
7194 if (is_string($path) && $path !== '') {
7195 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+
$CFG->sessiontimeout
);
7196 if (isset($ACCESSLIB_PRIVATE->dirtycontexts
)) {
7197 $ACCESSLIB_PRIVATE->dirtycontexts
[$path] = 1;
7200 $ACCESSLIB_PRIVATE->dirtycontexts
= array($path => 1);
7202 if (isset($USER->access
['time'])) {
7203 $ACCESSLIB_PRIVATE->dirtycontexts
= get_cache_flags('accesslib/dirtycontexts', $USER->access
['time']-2);
7205 $ACCESSLIB_PRIVATE->dirtycontexts
= array($path => 1);
7207 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
7214 * Update the path field of the context and all dep. subcontexts that follow
7216 * Update the path field of the context and
7217 * all the dependent subcontexts that follow
7220 * The most important thing here is to be as
7221 * DB efficient as possible. This op can have a
7222 * massive impact in the DB.
7224 * @deprecated since 2.2
7225 * @param context $context context obj
7226 * @param context $newparent new parent obj
7229 function context_moved(context
$context, context
$newparent) {
7230 $context->update_moved($newparent);
7234 * Remove a context record and any dependent entries,
7235 * removes context from static context cache too
7237 * @deprecated since 2.2, use $context->delete_content() instead
7238 * @param int $contextlevel
7239 * @param int $instanceid
7240 * @param bool $deleterecord false means keep record for now
7241 * @return bool returns true or throws an exception
7243 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
7244 if ($deleterecord) {
7245 context_helper
::delete_instance($contextlevel, $instanceid);
7247 $classname = context_helper
::get_class_for_level($contextlevel);
7248 if ($context = $classname::instance($instanceid, IGNORE_MISSING
)) {
7249 $context->delete_content();
7257 * Returns context level name
7259 * @deprecated since 2.2
7260 * @param integer $contextlevel $context->context level. One of the CONTEXT_... constants.
7261 * @return string the name for this type of context.
7263 function get_contextlevel_name($contextlevel) {
7264 return context_helper
::get_level_name($contextlevel);
7268 * Prints human readable context identifier.
7270 * @deprecated since 2.2
7271 * @param context $context the context.
7272 * @param boolean $withprefix whether to prefix the name of the context with the
7273 * type of context, e.g. User, Course, Forum, etc.
7274 * @param boolean $short whether to user the short name of the thing. Only applies
7275 * to course contexts
7276 * @return string the human readable context name.
7278 function print_context_name(context
$context, $withprefix = true, $short = false) {
7279 return $context->get_context_name($withprefix, $short);
7283 * Get a URL for a context, if there is a natural one. For example, for
7284 * CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
7285 * user profile page.
7287 * @deprecated since 2.2
7288 * @param context $context the context.
7289 * @return moodle_url
7291 function get_context_url(context
$context) {
7292 return $context->get_url();
7296 * Is this context part of any course? if yes return course context,
7297 * if not return null or throw exception.
7299 * @deprecated since 2.2, use $context->get_course_context() instead
7300 * @param context $context
7301 * @return course_context context of the enclosing course, null if not found or exception
7303 function get_course_context(context
$context) {
7304 return $context->get_course_context(true);
7308 * Returns current course id or null if outside of course based on context parameter.
7310 * @deprecated since 2.2, use $context->get_course_context instead
7311 * @param context $context
7312 * @return int|bool related course id or false
7314 function get_courseid_from_context(context
$context) {
7315 if ($coursecontext = $context->get_course_context(false)) {
7316 return $coursecontext->instanceid
;
7323 * Get an array of courses where cap requested is available
7324 * and user is enrolled, this can be relatively slow.
7326 * @deprecated since 2.2, use enrol_get_users_courses() instead
7327 * @param int $userid A user id. By default (null) checks the permissions of the current user.
7328 * @param string $cap - name of the capability
7329 * @param array $accessdata_ignored
7330 * @param bool $doanything_ignored
7331 * @param string $sort - sorting fields - prefix each fieldname with "c."
7332 * @param array $fields - additional fields you are interested in...
7333 * @param int $limit_ignored
7334 * @return array $courses - ordered array of course objects - see notes above
7336 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
7338 $courses = enrol_get_users_courses($userid, true, $fields, $sort);
7339 foreach ($courses as $id=>$course) {
7340 $context = context_course
::instance($id);
7341 if (!has_capability($cap, $context, $userid)) {
7342 unset($courses[$id]);
7350 * Extracts the relevant capabilities given a contextid.
7351 * All case based, example an instance of forum context.
7352 * Will fetch all forum related capabilities, while course contexts
7353 * Will fetch all capabilities
7356 * `name` varchar(150) NOT NULL,
7357 * `captype` varchar(50) NOT NULL,
7358 * `contextlevel` int(10) NOT NULL,
7359 * `component` varchar(100) NOT NULL,
7361 * @deprecated since 2.2
7362 * @param context $context
7365 function fetch_context_capabilities(context
$context) {
7366 return $context->get_capabilities();
7370 * Runs get_records select on context table and returns the result
7371 * Does get_records_select on the context table, and returns the results ordered
7372 * by contextlevel, and then the natural sort order within each level.
7373 * for the purpose of $select, you need to know that the context table has been
7374 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7376 * @deprecated since 2.2
7377 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7378 * @param array $params any parameters required by $select.
7379 * @return array the requested context records.
7381 function get_sorted_contexts($select, $params = array()) {
7383 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7387 $select = 'WHERE ' . $select;
7389 return $DB->get_records_sql("
7392 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER
. " AND u.id = ctx.instanceid
7393 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT
. " AND cat.id = ctx.instanceid
7394 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE
. " AND c.id = ctx.instanceid
7395 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE
. " AND cm.id = ctx.instanceid
7396 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK
. " AND bi.id = ctx.instanceid
7398 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7403 * This is really slow!!! do not use above course context level
7405 * @deprecated since 2.2
7406 * @param int $roleid
7407 * @param context $context
7410 function get_role_context_caps($roleid, context
$context) {
7413 //this is really slow!!!! - do not use above course context level!
7415 $result[$context->id
] = array();
7417 // first emulate the parent context capabilities merging into context
7418 $searchcontexts = array_reverse($context->get_parent_context_ids(true));
7419 foreach ($searchcontexts as $cid) {
7420 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7421 foreach ($capabilities as $cap) {
7422 if (!array_key_exists($cap->capability
, $result[$context->id
])) {
7423 $result[$context->id
][$cap->capability
] = 0;
7425 $result[$context->id
][$cap->capability
] +
= $cap->permission
;
7430 // now go through the contexts below given context
7431 $searchcontexts = array_keys($context->get_child_contexts());
7432 foreach ($searchcontexts as $cid) {
7433 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7434 foreach ($capabilities as $cap) {
7435 if (!array_key_exists($cap->contextid
, $result)) {
7436 $result[$cap->contextid
] = array();
7438 $result[$cap->contextid
][$cap->capability
] = $cap->permission
;
7447 * Gets a string for sql calls, searching for stuff in this context or above
7449 * NOTE: use $DB->get_in_or_equal($context->get_parent_context_ids()...
7451 * @deprecated since 2.2, $context->use get_parent_context_ids() instead
7452 * @param context $context
7455 function get_related_contexts_string(context
$context) {
7457 if ($parents = $context->get_parent_context_ids()) {
7458 return (' IN ('.$context->id
.','.implode(',', $parents).')');
7460 return (' ='.$context->id
);